sqlitebridge

package
v0.0.0-...-e628794 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package sqlitebridge wraps the vendored SQLite amalgamation via cgo.

Index

Constants

View Source
const (
	ResultOK         = int(C.SQLITE_OK)
	ResultError      = int(C.SQLITE_ERROR)
	ResultBusy       = int(C.SQLITE_BUSY)
	ResultLocked     = int(C.SQLITE_LOCKED)
	ResultFull       = int(C.SQLITE_FULL)
	ResultMisuse     = int(C.SQLITE_MISUSE)
	ResultConstraint = int(C.SQLITE_CONSTRAINT)
	ResultRow        = int(C.SQLITE_ROW)
	ResultDone       = int(C.SQLITE_DONE)
	ResultInterrupt  = int(C.SQLITE_INTERRUPT)
)
View Source
const DefaultOpenFlags = OpenReadWrite | OpenCreate | OpenURI | OpenNoMutex

DefaultOpenFlags is the recommended flag set for syzy connections: read/write, create-if-missing, URI-style filenames enabled, no per-connection mutex (callers serialize per Conn — see the Conn doc).

View Source
const ResultConstraintCommitHook = int(C.SQLITE_CONSTRAINT_COMMITHOOK)

ResultConstraintCommitHook is the extended code for a commit rejected by the registered commit hook — for syzy, a coordinated-UNIQUE reservation that conflicted or whose backend was unavailable. Higher layers can attach a distinct Go cause with SetCommitHookCause while retaining this SQLite result code.

Variables

This section is empty.

Functions

func ColumnExists

func ColumnExists(conn *Conn, table, col string) (bool, error)

ColumnExists reports whether pragma_table_info(table) yields a row whose name matches col. Cheaper and less fragile than parsing the table's CREATE statement.

func Complete

func Complete(sql string) bool

Complete reports whether sql ends with a complete SQL statement, per sqlite3_complete's lexical rules (a statement is complete at a semicolon that is not inside a string, comment, or trigger BEGIN...END body).

func FirstStatement

func FirstStatement(sql string) (stmt string, consumed int)

FirstStatement returns the first complete SQL statement in sql (including its terminating ';') and the byte offset where the remainder begins. When sql holds no top-level ';' — the common single-statement case — the whole input is returned with consumed == len(sql).

Candidate ';' positions come from a quote/comment-aware scan; each candidate prefix is verified with sqlite3_complete, which is what keeps a ';' inside a trigger body from splitting the statement. Each Complete call copies its prefix, so a statement with many interior ';' candidates (a trigger body) costs O(len²) in that statement's length — fine for the DDL-sized inputs this serves; don't point it at megabyte trigger bodies.

The lexical skippers below deliberately parallel the ones in internal/producer/ddl_parse.go (which scans inside a single statement for column spans); they answer different questions over the same token grammar, and producer's are private to its parser.

func IsCode

func IsCode(err error, code int) bool

IsCode reports whether err wraps a sqlitebridge.Error with the given primary or extended SQLite result code.

func IsVirtualTable

func IsVirtualTable(conn *Conn, name string) (bool, error)

IsVirtualTable reports whether name is a module-backed virtual table. Shadow tables are ordinary tables and do not match.

func LibVersion

func LibVersion() string

LibVersion returns the linked SQLite version string (e.g. "3.53.0").

func LibVersionNumber

func LibVersionNumber() int

LibVersionNumber returns the linked SQLite version as an integer (major*1_000_000 + minor*1_000 + patch). 3.53.0 → 3_053_000.

func ObjectExists

func ObjectExists(conn *Conn, kind, name string) (bool, error)

ObjectExists reports whether sqlite_master has a row of the given type ("table" | "index" | "view" | "trigger") with the given name. Used by callers that need to gate DDL replay on the current state of the catalog without parsing the SQL.

func OpenDB

func OpenDB(conn *Conn) *sql.DB

OpenDB returns a *sql.DB backed by a single *Conn. The pool is pinned to one connection (MaxOpenConns=1) so every database/sql operation routes through the producer-hooked conn the caller passed in. The caller retains ownership of the Conn; closing the *sql.DB is a no-op against the underlying Conn.

Callers must not widen the pool with SetMaxOpenConns(n>1): a second Connect call returns driver.ErrBadConn, which database/sql surfaces as a connection error rather than serializing. The pinned-conn contract is fundamental to the design: the producer's preupdate hooks are bound to one Conn.

func OpenReadPool

func OpenReadPool(path string, n int) (*sql.DB, error)

OpenReadPool returns a *sql.DB backed by up to n independent READ-ONLY connections to path, for concurrent reads that must not serialize behind the single producer-hooked writer Conn (see OpenDB). In WAL mode these readers run concurrently with each other and with the writer, reading the last committed snapshot. Each pooled connection owns and closes its own *Conn when database/sql retires it. Read-only by construction: the connections carry no producer hooks, so only SELECTs may route here — writes and transactions still go through the OpenDB writer.

A read-only WAL reader requires a concurrent read-write connection to have initialized the -shm; callers must keep that writer open on the same file.

func OpenReadPoolWithOptions

func OpenReadPoolWithOptions(path string, n int, opts ReadPoolOptions) (*sql.DB, error)

OpenReadPoolWithOptions is OpenReadPool with per-connection setup.

func QuoteIdent

func QuoteIdent(name string) string

QuoteIdent wraps name in double quotes per SQLite identifier rules, escaping embedded quotes by doubling.

func RegisterChangesVTab

func RegisterChangesVTab(c *Conn, feedPath string, provider ChangesProvider) error

RegisterChangesVTab installs the eponymous "syzy_changes" virtual table and its companion scalar functions on c. feedPath must point to the writer-created notify feed (typically notify.FeedPath(appPath)).

The notify Reader is opened eagerly so events between registration and the first SELECT are captured. If the feed file doesn't exist yet (auto-spawned daemon still starting), the Reader is left nil and xFilter retries on first SELECT, surfacing a clear error if it's still missing.

provider supplies syzy_my_origin and syzy_pk_decode behaviours; pass nil to register the vtab without the scalars (linked-mode tests).

Types

type Backup

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

Backup wraps a sqlite3_backup* and copies pages from a source Conn to a destination Conn. One Backup serves one source/destination pair; callers must Finish before reusing either connection for other work.

Concurrency: backup_step takes a brief writer-lock on the source per step, so concurrent writers on the source remain unblocked between steps. If the source is modified between steps, SQLite restarts the affected pages internally.

func BackupInit

func BackupInit(dst *Conn, dstSchema string, src *Conn, srcSchema string) (*Backup, error)

BackupInit prepares a page-copy from src.dbName ("main", "temp", or an attached schema) into dst.dbName. nil error + non-nil *Backup on success.

func (*Backup) Finish

func (b *Backup) Finish() error

Finish releases the backup handle. Must be called exactly once per successful BackupInit. Returns the deferred error from any Step that failed (including the SQLITE_BUSY/SQLITE_LOCKED retryables); a final SQLITE_OK from Finish means every step succeeded. Idempotent.

func (*Backup) PageCount

func (b *Backup) PageCount() int

PageCount returns the total number of source pages, as observed at the most recent Step. Zero before the first step.

func (*Backup) Remaining

func (b *Backup) Remaining() int

Remaining returns the number of source pages still to copy, as observed at the most recent Step.

func (*Backup) Step

func (b *Backup) Step(nPage int) error

Step copies up to nPage pages. Returns io.EOF after the final page is copied (analog of SQLITE_DONE). Pass nPage <= 0 to copy every remaining page in one go.

type Blob

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

Blob is a handle returned by Conn.OpenBlob; it wraps sqlite3_blob* for incremental BLOB I/O. Used by the blob_patch capture path (read-only, NEW bytes post-commit) and by the apply path (read-write, sqlite3_blob_write).

func (*Blob) Bytes

func (b *Blob) Bytes() int

Bytes returns the byte size of the blob.

func (*Blob) Close

func (b *Blob) Close() error

Close releases the handle. Idempotent.

func (*Blob) Read

func (b *Blob) Read(p []byte, off int) error

Read reads len(p) bytes from offset off into p.

func (*Blob) Reopen

func (b *Blob) Reopen(rowid int64) error

