sqlite

package
v0.9.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT, MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

SQLite

SQLite for MyGo, with Go connections and the @mygo-plugins/sqlite TypeScript client. Its SQLite is a native module written in Zig (internal/sqlitecore), published prebuilt for each platform, so apps build without cgo, a C compiler or Zig.

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.

import (
    "github.com/egoist/mygo"
    "github.com/egoist/mygo/plugins/sqlite"
)

func main() {
    mygo.Use(sqlite.Plugin)
    // Create windows, then call mygo.App.Run().
}
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 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:

# 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.

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.

Documentation

Overview

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.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("sqlite: database is closed")

ErrClosed is returned when an operation uses a closed database.

View Source
var Plugin = New(Options{})

Plugin is the page plugin with default options. It loads the native library only when a page opens its first database.

Functions

func Load

func Load() error

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 New

func New(opts Options) mygo.Plugin

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.

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

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.

func Open

func Open(ctx context.Context, path string, opts OpenOptions) (*DB, error)

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 (*DB) Close

func (d *DB) Close() error

Close cancels in-flight operations, waits for their statements to be finalized, and closes the connection. Repeated calls are harmless.

func (*DB) Execute

func (d *DB) Execute(ctx context.Context, sql string, args ...any) (result Result, err error)

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 (*DB) Query

func (d *DB) Query(ctx context.Context, sql string, args ...any) (rows Rows, err error)

Query runs exactly one statement and copies its rows. It also supports statements with RETURNING. For large results, select a bounded page.

func (*DB) Transaction

func (d *DB) Transaction(ctx context.Context, statements []Statement) (results []Result, err error)

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.

type Error

type Error struct {
	Code         int
	ExtendedCode int
	Message      string
}

Error is an SQLite error. Code is the primary result code; ExtendedCode distinguishes such errors as unique, foreign-key and not-null constraints.

func (*Error) Error

func (e *Error) Error() string

type OpenOptions

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
}

OpenOptions configure a connection. Foreign keys are enabled by default.

type 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
}

Options configure the page plugin. Go's Open accepts its own path and OpenOptions and does not use these options.

type Result

type Result struct {
	Changes      int64 `json:"changes"`
	LastInsertID int64 `json:"lastInsertId"`
}

Result describes a statement. Changes counts directly affected rows; LastInsertID is SQLite's last inserted rowid on this connection.

type Rows

type Rows struct {
	Columns []string `json:"columns"`
	Values  [][]any  `json:"rows"`
}

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 Statement

type Statement struct {
	SQL  string
	Args []any
}

Statement is one parameterized statement in a transaction.

Directories

Path Synopsis
internal
sqlitecore
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 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL