feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

@@ -0,0 +1,3 @@
build/
native/.zig-cache/
native/zig-out/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 MyGo contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76
View File
@@ -0,0 +1,76 @@
# SQLite
SQLite for MyGo, with Go connections and the `@mygo-plugins/sqlite`
TypeScript client. Its SQLite is a native module (`internal/sqlitecore`),
written in Zig on desktops, published prebuilt for each platform, so apps
build without cgo, a C compiler or Zig, and in Swift on iOS and Kotlin on
Android, which build with the app.
Register `mygo.Use(sqlite.Plugin)` only when the web frontend uses
`@mygo-plugins/sqlite`. Go and native UI apps call `sqlite.Open` directly;
they need no plugin registration and close their own connections.
```go
import (
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/sqlite"
)
func main() {
mygo.Use(sqlite.Plugin)
// Create windows, then call mygo.App.Run().
}
```
```ts
import { open } from "@mygo-plugins/sqlite";
const db = await open("app.db");
await db.execute("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)");
const inserted = await db.execute("INSERT INTO tasks(title, done) VALUES (?, ?)", ["Learn MyGo", false]);
const { columns, rows } = await db.query("SELECT id, title, done FROM tasks WHERE done = ?", [false]);
await db.transaction([
{ sql: "UPDATE tasks SET done = ? WHERE id = ?", params: [true, inserted.lastInsertId] },
{ sql: "INSERT INTO tasks(title, done) VALUES (?, ?)", params: ["Ship the app", false] },
]);
await db.close();
```
Use `bun add @mygo-plugins/sqlite` once the npm package is published. In a
checkout, `bun install && bun run build` installs and builds the workspace
package. See [the full guide](../../docs/plugins/sqlite.md) for the Go API,
types, cancellation, options and packaging.
## Building the native module
`internal/sqlitecore` declares the interface the plugin calls, `Engine`,
and `internal/sqlitecore/zig` implements it, compiling SQLite **3.53.4**,
which `build.zig.zon` pins by the hash of sqlite.org's amalgamation. Its
library exports only the module's functions: SQLite's own symbols stay
hidden, so a process that loaded another SQLite globally (WebKit does, on
Linux) cannot interpose on them.
With Zig **0.16.0** on the path, from the repository's root:
```sh
# Build this machine's library, which go test and go run use:
go run ./cmd/mygo native build -target host plugins/sqlite/internal/sqlitecore
# Build and publish every platform's:
go run ./cmd/mygo native build -upload plugins/sqlite/internal/sqlitecore
```
Linux targets glibc 2.28 or later; macOS targets 12 or later.
On iOS, `internal/sqlitecore/swift` links the same SQLite, built with the
same options by `swift/build-xcframework.sh` on a Mac into
`CSQLite-3.53.4.xcframework.zip`, an asset of the release
`native-sqlitecore` whose checksum `Package.swift` pins. On Android,
`internal/sqlitecore/kotlin` compiles it with CMake, which downloads the
amalgamation and checks its SHA-256. Upgrading SQLite changes the
version and hash in `build.zig.zon`, `build-xcframework.sh` and
`kotlin/src/main/c/CMakeLists.txt`, and the XCFramework's URL and
checksum.
SQLite is public domain; the plugin and its module use the repository's MIT
license. FTS5, RTree and JSON are enabled, with foreign keys on by default.
Loadable extensions, shared cache and deprecated APIs are omitted.
+397
View File
@@ -0,0 +1,397 @@
package sqlite
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/egoist/mygo/native"
"github.com/egoist/mygo/plugins/sqlite/internal/sqlitecore"
)
// ErrClosed is returned when an operation uses a closed database.
var ErrClosed = errors.New("sqlite: database is closed")
// Error is an SQLite error. Code is the primary result code; ExtendedCode
// distinguishes such errors as unique, foreign-key and not-null constraints.
type Error struct {
Code int
ExtendedCode int
Message string
}
func (e *Error) Error() string { return fmt.Sprintf("sqlite: %s (code %d)", e.Message, e.ExtendedCode) }
// OpenOptions configure a connection. Foreign keys are enabled by default.
type OpenOptions struct {
// ReadOnly opens an existing database without allowing writes.
ReadOnly bool
// BusyTimeout is how long an operation waits for another connection's
// lock: five seconds when zero, no wait when negative. Cancellation
// stops the wait early.
BusyTimeout time.Duration
}
// Result describes a statement. Changes counts directly affected rows;
// LastInsertID is SQLite's last inserted rowid on this connection.
type Result struct {
Changes int64 `json:"changes"`
LastInsertID int64 `json:"lastInsertId"`
}
// Rows holds columns and their values in order, preserving duplicate column
// names. Values are nil, int64, float64, string or []byte. BLOBs are copied
// before the next step, so they remain valid after the statement closes.
type Rows struct {
Columns []string `json:"columns"`
Values [][]any `json:"rows"`
}
// Statement is one parameterized statement in a transaction.
type Statement struct {
SQL string
Args []any
}
// DB is a connection to the plugin's SQLite library. It is safe from any
// goroutine; operations serialize on the connection and may be canceled
// while waiting for it. Use Transaction for atomic groups of statements.
type DB struct {
gate chan struct{}
life context.Context
cancel context.CancelFunc
conn sqlitecore.Conn // guarded by gate; nil once closed
}
var engine = sync.OnceValues(sqlitecore.NewEngine)
// Load loads the plugin's SQLite, a native module, once. Open calls it
// lazily, so binding the plugin and generating clients need no library.
func Load() error {
_, err := engine()
return err
}
// Open opens path (or ":memory:") with SQLite, which the plugin compiles
// with Zig into a native module, without cgo. It creates a missing file
// unless ReadOnly. The parent directory must already exist. Close the
// returned connection when done.
func Open(ctx context.Context, path string, opts OpenOptions) (*DB, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if path == "" || strings.IndexByte(path, 0) >= 0 || !utf8.ValidString(path) {
return nil, errors.New("sqlite: database path must be nonempty UTF-8 without NUL")
}
e, err := engine()
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
timeout := opts.BusyTimeout
if timeout == 0 {
timeout = 5 * time.Second
}
ms := timeout.Milliseconds()
if timeout > 0 && ms == 0 {
ms = 1
}
ms = max(0, min(ms, math.MaxInt32))
conn, err := e.Open(path, opts.ReadOnly, int(ms))
if err != nil {
return nil, sqliteError(err)
}
life, cancel := context.WithCancel(context.Background())
db := &DB{conn: conn, gate: make(chan struct{}, 1), life: life, cancel: cancel}
db.gate <- struct{}{}
if err := ctx.Err(); err != nil {
db.Close()
return nil, err
}
return db, nil
}
// Close cancels in-flight operations, waits for their statements to be
// finalized, and closes the connection. Repeated calls are harmless.
func (d *DB) Close() error {
d.cancel()
<-d.gate
defer func() { d.gate <- struct{}{} }()
if d.conn == nil {
return nil
}
if err := d.conn.Close(); err != nil {
return sqliteError(err)
}
d.conn = nil
return nil
}
// Execute runs exactly one statement with positional parameters. Supported
// values are nil, bool, integers, finite floats, strings, []byte and
// json.Number. SQL text may not contain NUL. Transaction control, ATTACH
// and VACUUM INTO are rejected; use Transaction for groups of statements.
func (d *DB) Execute(ctx context.Context, sql string, args ...any) (result Result, err error) {
err = d.operation(ctx, func(func()) error {
var e error
result, _, e = d.run(sql, args, false)
return e
})
return
}
// Query runs exactly one statement and copies its rows. It also supports
// statements with RETURNING. For large results, select a bounded page.
func (d *DB) Query(ctx context.Context, sql string, args ...any) (rows Rows, err error) {
err = d.operation(ctx, func(func()) error {
var e error
_, rows, e = d.run(sql, args, true)
return e
})
return
}
// Transaction runs statements under BEGIN IMMEDIATE, without interleaving
// other operations on this connection. Any error, including cancellation,
// rolls back the batch. Results are returned only after COMMIT succeeds.
func (d *DB) Transaction(ctx context.Context, statements []Statement) (results []Result, err error) {
err = d.operation(ctx, func(detach func()) (err error) {
if len(statements) == 0 {
results = []Result{}
return nil
}
if err = d.control("BEGIN IMMEDIATE"); err != nil {
return err
}
committed := false
defer func() {
if !committed {
// Cleanup must run even when the operation is canceled.
detach()
if rollback := d.control("ROLLBACK"); rollback != nil {
// SQLITE_INTERRUPT may already have rolled the transaction back.
if !d.conn.Autocommit() {
err = errors.Join(err, rollback)
}
}
}
}()
results = make([]Result, 0, len(statements))
for i, s := range statements {
if err = ctx.Err(); err != nil {
return err
}
var result Result
result, _, err = d.run(s.SQL, s.Args, false)
if err != nil {
return fmt.Errorf("sqlite: statement %d: %w", i+1, err)
}
results = append(results, result)
}
if err = ctx.Err(); err != nil {
return err
}
if d.life.Err() != nil {
return ErrClosed
}
if err = d.control("COMMIT"); err != nil {
return err
}
committed = true
return nil
})
if err != nil {
results = nil
}
return
}
// operation runs fn alone on the connection. Canceling ctx, or closing
// the connection, interrupts the statement running; fn's detach stops
// that, waiting for an interruption that started, as before cleanup.
func (d *DB) operation(ctx context.Context, fn func(detach func()) error) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-d.life.Done():
return ErrClosed
case <-d.gate:
}
defer func() { d.gate <- struct{}{} }()
if err := ctx.Err(); err != nil {
return err
}
if d.conn == nil || d.life.Err() != nil {
return ErrClosed
}
conn := d.conn
watch := func(c context.Context) func() {
done := make(chan struct{})
stop := context.AfterFunc(c, func() { conn.Interrupt(); close(done) })
return func() {
// An interruption that started ends before the next statement.
if !stop() {
<-done
}
}
}
stopCaller, stopClose := watch(ctx), watch(d.life)
detached := false
detach := func() {
if !detached {
detached = true
stopCaller()
stopClose()
}
}
defer detach()
err := fn(detach)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
if d.life.Err() != nil {
return ErrClosed
}
}
return err
}
// sqliteError makes an Error of an error of SQLite's that the module
// reports, by its extended code.
func sqliteError(err error) error {
var e *native.Error
if errors.As(err, &e) && e.Domain == "SQLite" {
code := int(e.Number)
return &Error{Code: code & 255, ExtendedCode: code, Message: e.Message}
}
if errors.As(err, &e) && e.Domain == "" && e.Code == "" {
return errors.New(e.Message)
}
return err
}
func checkSQL(sql string) error {
if len(sql) > math.MaxInt32-1 || strings.IndexByte(sql, 0) >= 0 || !utf8.ValidString(sql) {
return errors.New("sqlite: SQL must be UTF-8 without NUL and fit in a C int")
}
return nil
}
func (d *DB) run(sql string, args []any, query bool) (Result, Rows, error) {
if err := checkSQL(sql); err != nil {
return Result{}, Rows{}, err
}
values := make([]sqlitecore.Value, len(args))
for i, arg := range args {
v, err := value(arg)
if err != nil {
return Result{}, Rows{}, fmt.Errorf("sqlite: parameter %d: %w", i+1, err)
}
values[i] = v
}
out, err := d.conn.Run(sql, values, query)
if err != nil {
return Result{}, Rows{}, sqliteError(err)
}
rows := Rows{Columns: []string{}, Values: [][]any{}}
if query {
rows.Columns = append(rows.Columns, out.Columns...)
if n := len(out.Columns); n > 0 {
for i := 0; i+n <= len(out.Values); i += n {
row := make([]any, n)
for j, v := range out.Values[i : i+n] {
row[j] = goValue(v)
}
rows.Values = append(rows.Values, row)
}
}
}
return Result{Changes: out.Changes, LastInsertID: out.LastInsertID}, rows, nil
}
func (d *DB) control(sql string) error {
return sqliteError(d.conn.Control(sql))
}
// value converts a parameter of Go's to SQLite's.
func value(arg any) (sqlitecore.Value, error) {
switch v := arg.(type) {
case nil:
return sqlitecore.Value{Type: sqlitecore.Null}, nil
case []byte:
if len(v) > math.MaxInt32 {
return sqlitecore.Value{}, errors.New("BLOB is too large")
}
return sqlitecore.Value{Type: sqlitecore.Blob, Blob: v}, nil
case json.Number:
if i, err := v.Int64(); err == nil {
return value(i)
}
if !strings.ContainsAny(string(v), ".eE") {
return sqlitecore.Value{}, errors.New("integer exceeds SQLite's signed 64-bit range")
}
f, err := v.Float64()
if err != nil {
return sqlitecore.Value{}, err
}
return value(f)
}
v := reflect.ValueOf(arg)
switch v.Kind() {
case reflect.Bool:
n := int64(0)
if v.Bool() {
n = 1
}
return sqlitecore.Value{Type: sqlitecore.Integer, Int: n}, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return sqlitecore.Value{Type: sqlitecore.Integer, Int: v.Int()}, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if v.Uint() > math.MaxInt64 {
return sqlitecore.Value{}, errors.New("integer exceeds SQLite's signed 64-bit range")
}
return sqlitecore.Value{Type: sqlitecore.Integer, Int: int64(v.Uint())}, nil
case reflect.Float32, reflect.Float64:
f := v.Float()
if math.IsNaN(f) || math.IsInf(f, 0) {
return sqlitecore.Value{}, errors.New("number must be finite")
}
return sqlitecore.Value{Type: sqlitecore.Real, Real: f}, nil
case reflect.String:
s := v.String()
if len(s) > math.MaxInt32 || !utf8.ValidString(s) {
return sqlitecore.Value{}, errors.New("text must be UTF-8 and fit in a C int")
}
return sqlitecore.Value{Type: sqlitecore.Text, Text: s}, nil
}
return sqlitecore.Value{}, fmt.Errorf("unsupported value %T", arg)
}
// goValue converts a column of SQLite's to Go's: nil, int64, float64,
// string or []byte.
func goValue(v sqlitecore.Value) any {
switch v.Type {
case sqlitecore.Integer:
return v.Int
case sqlitecore.Real:
return v.Real
case sqlitecore.Text:
return v.Text
case sqlitecore.Blob:
if v.Blob == nil {
return []byte{}
}
return v.Blob
}
return nil
}
+294
View File
@@ -0,0 +1,294 @@
package sqlite
import (
"context"
"encoding/json"
"errors"
"math"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/egoist/mygo/internal/wait"
)
// needSQLite skips a test in -short mode, and where the plugin's native
// module is not built: mygo native build -target host
// ./plugins/sqlite/internal/sqlitecore builds it, with Zig.
func needSQLite(t *testing.T) {
t.Helper()
if testing.Short() {
t.Skip("requires the plugin's native module")
}
if err := Load(); err != nil && strings.Contains(err.Error(), "mygo native build") {
t.Skip(err)
}
}
func testDB(t *testing.T, path string) *DB {
t.Helper()
needSQLite(t)
db, err := Open(context.Background(), path, OpenOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := db.Close(); err != nil {
t.Error(err)
}
})
return db
}
func execute(t *testing.T, db *DB, sql string, args ...any) Result {
t.Helper()
r, err := db.Execute(context.Background(), sql, args...)
if err != nil {
t.Fatal(err)
}
return r
}
func query(t *testing.T, db *DB, sql string, args ...any) Rows {
t.Helper()
r, err := db.Query(context.Background(), sql, args...)
if err != nil {
t.Fatal(err)
}
return r
}
func TestValues(t *testing.T) {
db := testDB(t, ":memory:")
values := []any{nil, int64(math.MinInt64), int64(math.MaxInt64), -3.125, "中文🙂\x00text", []byte{0, 1, 255}, []byte{}, "", true}
rows := query(t, db, "SELECT ? AS same, ? AS same, ?, ?, ?, ?, ?, ?, ?", values...)
want := append([]any{}, values...)
want[8] = int64(1)
if !reflect.DeepEqual(rows.Values, [][]any{want}) {
t.Fatalf("values = %#v, want %#v", rows.Values, want)
}
if rows.Columns[0] != "same" || rows.Columns[1] != "same" {
t.Fatal(rows.Columns)
}
execute(t, db, "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT UNIQUE, bytes BLOB)")
r := execute(t, db, "INSERT INTO items(name, bytes) VALUES (?, ?)", "it's a ?; DROP TABLE items; --", []byte{1, 2})
if r.Changes != 1 || r.LastInsertID != 1 {
t.Fatal(r)
}
if n := execute(t, db, "CREATE TABLE other (n)").Changes; n != 0 {
t.Fatalf("DDL changes = %d", n)
}
got := query(t, db, "SELECT name, bytes FROM items").Values[0]
if got[0] != "it's a ?; DROP TABLE items; --" || !reflect.DeepEqual(got[1], []byte{1, 2}) {
t.Fatal(got)
}
// BLOB storage belongs to Go after SQLite finalizes the statement.
_ = query(t, db, "SELECT randomblob(65536)")
if !reflect.DeepEqual(got[1], []byte{1, 2}) {
t.Fatal("BLOB changed after a later step")
}
if rows := query(t, db, "SELECT * FROM items WHERE 0"); len(rows.Values) != 0 || len(rows.Columns) != 3 {
t.Fatal(rows)
}
if r := query(t, db, "INSERT INTO items(name) VALUES ('returning') RETURNING id"); r.Values[0][0] != int64(2) {
t.Fatal(r)
}
if r := query(t, db, "SELECT ?, ?, ?", json.Number("42"), json.Number("0.25"), uint32(7)); !reflect.DeepEqual(r.Values[0], []any{int64(42), 0.25, int64(7)}) {
t.Fatal(r)
}
}
func TestSQLiteFeatures(t *testing.T) {
db := testDB(t, ":memory:")
if v := query(t, db, "SELECT sqlite_version()").Values[0][0]; v != "3.53.4" {
t.Fatalf("SQLite = %v", v)
}
execute(t, db, "CREATE TABLE parent (id PRIMARY KEY)")
execute(t, db, "CREATE TABLE child (parent REFERENCES parent(id))")
_, err := db.Execute(context.Background(), "INSERT INTO child VALUES (1)")
var sqliteErr *Error
if !errors.As(err, &sqliteErr) || sqliteErr.Code != 19 || sqliteErr.ExtendedCode != 787 {
t.Fatalf("foreign key: %v", err)
}
execute(t, db, "CREATE VIRTUAL TABLE search USING fts5(body)")
execute(t, db, "INSERT INTO search VALUES ('hello sqlite')")
if n := query(t, db, "SELECT count(*) FROM search WHERE search MATCH 'sqlite'").Values[0][0]; n != int64(1) {
t.Fatal(n)
}
execute(t, db, "CREATE VIRTUAL TABLE spatial USING rtree(id, x0, x1, y0, y1)")
if v := query(t, db, `SELECT json_extract('{"a":42}', '$.a')`).Values[0][0]; v != int64(42) {
t.Fatal(v)
}
execute(t, db, "VACUUM")
}
func TestValidationBeforeExecution(t *testing.T) {
db := testDB(t, ":memory:")
execute(t, db, "CREATE TABLE items (n UNIQUE)")
for _, sql := range []string{"INSERT INTO items VALUES (1); INSERT INTO items VALUES (2)", "INSERT INTO items VALUES (3); invalid sql", "INSERT INTO items VALUES (4)\x00;", "", "-- only a comment", "BEGIN", "SAVEPOINT foo", "ATTACH ':memory:' AS other", "VACUUM INTO 'outside.db'"} {
if _, err := db.Execute(context.Background(), sql); err == nil {
t.Errorf("accepted %q", sql)
}
}
if n := query(t, db, "SELECT count(*) FROM items").Values[0][0]; n != int64(0) {
t.Fatalf("partial SQL ran: %v", n)
}
execute(t, db, "INSERT INTO items VALUES (?) ; -- trailing comment\n /* another */", 1)
for _, args := range [][]any{nil, {1, 2}, {math.NaN()}, {math.Inf(1)}, {uint64(math.MaxUint64)}, {json.Number("9223372036854775808")}, {struct{}{}}, {"\xff"}} {
if _, err := db.Execute(context.Background(), "INSERT INTO items VALUES (?)", args...); err == nil {
t.Errorf("accepted args %#v", args)
}
}
}
func TestTransactions(t *testing.T) {
db := testDB(t, ":memory:")
execute(t, db, "CREATE TABLE items (n UNIQUE)")
results, err := db.Transaction(context.Background(), []Statement{{"INSERT INTO items VALUES (?)", []any{1}}, {"INSERT INTO items VALUES (?)", []any{2}}})
if err != nil || len(results) != 2 || results[0].Changes != 1 || results[1].Changes != 1 {
t.Fatalf("%v, %v", results, err)
}
for _, second := range []string{"INSERT INTO items VALUES (2)", "COMMIT", "SAVEPOINT escape", "not sql"} {
results, err := db.Transaction(context.Background(), []Statement{{SQL: "INSERT INTO items VALUES (3)"}, {SQL: second}})
if err == nil || results != nil {
t.Fatalf("batch succeeded: %q: %v %v", second, results, err)
}
if n := query(t, db, "SELECT count(*) FROM items").Values[0][0]; n != int64(2) {
t.Fatalf("batch did not roll back: %q: %v", second, n)
}
}
if r, err := db.Transaction(context.Background(), nil); err != nil || r == nil || len(r) != 0 {
t.Fatalf("empty batch: %v %v", r, err)
}
}
const longQuery = "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<1000000000) SELECT sum(x) FROM n"
func TestCancellationAndRollback(t *testing.T) {
db := testDB(t, ":memory:")
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if _, err := db.Query(ctx, longQuery); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("cancellation: %v", err)
}
if n := query(t, db, "SELECT 42").Values[0][0]; n != int64(42) {
t.Fatal(n)
}
execute(t, db, "CREATE TABLE items (n)")
ctx, cancel = context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if _, err := db.Transaction(ctx, []Statement{{SQL: "INSERT INTO items VALUES (1)"}, {SQL: longQuery}}); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("batch cancellation: %v", err)
}
if n := query(t, db, "SELECT count(*) FROM items").Values[0][0]; n != int64(0) {
t.Fatal("canceled batch did not roll back", n)
}
}
func TestConcurrentOperations(t *testing.T) {
db := testDB(t, ":memory:")
execute(t, db, "CREATE TABLE counter(n)")
execute(t, db, "INSERT INTO counter VALUES (0)")
var wg sync.WaitGroup
for range 16 {
wg.Go(func() {
for range 8 {
if _, err := db.Execute(context.Background(), "UPDATE counter SET n=n+1"); err != nil {
t.Error(err)
return
}
}
})
}
wg.Wait()
if n := query(t, db, "SELECT n FROM counter").Values[0][0]; n != int64(128) {
t.Fatal(n)
}
}
func TestCloseAndQueuedCancellation(t *testing.T) {
db := testDB(t, ":memory:")
started := make(chan struct{})
done := make(chan error, 1)
go func() {
done <- db.operation(context.Background(), func(func()) error { close(started); _, _, err := db.run(longQuery, nil, true); return err })
}()
<-started
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
if _, err := db.Query(ctx, "SELECT 1"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("queued cancellation: %v", err)
}
if err := db.Close(); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if !errors.Is(err, ErrClosed) {
t.Fatal(err)
}
case <-time.After(wait.Guard):
t.Fatal("close did not interrupt query")
}
if _, err := db.Query(context.Background(), "SELECT 1"); !errors.Is(err, ErrClosed) {
t.Fatal(err)
}
if err := db.Close(); err != nil {
t.Fatal(err)
}
}
func TestDiskReadOnlyAndBusy(t *testing.T) {
path := filepath.Join(t.TempDir(), "disk.db")
w := testDB(t, path)
execute(t, w, "CREATE TABLE items(n)")
execute(t, w, "INSERT INTO items VALUES (42)")
r, err := Open(context.Background(), path, OpenOptions{ReadOnly: true})
if err != nil {
t.Fatal(err)
}
defer r.Close()
if n := query(t, r, "SELECT n FROM items").Values[0][0]; n != int64(42) {
t.Fatal(n)
}
if _, err := r.Execute(context.Background(), "DELETE FROM items"); err == nil {
t.Fatal("read-only write succeeded")
}
b, err := Open(context.Background(), path, OpenOptions{BusyTimeout: 30 * time.Millisecond})
if err != nil {
t.Fatal(err)
}
defer b.Close()
locked, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1)
go func() {
done <- w.operation(context.Background(), func(func()) error {
if err := w.control("BEGIN IMMEDIATE"); err != nil {
close(locked)
return err
}
close(locked)
<-release
return w.control("COMMIT")
})
}()
<-locked
defer func() {
close(release)
if err := <-done; err != nil {
t.Error(err)
}
}()
_, err = b.Execute(context.Background(), "INSERT INTO items VALUES (1)")
var sqliteErr *Error
if !errors.As(err, &sqliteErr) || sqliteErr.Code != 5 {
t.Fatalf("busy: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
if _, err := b.Execute(ctx, "INSERT INTO items VALUES (1)"); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("busy cancellation: %v", err)
}
}
@@ -0,0 +1 @@
/build
@@ -0,0 +1,26 @@
// The Kotlin of the native module sqlitecore: an Android library, which mygo
// build adds to the app's Gradle build. The build sets its SDK levels, Java
// and Kotlin, and its dependency on MyGo's host library (dev.mygo), which
// brings coroutines, and its NDK and ABIs, which its C builds for.
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.github.egoist.mygo.plugins.sqlite.internal.sqlitecore"
defaultConfig {
externalNativeBuild {
cmake {
// SQLite's amalgamation downloads once, for every ABI.
arguments += "-DSQLITE_DOWNLOADS=" + layout.buildDirectory.dir("sqlite").get().asFile.path
}
}
}
externalNativeBuild {
cmake { path = file("src/main/c/CMakeLists.txt") }
}
}
dependencies {
}
@@ -0,0 +1,37 @@
# SQLite on Android: the amalgamation, pinned by its hash, and the JNI the
# module's Kotlin calls, in one library, libsqlitecore.so. Its symbols stay
# hidden but for the JNI, as the Zig build's do.
cmake_minimum_required(VERSION 3.22)
project(sqlitecore C)
set(SQLITE_VERSION 3530400)
set(SQLITE_SHA256 1e71ddf93849c6a6ecf58b827c0692073d2dd7ee40196158068f7b29f422e87d)
set(SQLITE_DIR ${SQLITE_DOWNLOADS}/sqlite-amalgamation-${SQLITE_VERSION})
if(NOT EXISTS ${SQLITE_DIR}/sqlite3.c)
set(zip ${SQLITE_DOWNLOADS}/sqlite-${SQLITE_VERSION}-${ANDROID_ABI}.zip)
file(DOWNLOAD https://www.sqlite.org/2026/sqlite-amalgamation-${SQLITE_VERSION}.zip ${zip}
EXPECTED_HASH SHA256=${SQLITE_SHA256} TLS_VERIFY ON STATUS status)
list(GET status 0 code)
if(NOT code EQUAL 0)
message(FATAL_ERROR "downloading SQLite's amalgamation: ${status}")
endif()
# Each ABI configures on its own: the first to finish puts its copy in
# place, whole.
file(ARCHIVE_EXTRACT INPUT ${zip} DESTINATION ${SQLITE_DOWNLOADS}/${ANDROID_ABI})
file(RENAME ${SQLITE_DOWNLOADS}/${ANDROID_ABI}/sqlite-amalgamation-${SQLITE_VERSION} ${SQLITE_DIR} RESULT moved)
file(REMOVE_RECURSE ${SQLITE_DOWNLOADS}/${ANDROID_ABI} ${zip})
endif()
add_library(sqlitecore SHARED ${SQLITE_DIR}/sqlite3.c sqlitecore.c)
target_include_directories(sqlitecore PRIVATE ${SQLITE_DIR})
set_target_properties(sqlitecore PROPERTIES C_STANDARD 11 C_VISIBILITY_PRESET hidden)
target_compile_definitions(sqlitecore PRIVATE
SQLITE_THREADSAFE=1
SQLITE_DQS=0
SQLITE_DEFAULT_FOREIGN_KEYS=1
SQLITE_ENABLE_FTS5=1
SQLITE_ENABLE_RTREE=1
SQLITE_OMIT_LOAD_EXTENSION=1
SQLITE_OMIT_DEPRECATED=1
SQLITE_OMIT_SHARED_CACHE=1)
target_link_libraries(sqlitecore PRIVATE m)
@@ -0,0 +1,215 @@
// The JNI of the module's Kotlin (SQLite.kt): SQLite's C API, as much as
// it calls, with what must be C in C: the connection's handlers, which
// SQLite calls while it runs a statement, and the check that SQL holds
// exactly one statement. Text crosses as UTF-8 bytes, which Java's
// strings are not.
#include <jni.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#define EXPORT JNIEXPORT __attribute__((visibility("default")))
#define FN(name) Java_com_github_egoist_mygo_plugins_sqlite_internal_sqlitecore_SQLite_##name
// The results of prepare that are no code of SQLite's.
enum { NO_STATEMENT = -1, MORE_STATEMENTS = -2 };
typedef struct {
sqlite3 *db;
int timeout_ms, waited_ms;
int allow_control;
} conn;
static conn *of(jlong h) { return (conn *)(intptr_t)h; }
static sqlite3_stmt *stmt(jlong s) { return (sqlite3_stmt *)(intptr_t)s; }
// busy waits for another connection's lock, up to the connection's
// timeout, unless Interrupt ends it.
static int busy(void *data, int previous) {
conn *c = data;
if (previous == 0) c->waited_ms = 0;
if (sqlite3_is_interrupted(c->db) || c->waited_ms >= c->timeout_ms) return 0;
int delay = previous < 10 ? previous + 1 : 10;
if (delay > c->timeout_ms - c->waited_ms) delay = c->timeout_ms - c->waited_ms;
c->waited_ms += sqlite3_sleep(delay);
return !sqlite3_is_interrupted(c->db);
}
// authorize denies transaction control outside Control, which the batch
// API owns, and ATTACH (including VACUUM INTO), which could escape the
// plugin's database directory. Extension loading is omitted at compile
// time, and directory-changing pragmas are deprecated.
static int authorize(void *data, int action, const char *a, const char *b, const char *d, const char *e) {
conn *c = data;
(void)b, (void)d, (void)e;
switch (action) {
case SQLITE_TRANSACTION:
case SQLITE_SAVEPOINT:
case SQLITE_DETACH:
return c->allow_control ? SQLITE_OK : SQLITE_DENY;
case SQLITE_ATTACH:
// Ordinary VACUUM attaches an unnamed temporary database while
// stepping. User ATTACH is denied while preparing, and VACUUM
// INTO a named output file is denied here too.
return c->allow_control && a != NULL && a[0] == 0 ? SQLITE_OK : SQLITE_DENY;
}
return SQLITE_OK;
}
// bytes copies b into memory of C's, NUL-terminated, or returns NULL.
static char *bytes(JNIEnv *env, jbyteArray b, jsize *n) {
*n = (*env)->GetArrayLength(env, b);
char *p = malloc((size_t)*n + 1);
if (p == NULL) return NULL;
(*env)->GetByteArrayRegion(env, b, 0, *n, (jbyte *)p);
p[*n] = 0;
return p;
}
static jbyteArray array(JNIEnv *env, const void *p, int n) {
if (n < 0) n = 0;
jbyteArray b = (*env)->NewByteArray(env, n);
if (b != NULL && n > 0) (*env)->SetByteArrayRegion(env, b, 0, n, p);
return b;
}
EXPORT jint FN(threadsafe)(JNIEnv *env, jclass cls) { return sqlite3_threadsafe(); }
EXPORT jstring FN(version)(JNIEnv *env, jclass cls) { return (*env)->NewStringUTF(env, sqlite3_libversion()); }
// open opens path and puts its connection in out[0], when SQLite made one,
// even when it failed: its error is the connection's then, and closing it
// is the caller's.
EXPORT jint FN(open)(JNIEnv *env, jclass cls, jbyteArray path, jboolean readOnly, jint timeout, jlongArray out) {
jsize n;
char *name = bytes(env, path, &n);
if (name == NULL) return SQLITE_NOMEM;
int flags = readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
sqlite3 *db = NULL;
int rc = sqlite3_open_v2(name, &db, flags | SQLITE_OPEN_FULLMUTEX, NULL);
free(name);
if (db == NULL) return rc;
conn *c = calloc(1, sizeof *c);
if (c == NULL) {
sqlite3_close_v2(db);
return SQLITE_NOMEM;
}
c->db = db;
c->timeout_ms = timeout < 0 ? 0 : timeout;
c->allow_control = 1;
if (rc == SQLITE_OK) {
sqlite3_extended_result_codes(db, 1);
sqlite3_set_authorizer(db, authorize, c);
sqlite3_busy_handler(db, busy, c);
}
jlong h = (jlong)(intptr_t)c;
(*env)->SetLongArrayRegion(env, out, 0, 1, &h);
return rc;
}
// close closes the connection, and frees it unless SQLite could not.
EXPORT jint FN(close)(JNIEnv *env, jclass cls, jlong h) {
conn *c = of(h);
int rc = sqlite3_close_v2(c->db);
if (rc == SQLITE_OK) free(c);
return rc;
}
EXPORT jint FN(errcode)(JNIEnv *env, jclass cls, jlong h) { return sqlite3_extended_errcode(of(h)->db); }
EXPORT jbyteArray FN(errmsg)(JNIEnv *env, jclass cls, jlong h) {
const char *m = sqlite3_errmsg(of(h)->db);
return array(env, m, (int)strlen(m));
}
EXPORT jboolean FN(autocommit)(JNIEnv *env, jclass cls, jlong h) { return sqlite3_get_autocommit(of(h)->db) != 0; }
EXPORT void FN(interrupt)(JNIEnv *env, jclass cls, jlong h) { sqlite3_interrupt(of(h)->db); }
EXPORT jlong FN(changes)(JNIEnv *env, jclass cls, jlong h) { return sqlite3_changes64(of(h)->db); }
EXPORT jlong FN(totalChanges)(JNIEnv *env, jclass cls, jlong h) { return sqlite3_total_changes64(of(h)->db); }
EXPORT jlong FN(lastInsertID)(JNIEnv *env, jclass cls, jlong h) { return sqlite3_last_insert_rowid(of(h)->db); }
// prepare prepares sql, which must be exactly one statement, into out[0]:
// it compiles what follows the first before anything runs, so that extra
// SQL, even invalid, never runs a part of an operation. control allows
// transaction control in it.
EXPORT jint FN(prepare)(JNIEnv *env, jclass cls, jlong h, jbyteArray sql, jboolean control, jlongArray out) {
conn *c = of(h);
jsize n;
char *text = bytes(env, sql, &n);
if (text == NULL) return SQLITE_NOMEM;
c->allow_control = control;
sqlite3_stmt *first = NULL;
const char *tail = NULL;
int rc = sqlite3_prepare_v2(c->db, text, n, &first, &tail);
if (rc == SQLITE_OK && first == NULL) rc = NO_STATEMENT;
size_t offset = tail != NULL ? (size_t)(tail - text) : (size_t)n;
while (rc == SQLITE_OK && offset < (size_t)n) {
sqlite3_stmt *extra = NULL;
rc = sqlite3_prepare_v2(c->db, text + offset, (int)(n - offset), &extra, &tail);
if (extra != NULL) {
sqlite3_finalize(extra);
rc = MORE_STATEMENTS;
}
size_t next = tail != NULL ? (size_t)(tail - text) : (size_t)n;
if (next <= offset) break;
offset = next;
}
c->allow_control = 1;
free(text);
if (rc != SQLITE_OK) {
if (first != NULL) sqlite3_finalize(first);
return rc;
}
jlong s = (jlong)(intptr_t)first;
(*env)->SetLongArrayRegion(env, out, 0, 1, &s);
return SQLITE_OK;
}
EXPORT void FN(finalize)(JNIEnv *env, jclass cls, jlong s) { sqlite3_finalize(stmt(s)); }
EXPORT jint FN(step)(JNIEnv *env, jclass cls, jlong s) { return sqlite3_step(stmt(s)); }
EXPORT jint FN(parameters)(JNIEnv *env, jclass cls, jlong s) { return sqlite3_bind_parameter_count(stmt(s)); }
EXPORT jint FN(bindNull)(JNIEnv *env, jclass cls, jlong s, jint i) { return sqlite3_bind_null(stmt(s), i); }
EXPORT jint FN(bindInt)(JNIEnv *env, jclass cls, jlong s, jint i, jlong v) { return sqlite3_bind_int64(stmt(s), i, v); }
EXPORT jint FN(bindReal)(JNIEnv *env, jclass cls, jlong s, jint i, jdouble v) { return sqlite3_bind_double(stmt(s), i, v); }
// bindBytes binds b as text or a BLOB, which SQLite copies. An empty BLOB
// binds a pointer that is not NULL, which keeps it from being NULL.
EXPORT jint FN(bindBytes)(JNIEnv *env, jclass cls, jlong s, jint i, jbyteArray b, jboolean text) {
jsize n = (*env)->GetArrayLength(env, b);
jbyte *p = n > 0 ? (*env)->GetByteArrayElements(env, b, NULL) : NULL;
if (n > 0 && p == NULL) return SQLITE_NOMEM;
const void *v = p != NULL ? (const void *)p : "";
int rc = text ? sqlite3_bind_text(stmt(s), i, v, n, SQLITE_TRANSIENT) : sqlite3_bind_blob(stmt(s), i, v, n, SQLITE_TRANSIENT);
if (p != NULL) (*env)->ReleaseByteArrayElements(env, b, p, JNI_ABORT);
return rc;
}
EXPORT jint FN(columns)(JNIEnv *env, jclass cls, jlong s) { return sqlite3_column_count(stmt(s)); }
EXPORT jbyteArray FN(columnName)(JNIEnv *env, jclass cls, jlong s, jint i) {
const char *name = sqlite3_column_name(stmt(s), i);
return array(env, name, name != NULL ? (int)strlen(name) : 0);
}
EXPORT jint FN(columnType)(JNIEnv *env, jclass cls, jlong s, jint i) { return sqlite3_column_type(stmt(s), i); }
EXPORT jlong FN(columnInt)(JNIEnv *env, jclass cls, jlong s, jint i) { return sqlite3_column_int64(stmt(s), i); }
EXPORT jdouble FN(columnReal)(JNIEnv *env, jclass cls, jlong s, jint i) { return sqlite3_column_double(stmt(s), i); }
EXPORT jbyteArray FN(columnBytes)(JNIEnv *env, jclass cls, jlong s, jint i, jboolean text) {
const void *p = text ? (const void *)sqlite3_column_text(stmt(s), i) : sqlite3_column_blob(stmt(s), i);
return array(env, p, p != NULL ? sqlite3_column_bytes(stmt(s), i) : 0);
}
@@ -0,0 +1,42 @@
package com.github.egoist.mygo.plugins.sqlite.internal.sqlitecore
// SQLite's C API, as much as the module calls, in libsqlitecore.so
// (src/main/c): connections and statements are their pointers, text is
// UTF-8 bytes, and calls that fail return SQLite's code.
internal object SQLite {
init {
System.loadLibrary("sqlitecore")
}
const val OK = 0
const val ROW = 100
const val DONE = 101
const val NO_STATEMENT = -1
const val MORE_STATEMENTS = -2
@JvmStatic external fun threadsafe(): Int
@JvmStatic external fun version(): String
@JvmStatic external fun open(path: ByteArray, readOnly: Boolean, timeout: Int, out: LongArray): Int
@JvmStatic external fun close(h: Long): Int
@JvmStatic external fun errcode(h: Long): Int
@JvmStatic external fun errmsg(h: Long): ByteArray
@JvmStatic external fun autocommit(h: Long): Boolean
@JvmStatic external fun interrupt(h: Long)
@JvmStatic external fun changes(h: Long): Long
@JvmStatic external fun totalChanges(h: Long): Long
@JvmStatic external fun lastInsertID(h: Long): Long
@JvmStatic external fun prepare(h: Long, sql: ByteArray, control: Boolean, out: LongArray): Int
@JvmStatic external fun finalize(s: Long)
@JvmStatic external fun step(s: Long): Int
@JvmStatic external fun parameters(s: Long): Int
@JvmStatic external fun bindNull(s: Long, i: Int): Int
@JvmStatic external fun bindInt(s: Long, i: Int, v: Long): Int
@JvmStatic external fun bindReal(s: Long, i: Int, v: Double): Int
@JvmStatic external fun bindBytes(s: Long, i: Int, v: ByteArray, text: Boolean): Int
@JvmStatic external fun columns(s: Long): Int
@JvmStatic external fun columnName(s: Long, i: Int): ByteArray
@JvmStatic external fun columnType(s: Long, i: Int): Int
@JvmStatic external fun columnInt(s: Long, i: Int): Long
@JvmStatic external fun columnReal(s: Long, i: Int): Double
@JvmStatic external fun columnBytes(s: Long, i: Int, text: Boolean): ByteArray
}
@@ -0,0 +1,125 @@
package com.github.egoist.mygo.plugins.sqlite.internal.sqlitecore
import dev.mygo.NativeClosedException
import dev.mygo.NativeException
import dev.mygo.NativeGoException
// The implementation of package sqlitecore on Android: SQLite's
// amalgamation, which the module's C compiles in (src/main/c), as the Zig
// build does on desktops, called as the Zig does.
fun makeEngine(): Engine {
if (SQLite.threadsafe() == 0) throw NativeGoException("sqlite: the library is not threadsafe")
return SQLiteEngine()
}
private class SQLiteEngine : Engine {
override fun open(path: String, readOnly: Boolean, busyMillis: Long): Conn {
val out = LongArray(1)
val rc = SQLite.open(path.toByteArray(), readOnly, busyMillis.coerceIn(0, Int.MAX_VALUE.toLong()).toInt(), out)
if (rc != SQLite.OK) {
if (out[0] == 0L) throw NativeException("SQLite", rc.toLong(), "could not open database")
val err = failure(out[0])
SQLite.close(out[0])
throw err
}
return SQLiteConn(out[0])
}
override fun version(): String = SQLite.version()
}
private class SQLiteConn(private var h: Long) : Conn {
private fun db(): Long = h.takeIf { it != 0L } ?: throw NativeClosedException()
override fun close() {
if (h == 0L) return
if (SQLite.close(h) != SQLite.OK) throw failure(h)
h = 0
}
protected fun finalize() {
if (h != 0L) SQLite.close(h)
}
override fun autocommit(): Boolean = h == 0L || SQLite.autocommit(h)
override fun interrupt() {
h.takeIf { it != 0L }?.let { SQLite.interrupt(it) }
}
override fun control(sql: String) {
val db = db()
val s = prepare(db, sql, true)
try {
val rc = SQLite.step(s)
if (rc != SQLite.DONE) throw failure(db)
} finally {
SQLite.finalize(s)
}
}
override fun run(sql: String, args: List<Value>, query: Boolean): Outcome {
val db = db()
val s = prepare(db, sql, false)
try {
val count = SQLite.parameters(s)
if (count != args.size) throw NativeGoException("sqlite: statement needs $count parameters, got ${args.size}")
args.forEachIndexed { i, v -> check(db, bind(s, i + 1, v)) }
val n = if (query) SQLite.columns(s) else 0
val columns = List(n) { String(SQLite.columnName(s, it)) }
val values = ArrayList<Value>()
val before = SQLite.totalChanges(db)
while (true) {
when (val rc = SQLite.step(s)) {
SQLite.ROW -> if (query) for (i in 0 until n) values.add(column(s, i))
SQLite.DONE -> break
else -> throw failure(db)
}
}
val changes = if (SQLite.totalChanges(db) != before) SQLite.changes(db) else 0
return Outcome(changes, SQLite.lastInsertID(db), columns, values)
} finally {
SQLite.finalize(s)
}
}
}
/** Prepares sql, which must be exactly one statement, on db. */
private fun prepare(db: Long, sql: String, control: Boolean): Long {
val out = LongArray(1)
when (val rc = SQLite.prepare(db, sql.toByteArray(), control, out)) {
SQLite.OK -> return out[0]
SQLite.NO_STATEMENT -> throw NativeGoException("sqlite: SQL contains no statement")
SQLite.MORE_STATEMENTS -> throw NativeGoException("sqlite: expected exactly one statement")
else -> throw failure(db)
}
}
private fun bind(s: Long, i: Int, v: Value): Int = when (v.type) {
Type.NULL -> SQLite.bindNull(s, i)
Type.INTEGER -> SQLite.bindInt(s, i, v.int)
Type.REAL -> SQLite.bindReal(s, i, v.real)
Type.TEXT -> SQLite.bindBytes(s, i, v.text.toByteArray(), true)
Type.BLOB -> SQLite.bindBytes(s, i, v.blob, false)
}
/** The value of column i of the current row. */
private fun column(s: Long, i: Int): Value = when (SQLite.columnType(s, i)) {
1 -> Value(Type.INTEGER, SQLite.columnInt(s, i), 0.0, "")
2 -> Value(Type.REAL, 0, SQLite.columnReal(s, i), "")
3 -> Value(Type.TEXT, 0, 0.0, String(SQLite.columnBytes(s, i, true)))
4 -> Value(Type.BLOB, 0, 0.0, "", SQLite.columnBytes(s, i, false))
else -> Value(Type.NULL, 0, 0.0, "")
}
private fun check(db: Long, rc: Int) {
if (rc != SQLite.OK) throw failure(db)
}
/**
* The error of the last call on db that failed, which Go reports as an
* sqlite.Error: SQLite's extended code and message.
*/
private fun failure(db: Long): NativeException =
NativeException("SQLite", SQLite.errcode(db).toLong(), String(SQLite.errmsg(db)))
@@ -0,0 +1,244 @@
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
// mygo:native 3 06208a36de0f3133
//
// The declarations of package sqlitecore, which the implementation implements,
// and the object Go calls. See docs/native-modules.md.
@file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE", "RedundantVisibilityModifier", "FunctionName", "ClassName", "LocalVariableName")
package com.github.egoist.mygo.plugins.sqlite.internal.sqlitecore
import dev.mygo.GoFunc
import dev.mygo.NativeBuffer
import dev.mygo.NativeCodedError
import dev.mygo.NativeModule
import dev.mygo.NativeReader
import dev.mygo.NativeWireException
import dev.mygo.NativeWriter
import kotlinx.coroutines.flow.Flow
/**
* Engine opens connections.
*/
interface Engine {
/**
* Open opens path, or ":memory:", creating a missing file unless
* readOnly, with extended result codes on. busyMillis is how long an
* operation waits for another connection's lock.
*/
fun open(path: String, readOnly: Boolean, busyMillis: Long): Conn
/**
* Version is SQLite's version, as 3.53.4.
*/
fun version(): String
}
/**
* Conn is a connection. Its methods other than Interrupt are called one
* at a time.
*/
interface Conn : AutoCloseable {
/**
* Run prepares sql, which must hold exactly one statement and no
* transaction control or ATTACH, binds args to its parameters, and
* steps it to the end, returning its rows when query is true.
*/
fun run(sql: String, args: List<Value>, query: Boolean): Outcome
/**
* Control runs a statement of transaction control, such as BEGIN
* IMMEDIATE, COMMIT or ROLLBACK.
*/
fun control(sql: String)
/**
* Autocommit reports whether the connection is outside a transaction.
*/
fun autocommit(): Boolean
/**
* Interrupt stops the statement running, and its wait for another
* connection's lock, from any goroutine: the call running fails with
* SQLite's SQLITE_INTERRUPT, or SQLITE_BUSY.
*/
fun interrupt()
}
/**
* Value is a value of SQLite: a parameter, or a column of a row.
*/
data class Value(
val type: Type,
val int: Long,
val real: Double,
val text: String,
val blob: ByteArray = ByteArray(0),
)
/**
* Outcome is what a statement did. Values holds the rows one after the
* other, each the length of Columns.
*/
data class Outcome(
val changes: Long,
val lastInsertID: Long,
val columns: List<String> = emptyList(),
val values: List<Value> = emptyList(),
)
/**
* Type is the type of a Value, by SQLite's fundamental datatype codes.
*/
enum class Type(val value: Long) {
NULL(5L),
INTEGER(1L),
REAL(2L),
TEXT(3L),
BLOB(4L),
;
companion object {
/** The constant of a value, which Go sent. */
fun of(value: Long): Type = entries.firstOrNull { it.value == value } ?: throw NativeWireException("native: Type has no constant $value")
}
}
/**
* The errors package sqlitecore declares, with native.NewError: throw
* SqlitecoreException(SqlitecoreError.X) for Go to get that error, which errors.Is
* compares.
*/
enum class SqlitecoreError(val code: String) {
;
}
/** An error package sqlitecore declares. */
class SqlitecoreException(val error: SqlitecoreError, message: String = error.code) : Exception(message), NativeCodedError {
override val nativeCode: String get() = error.code
}
/** What Go calls: the functions of the module, by name. */
object MygoModule : NativeModule() {
override fun invoke(sym: String, h: Long, args: ByteArray, call: Long): ByteArray = when (sym) {
"new_Engine" -> answer { _w -> _w.u64(retain(makeEngine())) }
"Engine_Open" -> answer { _w ->
val _o: Engine = obj(h)
val _a = NativeReader(args)
val _p0 = _a.string()
val _p1 = _a.bool()
val _p2 = _a.i64()
val _r = _o.open(_p0, _p1, _p2)
_w.u64(MygoModule.handle(_r))
}
"Engine_Version" -> answer { _w ->
val _o: Engine = obj(h)
val _r = _o.version()
_w.string(_r)
}
"Conn_Run" -> answer { _w ->
val _o: Conn = obj(h)
val _a = NativeReader(args)
val _p0 = _a.string()
val _p1 = _read_slice_Value(_a)
val _p2 = _a.bool()
val _r = _o.run(_p0, _p1, _p2)
_write_Outcome(_w, _r)
}
"Conn_Control" -> answer { _w ->
val _o: Conn = obj(h)
val _a = NativeReader(args)
val _p0 = _a.string()
_o.control(_p0)
}
"Conn_Autocommit" -> answer { _w ->
val _o: Conn = obj(h)
val _r = _o.autocommit()
_w.bool(_r)
}
"Conn_Interrupt" -> answer { _w ->
val _o: Conn = obj(h)
_o.interrupt()
}
"close" -> answer { close(h) }
else -> unknown(sym)
}
override fun direct(sym: String, h: Long, args: LongArray): Long = try {
when (sym) {
"Conn_Autocommit_direct" -> {
if (obj<Conn>(h).autocommit()) 1L else 0L
}
"Conn_Interrupt_direct" -> {
obj<Conn>(h).interrupt()
0L
}
else -> 0L
}
} catch (e: Throwable) {
0L
}
override fun error(code: String): Throwable? = SqlitecoreError.entries.firstOrNull { it.code == code }?.let { SqlitecoreException(it) }
/** A handle of an object of the implementation, which Go holds. */
fun handle(v: Any): Long = retain(v)
}
private fun _read_Outcome(r: NativeReader): Outcome {
return Outcome(
changes = r.i64(),
lastInsertID = r.i64(),
columns = _read_slice_string(r),
values = _read_slice_Value(r),
)
}
private fun _write_Outcome(w: NativeWriter, v: Outcome) {
w.i64(v.changes.toLong())
w.i64(v.lastInsertID.toLong())
_write_slice_string(w, v.columns)
_write_slice_Value(w, v.values)
}
private fun _read_Type(r: NativeReader): Type {
return Type.of(r.i64())
}
private fun _write_Type(w: NativeWriter, v: Type) {
w.i64(v.value)
}
private fun _read_Value(r: NativeReader): Value {
return Value(
type = _read_Type(r),
int = r.i64(),
real = r.double(),
text = r.string(),
blob = r.data(),
)
}
private fun _write_Value(w: NativeWriter, v: Value) {
_write_Type(w, v.type)
w.i64(v.int.toLong())
w.double(v.real.toDouble())
w.string(v.text)
w.data(v.blob)
}
private fun _read_slice_Value(r: NativeReader): List<Value> {
val n = r.count()
return List(n) { _read_Value(r) }
}
private fun _write_slice_Value(w: NativeWriter, v: List<Value>) {
w.count(v.size)
for (x in v) _write_Value(w, x)
}
private fun _read_slice_string(r: NativeReader): List<String> {
val n = r.count()
return List(n) { r.string() }
}
private fun _write_slice_string(w: NativeWriter, v: List<String>) {
w.count(v.size)
for (x in v) w.string(x)
}
@@ -0,0 +1,46 @@
{
"libraries": [
{
"name": "Sqlitecore",
"release": "https://github.com/egoist/mygo/releases/download/native-sqlitecore",
"files": {
"darwin-amd64": {
"name": "libSqlitecore.dylib",
"url": "https://github.com/egoist/mygo/releases/download/native-sqlitecore/Sqlitecore-darwin-amd64-c491f101a653.dylib",
"sha256": "c491f101a65377953ef1822c3d80e78874560a668ea59161b2d68ebced225f23",
"sourceHash": "f9507095cbbe51626c43c6d9237a38bc94c596cf700a88c029d2f0abb065b818"
},
"darwin-arm64": {
"name": "libSqlitecore.dylib",
"url": "https://github.com/egoist/mygo/releases/download/native-sqlitecore/Sqlitecore-darwin-arm64-6834cd1cf7f4.dylib",
"sha256": "6834cd1cf7f48647276144ad5afb669edcd0c6c4ad169eebbc24a1cd1624abdb",
"sourceHash": "f9507095cbbe51626c43c6d9237a38bc94c596cf700a88c029d2f0abb065b818"
},
"linux-amd64": {
"name": "libSqlitecore.so",
"url": "https://github.com/egoist/mygo/releases/download/native-sqlitecore/Sqlitecore-linux-amd64-81aad721b6fd.so",
"sha256": "81aad721b6fd3673bca25436d9521b2896e4b01e75fa6d41af1b52cd1485fd33",
"sourceHash": "f9507095cbbe51626c43c6d9237a38bc94c596cf700a88c029d2f0abb065b818"
},
"linux-arm64": {
"name": "libSqlitecore.so",
"url": "https://github.com/egoist/mygo/releases/download/native-sqlitecore/Sqlitecore-linux-arm64-2a0725d65873.so",
"sha256": "2a0725d6587388fefe3f04b28f9eafbd66b2f67aa6d413f89aee32238d1ff4ef",
"sourceHash": "f9507095cbbe51626c43c6d9237a38bc94c596cf700a88c029d2f0abb065b818"
},
"windows-amd64": {
"name": "Sqlitecore.dll",
"url": "https://github.com/egoist/mygo/releases/download/native-sqlitecore/Sqlitecore-windows-amd64-029fd2db48c3.dll",
"sha256": "029fd2db48c3cc30de13f0a5f33c7604460f8f61496b9e641d7de7e394d3f8e6",
"sourceHash": "f9507095cbbe51626c43c6d9237a38bc94c596cf700a88c029d2f0abb065b818"
},
"windows-arm64": {
"name": "Sqlitecore.dll",
"url": "https://github.com/egoist/mygo/releases/download/native-sqlitecore/Sqlitecore-windows-arm64-db27799190bc.dll",
"sha256": "db27799190bce425f0c833c11298f1582489e747bfef6dd437df4a3fd2cc08ef",
"sourceHash": "f9507095cbbe51626c43c6d9237a38bc94c596cf700a88c029d2f0abb065b818"
}
}
}
]
}
@@ -0,0 +1,67 @@
// Package sqlitecore is the plugin's SQLite: a native module implemented
// in Zig, which compiles SQLite's amalgamation into the module's library
// for every platform. Package sqlite wraps it in its connections, which
// serialize and validate the calls; nothing else uses it.
package sqlitecore
import "io"
// Engine opens connections.
//
//mygo:native
type Engine interface {
// Open opens path, or ":memory:", creating a missing file unless
// readOnly, with extended result codes on. busyMillis is how long an
// operation waits for another connection's lock.
Open(path string, readOnly bool, busyMillis int) (Conn, error)
// Version is SQLite's version, as 3.53.4.
Version() string
}
// Conn is a connection. Its methods other than Interrupt are called one
// at a time.
type Conn interface {
io.Closer
// Run prepares sql, which must hold exactly one statement and no
// transaction control or ATTACH, binds args to its parameters, and
// steps it to the end, returning its rows when query is true.
Run(sql string, args []Value, query bool) (Outcome, error)
// Control runs a statement of transaction control, such as BEGIN
// IMMEDIATE, COMMIT or ROLLBACK.
Control(sql string) error
// Autocommit reports whether the connection is outside a transaction.
Autocommit() bool
// Interrupt stops the statement running, and its wait for another
// connection's lock, from any goroutine: the call running fails with
// SQLite's SQLITE_INTERRUPT, or SQLITE_BUSY.
Interrupt()
}
// Value is a value of SQLite: a parameter, or a column of a row.
type Value struct {
Type Type
Int int64
Real float64
Text string
Blob []byte
}
// Type is the type of a Value, by SQLite's fundamental datatype codes.
type Type int
const (
Null Type = 5
Integer Type = 1
Real Type = 2
Text Type = 3
Blob Type = 4
)
// Outcome is what a statement did. Values holds the rows one after the
// other, each the length of Columns.
type Outcome struct {
Changes int64
LastInsertID int64
Columns []string
Values []Value
}
@@ -0,0 +1,214 @@
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
// mygo:native 3 06208a36de0f3133
package sqlitecore
import (
_filepath "path/filepath"
_runtime "runtime"
_native "github.com/egoist/mygo/native"
)
// _module describes the module to the runtime.
var _module = &_native.Module{Name: "Sqlitecore", Symbol: "sqlitecore", Langs: []string{"swift", "kotlin", "zig"}, SwiftOS: []string{"ios"}, MinMacOS: "", MinIOS: "16", Kotlin: "com.github.egoist.mygo.plugins.sqlite.internal.sqlitecore.MygoModule", Dir: _dir(), Errors: []*_native.Error{}, Deps: []string{}}
// _dir returns the package's directory when the binary knows it, where
// mygo dev builds the implementation for go test and go run.
func _dir() string {
_, file, _, ok := _runtime.Caller(0)
if !ok || !_filepath.IsAbs(file) {
return ""
}
return _filepath.Dir(file)
}
func init() {
_native.Register(_module, map[string]_native.Wrapper{
"Engine": {Flags: 0, Wrap: func(o *_native.Object) any { return &_Engine{o} }},
"Conn": {Flags: 0, Wrap: func(o *_native.Object) any { return &_Conn{o} }},
})
}
// NewEngine makes the implementation of Engine on this platform. It returns
// errors.ErrUnsupported where the module has none, or the system lacks
// what it needs.
func NewEngine() (Engine, error) {
o, err := _module.New("Engine", 0)
if err != nil {
return nil, err
}
return &_Engine{o}, nil
}
// _Engine calls the platform's implementation of Engine.
type _Engine struct{ o *_native.Object }
// NativeObject returns the platform's object.
func (x *_Engine) NativeObject() *_native.Object { return x.o }
// _wrapEngine wraps a handle of the platform's, or returns nil.
func _wrapEngine(h uint64) Engine {
if h == 0 {
return nil
}
return &_Engine{_module.Object(h, 0)}
}
func (_x *_Engine) Open(path string, readOnly bool, busyMillis int) (Conn, error) {
_e := _native.NewEncoder()
_e.String(path)
_e.Bool(readOnly)
_e.Int(int64(busyMillis))
var _h uint64
_d, _err := _x.NativeObject().Call("Engine_Open", 0, _e)
if _err == nil {
_h = _d.Uint()
_err = _d.Close()
}
if _err != nil {
return nil, _err
}
return _wrapConn(_h), nil
}
func (_x *_Engine) Version() string {
var _r string
_d, _err := _x.NativeObject().Call("Engine_Version", 0, nil)
if _err == nil {
_r = _d.String()
_err = _d.Close()
}
_ = _err
return _r
}
// _Conn calls the platform's implementation of Conn.
type _Conn struct{ o *_native.Object }
// NativeObject returns the platform's object.
func (x *_Conn) NativeObject() *_native.Object { return x.o }
// _wrapConn wraps a handle of the platform's, or returns nil.
func _wrapConn(h uint64) Conn {
if h == 0 {
return nil
}
return &_Conn{_module.Object(h, 0)}
}
func (_x *_Conn) Close() error {
return _x.NativeObject().Close()
}
func (_x *_Conn) Run(sql string, args []Value, query bool) (Outcome, error) {
_e := _native.NewEncoder()
_e.String(sql)
_enc_slice_Value(_e, args)
_e.Bool(query)
var _r Outcome
_d, _err := _x.NativeObject().Call("Conn_Run", 0, _e)
if _err == nil {
_r = _dec_Outcome(_d)
_err = _d.Close()
}
return _r, _err
}
func (_x *_Conn) Control(sql string) error {
_e := _native.NewEncoder()
_e.String(sql)
_d, _err := _x.NativeObject().Call("Conn_Control", 0, _e)
if _err == nil {
_err = _d.Close()
}
return _err
}
func (_x *_Conn) Autocommit() bool {
return _x.NativeObject().Direct("Conn_Autocommit_direct") != 0
}
func (_x *_Conn) Interrupt() {
_x.NativeObject().Direct("Conn_Interrupt_direct")
}
func _enc_Outcome(_e *_native.Encoder, _v Outcome) {
_e.Int(int64(_v.Changes))
_e.Int(int64(_v.LastInsertID))
_enc_slice_string(_e, _v.Columns)
_enc_slice_Value(_e, _v.Values)
}
func _dec_Outcome(_d *_native.Decoder) Outcome {
return Outcome{
Changes: int64(_d.Int()),
LastInsertID: int64(_d.Int()),
Columns: _dec_slice_string(_d),
Values: _dec_slice_Value(_d),
}
}
func _enc_Type(_e *_native.Encoder, _v Type) {
_e.Int(int64(_v))
}
func _dec_Type(_d *_native.Decoder) Type {
return Type(_d.Int())
}
func _enc_Value(_e *_native.Encoder, _v Value) {
_enc_Type(_e, _v.Type)
_e.Int(int64(_v.Int))
_e.Float(float64(_v.Real))
_e.String(_v.Text)
_e.Bytes(_v.Blob)
}
func _dec_Value(_d *_native.Decoder) Value {
return Value{
Type: _dec_Type(_d),
Int: int64(_d.Int()),
Real: float64(_d.Float()),
Text: _d.String(),
Blob: _d.Bytes(),
}
}
func _enc_slice_Value(_e *_native.Encoder, _v []Value) {
_e.Len(len(_v))
for _, _x := range _v {
_enc_Value(_e, _x)
}
}
func _dec_slice_Value(_d *_native.Decoder) []Value {
_n := _d.Len()
if _n == 0 {
return nil
}
_v := make([]Value, _n)
for _i := range _v {
_v[_i] = _dec_Value(_d)
}
return _v
}
func _enc_slice_string(_e *_native.Encoder, _v []string) {
_e.Len(len(_v))
for _, _x := range _v {
_e.String(_x)
}
}
func _dec_slice_string(_d *_native.Decoder) []string {
_n := _d.Len()
if _n == 0 {
return nil
}
_v := make([]string, _n)
for _i := range _v {
_v[_i] = _d.String()
}
return _v
}
@@ -0,0 +1,2 @@
/.build
/.swiftpm
@@ -0,0 +1,21 @@
// swift-tools-version: 6.0
import PackageDescription
// The Swift of the native module sqlitecore, for iOS only: on macOS the
// module is its Zig. It links SQLite 3.53.4, which build-xcframework.sh
// builds from the amalgamation that the Zig build pins, with its options.
let package = Package(
name: "Sqlitecore",
platforms: [.iOS(.v16)],
products: [.library(name: "Sqlitecore", type: .dynamic, targets: ["Sqlitecore"])],
dependencies: [],
targets: [
.binaryTarget(
name: "CSQLite",
url: "https://github.com/egoist/mygo/releases/download/native-sqlitecore/CSQLite-3.53.4.xcframework.zip",
checksum: "5a48e398289f68487c6515fe7cd6b3be71217980a8b4e215772bf58ee5f8c177"
),
.target(name: "Sqlitecore", dependencies: ["CSQLite"]),
],
swiftLanguageModes: [.v5]
)
@@ -0,0 +1,971 @@
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
// mygo:native 3 06208a36de0f3133
//
// The declarations of package sqlitecore, which the implementation conforms to,
// and the functions Go calls. See docs/native-modules.md.
import Foundation
#if canImport(IOSurface)
import CoreVideo
import IOSurface
#endif
#if canImport(AppKit)
import AppKit
#elseif canImport(UIKit)
import UIKit
#endif
// MARK: - Declarations
/// Engine opens connections.
public protocol Engine: AnyObject {
/// Open opens path, or ":memory:", creating a missing file unless
/// readOnly, with extended result codes on. busyMillis is how long an
/// operation waits for another connection's lock.
func `open`(path: String, readOnly: Bool, busyMillis: Int) throws -> any Conn
/// Version is SQLite's version, as 3.53.4.
func version() -> String
}
/// Conn is a connection. Its methods other than Interrupt are called one
/// at a time.
public protocol Conn: AnyObject, Closer {
/// Run prepares sql, which must hold exactly one statement and no
/// transaction control or ATTACH, binds args to its parameters, and
/// steps it to the end, returning its rows when query is true.
func run(sql: String, args: [Value], query: Bool) throws -> Outcome
/// Control runs a statement of transaction control, such as BEGIN
/// IMMEDIATE, COMMIT or ROLLBACK.
func control(sql: String) throws
/// Autocommit reports whether the connection is outside a transaction.
func autocommit() -> Bool
/// Interrupt stops the statement running, and its wait for another
/// connection's lock, from any goroutine: the call running fails with
/// SQLite's SQLITE_INTERRUPT, or SQLITE_BUSY.
func interrupt()
}
/// Value is a value of SQLite: a parameter, or a column of a row.
public struct Value: Sendable, Hashable {
public var type: Type
public var int: Int64
public var real: Double
public var text: String
public var blob: Data
public init(type: Type, int: Int64, real: Double, text: String, blob: Data = Data()) {
self.type = type
self.int = int
self.real = real
self.text = text
self.blob = blob
}
}
/// Outcome is what a statement did. Values holds the rows one after the
/// other, each the length of Columns.
public struct Outcome: Sendable, Hashable {
public var changes: Int64
public var lastInsertID: Int64
public var columns: [String]
public var values: [Value]
public init(changes: Int64, lastInsertID: Int64, columns: [String] = [], values: [Value] = []) {
self.changes = changes
self.lastInsertID = lastInsertID
self.columns = columns
self.values = values
}
}
/// Type is the type of a Value, by SQLite's fundamental datatype codes.
public enum Type: Int, Sendable, Hashable, CaseIterable {
case null = 5
case integer = 1
case real = 2
case text = 3
case blob = 4
}
/// The errors package sqlitecore declares, with native.NewError: none.
public struct SqlitecoreError: Error, Sendable, RawRepresentable {
public let rawValue: String
public init?(rawValue: String) { return nil }
}
// MARK: - What Go calls
@_cdecl("mygo_sqlitecore_init")
public func _mygo_init(_ cb: _MygoCallback, _ idBase: UInt64, _ malloc: UnsafeRawPointer?, _ free: UnsafeRawPointer?) {
_mygoCallback = cb
_mygoIDBase = idBase
}
@_cdecl("mygo_sqlitecore_new_Engine")
public func _mygo_new_Engine(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
_mygoRun { _w in
let v: any Engine = try _mygoCall(makeEngine)
_w.u64(_mygoRetain(v))
}
}
@_cdecl("mygo_sqlitecore_Engine_Open")
public func _mygo_Engine_Open(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
_mygoRun { _w in
let _o: any Engine = _mygoObject(obj)
var _a = _MygoReader(args, n)
let _p0 = try _a.string()
let _p1 = try _a.bool()
let _p2 = Int(truncatingIfNeeded: try _a.i64())
let _r = try _o.`open`(path: _p0, readOnly: _p1, busyMillis: _p2)
_w.u64(_mygoRetain(_r))
}
}
@_cdecl("mygo_sqlitecore_Engine_Version")
public func _mygo_Engine_Version(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
_mygoRun { _w in
let _o: any Engine = _mygoObject(obj)
let _r = _o.version()
_w.string(_r)
}
}
@_cdecl("mygo_sqlitecore_Conn_Run")
public func _mygo_Conn_Run(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
_mygoRun { _w in
let _o: any Conn = _mygoObject(obj)
var _a = _MygoReader(args, n)
let _p0 = try _a.string()
let _p1 = try _mygoRead_slice_Value(&_a)
let _p2 = try _a.bool()
let _r = try _o.run(sql: _p0, args: _p1, query: _p2)
_mygoWrite_Outcome(&_w, _r)
}
}
@_cdecl("mygo_sqlitecore_Conn_Control")
public func _mygo_Conn_Control(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
_mygoRun { _ in
let _o: any Conn = _mygoObject(obj)
var _a = _MygoReader(args, n)
let _p0 = try _a.string()
try _o.control(sql: _p0)
}
}
@_cdecl("mygo_sqlitecore_Conn_Autocommit_direct")
public func _mygo_Conn_Autocommit_direct(_ obj: UInt64) -> UInt64 {
let _o: any Conn = _mygoObject(obj)
return _o.autocommit() ? 1 : 0
}
@_cdecl("mygo_sqlitecore_Conn_Interrupt_direct")
public func _mygo_Conn_Interrupt_direct(_ obj: UInt64) -> UInt64 {
let _o: any Conn = _mygoObject(obj)
_o.interrupt()
return 0
}
@_cdecl("mygo_sqlitecore_close")
public func _mygo_close(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
_mygoRun { _ in
let o = _mygoAnyObject(obj)
if let c = o as? any Closer { try c.close() }
#if canImport(AppKit) || canImport(UIKit)
// A view closed leaves the windows showing it; Go closes views on
// the main thread.
if let v = o as? NativeView { MainActor.assumeIsolated { v.removeFromSuperview() } }
#endif
}
}
@_cdecl("mygo_sqlitecore_release")
public func _mygo_release(_ obj: UInt64) {
_mygoRelease(obj)
}
@_cdecl("mygo_sqlitecore_cancel")
public func _mygo_cancel(_ call: UInt64) {
_mygoTasks.cancel(call)
}
@_cdecl("mygo_sqlitecore_next")
public func _mygo_next(_ call: UInt64) {
_mygoDemands.get(call)?.yield(())
}
@_cdecl("mygo_sqlitecore_resume")
public func _mygo_resume(_ cont: UInt64, _ block: UnsafeMutableRawPointer?) {
if let c = _mygoConts.remove(cont) {
c.resume(returning: _MygoBlock(p: block))
} else {
free(block)
}
}
// MARK: - Encoding
func _mygoRead_Outcome(_ r: inout _MygoReader) throws -> Outcome {
return Outcome(
changes: Int64(truncatingIfNeeded: try r.i64()),
lastInsertID: Int64(truncatingIfNeeded: try r.i64()),
columns: try _mygoRead_slice_string(&r),
values: try _mygoRead_slice_Value(&r)
)
}
func _mygoWrite_Outcome(_ w: inout _MygoWriter, _ v: Outcome) {
w.i64(Int64(truncatingIfNeeded: v.changes))
w.i64(Int64(truncatingIfNeeded: v.lastInsertID))
_mygoWrite_slice_string(&w, v.columns)
_mygoWrite_slice_Value(&w, v.values)
}
func _mygoRead_Type(_ r: inout _MygoReader) throws -> Type {
let raw = Int(truncatingIfNeeded: try r.i64())
guard let v = Type(rawValue: raw) else { throw _MygoWireError.value("Type", "\(raw)") }
return v
}
func _mygoWrite_Type(_ w: inout _MygoWriter, _ v: Type) {
w.i64(Int64(truncatingIfNeeded: v.rawValue))
}
func _mygoRead_Value(_ r: inout _MygoReader) throws -> Value {
return Value(
type: try _mygoRead_Type(&r),
int: Int64(truncatingIfNeeded: try r.i64()),
real: try r.double(),
text: try r.string(),
blob: try r.data()
)
}
func _mygoWrite_Value(_ w: inout _MygoWriter, _ v: Value) {
_mygoWrite_Type(&w, v.type)
w.i64(Int64(truncatingIfNeeded: v.int))
w.double(v.real)
w.string(v.text)
w.data(v.blob)
}
func _mygoRead_slice_Value(_ r: inout _MygoReader) throws -> [Value] {
let n = try r.count()
var v: [Value] = []
v.reserveCapacity(n)
for _ in 0..<n { v.append(try _mygoRead_Value(&r)) }
return v
}
func _mygoWrite_slice_Value(_ w: inout _MygoWriter, _ v: [Value]) {
w.count(v.count)
for x in v { _mygoWrite_Value(&w, x) }
}
func _mygoRead_slice_string(_ r: inout _MygoReader) throws -> [String] {
let n = try r.count()
var v: [String] = []
v.reserveCapacity(n)
for _ in 0..<n { v.append(try r.string()) }
return v
}
func _mygoWrite_slice_string(_ w: inout _MygoWriter, _ v: [String]) {
w.count(v.count)
for x in v { w.string(x) }
}
// MARK: - Types for the implementation
/// Errors an implementation throws that are not the module's own.
public enum NativeError: Error, Sendable {
/// Reaches Go as errors.ErrUnsupported: the system lacks what the
/// implementation needs, such as a framework of a newer version.
case unsupported
/// Reaches Go as native.ErrClosed.
case closed
/// An error a Go function or method returned.
case go(String)
}
/// What stops what a method started, as Go's io.Closer.
public protocol Closer: AnyObject {
func close() throws
}
/// A Closer that runs a closure, once.
public final class NativeCloser: Closer, @unchecked Sendable {
private let lock = NSLock()
private var fn: (() -> Void)?
public init(_ fn: @escaping () -> Void) { self.fn = fn }
public func close() {
lock.lock()
let f = fn
fn = nil
lock.unlock()
f?()
}
}
/// Memory that Go and the implementation both use: a *native.Buffer.
public final class NativeBuffer: @unchecked Sendable {
/// The buffer's memory, valid as long as the buffer.
public let bytes: UnsafeMutableRawBufferPointer
private let owned: Bool
/// The pool the buffer goes back to once Go is done with it.
fileprivate weak var pool: NativeBufferPool?
/// Makes a buffer of count bytes, which the implementation may yield
/// from a stream: Go reads it until its loop asks for the next value.
public init(count: Int) {
bytes = .allocate(byteCount: Swift.max(count, 1), alignment: 16)
owned = true
}
public var count: Int { bytes.count }
/// The buffer of Go's at p.
init(p: UInt64, count: Int) {
bytes = UnsafeMutableRawBufferPointer(start: UnsafeMutableRawPointer(bitPattern: UInt(p)), count: count)
owned = false
}
deinit {
if owned { bytes.deallocate() }
}
/// Gives the buffer back to its pool, as Go's loop moved on.
fileprivate func recycle() { pool?.put(self) }
}
/// Buffers of one size that a stream yields, each reused once Go's loop
/// moves on from it, so that a stream of buffers allocates none once it
/// runs: get one, fill it, yield it.
public final class NativeBufferPool: @unchecked Sendable {
/// The size of the pool's buffers.
public let size: Int
private let lock = NSLock()
private var free: [NativeBuffer] = []
public init(size: Int) { self.size = size }
/// Returns a buffer Go is done with, or a new one.
public func get() -> NativeBuffer {
lock.lock()
defer { lock.unlock() }
if let b = free.popLast() { return b }
let b = NativeBuffer(count: size)
b.pool = self
return b
}
fileprivate func put(_ b: NativeBuffer) {
lock.lock()
free.append(b)
lock.unlock()
}
}
/// An image on the GPU that native UI shows: a *native.Texture. Present
/// frames into it, IOSurfaces or CVPixelBuffers backed by them, which show
/// in the next frame of the windows showing it.
public final class NativeTexture: @unchecked Sendable {
let id: UInt64
init(id: UInt64) { self.id = id }
#if canImport(IOSurface)
/// The attributes of the pixel buffers native UI draws without
/// converting them: 32-bit BGRA, backed by IOSurfaces, for Metal.
public var pixelBufferAttributes: [String: Any] {
[
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
kCVPixelBufferIOSurfacePropertiesKey as String: [String: Any](),
kCVPixelBufferMetalCompatibilityKey as String: true,
]
}
/// Shows surface, 32-bit BGRA, in the next frame. Native UI keeps it
/// until another one replaces it: draw the next frame into another
/// surface, as a pool of pixel buffers gives.
public func present(_ surface: IOSurfaceRef) {
let p = Unmanaged.passRetained(surface).toOpaque()
_mygoSend(_mygoKindPresent, id, Int64(Int(bitPattern: p)), nil)
}
/// Shows the IOSurface backing buffer in the next frame.
public func present(_ buffer: CVPixelBuffer) {
guard let s = CVPixelBufferGetIOSurface(buffer)?.takeUnretainedValue() else { return }
present(s)
}
#endif
#if os(macOS)
/// Calls f on each refresh of the display, with the host time the
/// frame will show at, in seconds (as CACurrentMediaTime counts),
/// until the link is invalidated.
public func displayLink(_ f: @escaping @Sendable (CFTimeInterval) -> Void) -> NativeDisplayLink {
NativeDisplayLink(f)
}
#endif
}
#if os(macOS)
/// Calls back on each refresh of the display, until invalidated.
public final class NativeDisplayLink: @unchecked Sendable {
private var link: CVDisplayLink?
init(_ f: @escaping @Sendable (CFTimeInterval) -> Void) {
CVDisplayLinkCreateWithActiveCGDisplays(&link)
guard let link else { return }
let frequency = CVGetHostClockFrequency()
CVDisplayLinkSetOutputHandler(link) { _, _, out, _, _ in
f(Double(out.pointee.hostTime) / frequency)
return kCVReturnSuccess
}
CVDisplayLinkStart(link)
}
/// Stops the callbacks.
public func invalidate() {
if let link { CVDisplayLinkStop(link) }
link = nil
}
deinit { invalidate() }
}
#endif
// MARK: - Glue
public typealias _MygoCallback = @convention(c) (UInt64, UInt64, Int64, UnsafeRawPointer?, Int) -> UnsafeMutableRawPointer?
nonisolated(unsafe) var _mygoCallback: _MygoCallback?
let _mygoKindResult: UInt64 = 1
let _mygoKindItem: UInt64 = 2
let _mygoKindNotify: UInt64 = 3
let _mygoKindAsk: UInt64 = 4
let _mygoKindRelease: UInt64 = 5
let _mygoKindInvoke: UInt64 = 6
let _mygoKindInvokeAsync: UInt64 = 7
let _mygoKindCancel: UInt64 = 8
let _mygoKindPresent: UInt64 = 9
// Values cross in a binary encoding, which package native describes, in
// the order of the declarations: every integer as 8 bytes, little-endian,
// floats as Double, bools as a byte, strings, Data, arrays and
// dictionaries as their count then their contents, optionals as a Bool
// then the value, structs as their fields, enums as their raw values.
/// Writes values for Go, after the 16 bytes of a block's head: its status
/// and its length.
struct _MygoWriter {
private(set) var p: UnsafeMutableRawPointer
private var cap: Int
private(set) var n = 16
init() {
cap = 128
p = malloc(cap)!
}
private mutating func reserve(_ k: Int) {
if n + k <= cap { return }
cap = Swift.max(cap * 2, n + k)
p = realloc(p, cap)!
}
mutating func raw(_ b: UnsafeRawBufferPointer) {
guard let base = b.baseAddress, b.count > 0 else { return }
reserve(b.count)
(p + n).copyMemory(from: base, byteCount: b.count)
n += b.count
}
mutating func u64(_ v: UInt64) {
reserve(8)
p.storeBytes(of: v.littleEndian, toByteOffset: n, as: UInt64.self)
n += 8
}
mutating func u8(_ v: UInt8) {
reserve(1)
p.storeBytes(of: v, toByteOffset: n, as: UInt8.self)
n += 1
}
mutating func i64(_ v: Int64) { u64(UInt64(bitPattern: v)) }
mutating func bool(_ v: Bool) { u8(v ? 1 : 0) }
mutating func double(_ v: Double) { u64(v.bitPattern) }
mutating func count(_ c: Int) { i64(Int64(c)) }
mutating func string(_ s: String) {
var s = s
s.withUTF8 { b in
self.count(b.count)
self.raw(UnsafeRawBufferPointer(b))
}
}
mutating func data(_ d: Data) {
count(d.count)
d.withUnsafeBytes { self.raw($0) }
}
mutating func date(_ d: Date) {
let t = d.timeIntervalSince1970
var s = t.rounded(.down)
var ns = ((t - s) * 1e9).rounded()
if ns >= 1e9 {
s += 1
ns -= 1e9
}
i64(Int64(s))
i64(Int64(ns))
}
mutating func rect(_ r: CGRect) {
double(Double(r.minX))
double(Double(r.minY))
double(Double(r.width))
double(Double(r.height))
}
mutating func buffer(_ b: NativeBuffer) {
u64(UInt64(UInt(bitPattern: b.bytes.baseAddress)))
count(b.count)
}
mutating func texture(_ t: NativeTexture) { u64(t.id) }
/// The values written, without the head.
var bytes: UnsafeRawBufferPointer { UnsafeRawBufferPointer(start: p + 16, count: n - 16) }
/// Forgets what was written.
mutating func reset() { n = 16 }
/// Gives the values to Go as a block, which Go frees.
func block(_ status: Int64) -> UnsafeMutableRawPointer {
p.storeBytes(of: status, as: Int64.self)
p.storeBytes(of: Int64(n - 16), toByteOffset: 8, as: Int64.self)
return p
}
/// Frees the writer, which a block Go was given does not need.
func free() { Foundation.free(p) }
}
enum _MygoWireError: Error {
case short
case value(String, String)
}
/// Reads the values Go wrote.
struct _MygoReader {
let p: UnsafeRawPointer?
let n: Int
var i = 0
init(_ p: UnsafeRawPointer?, _ n: Int) {
self.p = p
self.n = n
}
mutating func take(_ k: Int) throws -> UnsafeRawPointer {
guard k >= 0, k <= n - i, let p else { throw _MygoWireError.short }
defer { i += k }
return p + i
}
mutating func u64() throws -> UInt64 { UInt64(littleEndian: try take(8).loadUnaligned(as: UInt64.self)) }
mutating func u8() throws -> UInt8 { try take(1).load(as: UInt8.self) }
mutating func i64() throws -> Int64 { Int64(bitPattern: try u64()) }
mutating func bool() throws -> Bool { try u8() != 0 }
mutating func double() throws -> Double { Double(bitPattern: try u64()) }
/// Reads the count of an array or a dictionary, whose elements take a
/// byte each at least.
mutating func count() throws -> Int {
let c = try i64()
guard c >= 0, c <= Int64(n - i) else { throw _MygoWireError.short }
return Int(c)
}
mutating func string() throws -> String {
let c = try count()
return String(decoding: UnsafeRawBufferPointer(start: try take(c), count: c), as: UTF8.self)
}
mutating func data() throws -> Data {
let c = try count()
return Data(bytes: try take(c), count: c)
}
mutating func date() throws -> Date {
let s = try i64()
let ns = try i64()
return Date(timeIntervalSince1970: Double(s) + Double(ns) / 1e9)
}
mutating func rect() throws -> CGRect {
CGRect(x: try double(), y: try double(), width: try double(), height: try double())
}
mutating func buffer() throws -> NativeBuffer {
let p = try u64()
return NativeBuffer(p: p, count: Int(try i64()))
}
mutating func texture() throws -> NativeTexture { NativeTexture(id: try u64()) }
}
/// Tells Go something, with the values w holds, and returns its answer, a
/// block to read with _mygoAnswer, if any.
@discardableResult
func _mygoSend(_ kind: UInt64, _ id: UInt64, _ status: Int64, _ w: _MygoWriter?) -> UnsafeMutableRawPointer? {
guard let cb = _mygoCallback else { return nil }
guard let w, w.n > 16 else { return cb(kind, id, status, nil, 0) }
return cb(kind, id, status, w.p + 16, w.n - 16)
}
/// Reads a block Go answered with, and frees it.
func _mygoAnswer<R>(_ p: UnsafeMutableRawPointer?, _ read: (inout _MygoReader) throws -> R) throws -> R {
guard let p else { throw NativeError.closed }
defer { free(p) }
let st = p.loadUnaligned(as: Int64.self)
var r = _MygoReader(p + 16, Int(p.loadUnaligned(fromByteOffset: 8, as: Int64.self)))
if st == 1 { throw _mygoReadError(&r) }
return try read(&r)
}
/// Runs what returns at once, which writes its result to w.
func _mygoRun(_ body: (inout _MygoWriter) throws -> Void) -> UnsafeMutableRawPointer? {
var w = _MygoWriter()
do {
try body(&w)
return w.block(0)
} catch {
w.reset()
_mygoWriteError(&w, error)
return w.block(1)
}
}
func _mygoRunMain(_ body: @MainActor (inout _MygoWriter) throws -> Void) -> UnsafeMutableRawPointer? {
_mygoRun { w in try MainActor.assumeIsolated { try body(&w) } }
}
/// Runs what starts an asynchronous call or a stream: Go waits for its
/// results through the callback.
func _mygoStart(_ body: () throws -> Void) -> UnsafeMutableRawPointer? {
var w = _MygoWriter()
do {
try body()
return w.block(2)
} catch {
_mygoWriteError(&w, error)
return w.block(1)
}
}
func _mygoCall<T>(_ f: () throws -> T) rethrows -> T { try f() }
@MainActor func _mygoCallMain<T>(_ f: @MainActor () throws -> T) rethrows -> T { try f() }
func _mygoMust<T>(_ f: () throws -> T) -> T {
do {
return try f()
} catch {
fatalError("Sqlitecore: Go failed to answer: \(error)")
}
}
func _mygoFail<T>() -> T { fatalError("Sqlitecore: Go failed to answer") }
// The kinds of errors, as they cross both ways: the kind, then the code,
// domain, number and message.
let _mygoErrOther: UInt8 = 0
let _mygoErrCode: UInt8 = 1
let _mygoErrUnsupported: UInt8 = 2
let _mygoErrClosed: UInt8 = 3
let _mygoErrCanceled: UInt8 = 4
let _mygoErrGo: UInt8 = 5
func _mygoWriteError(_ w: inout _MygoWriter, _ error: any Error) {
var kind = _mygoErrOther
var code = "", domain = "", message = ""
var number = 0
switch error {
case let e as SqlitecoreError:
kind = _mygoErrCode
code = e.rawValue
case NativeError.unsupported:
kind = _mygoErrUnsupported
case NativeError.closed:
kind = _mygoErrClosed
case NativeError.go(let m):
kind = _mygoErrGo
message = m
case is CancellationError:
kind = _mygoErrCanceled
default:
let ns = error as NSError
if type(of: error) is NSError.Type {
domain = ns.domain
message = ns.localizedDescription
} else {
let name = String(describing: type(of: error))
domain = name
message = (error as? LocalizedError)?.errorDescription ?? "\(name).\(error)"
}
number = ns.code
}
w.u8(kind)
w.string(code)
w.string(domain)
w.i64(Int64(number))
w.string(message)
}
func _mygoReadError(_ r: inout _MygoReader) -> any Error {
guard let kind = try? r.u8(), let code = try? r.string(), (try? r.string()) != nil, (try? r.i64()) != nil, let message = try? r.string() else {
return NativeError.go("an error of Go's that does not decode")
}
switch kind {
case _mygoErrCode: return SqlitecoreError(rawValue: code) ?? NativeError.go(message)
case _mygoErrUnsupported: return NativeError.unsupported
case _mygoErrClosed: return NativeError.closed
case _mygoErrCanceled: return CancellationError()
default: return NativeError.go(message)
}
}
func _mygoRetain(_ v: AnyObject) -> UInt64 {
UInt64(UInt(bitPattern: Unmanaged.passRetained(v).toOpaque()))
}
func _mygoAnyObject(_ h: UInt64) -> AnyObject {
guard let p = UnsafeRawPointer(bitPattern: UInt(h)) else { fatalError("Sqlitecore: Go passed nil for an object") }
return Unmanaged<AnyObject>.fromOpaque(p).takeUnretainedValue()
}
func _mygoObject<T>(_ h: UInt64) -> T {
guard let v = _mygoAnyObject(h) as? T else { fatalError("Sqlitecore: Go passed an object of the wrong type for \(T.self)") }
return v
}
func _mygoRelease(_ h: UInt64) {
guard let p = UnsafeRawPointer(bitPattern: UInt(h)) else { return }
Unmanaged<AnyObject>.fromOpaque(p).release()
}
#if canImport(AppKit)
/// The views of native UI's windows, which views of the module are, and
/// the windows methods take: AppKit's on macOS, UIKit's on iOS, where a
/// window is its view controller.
public typealias NativeView = NSView
public typealias NativeWindow = NSWindow
@MainActor func _mygoWindow(_ h: UInt64) -> NSWindow {
let w: NSWindow = _mygoObject(h)
return w
}
/// Turns a rectangle of native UI, whose origin is the window's top-left,
/// into the coordinates of the window's content view.
@MainActor func _mygoFlip(_ r: CGRect, in w: NSWindow) -> CGRect {
guard let v = w.contentView, !v.isFlipped else { return r }
return CGRect(x: r.minX, y: v.bounds.height - r.minY - r.height, width: r.width, height: r.height)
}
#elseif canImport(UIKit)
public typealias NativeView = UIView
public typealias NativeWindow = UIViewController
/// The view controller of a window of the app, which the host keeps by its
/// number: Go's handle of it.
@MainActor func _mygoWindow(_ h: UInt64) -> UIViewController {
guard let windows = NSClassFromString("MyGoWindows") as? NSObject.Type,
let c = windows.perform(NSSelectorFromString("controller:"), with: NSNumber(value: h))?.takeUnretainedValue() as? UIViewController else {
fatalError("Sqlitecore: the window Go passed is gone")
}
return c
}
/// UIKit's coordinates are native UI's: from the top-left.
@MainActor func _mygoFlip(_ r: CGRect, in w: UIViewController) -> CGRect { r }
#endif
final class _MygoTable<V>: @unchecked Sendable {
private let lock = NSLock()
private var values: [UInt64: V] = [:]
func put(_ k: UInt64, _ v: V) { lock.lock(); values[k] = v; lock.unlock() }
func get(_ k: UInt64) -> V? { lock.lock(); defer { lock.unlock() }; return values[k] }
@discardableResult func remove(_ k: UInt64) -> V? { lock.lock(); defer { lock.unlock() }; return values.removeValue(forKey: k) }
}
/// The tasks of asynchronous calls and streams, by their call, which Go
/// cancels.
final class _MygoTasks: @unchecked Sendable {
private let lock = NSLock()
private var tasks: [UInt64: Task<Void, Never>] = [:]
private var done: Set<UInt64> = []
private var canceled: Set<UInt64> = []
func put(_ call: UInt64, _ t: Task<Void, Never>) {
lock.lock()
defer { lock.unlock() }
if done.remove(call) != nil { return }
if canceled.remove(call) != nil { t.cancel() }
tasks[call] = t
}
func finish(_ call: UInt64) {
lock.lock()
defer { lock.unlock() }
if tasks.removeValue(forKey: call) == nil { done.insert(call) }
canceled.remove(call)
}
func cancel(_ call: UInt64) {
lock.lock()
let t = tasks.removeValue(forKey: call)
if t == nil, done.remove(call) == nil { canceled.insert(call) }
lock.unlock()
t?.cancel()
}
}
let _mygoTasks = _MygoTasks()
let _mygoDemands = _MygoTable<AsyncStream<Void>.Continuation>()
let _mygoConts = _MygoTable<CheckedContinuation<_MygoBlock, Never>>()
/// A block Go answered with, for a continuation.
struct _MygoBlock: @unchecked Sendable {
let p: UnsafeMutableRawPointer?
}
private let _mygoIDLock = NSLock()
nonisolated(unsafe) private var _mygoLastID: UInt64 = 0
/// The module's index, from Go, in the high bits of every id, which makes
/// the ids of continuations unique among modules.
nonisolated(unsafe) var _mygoIDBase: UInt64 = 0
func _mygoNextID() -> UInt64 {
_mygoIDLock.lock()
defer { _mygoIDLock.unlock() }
_mygoLastID += 1
return _mygoIDBase | _mygoLastID
}
func _mygoFinish(_ call: UInt64, _ body: (inout _MygoWriter) async throws -> Void) async {
var w = _MygoWriter()
var status: Int64 = 0
do {
try await body(&w)
} catch {
w.reset()
_mygoWriteError(&w, error)
status = 1
}
_mygoTasks.finish(call)
_mygoSend(_mygoKindResult, call, status, w)
w.free()
}
func _mygoTask(_ call: UInt64, _ body: @escaping (inout _MygoWriter) async throws -> Void) {
_mygoTasks.put(call, Task { await _mygoFinish(call, body) })
}
func _mygoTaskMain(_ call: UInt64, _ body: @escaping @MainActor (inout _MygoWriter) async throws -> Void) {
_mygoTasks.put(call, Task { @MainActor in await _mygoFinish(call, body) })
}
func _mygoIterate<S: AsyncSequence & Sendable>(_ call: UInt64, _ s: S, _ demand: AsyncStream<Void>, _ enc: (inout _MygoWriter, S.Element) -> Void) async {
var it = s.makeAsyncIterator()
var lent: S.Element? = nil
var w = _MygoWriter()
for await _ in demand {
// Go is done with what the previous value lent.
(lent as? NativeBuffer)?.recycle()
lent = nil
w.reset()
do {
guard let v = try await it.next() else {
_mygoSend(_mygoKindItem, call, 3, nil)
break
}
lent = v
enc(&w, v)
_mygoSend(_mygoKindItem, call, 0, w)
} catch {
_mygoWriteError(&w, error)
_mygoSend(_mygoKindItem, call, 1, w)
break
}
}
w.free()
withExtendedLifetime(lent) {}
_mygoDemands.remove(call)
_mygoTasks.finish(call)
}
func _mygoDemand(_ call: UInt64) -> AsyncStream<Void> {
var cont: AsyncStream<Void>.Continuation!
let demand = AsyncStream<Void>(bufferingPolicy: .unbounded) { cont = $0 }
_mygoDemands.put(call, cont)
return demand
}
func _mygoStream<S: AsyncSequence & Sendable>(_ call: UInt64, _ make: @escaping () -> S, _ enc: @escaping (inout _MygoWriter, S.Element) -> Void) {
let demand = _mygoDemand(call)
_mygoTasks.put(call, Task { await _mygoIterate(call, make(), demand, enc) })
}
func _mygoStreamMain<S: AsyncSequence & Sendable>(_ call: UInt64, _ make: @escaping @MainActor () -> S, _ enc: @escaping (inout _MygoWriter, S.Element) -> Void) {
let demand = _mygoDemand(call)
_mygoTasks.put(call, Task { @MainActor in await _mygoIterate(call, make(), demand, enc) })
}
/// A Go function the implementation calls: a notification, or a question
/// Go answers at once. Both take the writer of the arguments, and free it.
final class _MygoGoFunc: @unchecked Sendable {
let id: UInt64
init(_ id: UInt64) { self.id = id }
deinit { if id != 0 { _mygoSend(_mygoKindRelease, id, 0, nil) } }
func notify(_ w: _MygoWriter) {
if id != 0 { _mygoSend(_mygoKindNotify, id, 0, w) }
w.free()
}
func ask<R>(_ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) throws -> R {
defer { w.free() }
guard id != 0 else { throw NativeError.closed }
return try _mygoAnswer(_mygoSend(_mygoKindAsk, id, 0, w), read)
}
}
/// Calls the method of a value of Go's that w names, with the arguments
/// after it, and frees w.
func _mygoInvoke<R>(_ id: UInt64, _ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) throws -> R {
defer { w.free() }
return try _mygoAnswer(_mygoSend(_mygoKindInvoke, id, 0, w), read)
}
func _mygoInvokeAsync<R>(_ id: UInt64, _ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) async throws -> R {
let cont = _mygoNextID()
let b = await withTaskCancellationHandler {
await withCheckedContinuation { (c: CheckedContinuation<_MygoBlock, Never>) in
_mygoConts.put(cont, c)
_mygoSend(_mygoKindInvokeAsync, id, Int64(bitPattern: cont), w)
w.free()
}
} onCancel: {
_mygoSend(_mygoKindCancel, cont, 0, nil)
}
return try _mygoAnswer(b.p, read)
}
@@ -0,0 +1,244 @@
import CSQLite
import Foundation
// The implementation of package sqlitecore on iOS: SQLite 3.53.4, which
// CSQLite links in (build-xcframework.sh), called as the Zig does on
// desktops.
func makeEngine() throws -> any Engine {
if sqlite3_threadsafe() == 0 { throw NativeError.go("sqlite: the library is not threadsafe") }
return SQLiteEngine()
}
/// SQLITE_TRANSIENT: SQLite copies the value before the bind returns.
private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
final class SQLiteEngine: Engine {
func `open`(path: String, readOnly: Bool, busyMillis: Int) throws -> any Conn {
let flags = (readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) | SQLITE_OPEN_FULLMUTEX
var db: OpaquePointer?
let rc = sqlite3_open_v2(path, &db, flags, nil)
guard rc == SQLITE_OK, let db else {
let err = failure(db, rc)
if let db { _ = sqlite3_close_v2(db) }
throw err
}
_ = sqlite3_extended_result_codes(db, 1)
return SQLiteConn(db, timeout: Int32(clamping: max(busyMillis, 0)))
}
func version() -> String { String(cString: sqlite3_libversion()) }
}
final class SQLiteConn: Conn {
/// The connection, nil once closed.
private var db: OpaquePointer?
/// The state SQLite's handlers read, which it holds a pointer to.
private let handlers: UnsafeMutablePointer<Handlers>
init(_ db: OpaquePointer, timeout: Int32) {
self.db = db
handlers = .allocate(capacity: 1)
handlers.initialize(to: Handlers(db: db, timeout: timeout))
_ = sqlite3_set_authorizer(db, authorize, handlers)
_ = sqlite3_busy_handler(db, busy, handlers)
}
deinit {
if let db { _ = sqlite3_close_v2(db) }
handlers.deinitialize(count: 1)
handlers.deallocate()
}
private func connection() throws -> OpaquePointer {
guard let db else { throw NativeError.closed }
return db
}
func close() throws {
guard let db else { return }
let rc = sqlite3_close_v2(db)
if rc != SQLITE_OK { throw failure(db, rc) }
self.db = nil
}
func autocommit() -> Bool { db.map { sqlite3_get_autocommit($0) != 0 } ?? true }
func interrupt() {
if let db { sqlite3_interrupt(db) }
}
func control(sql: String) throws {
let db = try connection()
let stmt = try prepare(db, sql, control: true)
defer { _ = sqlite3_finalize(stmt) }
let rc = sqlite3_step(stmt)
if rc != SQLITE_DONE { throw failure(db, rc) }
}
func run(sql: String, args: [Value], query: Bool) throws -> Outcome {
let db = try connection()
let stmt = try prepare(db, sql, control: false)
defer { _ = sqlite3_finalize(stmt) }
let count = Int(sqlite3_bind_parameter_count(stmt))
if count != args.count { throw NativeError.go("sqlite: statement needs \(count) parameters, got \(args.count)") }
for (i, arg) in args.enumerated() {
let rc = bind(stmt, Int32(i + 1), arg)
if rc != SQLITE_OK { throw failure(db, rc) }
}
let n = query ? sqlite3_column_count(stmt) : 0
var out = Outcome(changes: 0, lastInsertID: 0, columns: [], values: [])
out.columns = (0..<n).map { sqlite3_column_name(stmt, $0).map { String(cString: $0) } ?? "" }
let before = sqlite3_total_changes64(db)
while true {
let rc = sqlite3_step(stmt)
if rc == SQLITE_ROW {
if query { for i in 0..<n { out.values.append(column(stmt, i)) } }
} else if rc == SQLITE_DONE {
break
} else {
throw failure(db, rc)
}
}
out.lastInsertID = sqlite3_last_insert_rowid(db)
if sqlite3_total_changes64(db) != before { out.changes = sqlite3_changes64(db) }
return out
}
/// Prepares sql, which must be exactly one statement: it compiles what
/// follows the first before anything runs, so that extra SQL, even
/// invalid, never runs a part of an operation.
private func prepare(_ db: OpaquePointer, _ sql: String, control: Bool) throws -> OpaquePointer {
handlers.pointee.allowControl = control
defer { handlers.pointee.allowControl = true }
var text = Array(sql.utf8)
let n = text.count
text.append(0)
return try text.withUnsafeBufferPointer { buf -> OpaquePointer in
let base = UnsafeRawPointer(buf.baseAddress!).assumingMemoryBound(to: CChar.self)
var first: OpaquePointer?
var tail: UnsafePointer<CChar>?
var rc = sqlite3_prepare_v2(db, base, Int32(n), &first, &tail)
if rc != SQLITE_OK {
if let first { _ = sqlite3_finalize(first) }
throw failure(db, rc)
}
guard let first else { throw NativeError.go("sqlite: SQL contains no statement") }
var offset = tail.map { base.distance(to: $0) } ?? n
while offset < n {
var extra: OpaquePointer?
rc = sqlite3_prepare_v2(db, base + offset, Int32(n - offset), &extra, &tail)
if rc != SQLITE_OK || extra != nil {
let err: any Error
if rc != SQLITE_OK {
err = failure(db, rc)
} else {
err = NativeError.go("sqlite: expected exactly one statement")
}
if let extra { _ = sqlite3_finalize(extra) }
_ = sqlite3_finalize(first)
throw err
}
let next = tail.map { base.distance(to: $0) } ?? n
if next <= offset { break }
offset = next
}
return first
}
}
}
/// What SQLite's handlers read: the wait for a lock, which Interrupt ends
/// too, and the transaction control a call allows.
private struct Handlers {
let db: OpaquePointer
let timeout: Int32
var waited: Int32 = 0
var allowControl = true
}
private let busy: @convention(c) (UnsafeMutableRawPointer?, Int32) -> Int32 = { data, previous in
let h = data!.assumingMemoryBound(to: Handlers.self)
if previous == 0 { h.pointee.waited = 0 }
if sqlite3_is_interrupted(h.pointee.db) != 0 || h.pointee.waited >= h.pointee.timeout { return 0 }
let delay = min(previous < 10 ? previous + 1 : 10, h.pointee.timeout - h.pointee.waited)
h.pointee.waited += sqlite3_sleep(delay)
return sqlite3_is_interrupted(h.pointee.db) == 0 ? 1 : 0
}
// Transactions belong to the batch API. ATTACH (including VACUUM INTO)
// could escape the plugin's database directory. Extension loading is
// omitted at compile time, and directory-changing pragmas are deprecated.
private let authorize: @convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<CChar>?, UnsafePointer<CChar>?, UnsafePointer<CChar>?, UnsafePointer<CChar>?) -> Int32 = { data, action, a, _, _, _ in
let allow = data!.assumingMemoryBound(to: Handlers.self).pointee.allowControl
switch action {
case SQLITE_TRANSACTION, SQLITE_SAVEPOINT, SQLITE_DETACH:
return allow ? SQLITE_OK : SQLITE_DENY
case SQLITE_ATTACH:
// Ordinary VACUUM attaches an unnamed temporary database while
// stepping. User ATTACH is denied while preparing, and VACUUM INTO
// a named output file is denied here too.
return allow && a != nil && a!.pointee == 0 ? SQLITE_OK : SQLITE_DENY
default:
return SQLITE_OK
}
}
private func bind(_ stmt: OpaquePointer, _ i: Int32, _ v: Value) -> Int32 {
switch v.type {
case .null:
return sqlite3_bind_null(stmt, i)
case .integer:
return sqlite3_bind_int64(stmt, i, v.int)
case .real:
return sqlite3_bind_double(stmt, i, v.real)
case .text:
var text = v.text
return text.withUTF8 { buf in
buf.withMemoryRebound(to: CChar.self) { chars in
guard let p = chars.baseAddress else { return "".withCString { sqlite3_bind_text(stmt, i, $0, 0, transient) } }
return sqlite3_bind_text(stmt, i, p, Int32(chars.count), transient)
}
}
case .blob:
// A pointer that is not null, even for no bytes, keeps an empty BLOB
// from being NULL.
return v.blob.withUnsafeBytes { buf in
guard let p = buf.baseAddress, buf.count > 0 else { return "".withCString { sqlite3_bind_blob(stmt, i, $0, 0, transient) } }
return sqlite3_bind_blob(stmt, i, p, Int32(buf.count), transient)
}
}
}
/// The value of column i of the current row, copied.
private func column(_ stmt: OpaquePointer, _ i: Int32) -> Value {
var v = Value(type: .null, int: 0, real: 0, text: "", blob: Data())
switch sqlite3_column_type(stmt, i) {
case SQLITE_INTEGER:
v.type = .integer
v.int = sqlite3_column_int64(stmt, i)
case SQLITE_FLOAT:
v.type = .real
v.real = sqlite3_column_double(stmt, i)
case SQLITE_TEXT:
v.type = .text
let p = sqlite3_column_text(stmt, i)
let n = Int(sqlite3_column_bytes(stmt, i))
v.text = p.map { String(decoding: UnsafeBufferPointer(start: $0, count: n), as: UTF8.self) } ?? ""
case SQLITE_BLOB:
v.type = .blob
let p = sqlite3_column_blob(stmt, i)
let n = Int(sqlite3_column_bytes(stmt, i))
if let p, n > 0 { v.blob = Data(bytes: p, count: n) }
default:
break
}
return v
}
/// The error of the last call on db that failed with rc, which Go reports
/// as an sqlite.Error: SQLite's extended code and message.
private func failure(_ db: OpaquePointer?, _ rc: Int32) -> NSError {
guard let db else { return NSError(domain: "SQLite", code: Int(rc), userInfo: [NSLocalizedDescriptionKey: "could not open database"]) }
return NSError(domain: "SQLite", code: Int(sqlite3_extended_errcode(db)), userInfo: [NSLocalizedDescriptionKey: String(cString: sqlite3_errmsg(db))])
}
@@ -0,0 +1,50 @@
#!/bin/sh
# Builds CSQLite.xcframework, the SQLite that the module's Swift links on
# iOS, from the amalgamation that the Zig build pins, with its options, as
# a static library for iOS and its simulator on arm64. Its symbols stay
# hidden in the module's framework, as they do in the Zig build's library,
# so that the system's SQLite, which UIKit loads, never meets it. On a
# Mac, with Xcode:
#
# ./build-xcframework.sh out
#
# writes out/CSQLite.xcframework.zip and prints its checksum, for
# Package.swift, which downloads it from the release native-sqlitecore.
set -eu
version=3530400
sha256=1e71ddf93849c6a6ecf58b827c0692073d2dd7ee40196158068f7b29f422e87d
out=$(mkdir -p "$1" && cd "$1" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
curl -fsSL -o "$work/sqlite.zip" "https://www.sqlite.org/2026/sqlite-amalgamation-$version.zip"
echo "$sha256 $work/sqlite.zip" | shasum -a 256 -c -
unzip -q "$work/sqlite.zip" -d "$work"
src="$work/sqlite-amalgamation-$version"
mkdir -p "$work/headers"
cp "$src/sqlite3.h" "$work/headers/"
cat > "$work/headers/module.modulemap" <<'MAP'
module CSQLite {
header "sqlite3.h"
export *
}
MAP
set --
for sdk in iphoneos:arm64-apple-ios16.0 iphonesimulator:arm64-apple-ios16.0-simulator; do
name=${sdk%%:*}
mkdir -p "$work/$name"
xcrun --sdk "$name" clang -c -O2 -std=c11 -fvisibility=hidden -target "${sdk#*:}" \
-DSQLITE_THREADSAFE=1 -DSQLITE_DQS=0 -DSQLITE_DEFAULT_FOREIGN_KEYS=1 \
-DSQLITE_ENABLE_FTS5=1 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_OMIT_LOAD_EXTENSION=1 \
-DSQLITE_OMIT_DEPRECATED=1 -DSQLITE_OMIT_SHARED_CACHE=1 \
-o "$work/$name/sqlite3.o" "$src/sqlite3.c"
xcrun libtool -static -o "$work/$name/libCSQLite.a" "$work/$name/sqlite3.o"
set -- "$@" -library "$work/$name/libCSQLite.a" -headers "$work/headers"
done
rm -rf "$out/CSQLite.xcframework" "$out/CSQLite.xcframework.zip"
xcodebuild -create-xcframework "$@" -output "$out/CSQLite.xcframework"
(cd "$out" && zip -qry CSQLite.xcframework.zip CSQLite.xcframework)
swift package compute-checksum "$out/CSQLite.xcframework.zip"
@@ -0,0 +1,3 @@
/zig-out
/.zig-cache
/zig-pkg
@@ -0,0 +1,31 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const module = b.createModule(.{
.root_source_file = b.path("src/mygo.zig"),
.target = target,
.optimize = b.standardOptimizeOption(.{}),
.link_libc = true,
});
// SQLite's amalgamation, pinned by its hash in build.zig.zon. Its
// symbols stay hidden in the library, which exports only the module's:
// a process that loaded another SQLite globally, as WebKit does on
// Linux, can neither interpose on its calls nor see it.
const sqlite = b.dependency("sqlite", .{});
module.addIncludePath(sqlite.path(""));
module.addCSourceFile(.{ .file = sqlite.path("sqlite3.c"), .flags = &.{ "-std=c11", "-fvisibility=hidden" } });
module.addCMacro("SQLITE_THREADSAFE", "1");
module.addCMacro("SQLITE_DQS", "0");
module.addCMacro("SQLITE_DEFAULT_FOREIGN_KEYS", "1");
module.addCMacro("SQLITE_ENABLE_FTS5", "1");
module.addCMacro("SQLITE_ENABLE_RTREE", "1");
module.addCMacro("SQLITE_OMIT_LOAD_EXTENSION", "1");
module.addCMacro("SQLITE_OMIT_DEPRECATED", "1");
module.addCMacro("SQLITE_OMIT_SHARED_CACHE", "1");
if (target.result.os.tag != .windows) {
module.linkSystemLibrary("m", .{});
module.linkSystemLibrary("pthread", .{});
}
b.installArtifact(b.addLibrary(.{ .name = "Sqlitecore", .linkage = .dynamic, .root_module = module }));
}
@@ -0,0 +1,13 @@
.{
.name = .sqlitecore,
.version = "0.0.0",
.fingerprint = 0xbeed00044bd68e0,
.minimum_zig_version = "0.16.0",
.dependencies = .{
.sqlite = .{
.url = "https://www.sqlite.org/2026/sqlite-amalgamation-3530400.zip",
.hash = "N-V-__8AAGVtrgCcOcmjrOJnagmnRyMrcKaOo09KbU-vu8w8",
},
},
.paths = .{ "build.zig", "build.zig.zon", "src" },
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,276 @@
//! The plugin's SQLite: the amalgamation build.zig compiles in, called
//! through its C API.
const std = @import("std");
const mygo = @import("mygo.zig");
const Allocator = std.mem.Allocator;
pub fn makeEngine() mygo.Error!mygo.Engine {
if (sqlite3_threadsafe() == 0) return mygo.failGo("sqlite: the library is not threadsafe");
const v = try mygo.allocator.create(Engine);
v.* = .{};
return mygo.Engine.of(v);
}
const Engine = struct {
pub fn deinit(self: *Engine) void {
mygo.allocator.destroy(self);
}
pub fn open(_: *Engine, arena: Allocator, path: []const u8, read_only: bool, busy_millis: i64) mygo.Error!mygo.Conn {
const name = try arena.dupeSentinel(u8, path, 0);
const flags: c_int = if (read_only) open_readonly | open_fullmutex else open_readwrite | open_create | open_fullmutex;
var db: ?*Db = null;
const rc = sqlite3_open_v2(name, &db, flags, null);
if (rc != ok) {
const err = failure(db, rc);
if (db) |h| _ = sqlite3_close_v2(h);
return err;
}
_ = sqlite3_extended_result_codes(db.?, 1);
const c = mygo.allocator.create(Conn) catch |err| {
_ = sqlite3_close_v2(db.?);
return err;
};
c.* = .{ .db = db, .timeout_ms = @intCast(std.math.clamp(busy_millis, 0, std.math.maxInt(c_int))) };
c.handle();
return mygo.Conn.of(c);
}
pub fn version(_: *Engine, _: Allocator) []const u8 {
return std.mem.span(sqlite3_libversion());
}
};
const Conn = struct {
db: ?*Db,
timeout_ms: c_int,
waited_ms: c_int = 0,
allow_control: bool = true,
/// Installs the connection's handlers: the wait for a lock, which
/// Interrupt ends too, and the transaction control a call allows.
fn handle(c: *Conn) void {
_ = sqlite3_set_authorizer(c.db.?, authorize, c);
_ = sqlite3_busy_handler(c.db.?, busy, c);
}
pub fn deinit(self: *Conn) void {
if (self.db) |db| _ = sqlite3_close_v2(db);
mygo.allocator.destroy(self);
}
pub fn close(self: *Conn) mygo.Error!void {
const db = self.db orelse return;
const rc = sqlite3_close_v2(db);
if (rc != ok) return failure(db, rc);
self.db = null;
}
pub fn autocommit(self: *Conn, _: Allocator) bool {
const db = self.db orelse return true;
return sqlite3_get_autocommit(db) != 0;
}
pub fn interrupt(self: *Conn, _: Allocator) void {
if (self.db) |db| sqlite3_interrupt(db);
}
pub fn control(self: *Conn, _: Allocator, sql: []const u8) mygo.Error!void {
const db = self.db orelse return error.Closed;
const stmt = try prepare(self, sql, true);
defer _ = sqlite3_finalize(stmt);
const rc = sqlite3_step(stmt);
if (rc != done) return failure(db, rc);
}
pub fn run(self: *Conn, arena: Allocator, sql: []const u8, args: []const mygo.Value, query: bool) mygo.Error!mygo.Outcome {
const db = self.db orelse return error.Closed;
const stmt = try prepare(self, sql, false);
defer _ = sqlite3_finalize(stmt);
const count = sqlite3_bind_parameter_count(stmt);
if (count != args.len) {
return mygo.failGo(try std.fmt.allocPrint(arena, "sqlite: statement needs {d} parameters, got {d}", .{ count, args.len }));
}
for (args, 1..) |arg, i| try bind(db, stmt, @intCast(i), arg);
var out: mygo.Outcome = .{};
const n: usize = if (query) @intCast(sqlite3_column_count(stmt)) else 0;
if (query) {
const columns = try arena.alloc([]const u8, n);
for (columns, 0..) |*c, i| {
c.* = if (sqlite3_column_name(stmt, @intCast(i))) |name| try arena.dupe(u8, std.mem.span(name)) else "";
}
out.columns = columns;
}
var values: std.ArrayList(mygo.Value) = .empty;
const before = sqlite3_total_changes64(db);
while (true) {
const rc = sqlite3_step(stmt);
if (rc == row) {
if (!query) continue;
for (0..n) |i| try values.append(arena, try column(arena, stmt, @intCast(i)));
} else if (rc == done) {
break;
} else {
return failure(db, rc);
}
}
out.values = values.items;
out.last_insert_id = sqlite3_last_insert_rowid(db);
if (sqlite3_total_changes64(db) != before) out.changes = sqlite3_changes64(db);
return out;
}
};
fn busy(data: ?*anyopaque, previous: c_int) callconv(.c) c_int {
const c: *Conn = @ptrCast(@alignCast(data.?));
if (previous == 0) c.waited_ms = 0;
if (sqlite3_is_interrupted(c.db.?) != 0 or c.waited_ms >= c.timeout_ms) return 0;
var delay: c_int = if (previous < 10) previous + 1 else 10;
delay = @min(delay, c.timeout_ms - c.waited_ms);
c.waited_ms += sqlite3_sleep(delay);
return @intFromBool(sqlite3_is_interrupted(c.db.?) == 0);
}
// Transactions belong to the batch API. ATTACH (including VACUUM INTO)
// could escape the plugin's database directory. Extension loading is
// omitted at compile time, and directory-changing pragmas are deprecated.
fn authorize(data: ?*anyopaque, action: c_int, a: ?[*:0]const u8, _: ?[*:0]const u8, _: ?[*:0]const u8, _: ?[*:0]const u8) callconv(.c) c_int {
const c: *Conn = @ptrCast(@alignCast(data.?));
return switch (action) {
action_transaction, action_savepoint, action_detach => if (c.allow_control) ok else deny,
// Ordinary VACUUM attaches an unnamed temporary database while
// stepping. User ATTACH is denied while preparing, and VACUUM INTO
// a named output file is denied here too.
action_attach => if (c.allow_control and a != null and a.?[0] == 0) ok else deny,
else => ok,
};
}
/// Prepares sql, which must be exactly one statement: it compiles what
/// follows the first before anything runs, so that extra SQL, even invalid,
/// never runs a part of an operation.
fn prepare(c: *Conn, sql: []const u8, control: bool) mygo.Error!*Stmt {
const db = c.db.?;
c.allow_control = control;
defer c.allow_control = true;
var stmt: ?*Stmt = null;
var tail: ?[*]const u8 = null;
var rc = sqlite3_prepare_v2(db, sql.ptr, @intCast(sql.len), &stmt, &tail);
if (rc != ok) {
const err = failure(db, rc);
if (stmt) |s| _ = sqlite3_finalize(s);
return err;
}
const first = stmt orelse return mygo.failGo("sqlite: SQL contains no statement");
var offset = if (tail) |t| @intFromPtr(t) - @intFromPtr(sql.ptr) else sql.len;
while (offset < sql.len) {
var extra: ?*Stmt = null;
rc = sqlite3_prepare_v2(db, sql.ptr + offset, @intCast(sql.len - offset), &extra, &tail);
if (rc != ok or extra != null) {
const err = if (rc != ok) failure(db, rc) else mygo.failGo("sqlite: expected exactly one statement");
if (extra) |s| _ = sqlite3_finalize(s);
_ = sqlite3_finalize(first);
return err;
}
const next = if (tail) |t| @intFromPtr(t) - @intFromPtr(sql.ptr) else sql.len;
if (next <= offset) break;
offset = next;
}
return first;
}
fn bind(db: *Db, stmt: *Stmt, index: c_int, v: mygo.Value) mygo.Error!void {
const rc = switch (v.type) {
.null => sqlite3_bind_null(stmt, index),
.integer => sqlite3_bind_int64(stmt, index, v.int),
.real => sqlite3_bind_double(stmt, index, v.real),
.text => sqlite3_bind_text(stmt, index, v.text.ptr, @intCast(v.text.len), transient),
// A pointer that is not null, even for no bytes, keeps an empty
// BLOB from being NULL.
.blob => sqlite3_bind_blob(stmt, index, if (v.blob.len == 0) "".ptr else v.blob.ptr, @intCast(v.blob.len), transient),
};
if (rc != ok) return failure(db, rc);
}
/// The value of column i of the current row, copied into arena.
fn column(arena: Allocator, stmt: *Stmt, i: c_int) mygo.Error!mygo.Value {
return switch (sqlite3_column_type(stmt, i)) {
1 => .{ .type = .integer, .int = sqlite3_column_int64(stmt, i) },
2 => .{ .type = .real, .real = sqlite3_column_double(stmt, i) },
3 => .{ .type = .text, .text = try bytes(arena, sqlite3_column_text(stmt, i), sqlite3_column_bytes(stmt, i)) },
4 => .{ .type = .blob, .blob = try bytes(arena, @ptrCast(sqlite3_column_blob(stmt, i)), sqlite3_column_bytes(stmt, i)) },
else => .{ .type = .null },
};
}
fn bytes(arena: Allocator, p: ?[*]const u8, n: c_int) mygo.Error![]const u8 {
if (n <= 0) return &.{};
return arena.dupe(u8, p.?[0..@intCast(n)]);
}
/// The error of the last call on db that failed with rc, which Go reports
/// as an sqlite.Error: SQLite's extended code and message.
fn failure(db: ?*Db, rc: c_int) mygo.Error {
const h = db orelse return mygo.fail("SQLite", rc, "could not open database");
return mygo.fail("SQLite", sqlite3_extended_errcode(h), std.mem.span(sqlite3_errmsg(h)));
}
// SQLite's C API, as much as the module calls.
const Db = opaque {};
const Stmt = opaque {};
/// A destructor of a bound value, as an integer: SQLITE_TRANSIENT, -1, is
/// no aligned function pointer.
const Destructor = isize;
const ok = 0;
const deny = 1;
const row = 100;
const done = 101;
const open_readonly = 0x00000001;
const open_readwrite = 0x00000002;
const open_create = 0x00000004;
const open_fullmutex = 0x00010000;
const action_attach = 24;
const action_detach = 25;
const action_transaction = 22;
const action_savepoint = 32;
/// SQLITE_TRANSIENT: SQLite copies the value before the bind returns.
const transient: Destructor = -1;
extern fn sqlite3_threadsafe() c_int;
extern fn sqlite3_libversion() [*:0]const u8;
extern fn sqlite3_open_v2(filename: [*:0]const u8, db: *?*Db, flags: c_int, vfs: ?[*:0]const u8) c_int;
extern fn sqlite3_close_v2(db: *Db) c_int;
extern fn sqlite3_extended_result_codes(db: *Db, on: c_int) c_int;
extern fn sqlite3_errmsg(db: *Db) [*:0]const u8;
extern fn sqlite3_extended_errcode(db: *Db) c_int;
extern fn sqlite3_get_autocommit(db: *Db) c_int;
extern fn sqlite3_changes64(db: *Db) i64;
extern fn sqlite3_total_changes64(db: *Db) i64;
extern fn sqlite3_last_insert_rowid(db: *Db) i64;
extern fn sqlite3_sleep(ms: c_int) c_int;
extern fn sqlite3_set_authorizer(db: *Db, f: ?*const fn (?*anyopaque, c_int, ?[*:0]const u8, ?[*:0]const u8, ?[*:0]const u8, ?[*:0]const u8) callconv(.c) c_int, data: ?*anyopaque) c_int;
extern fn sqlite3_interrupt(db: *Db) void;
extern fn sqlite3_is_interrupted(db: *Db) c_int;
extern fn sqlite3_busy_handler(db: *Db, f: ?*const fn (?*anyopaque, c_int) callconv(.c) c_int, data: ?*anyopaque) c_int;
extern fn sqlite3_prepare_v2(db: *Db, sql: [*]const u8, n: c_int, stmt: *?*Stmt, tail: *?[*]const u8) c_int;
extern fn sqlite3_finalize(stmt: *Stmt) c_int;
extern fn sqlite3_step(stmt: *Stmt) c_int;
extern fn sqlite3_bind_parameter_count(stmt: *Stmt) c_int;
extern fn sqlite3_bind_null(stmt: *Stmt, i: c_int) c_int;
extern fn sqlite3_bind_int64(stmt: *Stmt, i: c_int, v: i64) c_int;
extern fn sqlite3_bind_double(stmt: *Stmt, i: c_int, v: f64) c_int;
extern fn sqlite3_bind_text(stmt: *Stmt, i: c_int, v: [*]const u8, n: c_int, d: Destructor) c_int;
extern fn sqlite3_bind_blob(stmt: *Stmt, i: c_int, v: [*]const u8, n: c_int, d: Destructor) c_int;
extern fn sqlite3_column_count(stmt: *Stmt) c_int;
extern fn sqlite3_column_name(stmt: *Stmt, i: c_int) ?[*:0]const u8;
extern fn sqlite3_column_type(stmt: *Stmt, i: c_int) c_int;
extern fn sqlite3_column_int64(stmt: *Stmt, i: c_int) i64;
extern fn sqlite3_column_double(stmt: *Stmt, i: c_int) f64;
extern fn sqlite3_column_text(stmt: *Stmt, i: c_int) ?[*]const u8;
extern fn sqlite3_column_blob(stmt: *Stmt, i: c_int) ?*const anyopaque;
extern fn sqlite3_column_bytes(stmt: *Stmt, i: c_int) c_int;
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@mygo-plugins/sqlite",
"version": "0.10.0",
"description": "Parameterized SQLite queries and transactions for MyGo desktop apps",
"keywords": [
"mygo",
"desktop",
"sqlite",
"go",
"zig"
],
"repository": {
"type": "git",
"url": "git+https://github.com/egoist/mygo.git",
"directory": "plugins/sqlite"
},
"license": "MIT",
"type": "module",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"types": "./dist/index.d.ts",
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"build": "bun run ../build.ts",
"test": "bun test"
},
"peerDependencies": {
"mygo-runtime": "^0.10.0"
},
"devDependencies": {
"mygo-runtime": "^0.10.0"
}
}
+232
View File
@@ -0,0 +1,232 @@
// Package sqlite is MyGo's SQLite plugin. SQLite runs in a native module
// written in Zig (internal/sqlitecore), published prebuilt for each
// platform: no cgo, Zig, Bun or compiler is needed to build or run an app.
//
// Register the plugin only when the web frontend uses @mygo-plugins/sqlite:
//
// mygo.Use(sqlite.Plugin)
//
// The frontend uses open from @mygo-plugins/sqlite. It opens named databases
// in the app's user-data directory, executes parameterized SQL, queries
// rows and runs batches in transactions. Go and native UI apps call Open
// directly and close their own connections; no mygo.Use is needed.
package sqlite
import (
"context"
"crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/egoist/mygo"
)
// Options configure the page plugin. Go's Open accepts its own path and
// OpenOptions and does not use these options.
type Options struct {
// Directory holds the page's database files, mygo.PathUserData when
// empty. Pages may open file names here, or ":memory:", not paths.
Directory string
// BusyTimeout follows OpenOptions.BusyTimeout.
BusyTimeout time.Duration
}
// Plugin is the page plugin with default options. It loads the native
// library only when a page opens its first database.
var Plugin = New(Options{})
// New returns a plugin with options. Connections belong to their page,
// close when it navigates away or its window closes, and close on app quit.
func New(opts Options) mygo.Plugin {
s := &service{opts: opts, dbs: map[key]*connection{}}
return mygo.Plugin{Name: "sqlite", Service: s, Setup: func() error {
mygo.App.OnQuit(s.shutdown)
return nil
}}
}
// key identifies a connection: by its page (a *mygo.Page), as a window
// may show several, those of its web views.
type key struct {
page any
id string
}
type connection struct {
db *DB
stop func() bool
page context.Context
}
type service struct {
opts Options
mu sync.Mutex
dbs map[key]*connection
closed bool
}
type openOptions struct {
ReadOnly bool `json:"readOnly"`
}
func (s *service) Open(ctx context.Context, name string, opts openOptions) (string, error) {
return s.open(ctx, mygo.CallerPage(ctx), name, opts)
}
func (s *service) Execute(ctx context.Context, id, sql string, args []wireValue) (wireResult, error) {
db, err := s.database(mygo.CallerPage(ctx), id)
if err != nil {
return wireResult{}, err
}
params, err := parameters(args)
if err != nil {
return wireResult{}, err
}
result, err := db.Execute(ctx, sql, params...)
return resultWire(result), err
}
func (s *service) Query(ctx context.Context, id, sql string, args []wireValue) (wireRows, error) {
db, err := s.database(mygo.CallerPage(ctx), id)
if err != nil {
return wireRows{}, err
}
params, err := parameters(args)
if err != nil {
return wireRows{}, err
}
rows, err := db.Query(ctx, sql, params...)
if err != nil {
return wireRows{}, err
}
return rowsWire(rows), nil
}
func (s *service) Transaction(ctx context.Context, id string, statements []wireStatement) ([]wireResult, error) {
db, err := s.database(mygo.CallerPage(ctx), id)
if err != nil {
return nil, err
}
batch := make([]Statement, len(statements))
for i, stmt := range statements {
args, err := parameters(stmt.Args)
if err != nil {
return nil, err
}
batch[i] = Statement{SQL: stmt.SQL, Args: args}
}
results, err := db.Transaction(ctx, batch)
if err != nil {
return nil, err
}
wire := make([]wireResult, len(results))
for i, result := range results {
wire[i] = resultWire(result)
}
return wire, nil
}
func (s *service) Close(ctx context.Context, id string) error {
return s.close(key{mygo.CallerPage(ctx), id})
}
func (s *service) open(ctx context.Context, page any, name string, opts openOptions) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
path := name
if name != ":memory:" {
if err := databaseName(name); err != nil {
return "", err
}
dir := s.opts.Directory
if dir == "" {
var err error
dir, err = mygo.App.Path(mygo.PathUserData)
if err != nil {
return "", err
}
}
if !opts.ReadOnly {
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
}
path = filepath.Join(dir, name)
if info, err := os.Lstat(path); err == nil && info.Mode()&os.ModeSymlink != 0 {
return "", errors.New("sqlite: database file may not be a symbolic link")
}
}
db, err := Open(ctx, path, OpenOptions{ReadOnly: opts.ReadOnly, BusyTimeout: s.opts.BusyTimeout})
if err != nil {
return "", err
}
id := rand.Text()
k := key{page, id}
s.mu.Lock()
if s.closed || ctx.Err() != nil {
s.mu.Unlock()
db.Close()
if err := ctx.Err(); err != nil {
return "", err
}
return "", ErrClosed
}
c := &connection{db: db, page: ctx}
s.dbs[k] = c
c.stop = context.AfterFunc(ctx, func() { _ = s.close(k) })
s.mu.Unlock()
return id, nil
}
func databaseName(name string) error {
if name == "" || name == "." || name == ".." || !utf8.ValidString(name) ||
strings.ContainsAny(name, "/\\\x00:<>\"|?*") || strings.TrimSpace(name) != name || strings.HasSuffix(name, ".") {
return errors.New("sqlite: use a database file name without directories, or :memory:")
}
// Windows device names remain reserved even with a file extension.
base, _, _ := strings.Cut(strings.ToUpper(name), ".")
if base == "CON" || base == "PRN" || base == "AUX" || base == "NUL" ||
(len(base) == 4 && (strings.HasPrefix(base, "COM") || strings.HasPrefix(base, "LPT")) && base[3] >= '1' && base[3] <= '9') {
return errors.New("sqlite: database file name is reserved on Windows")
}
return nil
}
func (s *service) database(page any, id string) (*DB, error) {
s.mu.Lock()
defer s.mu.Unlock()
c := s.dbs[key{page, id}]
if c == nil || c.page.Err() != nil {
return nil, fmt.Errorf("sqlite: database is closed or belongs to another page")
}
return c.db, nil
}
func (s *service) close(k key) error {
s.mu.Lock()
c := s.dbs[k]
delete(s.dbs, k)
s.mu.Unlock()
if c == nil {
return nil
}
c.stop()
return c.db.Close()
}
func (s *service) shutdown() {
s.mu.Lock()
s.closed = true
dbs := s.dbs
s.dbs = map[key]*connection{}
s.mu.Unlock()
for _, c := range dbs {
c.stop()
_ = c.db.Close()
}
}
+145
View File
@@ -0,0 +1,145 @@
package sqlite
import (
"context"
"encoding/json/v2"
"errors"
"math"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
func TestPluginBindings(t *testing.T) {
mygo.Use(New(Options{Directory: t.TempDir()}))
ts, err := mygo.GenerateTypeScript()
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(ts), "plugin:sqlite") {
t.Fatal("plugin leaked into generated client")
}
}
func TestPageOwnershipAndCleanup(t *testing.T) {
needSQLite(t)
s := New(Options{Directory: t.TempDir()}).Service.(*service)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
id, err := s.open(ctx, 1, ":memory:", openOptions{})
if err != nil {
t.Fatal(err)
}
db, err := s.database(1, id)
if err != nil {
t.Fatal(err)
}
if _, err := s.database(2, id); err == nil {
t.Fatal("another window got the connection")
}
if err := s.close(key{2, id}); err != nil {
t.Fatal(err)
}
execute(t, db, "CREATE TABLE items(n)")
cancel()
if _, err := s.database(1, id); err == nil {
t.Fatal("a canceled page retained access before asynchronous cleanup")
}
select {
case <-db.life.Done():
case <-time.After(wait.Guard):
t.Fatal("page navigation did not close connection")
}
if _, err := db.Query(context.Background(), "SELECT 1"); !errors.Is(err, ErrClosed) {
t.Fatal(err)
}
id, err = s.open(context.Background(), 1, ":memory:", openOptions{})
if err != nil {
t.Fatal(err)
}
db, _ = s.database(1, id)
s.shutdown()
if _, err := db.Query(context.Background(), "SELECT 1"); !errors.Is(err, ErrClosed) {
t.Fatal(err)
}
if _, err := s.open(context.Background(), 1, ":memory:", openOptions{}); !errors.Is(err, ErrClosed) {
t.Fatal(err)
}
}
func TestPageDatabaseNames(t *testing.T) {
for _, name := range []string{"", ".", "..", "../a.db", "/tmp/a.db", `C:\a.db`, `dir\a.db`, "a\x00b", "CON.db", "nul", "LPT1.db", "a.db.", " a.db", "file:other.db"} {
if err := databaseName(name); err == nil {
t.Errorf("accepted %q", name)
}
}
for _, name := range []string{"app.db", "中文.db", "company.db", "a-b.db"} {
if err := databaseName(name); err != nil {
t.Errorf("%q: %v", name, err)
}
}
dir := t.TempDir()
path := filepath.Join(dir, "link.db")
if err := os.Symlink(filepath.Join(t.TempDir(), "outside.db"), path); err == nil {
s := New(Options{Directory: dir}).Service.(*service)
if _, err := s.open(context.Background(), 1, "link.db", openOptions{}); err == nil || !strings.Contains(err.Error(), "symbolic link") {
t.Fatal(err)
}
}
}
func TestWireRoundTrip(t *testing.T) {
values := []any{nil, int64(-9223372036854775808), int64(9223372036854775807), 0.125, "中文\x00", []byte{0, 255}, []byte{}, "", float64(0)}
wire := rowsWire(Rows{Values: [][]any{values}})
data, err := json.Marshal(wire)
if err != nil {
t.Fatal(err)
}
var decoded wireRows
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
got, err := parameters(decoded.Rows[0])
if err != nil {
t.Fatal(err)
}
// Omitted empty BLOB fields decode as a nil []byte, still an empty BLOB.
got[6] = []byte{}
if !reflect.DeepEqual(got, values) {
t.Fatalf("got %#v, want %#v", got, values)
}
for _, value := range []wireValue{{Type: "integer", Integer: "9223372036854775808"}, {Type: "integer"}, {Type: "oops"}} {
if _, err := parameters([]wireValue{value}); err == nil {
t.Fatal("invalid value accepted", value)
}
}
}
func TestInfiniteQueryResult(t *testing.T) {
db := testDB(t, ":memory:")
rows := query(t, db, "SELECT 1e999, -1e999")
if !math.IsInf(rows.Values[0][0].(float64), 1) || !math.IsInf(rows.Values[0][1].(float64), -1) {
t.Fatal("lost SQLite's infinite REAL values", rows)
}
wire := rowsWire(rows)
data, err := json.Marshal(wire)
if err != nil {
t.Fatal(err)
}
var decoded wireRows
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Rows[0][0].Special != "Infinity" || decoded.Rows[0][1].Special != "-Infinity" {
t.Fatal(string(data))
}
if _, err := parameters(decoded.Rows[0]); err == nil {
t.Fatal("nonfinite parameters should still be rejected")
}
}
+95
View File
@@ -0,0 +1,95 @@
import { afterEach, expect, test } from "bun:test";
import { fakeGo } from "../../fake-go";
import { open } from "./index";
let go: ReturnType<typeof fakeGo> | undefined;
afterEach(() => go?.uninstall());
test("encodes parameters and decodes every SQLite storage class", async () => {
go = fakeGo({
"plugin:sqlite.Open": () => "db-1",
"plugin:sqlite.Query": () => ({
columns: ["n", "n", "big", "real", "text", "blob", "emptyBlob", "emptyText", "zero", "negative"],
rows: [[{ type: "null" }, { type: "integer", integer: "42" }, { type: "integer", integer: "9223372036854775807" },
{ type: "real", real: 0.25 }, { type: "text", text: "中文\0🙂" }, { type: "blob", blob: "AP8=" },
{ type: "blob" }, { type: "text" }, { type: "real" }, { type: "integer", integer: "-9223372036854775808" }]],
}),
});
const db = await open("app.db", { readOnly: true });
const blob = new Uint8Array([9, 0, 255, 9]).subarray(1, 3);
const rows = await db.query("SELECT ?, ?, ?, ?, ?, ?, ?, ?", [null, true, 42, -9223372036854775808n, 0.25, "中文\0🙂", blob, new Uint8Array()]);
expect(rows.columns.slice(0, 2)).toEqual(["n", "n"]);
expect(rows.rows[0]).toEqual([null, 42, 9223372036854775807n, 0.25, "中文\0🙂", new Uint8Array([0, 255]), new Uint8Array(), "", 0, -9223372036854775808n]);
expect(go.calls[0]).toEqual(["plugin:sqlite.Open", ["app.db", { readOnly: true }]]);
expect(go.calls[1]![1][2]).toEqual([
{ type: "null" }, { type: "integer", integer: "1" }, { type: "integer", integer: "42" },
{ type: "integer", integer: "-9223372036854775808" }, { type: "real", real: 0.25 },
{ type: "text", text: "中文\0🙂" }, { type: "blob", blob: "AP8=" }, { type: "blob", blob: "" },
]);
});
test("execute and transaction preserve rowids, and send a single atomic batch", async () => {
const reply = { changes: 1, lastInsertId: "9007199254740993" };
go = fakeGo({ "plugin:sqlite.Open": () => "db", "plugin:sqlite.Execute": () => reply, "plugin:sqlite.Transaction": () => [reply, reply] });
const db = await open(":memory:");
expect(await db.execute("INSERT", [false])).toEqual({ changes: 1, lastInsertId: 9007199254740993n });
expect(await db.transaction([{ sql: "INSERT", params: [1] }, { sql: "UPDATE" }])).toEqual([
{ changes: 1, lastInsertId: 9007199254740993n }, { changes: 1, lastInsertId: 9007199254740993n },
]);
expect(go.calls[2]).toEqual(["plugin:sqlite.Transaction", ["db", [{ sql: "INSERT", args: [{ type: "integer", integer: "1" }] }, { sql: "UPDATE", args: [] }]]]);
});
test("rejects unsafe parameters before making an IPC call", async () => {
go = fakeGo({ "plugin:sqlite.Open": () => "db" });
const db = await open(":memory:");
for (const param of [NaN, Infinity, -Infinity, Number.MAX_SAFE_INTEGER + 1, 1n << 63n, -(1n << 63n) - 1n]) {
await expect(db.execute("SELECT ?", [param])).rejects.toThrow("sqlite:");
}
await expect(db.transaction([{ sql: "SELECT 1" }, { sql: "SELECT ?", params: [NaN] }])).rejects.toThrow("finite");
expect(go.calls.length).toBe(1);
});
test("large BLOBs do not overflow the browser's argument stack", async () => {
go = fakeGo({ "plugin:sqlite.Open": () => "db", "plugin:sqlite.Execute": () => ({ changes: 0, lastInsertId: "0" }) });
const db = await open(":memory:");
const bytes = new Uint8Array(256 * 1024).fill(255);
await db.execute("SELECT ?", [bytes]);
const [arg] = go.calls[1]![1][2] as [{ blob: string }];
expect(atob(arg.blob).length).toBe(bytes.length);
});
test("close is idempotent and rejects further use", async () => {
go = fakeGo({ "plugin:sqlite.Open": () => "db", "plugin:sqlite.Close": () => undefined });
const db = await open(":memory:");
const a = db.close();
const b = db.close();
expect(a).toBe(b);
await expect(db.query("SELECT 1")).rejects.toThrow("closed");
await Promise.all([a, b]);
await db.close();
await expect(db.execute("SELECT 1")).rejects.toThrow("closed");
expect(go.calls.length).toBe(2);
});
test("propagates Go errors and permits retrying a failed close", async () => {
let attempts = 0;
go = fakeGo({
"plugin:sqlite.Open": () => "db",
"plugin:sqlite.Query": () => { throw new Error("sqlite: no such table"); },
"plugin:sqlite.Close": () => { if (++attempts === 1) throw new Error("close failed"); },
});
const db = await open(":memory:");
await expect(db.query("SELECT * FROM missing")).rejects.toThrow("no such table");
await expect(db.close()).rejects.toThrow("close failed");
await db.close();
expect(attempts).toBe(2);
});
test("decodes infinite REAL results without losing their SQLite type", async () => {
go = fakeGo({
"plugin:sqlite.Open": () => "db",
"plugin:sqlite.Query": () => ({ columns: ["positive", "negative"], rows: [[{ type: "real", special: "Infinity" }, { type: "real", special: "-Infinity" }]] }),
});
const db = await open(":memory:");
expect((await db.query("SELECT 1e999, -1e999")).rows).toEqual([[Infinity, -Infinity]]);
});
+114
View File
@@ -0,0 +1,114 @@
import { call } from "mygo-runtime";
/** SQLite values: integers beyond Number's safe range are returned as bigint. */
export type Value = null | number | bigint | string | Uint8Array;
/** Booleans bind as SQLite integers 0 and 1. */
export type Parameter = Value | boolean;
export interface OpenOptions { readOnly?: boolean }
export interface Result {
changes: number;
/** The last inserted rowid on this connection, without precision loss. */
lastInsertId: bigint;
}
/** Ordered columns and cells preserve duplicate column names. */
export interface Rows { columns: string[]; rows: Value[][] }
export interface Statement { sql: string; params?: readonly Parameter[] }
interface WireValue { type: string; integer?: string; real?: number; special?: "Infinity" | "-Infinity" | "NaN"; text?: string; blob?: string }
interface WireResult { changes: number; lastInsertId: string }
interface WireRows { columns: string[]; rows: WireValue[][] }
/** Opens a file name in the Go plugin's directory, or a private :memory: database. */
export async function open(name: string, options: OpenOptions = {}): Promise<Database> {
return Database.open(name, options);
}
/** A page-owned connection. It closes when the page navigates or the app quits. */
export class Database {
private closing?: Promise<void>;
private closed = false;
private constructor(private readonly id: string) {}
static async open(name: string, options: OpenOptions = {}): Promise<Database> {
const id = await call<string>("plugin:sqlite.Open", name, { readOnly: options.readOnly ?? false });
return new Database(id);
}
/** Executes exactly one statement. Use placeholders, never interpolate values. */
async execute(sql: string, params: readonly Parameter[] = []): Promise<Result> {
this.assertOpen();
return result(await call<WireResult>("plugin:sqlite.Execute", this.id, sql, params.map(encode)));
}
/** Queries one statement, including RETURNING; select a bounded page for large results. */
async query(sql: string, params: readonly Parameter[] = []): Promise<Rows> {
this.assertOpen();
const value = await call<WireRows>("plugin:sqlite.Query", this.id, sql, params.map(encode));
return { columns: value.columns, rows: value.rows.map((row) => row.map(decode)) };
}
/** Runs an atomic BEGIN IMMEDIATE batch. A failure rolls back every statement. */
async transaction(statements: readonly Statement[]): Promise<Result[]> {
this.assertOpen();
const batch = statements.map((stmt) => ({ sql: stmt.sql, args: (stmt.params ?? []).map(encode) }));
return (await call<WireResult[]>("plugin:sqlite.Transaction", this.id, batch)).map(result);
}
/** Closes this connection. Concurrent and repeated closes share the same call. */
close(): Promise<void> {
if (this.closed) return Promise.resolve();
if (!this.closing) {
this.closing = call<void>("plugin:sqlite.Close", this.id).then(
() => { this.closed = true; },
(error: unknown) => { this.closing = undefined; throw error; },
);
}
return this.closing;
}
private assertOpen(): void {
if (this.closed || this.closing) throw new Error("sqlite: database is closed");
}
}
function result(value: WireResult): Result {
return { changes: value.changes, lastInsertId: BigInt(value.lastInsertId) };
}
function encode(value: Parameter): WireValue {
if (value === null) return { type: "null" };
if (typeof value === "boolean") return { type: "integer", integer: value ? "1" : "0" };
if (typeof value === "bigint") {
if (value < -(1n << 63n) || value >= (1n << 63n)) throw new RangeError("sqlite: integer exceeds signed 64-bit range");
return { type: "integer", integer: String(value) };
}
if (typeof value === "number") {
if (!Number.isFinite(value)) throw new TypeError("sqlite: number must be finite");
if (Number.isInteger(value)) {
if (!Number.isSafeInteger(value)) throw new RangeError("sqlite: use bigint for integers outside Number's safe range");
return { type: "integer", integer: String(value) };
}
return { type: "real", real: value };
}
if (typeof value === "string") return { type: "text", text: value };
if (value instanceof Uint8Array) {
let text = "";
for (let i = 0; i < value.length; i += 8192) text += String.fromCharCode(...value.subarray(i, i + 8192));
return { type: "blob", blob: btoa(text) };
}
throw new TypeError("sqlite: unsupported parameter");
}
function decode(value: WireValue): Value {
switch (value.type) {
case "null": return null;
case "integer": {
const n = BigInt(value.integer!);
return n >= BigInt(Number.MIN_SAFE_INTEGER) && n <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(n) : n;
}
case "real": return Number(value.special ?? value.real ?? 0);
case "text": return value.text ?? "";
case "blob": return Uint8Array.from(atob(value.blob ?? ""), (c) => c.charCodeAt(0));
default: throw new TypeError(`sqlite: unknown value type ${value.type}`);
}
}
+43
View File
@@ -0,0 +1,43 @@
//go:build linux && !android && (amd64 || arm64) && !android
package sqlite
import (
"os"
"os/exec"
"reflect"
"testing"
"github.com/ebitengine/purego"
)
// The webview loads the system SQLite globally before the page uses the
// plugin. Run in a fresh process so other tests cannot preload our library
// and conceal symbol interposition between the two SQLite versions.
func TestSystemSQLiteLoadedFirst(t *testing.T) {
if testing.Short() {
t.Skip("requires the native plugin and system SQLite libraries")
}
const child = "MYGO_SQLITE_TEST_SYSTEM_FIRST"
if os.Getenv(child) != "1" {
cmd := exec.Command(os.Args[0], "-test.run=^TestSystemSQLiteLoadedFirst$", "-test.v")
cmd.Env = append(os.Environ(), child+"=1")
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("system SQLite loaded first: %v\n%s", err, output)
}
return
}
h, err := purego.Dlopen("libsqlite3.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
t.Skipf("system SQLite is unavailable: %v", err)
}
t.Cleanup(func() { _ = purego.Dlclose(h) })
db := testDB(t, ":memory:")
execute(t, db, "CREATE TABLE items (n INTEGER, real REAL, bytes BLOB)")
execute(t, db, "INSERT INTO items VALUES (?, ?, ?)", int64(42), 0.25, []byte{0, 255})
rows := query(t, db, "SELECT sqlite_version(), n, real, bytes FROM items")
want := []any{"3.53.4", int64(42), 0.25, []byte{0, 255}}
if !reflect.DeepEqual(rows.Values[0], want) {
t.Fatalf("query used another SQLite implementation: %#v", rows.Values[0])
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}
+95
View File
@@ -0,0 +1,95 @@
package sqlite
import (
"fmt"
"math"
"strconv"
)
// Every cell carries its SQLite storage class: JSON alone cannot distinguish
// BLOBs from text, or carry int64 without losing JavaScript precision.
type wireValue struct {
Type string `json:"type"`
Integer string `json:"integer,omitzero"`
Real float64 `json:"real,omitzero"`
Special string `json:"special,omitzero"`
Text string `json:"text,omitzero"`
Blob []byte `json:"blob,omitzero"`
}
type wireStatement struct {
SQL string `json:"sql"`
Args []wireValue `json:"args"`
}
type wireResult struct {
Changes int64 `json:"changes"`
LastInsertID string `json:"lastInsertId"`
}
type wireRows struct {
Columns []string `json:"columns"`
Rows [][]wireValue `json:"rows"`
}
func parameters(values []wireValue) ([]any, error) {
args := make([]any, len(values))
for i, value := range values {
switch value.Type {
case "null":
args[i] = nil
case "integer":
n, err := strconv.ParseInt(value.Integer, 10, 64)
if err != nil {
return nil, fmt.Errorf("sqlite: parameter %d: invalid signed 64-bit integer", i+1)
}
args[i] = n
case "real":
if value.Special != "" || math.IsNaN(value.Real) || math.IsInf(value.Real, 0) {
return nil, fmt.Errorf("sqlite: parameter %d: number must be finite", i+1)
}
args[i] = value.Real
case "text":
args[i] = value.Text
case "blob":
args[i] = value.Blob
default:
return nil, fmt.Errorf("sqlite: parameter %d: unknown value type %q", i+1, value.Type)
}
}
return args, nil
}
func resultWire(result Result) wireResult {
return wireResult{Changes: result.Changes, LastInsertID: strconv.FormatInt(result.LastInsertID, 10)}
}
func rowsWire(rows Rows) wireRows {
result := wireRows{Columns: rows.Columns, Rows: make([][]wireValue, len(rows.Values))}
for i, row := range rows.Values {
result.Rows[i] = make([]wireValue, len(row))
for j, cell := range row {
value := wireValue{Type: "null"}
switch v := cell.(type) {
case int64:
value.Type, value.Integer = "integer", strconv.FormatInt(v, 10)
case float64:
value.Type, value.Real = "real", v
if math.IsInf(v, 0) || math.IsNaN(v) {
value.Real = 0
switch {
case math.IsInf(v, 1):
value.Special = "Infinity"
case math.IsInf(v, -1):
value.Special = "-Infinity"
default:
value.Special = "NaN"
}
}
case string:
value.Type, value.Text = "text", v
case []byte:
value.Type, value.Blob = "blob", v
}
result.Rows[i][j] = value
}
}
return result
}