Reopen redirects the handle to (same column on) a different rowid. Cheaper than Close + OpenBlob when iterating rows.

func (*Blob) Write

func (b *Blob) Write(p []byte, off int) error

Write writes len(p) bytes from p at offset off.

type ChangesProvider

type ChangesProvider interface {
	Origin() uint64
	DecodePK(table string, pk []byte) (string, bool)
}

ChangesProvider supplies the per-connection extras the syzy_changes vtab and its companion scalars need: the connection's own origin (for syzy_my_origin) and a PK decoder keyed by table name (for syzy_pk_decode). Implementations must be safe for concurrent reads.

The extension shim implements this; the linked binary's tests can pass nil to register the vtab without the scalars.

type ColumnType

type ColumnType int

ColumnType matches SQLITE_INTEGER/FLOAT/TEXT/BLOB/NULL.

const (
	ColumnInt  ColumnType = C.SQLITE_INTEGER
	ColumnReal ColumnType = C.SQLITE_FLOAT
	ColumnText ColumnType = C.SQLITE_TEXT
	ColumnBlob ColumnType = C.SQLITE_BLOB
	ColumnNull ColumnType = C.SQLITE_NULL
)

type CommitHook

type CommitHook func() int

CommitHook is invoked on COMMIT before the change becomes durable. Return nonzero to convert the COMMIT into a ROLLBACK; SQLite surfaces this to the app as SQLITE_CONSTRAINT_COMMITHOOK.

type Conn

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

Conn wraps a sqlite3* handle.

Conn is not safe for concurrent use. Callers must serialize per-connection access. We compile SQLite with SQLITE_THREADSAFE=2 (multi-threaded mode) and open with SQLITE_OPEN_NOMUTEX, so this isolation is the caller's responsibility.

func Open

func Open(path string, flags OpenFlag) (*Conn, error)

Open returns a new Conn against path (which may be a SQLite URI when OpenURI is set). flags=0 selects DefaultOpenFlags.

func WrapHandle

func WrapHandle(p unsafe.Pointer) (*Conn, error)

WrapHandle adopts an existing *sqlite3 handle (passed as an unsafe.Pointer to keep this header free of cgo types). The returned Conn does NOT own the handle's lifecycle — Release tears down our per-conn state without calling sqlite3_close. Used by the loadable-extension shim where the host SQLite owns the handle and the extension only attaches hooks to it.

func (*Conn) AppendBlobIntent

func (c *Conn) AppendBlobIntent(dbName, table, column string, rowid int64, offset uint64, length uint32)

AppendBlobIntent appends a SYZY_OP_BLOB_INTENT record to the touch journal: the (table, column, rowid, offset, length) the caller is about to write via sqlite3_blob_write. The drainer reads NEW bytes for the recorded range from the post-commit DB. dbName "" defaults to "main".

func (*Conn) BlobWriteAt

func (c *Conn) BlobWriteAt(table, column string, rowid int64, offset int, data []byte) error

BlobWriteAt writes data at offset on (table, column, rowid) in the "main" schema as a syzy-compact blob-write: append a BLOB_INTENT to the touch journal and silence the preupdate trampoline's OLD-image emission so peers receive intent-only, not a full OLD/NEW row image. The row must already exist with the column allocated to at least offset+len(data) bytes; growing the column is the caller's job (see the SuppressDMLCapture-wrapped UPDATE pattern in syzy.Tx.BlobWriteAt- Extending and the SyzyFS adapter).

func (*Conn) Changes

func (c *Conn) Changes() int64

Changes returns the number of rows modified by the most recent INSERT, UPDATE, or DELETE on this connection (sqlite3_changes64).

func (*Conn) ClearTouchJournal

func (c *Conn) ClearTouchJournal()

ClearTouchJournal resets the journal byte length to zero (and clears the truncation flag) without freeing the underlying buffer.

func (*Conn) Close

func (c *Conn) Close() error

Close releases the connection's resources. Safe to call multiple times.

func (*Conn) DisableTouchJournal

func (c *Conn) DisableTouchJournal()

DisableTouchJournal stops auto-capture. The buffer persists for read-out until ClearTouchJournal or Close. Re-enabling resumes appending after the existing contents.

