Improved blobio extension.

This commit is contained in:
Nuno Cruces
2024-09-05 12:08:32 +01:00
parent e2a2d447ce
commit 356dd56e5f
2 changed files with 27 additions and 17 deletions

View File

@@ -11,11 +11,11 @@ import (
// Register registers the SQL functions:
//
// readblob(schema, table, column, rowid, offset, n)
// readblob(schema, table, column, rowid, offset, n/writer)
//
// Reads n bytes of a blob, starting at offset.
//
// writeblob(schema, table, column, rowid, offset, data)
// writeblob(schema, table, column, rowid, offset, data/reader)
//
// Writes data into a blob, at the given offset.
//
@@ -52,19 +52,24 @@ func readblob(ctx sqlite3.Context, arg ...sqlite3.Value) {
return // notest
}
n := arg[5].Int64()
if n <= 0 {
return
if p, ok := arg[5].Pointer().(io.Writer); ok {
var n int64
n, err = blob.WriteTo(p)
ctx.ResultInt64(n)
} else {
n := arg[5].Int64()
if n <= 0 {
return
}
buf := make([]byte, n)
_, err = io.ReadFull(blob, buf)
ctx.ResultBlob(buf)
}
buf := make([]byte, n)
_, err = io.ReadFull(blob, buf)
if err != nil {
ctx.ResultError(err)
return // notest
}
ctx.ResultBlob(buf)
setAuxBlob(ctx, blob, false)
}
@@ -82,7 +87,9 @@ func writeblob(ctx sqlite3.Context, arg ...sqlite3.Value) {
}
if p, ok := arg[5].Pointer().(io.Reader); ok {
_, err = blob.ReadFrom(p)
var n int64
n, err = blob.ReadFrom(p)
ctx.ResultInt64(n)
} else {
_, err = blob.Write(arg[5].RawBlob())
}

View File

@@ -34,23 +34,26 @@ func Example() {
const message = "Hello BLOB!"
// Create the BLOB.
_, err = db.Exec(`INSERT INTO test VALUES (?)`, sqlite3.ZeroBlob(len(message)))
r, err := db.Exec(`INSERT INTO test VALUES (?)`, sqlite3.ZeroBlob(len(message)))
if err != nil {
log.Fatal(err)
}
id, err := r.LastInsertId()
if err != nil {
log.Fatal(err)
}
// Write the BLOB.
_, err = db.Exec(`SELECT writeblob('main', 'test', 'col', last_insert_rowid(), 0, ?)`, message)
_, err = db.Exec(`SELECT writeblob('main', 'test', 'col', ?, 0, ?)`,
id, message)
if err != nil {
log.Fatal(err)
}
// Read the BLOB.
_, err = db.Exec(`SELECT openblob('main', 'test', 'col', rowid, false, ?) FROM test`,
sqlite3.Pointer[blobio.OpenCallback](func(blob *sqlite3.Blob, _ ...sqlite3.Value) error {
_, err = blob.WriteTo(os.Stdout)
return err
}))
_, err = db.Exec(`SELECT readblob('main', 'test', 'col', ?, 0, ?)`,
id, sqlite3.Pointer(os.Stdout))
if err != nil {
log.Fatal(err)
}