func (*Conn) EnableTouchJournal

func (c *Conn) EnableTouchJournal()

EnableTouchJournal turns on auto-capture of preupdate fires into the connection's C-side journal buffer. Each fire is appended without crossing cgo. Read with TouchJournal/TouchJournalLen and reset with ClearTouchJournal. Rollback automatically clears the buffer.

The journal records, per fire:

  • 1 byte op (SQLITE_INSERT=18, SQLITE_UPDATE=23, SQLITE_DELETE=9)
  • 8 bytes rowid_old (big-endian int64)
  • 8 bytes rowid_new (big-endian int64)
  • 2 bytes db_name length (big-endian uint16) + UTF-8 bytes
  • 2 bytes table_name length (big-endian uint16) + UTF-8 bytes
  • 2 bytes column_count (big-endian uint16)
  • column_count values (1 byte type tag {0=null,1=int,2=real,3=text,4=blob} plus 8 bytes for int/real or 4-byte length + bytes for text/blob).
  • For UPDATE only: an additional column_count values section with the post-DML NEW values (same encoding).

INSERT records NEW values. DELETE records OLD values. UPDATE records both OLD then NEW. Independent of any Go preupdate callback installed via SetPreupdateHook.

func (*Conn) EnableWALFrameCapture

func (c *Conn) EnableWALFrameCapture()

EnableWALFrameCapture keeps a wal_hook trampoline installed on this connection even with no callback registered, so TakeCommitWALFrames can report the frame count of the connection's own commits — recorded by SQLite inside the committing writer's locked region, the only race-free way to tell a WAL-restarting commit (count reset) from an appending one. Installing a wal_hook displaces SQLite's wal_autocheckpoint and vice versa, so enable this after autocheckpoint is configured; mind SetWALCheckpointThreshold for the trampoline's own backstop.

func (*Conn) Exec

func (c *Conn) Exec(sql string) error

Exec runs one or more SQL statements with no parameter binding and no result rows. It is appropriate for DDL, pragmas, and other administrative SQL. Use Prepare/Step for queries that bind parameters or read columns.

func (*Conn) InAutocommit

func (c *Conn) InAutocommit() bool

InAutocommit reports whether the connection is in autocommit mode (no open transaction). Used by trace_v2 to reject DDL inside explicit BEGIN / SAVEPOINT.

func (*Conn) Interrupt

func (c *Conn) Interrupt()

Interrupt aborts any in-progress operation on the connection. Returns when SQLite acknowledges the interrupt request; the affected statement returns SQLITE_INTERRUPT to its caller. No-op when the connection is already closed; matches the nil-safety of Close / Release.

func (*Conn) LastInsertRowID

func (c *Conn) LastInsertRowID() int64

LastInsertRowID returns the rowid of the most recent successful INSERT on this connection (sqlite3_last_insert_rowid).

func (*Conn) OpenBlob

func (c *Conn) OpenBlob(dbName, table, column string, rowid int64, writable bool) (*Blob, error)

OpenBlob opens an incremental BLOB handle on (dbName, table, column, rowid). dbName "" defaults to "main". writable=true requests read-write; false is read-only.

func (*Conn) Prepare

func (c *Conn) Prepare(sql string) (stmt *Stmt, tail string, err error)

Prepare compiles a single SQL statement. Returns the compiled statement and the leftover tail (text past the first terminating semicolon). For multi-statement SQL, call Prepare in a loop, feeding each tail back in.

If sql contains only whitespace or comments, both stmt and err are nil and tail is the empty string.

func (*Conn) PreprocessSQL

func (c *Conn) PreprocessSQL(sql string) (string, error)

PreprocessSQL runs the installed preprocessor on sql and returns the result. Used by the loadable-extension prepare interposer, where the host app's sqlite3_prepare* calls bypass this package's Prepare/Exec and the rewrite has to be applied from the interposition shim instead. Returns sql unchanged when no preprocessor is installed.

func (*Conn) QueryInt64Row

func (c *Conn) QueryInt64Row(sql string) ([]int64, error)

QueryInt64Row executes sql and returns the integer columns of its first row. For statements like PRAGMA wal_checkpoint or PRAGMA data_version whose result is one row of integers.

func (*Conn) ReassertWALHook

func (c *Conn) ReassertWALHook()

ReassertWALHook re-installs the registered wal_hook trampoline.

Needed by the loadable-extension shim: sqlite3's openDatabase calls sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT) AFTER sqlite3AutoLoadExtensions, and wal_autocheckpoint registers SQLite's internal checkpoint wal_hook — silently clobbering the producer wal_hook an auto-loaded attach just installed. Without the re-assert, an autoloaded producer journals nothing and never resolves DDL intents. The shim's open interposers call this after the real open returns. No-op when no wal hook is registered. (Checkpointing stays covered: the producer trampoline runs a PASSIVE checkpoint past SYZY_WAL_CHECKPOINT_THRESHOLD frames.)

func (*Conn) RecycleCommit

func (c *Conn) RecycleCommit(validate func() error) (int64, error)

RecycleCommit runs the coordinated WAL-recycle write bracket (ltxstream.CheckpointHooks.Recycle): BEGIN IMMEDIATE, validate() (rolled back on failure), a same-value PRAGMA user_version rewrite — a minimal commit dirtying page 1, which invites SQLite to restart a fully-backfilled WAL — then COMMIT, returning the frame count recorded for that commit (see TakeCommitWALFrames; requires EnableWALFrameCapture or another wal_hook on this connection). The write lock held from BEGIN IMMEDIATE keeps validate's observation true through the commit.

The caller owns the Conn's cross-goroutine serialization for the whole bracket. In particular, if the Conn sits behind an OpenDB pool, run the bracket with the pooled connection checked out ((*sql.Conn).Raw): database/sql reads serialize only on that checkout, and interleaving one with the bracket is undefined behavior on a NOMUTEX connection.

func (*Conn) Release

func (c *Conn) Release() error

Release tears down per-conn syzy state (touch journal, hooks, gen_id state) WITHOUT calling sqlite3_close_v2 on the handle. Pair with WrapHandle. Idempotent.

func (*Conn) SetCommitHook

func (c *Conn) SetCommitHook(fn CommitHook)

SetCommitHook registers fn as the commit hook. Pass nil to clear.

func (*Conn) SetCommitHookCause

func (c *Conn) SetCommitHookCause(err error)

SetCommitHookCause attaches a Go cause to the next SQLITE_CONSTRAINT_COMMITHOOK returned by this connection. A commit hook that returns nonzero may call this first to preserve a distinction SQLite's integer hook result cannot encode. Passing nil clears a pending cause.

func (*Conn) SetPreupdateHook

func (c *Conn) SetPreupdateHook(fn PreupdateHook)

SetPreupdateHook registers fn. Pass nil to clear.

func (*Conn) SetProducerWALHook

func (c *Conn) SetProducerWALHook(fn ProducerWALHook)

SetProducerWALHook installs a specialized wal_hook that reads + clears the C-side touch journal in the trampoline and hands the data slice directly to fn — eliminating the TouchJournalTake cgo crossing the regular SetWALHook + TouchJournalTake pair would otherwise need.

Mutually exclusive with SetWALHook on the same connection (the last installer wins). Pass nil to clear and revert to no wal_hook.

func (*Conn) SetRollbackHook

func (c *Conn) SetRollbackHook(fn RollbackHook)

SetRollbackHook registers fn. Pass nil to clear.

func (*Conn) SetSQLPreprocessor

func (c *Conn) SetSQLPreprocessor(fn SQLPreprocessor)

SetSQLPreprocessor installs (or with nil, clears) a preprocessor that transforms SQL text before Prepare / Exec submit it to SQLite. The rewritten string is what SQLite compiles and what flows back through the trace hook on first Step, so any downstream classifier sees the rewritten form. Invocations are serialized by the per-Conn single- writer contract.

func (*Conn) SetTraceHook

func (c *Conn) SetTraceHook(mask TraceEvent, fn TraceHook)

SetTraceHook registers fn for events matching mask. Pass fn=nil to clear.

func (*Conn) SetWALCheckpointThreshold

func (c *Conn) SetWALCheckpointThreshold(n int)

SetWALCheckpointThreshold overrides the WAL frame count at which this connection's wal_hook trampolines run their backstop PASSIVE checkpoint (the auto-checkpoint replacement that sqlite3_wal_hook displaces). n == 0 restores the built-in default; n < 0 disables the backstop for embedders that own WAL bounding themselves (e.g. a publisher's coordinated recycle, which an uncoordinated backfill would force to rebaseline).

func (*Conn) SetWALHook

func (c *Conn) SetWALHook(fn WALHook)

SetWALHook registers fn. Pass nil to clear.

func (*Conn) SuppressBlobCapture

func (c *Conn) SuppressBlobCapture(on bool)

SuppressBlobCapture toggles the per-conn flag that tells the preupdate trampoline to skip the OLD-image SYZY_OP_BLOB_WRITE branch for the next sqlite3_blob_write fire(s). Use to wrap a Syzy-owned blob_write call paired with AppendBlobIntent: the wrapper records compact intent in the touch journal and the preupdate fire is silenced. Counter semantics — pair Suppress(true) with Suppress(false).

func (*Conn) SuppressDMLCapture

func (c *Conn) SuppressDMLCapture(on bool)

SuppressDMLCapture toggles the per-conn flag that tells the preupdate trampoline to skip the regular OLD/NEW row-image emission for the next ordinary DML fires. Use to silence captures for trusted writers whose effect on peers is communicated via a paired journal record — SyzyFS wraps its `data || zeroblob(...)` chunk-extension UPDATE so the journal carries only the BlobWriteAt's BLOB_INTENT and the receiver's ensureBlobLen rederives the extension. Counter semantics — pair Suppress(true) with Suppress(false).

func (*Conn) TakeCommitWALFrames

func (c *Conn) TakeCommitWALFrames() int64

TakeCommitWALFrames returns the WAL frame count recorded for this connection's most recent committed write and clears it. 0 means no commit fired the connection's wal_hook since the last take (nothing committed, or no trampoline installed — see EnableWALFrameCapture).

func (*Conn) TouchJournal

func (c *Conn) TouchJournal() []byte

TouchJournal returns a slice aliasing the C-side journal buffer. The slice is valid only until the next preupdate fire or call to ClearTouchJournal — both of which mutate the buffer underneath. Callers that need ownership past those points must copy.

The producer's wal_hook hot path consumes the slice immediately by passing it to journal.Append (which copies into the mmap), then calls ClearTouchJournal — so aliasing is safe and skips the C.GoBytes allocation that a defensive copy would force.

func (*Conn) TouchJournalCopy

func (c *Conn) TouchJournalCopy() []byte

TouchJournalCopy returns a Go-owned copy of the current journal bytes. Use this when the caller needs the slice to outlive the next preupdate fire or ClearTouchJournal call. Empty slice if the journal is empty or never enabled.

func (*Conn) TouchJournalEnabled

func (c *Conn) TouchJournalEnabled() bool

TouchJournalEnabled reports whether auto-capture is currently on.

func (*Conn) TouchJournalLen

func (c *Conn) TouchJournalLen() int

TouchJournalLen returns the current journal byte length without copying.

func (*Conn) TouchJournalTake

func (c *Conn) TouchJournalTake() []byte

TouchJournalTake returns a slice aliasing the C-side journal buffer AND clears the buffer in a single cgo crossing. Use this on hot paths that would otherwise call TouchJournal followed by ClearTouchJournal — combining them eliminates two cgo crossings (syzy_journal_len and syzy_journal_clear) per commit.

The returned slice is valid until the next preupdate fire writes into the buffer. The producer's wal_hook is safe because SQLite cannot fire another preupdate until the hook returns.

func (*Conn) TouchJournalTruncated

func (c *Conn) TouchJournalTruncated() bool

TouchJournalTruncated reports whether any append since the last clear hit an OOM and dropped data. Consumers should treat the buffer as suspect when this returns true and recover via the same mechanism as a metadata I/O failure (rollback + retry, or process exit + prepared recovery).

type Error

type Error struct {
	Code     int
	Extended int
	Msg      string
}

Error wraps a SQLite result code and message. Code holds the primary or extended SQLite result code as documented at <https://sqlite.org/rescode.html>. Extended holds the extended result code when the connection reported one refining Code (else it equals Code) — e.g. SQLITE_CONSTRAINT_COMMITHOOK vs SQLITE_CONSTRAINT_UNIQUE, which Code alone merges as SQLITE_CONSTRAINT.

func (Error) Error

func (e Error) Error() string

type OpenFlag

type OpenFlag int

OpenFlag selects bits in the SQLITE_OPEN_* family. Combine with bitwise OR.

type PinnedConn

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

PinnedConn is the driver.Conn database/sql sees for an OpenDB pool. Exported so callers can recover the underlying *Conn via (*sql.Conn).Raw to reach Conn-level APIs (OpenBlob, AppendBlobIntent, etc.) inside a transaction. Close returns the pinned conn to the connector's pool; it does not close the underlying *Conn.

func (*PinnedConn) Begin

func (c *PinnedConn) Begin() (driver.Tx, error)

func (*PinnedConn) Close

func (c *PinnedConn) Close() error

func (*PinnedConn) Conn

func (c *PinnedConn) Conn() *Conn

Conn returns the underlying *Conn. Valid until the PinnedConn is closed by database/sql.

func (*PinnedConn) Prepare

func (c *PinnedConn) Prepare(query string) (driver.Stmt, error)

type PreupdateEvent

type PreupdateEvent struct {
	Op        PreupdateOp
	DBName    string
	TableName string
	OldRowID  int64
	NewRowID  int64
	// contains filtered or unexported fields
}

PreupdateEvent describes a row mutation about to commit. The accessor methods are valid only for the duration of the callback — do not retain the event past return.

func (*PreupdateEvent) BlobWrite

func (e *PreupdateEvent) BlobWrite() int

BlobWrite returns the column index whose blob is being mutated by an in-progress sqlite3_blob_write, or -1 for ordinary DML.

func (*PreupdateEvent) Count

func (e *PreupdateEvent) Count() int

Count returns the number of columns in the row being mutated.

func (*PreupdateEvent) Depth

func (e *PreupdateEvent) Depth() int

Depth returns the trigger-nesting depth (0 for direct DML; >0 inside a trigger or cascading FK).

type PreupdateHook

type PreupdateHook func(*PreupdateEvent)

PreupdateHook fires once per direct DML row before the txn commits.

type PreupdateOp

type PreupdateOp int

PreupdateOp identifies the kind of row mutation visible to the preupdate hook.

const (
	PreupdateInsert PreupdateOp = C.SQLITE_INSERT
	PreupdateUpdate PreupdateOp = C.SQLITE_UPDATE
	PreupdateDelete PreupdateOp = C.SQLITE_DELETE
)

type ProducerWALHook

type ProducerWALHook func(touchData []byte, nFrame int) int

ProducerWALHook is the specialized callback signature for SetProducerWALHook. touchData aliases the connection's touch journal buffer and is valid for the duration of the call. nFrame is the WAL frame count delivered by SQLite. Returning non-zero aborts the WAL pipeline (avoid in steady state).

type ReadPoolOptions

type ReadPoolOptions struct {
	// Pragmas runs on every new read connection after the built-in
	// busy_timeout, to match the writer's I/O settings.
	Pragmas string
}

ReadPoolOptions tunes the connections OpenReadPool opens.

type RollbackHook

type RollbackHook func()

RollbackHook fires after a ROLLBACK. Return value is ignored.

type SQLPreprocessor

type SQLPreprocessor func(sql string) (string, error)

SQLPreprocessor is an optional per-Conn hook that rewrites SQL text before Prepare / Exec hand it to SQLite. A non-nil error short- circuits Prepare / Exec with that error. The producer uses this hook to rewrite rowid-alias DDL into a multi-writer-safe shape; see internal/producer/ddl_rewrite.go.

type Stmt

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

Stmt wraps a sqlite3_stmt*. Like Conn, Stmt is not safe for concurrent use.

func (*Stmt) BindBlob

func (s *Stmt) BindBlob(i int, v []byte) error

BindBlob binds raw bytes. A nil/empty slice binds as a zero-length BLOB (x”), not NULL — sqlite3_bind_blob with a NULL pointer binds SQL NULL regardless of length, so the empty case routes through a non-NULL sentinel. Use BindNull to bind a SQL NULL.

func (*Stmt) BindFloat64

func (s *Stmt) BindFloat64(i int, v float64) error

BindFloat64 binds an IEEE-754 double.

func (*Stmt) BindInt64

func (s *Stmt) BindInt64(i int, v int64) error

BindInt64 binds a 64-bit integer.

func (*Stmt) BindNull

func (s *Stmt) BindNull(i int) error

BindNull binds NULL to the i-th parameter (1-based).

func (*Stmt) BindParamCount

func (s *Stmt) BindParamCount() int

BindParamCount returns the number of parameter placeholders (?, ?n, :n, $n) in the prepared statement.

func (*Stmt) BindText

func (s *Stmt) BindText(i int, v string) error

BindText binds a UTF-8 string. The empty string binds as TEXT ” (not NULL); use BindNull to bind a SQL NULL.

func (*Stmt) ClearBindings

func (s *Stmt) ClearBindings() error

ClearBindings resets all bound parameters to NULL.

func (*Stmt) ColumnBlob

func (s *Stmt) ColumnBlob(i int) []byte

ColumnBlob returns a copy of the i-th column's raw bytes. The result is owned by the caller and survives Reset/Step/Finalize.

func (*Stmt) ColumnCount

func (s *Stmt) ColumnCount() int

ColumnCount returns the number of result columns produced by the statement.

func (*Stmt) ColumnDecltype

func (s *Stmt) ColumnDecltype(i int) string

ColumnDecltype returns the declared type of the i-th column from the table that produced it (e.g. "DATETIME", "INTEGER"). For expression columns or sub-selects without a corresponding table column, returns the empty string. Wraps sqlite3_column_decltype.

func (*Stmt) ColumnFloat64

func (s *Stmt) ColumnFloat64(i int) float64

ColumnFloat64 returns the i-th column as a double.

func (*Stmt) ColumnInt64

func (s *Stmt) ColumnInt64(i int) int64

ColumnInt64 returns the i-th column of the current row as int64. Type coercions follow SQLite's standard rules.

func (*Stmt) ColumnIsNull

func (s *Stmt) ColumnIsNull(i int) bool

ColumnIsNull reports whether the i-th column of the current row is SQL NULL. Equivalent to ColumnType(i) == ColumnNull.

func (*Stmt) ColumnName

func (s *Stmt) ColumnName(i int) string

ColumnName returns the name of the i-th result column (0-based).

func (*Stmt) ColumnText

func (s *Stmt) ColumnText(i int) string

ColumnText returns the i-th column as a UTF-8 string.

func (*Stmt) ColumnType

func (s *Stmt) ColumnType(i int) ColumnType

ColumnType returns the dynamic type of the i-th result column in the current row (0-based).

func (*Stmt) Finalize

func (s *Stmt) Finalize() error

Finalize releases the statement. Safe to call multiple times.

func (*Stmt) Reset

func (s *Stmt) Reset() error

Reset returns the statement to its initial pre-Step state. Bindings are preserved; call ClearBindings to also reset them.

func (*Stmt) Step

func (s *Stmt) Step() (hasRow bool, err error)

Step advances the statement.

  • hasRow=true, err=nil → SQLITE_ROW; read columns via Column*.
  • hasRow=false, err=nil → SQLITE_DONE; statement finished cleanly.
  • err non-nil → SQLite error or SQLITE_INTERRUPT.

type TraceEvent

type TraceEvent uint

TraceEvent identifies which sqlite3_trace_v2 event fired.

type TraceHook

type TraceHook func(evt TraceEvent, sql string) int

TraceHook fires for events selected by the mask passed to SetTraceHook. For TraceStmt, sql is the unexpanded SQL text; other events deliver an empty sql.

type WALHook

type WALHook func(dbName string, frameCount int) int

WALHook fires after each WAL commit. dbName is the schema (typically "main"); frameCount is the WAL frame total at that commit. Return SQLITE_OK normally.

Jump to

Keyboard shortcuts

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