Documentation
¶
Overview ¶
Package sqlite is a CGo-free SQLite driver for Go's database/sql. It is a drop-in replacement for both github.com/mattn/go-sqlite3 (the dominant CGo-based driver) and modernc.org/sqlite (the upstream CGo-free wrapper this module is built on top of), and serves as the dialector source for the sibling gorm package.
Modern Go-typed open (recommended) ¶
New code should reach for the structured Config entry. No DSN string assembly, no `_pragma=` URL flags to memorize, and a single defer Close that bundles the connection pool AND any encryption VFS lifecycle:
import sqlite "gosqlite.org"
db, err := sqlite.Open(sqlite.Config{
Path: "myapp.db",
Pragmas: sqlite.RecommendedPragmas(), // WAL + busy_timeout=5s + foreign_keys
MaxOpenConns: 8,
})
if err != nil { ... }
defer db.Close()
rows, _ := db.Query("SELECT ...") // *sql.DB methods, embedded
PRAGMAs ride in via DSN `_pragma=` URL flags under the hood, so the driver applies them on every new connection in the pool — not just the one database/sql happens to pick for the first Exec.
Encryption at rest takes the same Config shape, with one extra field:
db, _ := sqlite.Open(sqlite.Config{
Path: "secret.db",
Pragmas: sqlite.RecommendedPragmas(),
Encryption: &sqlite.Encryption{
Key: key, // 32 bytes for [Adiantum]
Cipher: sqlite.Adiantum,
},
})
Use crypto.DeriveKey from the vfs/crypto sub-package to turn a passphrase + salt into the right key length. The returned *DB embeds *sql.DB, so every database/sql method works unchanged; the wrapper exists to release the pool AND unregister the encryption VFS in the right order on Close.
See examples/getting-started/config for the full plain + encrypted demo, and the [gorm] sub-package's [OpenConfig] for the gorm flavor (same Config type, *gorm.DB return).
Driver registration (DSN form, still supported) ¶
Importing the package for side effects registers the driver under both names at once, so existing code using either keeps working:
import (
"database/sql"
_ "gosqlite.org"
)
db, _ := sql.Open("sqlite", ":memory:") // modernc-style name
db, _ := sql.Open("sqlite3", ":memory:") // mattn-style name
Both names resolve to the same singleton driver, so calling (*Driver).RegisterFunction / RegisterConnectionHook once affects every connection regardless of which name was used to open it.
Mattn-compatible surface ¶
The mattn drop-in is exhaustive — change the import path and existing code typically keeps compiling:
- Construction via &sqlite.SQLiteDriver{Extensions, ConnectHook} (struct literal with the field names mattn used).
- Type aliases: SQLiteConn, SQLiteStmt, SQLiteRows, SQLiteTx, SQLiteResult, SQLiteBackup, SQLiteError.
- Reflective RegisterFunc / RegisterAggregator with the same call shape mattn exposes — variadic args, (T, error) returns, pure-vs-deterministic UDF flag.
- DSN flag translation: every `_*` flag mattn supports (_foreign_keys, _busy_timeout, _journal_mode, _txlock, _time_format, …) lands as the equivalent PRAGMA. See dsn.go for the full table; unknown flags surface a clear error rather than being silently dropped.
- Error code introspection: (*Error).Code() / ExtendedCode() plus the SQLITE_* / SQLITE_CONSTRAINT_* sentinels exposed in constants.go. Works with errors.Is.
The compat surface is enforced by tests we vendored from mattn's own suite — see dev/upstream/mattn.md and the `mattn_upstream` CI lane in the repo root.
Hooks and per-conn state ¶
Hooks that modernc never exposed but mattn users depend on are wired in via the same trampoline pattern modernc uses for the hooks it does expose:
- (*Conn).RegisterAuthorizer
- (*Conn).RegisterUpdateHook
- (*Conn).RegisterCommitHook / RegisterRollbackHook
- (*Conn).RegisterPreUpdateHook
- (*Conn).SetTrace
- (*Conn).Backup / SerializeSchema / Deserialize
- top-level Serialize(ctx, *sql.DB) → []byte
Hooks are per-connection. To install one on a known *Conn, pin the pool to one with db.SetMaxOpenConns(1), grab a *sql.Conn, and use Conn.Raw to reach the underlying *sqlite.Conn. See examples/ mattn-compat for the canonical pattern.
Quick start ¶
package main
import (
"database/sql"
"errors"
"fmt"
sqlite "gosqlite.org"
)
func main() {
sql.Register("with-udfs", &sqlite.SQLiteDriver{
ConnectHook: func(c *sqlite.SQLiteConn) error {
return c.RegisterFunc("double",
func(x int64) int64 { return x * 2 }, true)
},
})
db, _ := sql.Open("with-udfs",
":memory:?_foreign_keys=on&_busy_timeout=5000")
defer db.Close()
var v int64
if err := db.QueryRow("SELECT double(21)").Scan(&v); err != nil {
var se *sqlite.Error
if errors.As(err, &se) {
fmt.Println("sqlite code:", se.Code(), "ext:", se.ExtendedCode())
}
}
fmt.Println(v) // 42
}
Sub-packages ¶
Higher-level capabilities live in sibling packages, each with its own doc:
- gosqlite.org/gorm — gorm dialector + Migrator, drop-in for gorm.io/driver/sqlite and glebarez/sqlite.
- gosqlite.org/vec — sqlite-vec vector search (auto-registered extension + typed Go API).
- gosqlite.org/vec/gorm — tag-driven vec sidecars wired into gorm models.
- gosqlite.org/fts — typed FTS5 full-text search (Index[K, V], query builder, tokenizers, BM25 + snippet / highlight).
- gosqlite.org/fts/gorm — tag-driven FTS5 indexes wired into gorm models (external / in-table / contentless modes).
- gosqlite.org/fusion — rank-fusion helpers (Reciprocal Rank Fusion) for combining vec.KNN and fts.Search results into a single hybrid-search ranking.
- gosqlite.org/vfs — io/fs.FS-backed read-only databases (e.g. opening a SQLite file out of an embed.FS). Also exposes vfs.NewReader(io.ReaderAt, size) for the simpler direct-buffer case.
- gosqlite.org/vfs/crypto — pure-Go encryption-at-rest VFS (Adiantum or AES-XTS-256, transparent page-level encryption of main DB + journal + WAL + temp files).
- gosqlite.org/vfs/cksm — pure-Go page-level checksum VFS (Fletcher-style 8-byte trailer per page, on-disk compatible with SQLite's cksumvfs). Composes beneath vfs/crypto.
- gosqlite.org/vfs/mvcc — in-memory MVCC VFS with snapshot-isolation reads + atomic publish on commit; shared (file:/name) and private (file:name) DBs.
- gosqlite.org/vfs/memdb — plain in-memory VFS with direct per-page store, no MVCC; smaller-surface alternative to vfs/mvcc for tests and scratch DBs.
- gosqlite.org/ext — opt-in loadable Go extensions: array, blobio, bloom, closure, csv, fileio, hash, ipaddr, lines, pivot, regexp, spellfix1, statement, stats, unicode, uuid, zorder. Each sub-package is independent — pick what you need and leave the rest off your import graph. Register per-conn via <name>.Register(c) or pool-wide via blank-import of <name>/auto. See dev/coverage/ext.md for the matrix.
Virtual tables from Go ¶
(*Conn).CreateModule and (*Conn).CreateEponymousModule expose Go-implemented virtual tables to SQLite. Implement the VTab and VTabCursor interfaces (plus optional VTabUpdater / VTabRenamer / VTabTransactional), then register a constructor that calls Conn.DeclareVTab inside its body. The eponymous variant lets the table be queried directly by its module name (e.g. `SELECT … FROM array(?)`) without a preceding CREATE VIRTUAL TABLE.
Custom pointer bindings ¶
Pointer wraps an arbitrary Go value so it can be bound as a SQL parameter and ferry through to a UDF's args slice or a vtab's Filter callback as the original Go object (rather than a SQLite primitive). SQLite drives the binding lifetime through a destructor callback — no caller-side Release is needed. See ext/array for the canonical use case.
SQLite version, libc pin ¶
The bundled SQLite is whatever build modernc.org/sqlite is pinned to in this module's go.mod. SQLite itself is not vendored or pinned by this module.
modernc.org/libc is a hard ABI dependency of modernc.org/sqlite's transpiled C. Bumping one without the other breaks the generated code. If you redirect this module's deps in your own go.mod, keep the libc version aligned with what go.mod here declares. See https://gitlab.com/cznic/sqlite/-/issues/177 for context.
Supported platforms ¶
Coverage matches modernc.org/sqlite's transpilation matrix:
darwin amd64, arm64 freebsd amd64, arm64 linux 386, amd64, arm, arm64, loong64, ppc64le, riscv64, s390x windows 386, amd64, arm64
The vec sub-package is transpiled per-target by modernc.org/sqlite/vec and may skip some of these (see that package's build tags); fts and the core driver cover the full set.
Index ¶
- Constants
- Variables
- func ApplyPragmas(db *sql.DB, p Pragmas) error
- func BuildDSN(cfg Config) string
- func CompileOptionGet(i int) (string, bool)
- func CompileOptionUsed(name string) bool
- func Complete(sql string) bool
- func Deserialize(ctx context.Context, db *sql.DB, buf []byte) error
- func IsKeyword(s string) bool
- func KeywordCount() int
- func KeywordName(i int) (string, bool)
- func Limit(c *sql.Conn, id int, newVal int) (r int, err error)
- func MustRegisterCollationUtf8(zName string, impl func(left, right string) int)
- func MustRegisterDeterministicScalarFunction(zFuncName string, nArg int32, ...)
- func MustRegisterFunction(zFuncName string, impl *FunctionImpl)
- func MustRegisterScalarFunction(zFuncName string, nArg int32, ...)
- func Pointer(v any) any
- func RegisterAutoHook(reg func(*Conn) error)
- func RegisterCollationUtf8(zName string, impl func(left, right string) int) error
- func RegisterConnectionHook(fn ConnectionHookFn)
- func RegisterDeterministicScalarFunction(zFuncName string, nArg int32, ...) (err error)
- func RegisterFunction(zFuncName string, impl *FunctionImpl) error
- func RegisterScalarFunction(zFuncName string, nArg int32, ...) (err error)
- func Serialize(ctx context.Context, db *sql.DB) ([]byte, error)
- func StrGlob(pattern, s string) bool
- func StrLike(pattern, s string, escape byte) bool
- func ValuePointer(v Value) (any, bool)
- type AccessMode
- type AggregateFunction
- type ApplyOption
- type AuthorizerFn
- type Backup
- type Blob
- func (b *Blob) Close() error
- func (b *Blob) Read(p []byte) (int, error)
- func (b *Blob) ReadAt(p []byte, off int64) (int, error)
- func (b *Blob) Reopen(rowid int64) error
- func (b *Blob) Seek(offset int64, whence int) (int64, error)
- func (b *Blob) Size() int64
- func (b *Blob) Write(p []byte) (int, error)
- func (b *Blob) WriteAt(p []byte, off int64) (int, error)
- type BusyHandler
- type CacheMode
- type CheckpointMode
- type Cipher
- type ColumnInfo
- type ColumnMetadata
- type CommitHookFn
- type Config
- type ConflictAction
- type ConflictHandler
- type ConflictType
- type Conn
- func (c *Conn) AnyCollationNeeded() error
- func (c *Conn) ApplyChangeset(changeset []byte, opts ...ApplyOption) error
- func (c *Conn) AutoCommit() bool
- func (dst *Conn) Backup(destSchema string, src *Conn, srcSchema string) (*Backup, error)
- func (c *Conn) CacheFlush() error
- func (c *Conn) CollationNeeded(fn func(conn *Conn, name string)) error
- func (c *Conn) ConcatChangesets(a, b []byte) ([]byte, error)
- func (c *Conn) CreateEponymousModule(name string, ctor VTabCtor) error
- func (c *Conn) CreateModule(name string, ctor VTabCtor) error
- func (c *Conn) CreateModuleSplit(name string, create, connect VTabCtor) error
- func (c *Conn) CreateSession(schema string) (*Session, error)
- func (c *Conn) DeclareVTab(schema string) error
- func (c *Conn) EnableChecksums(schema string) error
- func (c *Conn) EnableLoadExtension(on bool) error
- func (c *Conn) ErrorOffset() int
- func (c *Conn) Filename(schema string) string
- func (c *Conn) GetLimit(id int) int
- func (c *Conn) GetSnapshot(schema string) (*Snapshot, error)
- func (c *Conn) InvertChangeset(changeset []byte) ([]byte, error)
- func (c *Conn) LoadExtension(libPath, entry string) error
- func (c *Conn) OpenBlob(schema, table, column string, rowid int64, write bool) (*Blob, error)
- func (c *Conn) OpenSnapshot(schema string, snap *Snapshot) error
- func (c *Conn) QueryDBConfig(op DBConfigOp) (bool, error)
- func (c *Conn) RegisterAggregator(name string, impl any, pure bool) error
- func (c *Conn) RegisterAuthorizer(fn AuthorizerFn)
- func (c *Conn) RegisterBusyHandler(handler BusyHandler)
- func (c *Conn) RegisterCollation(name string, cmp func(a, b string) int) error
- func (c *Conn) RegisterFTS5Tokenizer(name string, newTokenizer func(args []string) (FTS5Tokenizer, error)) error
- func (c *Conn) RegisterFunc(name string, impl any, pure bool) error
- func (c *Conn) RegisterRTreeGeometry(name string, fn RTreeGeometryFunc) error
- func (c *Conn) RegisterRTreeQuery(name string, fn RTreeQueryFunc) error
- func (c *Conn) RegisterUpdateHook(fn UpdateHookFn)
- func (c *Conn) RegisterWALHook(hook WALHook)
- func (c *Conn) RegisterWindowFunction(name string, nArg int, constructor func() WindowAccumulator, pure bool) error
- func (c *Conn) ResetCache(schema string) error
- func (c *Conn) SerializeSchema(schema string) ([]byte, error)
- func (c *Conn) SetDBConfig(op DBConfigOp, enable bool) (bool, error)
- func (c *Conn) SetFileControlInt(schema string, op, val int) (int, error)
- func (c *Conn) SetLimit(id, newVal int) int
- func (c *Conn) SetProgressHandler(n int, handler ProgressHandler)
- func (c *Conn) SetTrace(cfg *TraceConfig) error
- func (c *Conn) SnapshotRecover(schema string) error
- func (c *Conn) Status(op DBStatus, reset bool) (current, highwater int, err error)
- func (c *Conn) TableColumnMetadata(schema, table, column string) (ColumnMetadata, error)
- func (c *Conn) TxnState(schema string) TxnState
- func (c *Conn) WALAutoCheckpoint(frames int) error
- func (c *Conn) WALCheckpoint(schema string, mode CheckpointMode) (logFrames, checkpointed int, err error)
- type ConnectionHookFn
- type Constraint
- type ConstraintOp
- type DB
- type DBConfigOp
- type DBStatus
- type Driver
- type Encryption
- type ErrNo
- type ErrNoExtended
- type Error
- type ExecQuerierContext
- type FTS5Tokenizer
- type FileControl
- type FunctionContext
- type FunctionImpl
- type HookRegisterer
- type IndexInfo
- type JournalMode
- type OrderBy
- type Pragmas
- type PreUpdateHookFn
- type ProgressHandler
- type RTreeGeometryFunc
- type RTreeQueryFunc
- type RTreeQueryInfo
- type RTreeWithin
- type Result
- type RollbackHookFn
- type Rows
- type SQLiteBackup
- type SQLiteConn
- type SQLiteContext
- type SQLiteDriver
- type SQLiteError
- type SQLitePreUpdateData
- type SQLiteResult
- type SQLiteRows
- type SQLiteStmt
- type SQLiteTx
- type Session
- func (s *Session) Attach(table string) error
- func (s *Session) Changeset() ([]byte, error)
- func (s *Session) Close() error
- func (s *Session) Diff(fromSchema, table string) error
- func (s *Session) Enable(on bool)
- func (s *Session) IsEmpty() bool
- func (s *Session) IsEnabled() bool
- func (s *Session) Patchset() ([]byte, error)
- type Snapshot
- type Stmt
- type StmtCacheStats
- type StmtStatus
- type Synchronous
- type TableFilter
- type TempStore
- type TraceConfig
- type TraceEvent
- type TraceFn
- type TraceInfo
- type Tx
- type TxnState
- type UpdateHookFn
- type VTab
- type VTabCtor
- type VTabCursor
- type VTabRenamer
- type VTabTransactional
- type VTabUpdater
- type Value
- type WALHook
- type WindowAccumulator
- type WindowFinalizer
Constants ¶
const ( PragmaJournalMode = "journal_mode" PragmaBusyTimeout = "busy_timeout" PragmaSynchronous = "synchronous" PragmaForeignKeys = "foreign_keys" PragmaCacheSize = "cache_size" PragmaTempStore = "temp_store" )
Exported pragma-key constants. Used internally by the DSN renderer and the ApplyPragmas / BuildDSN code paths; exposed so callers building custom pragma strings or migration scripts can reference the canonical SQLite spelling without re-hardcoding it.
const ( Adiantum = crypto.Adiantum AESXTS = crypto.AESXTS )
Re-exported cipher constants. Use these directly via the root package: `sqlite.Adiantum`, `sqlite.AESXTS`.
const ( SQLITE_INSERT = sqlite3.SQLITE_INSERT SQLITE_UPDATE = sqlite3.SQLITE_UPDATE SQLITE_DELETE = sqlite3.SQLITE_DELETE )
SQLite operation codes re-exported for use by hook callbacks. These match the upstream SQLITE_* constants.
const ( SQLITE_OK = sqlite3.SQLITE_OK SQLITE_DENY = sqlite3.SQLITE_DENY SQLITE_IGNORE = sqlite3.SQLITE_IGNORE )
Authorizer return codes.
const ( SQLITE_CREATE_INDEX = sqlite3.SQLITE_CREATE_INDEX SQLITE_CREATE_TABLE = sqlite3.SQLITE_CREATE_TABLE SQLITE_CREATE_TEMP_INDEX = sqlite3.SQLITE_CREATE_TEMP_INDEX SQLITE_CREATE_TEMP_TABLE = sqlite3.SQLITE_CREATE_TEMP_TABLE SQLITE_CREATE_TEMP_TRIGGER = sqlite3.SQLITE_CREATE_TEMP_TRIGGER SQLITE_CREATE_TEMP_VIEW = sqlite3.SQLITE_CREATE_TEMP_VIEW SQLITE_CREATE_TRIGGER = sqlite3.SQLITE_CREATE_TRIGGER SQLITE_CREATE_VIEW = sqlite3.SQLITE_CREATE_VIEW SQLITE_CREATE_VTABLE = sqlite3.SQLITE_CREATE_VTABLE SQLITE_DROP_INDEX = sqlite3.SQLITE_DROP_INDEX SQLITE_DROP_TABLE = sqlite3.SQLITE_DROP_TABLE SQLITE_DROP_TEMP_INDEX = sqlite3.SQLITE_DROP_TEMP_INDEX SQLITE_DROP_TEMP_TABLE = sqlite3.SQLITE_DROP_TEMP_TABLE SQLITE_DROP_TEMP_TRIGGER = sqlite3.SQLITE_DROP_TEMP_TRIGGER SQLITE_DROP_TEMP_VIEW = sqlite3.SQLITE_DROP_TEMP_VIEW SQLITE_DROP_TRIGGER = sqlite3.SQLITE_DROP_TRIGGER SQLITE_DROP_VIEW = sqlite3.SQLITE_DROP_VIEW SQLITE_DROP_VTABLE = sqlite3.SQLITE_DROP_VTABLE SQLITE_PRAGMA = sqlite3.SQLITE_PRAGMA SQLITE_READ = sqlite3.SQLITE_READ SQLITE_SELECT = sqlite3.SQLITE_SELECT SQLITE_TRANSACTION = sqlite3.SQLITE_TRANSACTION SQLITE_ATTACH = sqlite3.SQLITE_ATTACH SQLITE_DETACH = sqlite3.SQLITE_DETACH SQLITE_ALTER_TABLE = sqlite3.SQLITE_ALTER_TABLE SQLITE_REINDEX = sqlite3.SQLITE_REINDEX SQLITE_ANALYZE = sqlite3.SQLITE_ANALYZE SQLITE_FUNCTION = sqlite3.SQLITE_FUNCTION SQLITE_SAVEPOINT = sqlite3.SQLITE_SAVEPOINT SQLITE_COPY = sqlite3.SQLITE_COPY SQLITE_RECURSIVE = sqlite3.SQLITE_RECURSIVE )
Authorizer action codes (a subset matching mattn).
const ( SQLITE_ERROR = sqlite3.SQLITE_ERROR SQLITE_BUSY = sqlite3.SQLITE_BUSY SQLITE_LOCKED = sqlite3.SQLITE_LOCKED SQLITE_CONSTRAINT = sqlite3.SQLITE_CONSTRAINT SQLITE_MISUSE = sqlite3.SQLITE_MISUSE SQLITE_NOTFOUND = sqlite3.SQLITE_NOTFOUND SQLITE_FULL = sqlite3.SQLITE_FULL SQLITE_DONE = sqlite3.SQLITE_DONE SQLITE_ROW = sqlite3.SQLITE_ROW )
Result code constants (subset).
const ( SQLITE_CONSTRAINT_CHECK = sqlite3.SQLITE_CONSTRAINT_CHECK SQLITE_CONSTRAINT_FOREIGNKEY = sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY SQLITE_CONSTRAINT_NOTNULL = sqlite3.SQLITE_CONSTRAINT_NOTNULL SQLITE_CONSTRAINT_PRIMARYKEY = sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY SQLITE_CONSTRAINT_TRIGGER = sqlite3.SQLITE_CONSTRAINT_TRIGGER SQLITE_CONSTRAINT_UNIQUE = sqlite3.SQLITE_CONSTRAINT_UNIQUE SQLITE_CONSTRAINT_ROWID = sqlite3.SQLITE_CONSTRAINT_ROWID )
Extended constraint result codes (mattn-compatible aliases).
const ( SQLITE_LIMIT_LENGTH = sqlite3.SQLITE_LIMIT_LENGTH SQLITE_LIMIT_SQL_LENGTH = sqlite3.SQLITE_LIMIT_SQL_LENGTH SQLITE_LIMIT_COLUMN = sqlite3.SQLITE_LIMIT_COLUMN SQLITE_LIMIT_EXPR_DEPTH = sqlite3.SQLITE_LIMIT_EXPR_DEPTH SQLITE_LIMIT_COMPOUND_SELECT = sqlite3.SQLITE_LIMIT_COMPOUND_SELECT SQLITE_LIMIT_VDBE_OP = sqlite3.SQLITE_LIMIT_VDBE_OP SQLITE_LIMIT_FUNCTION_ARG = sqlite3.SQLITE_LIMIT_FUNCTION_ARG SQLITE_LIMIT_ATTACHED = sqlite3.SQLITE_LIMIT_ATTACHED SQLITE_LIMIT_LIKE_PATTERN_LENGTH = sqlite3.SQLITE_LIMIT_LIKE_PATTERN_LENGTH SQLITE_LIMIT_VARIABLE_NUMBER = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER SQLITE_LIMIT_TRIGGER_DEPTH = sqlite3.SQLITE_LIMIT_TRIGGER_DEPTH SQLITE_LIMIT_WORKER_THREADS = sqlite3.SQLITE_LIMIT_WORKER_THREADS )
SQLITE_LIMIT_* identifiers used with Conn.GetLimit / Conn.SetLimit.
const ( FlagPragma = "_pragma" FlagForeignKeys = "_foreign_keys" FlagFK = "_fk" FlagBusyTimeout = "_busy_timeout" FlagTimeout = "_timeout" FlagJournalMode = "_journal_mode" FlagJournal = "_journal" FlagSynchronous = "_synchronous" FlagSync = "_sync" FlagLockingMode = "_locking_mode" FlagLocking = "_locking" FlagSecureDelete = "_secure_delete" FlagRecursiveTriggers = "_recursive_triggers" FlagRT = "_rt" FlagCacheSize = "_cache_size" FlagAutoVacuum = "_auto_vacuum" FlagVacuum = "_vacuum" FlagDeferForeignKeys = "_defer_foreign_keys" FlagDeferFK = "_defer_fk" FlagIgnoreCheckConstraints = "_ignore_check_constraints" FlagCaseSensitiveLike = "_case_sensitive_like" FlagCSLike = "_cslike" FlagQueryOnly = "_query_only" FlagWritableSchema = "_writable_schema" FlagMutex = "_mutex" FlagLoc = "_loc" FlagTimezone = "_timezone" FlagTimeFormat = "_time_format" FlagTimeIntegerFormat = "_time_integer_format" FlagIntToTime = "_inttotime" FlagTextToTime = "_texttotime" FlagTxLock = "_txlock" FlagStmtCacheSize = "_stmt_cache_size" FlagStrict = "_strict" )
Mattn-compat DSN flag names. Exposed so callers building DSN strings or filtering query parameters can reference the canonical spelling without re-hardcoding it. Aliases (e.g. `_fk` ↔ `_foreign_keys`) share the underlying pragma; both names are valid in DSNs.
const ( OpUnknown = vtab.OpUnknown OpEQ = vtab.OpEQ OpGT = vtab.OpGT OpLE = vtab.OpLE OpLT = vtab.OpLT OpGE = vtab.OpGE OpMATCH = vtab.OpMATCH OpNE = vtab.OpNE OpIS = vtab.OpIS OpISNOT = vtab.OpISNOT OpISNULL = vtab.OpISNULL OpISNOTNULL = vtab.OpISNOTNULL OpLIKE = vtab.OpLIKE OpGLOB = vtab.OpGLOB OpREGEXP = vtab.OpREGEXP OpFUNCTION = vtab.OpFUNCTION OpLIMIT = vtab.OpLIMIT OpOFFSET = vtab.OpOFFSET )
Constraint operator re-exports for BestIndex.
const ( // DriverName is the primary registration name: "sqlite". DriverName = "sqlite" // DriverNameSQLite3 is the compatibility registration: "sqlite3". // Registered so existing code that opens with sql.Open("sqlite3", ...) // keeps working unchanged — historically that name was claimed by the // cgo-based sqlite3 driver, and downstream code that targets it can // switch by swapping its import for this package without touching DSNs. DriverNameSQLite3 = "sqlite3" )
Driver names registered with the database/sql package.
const InMemory = ":memory:"
InMemory is the canonical SQLite path for a private per-conn in-memory database — the literal string ":memory:". Use it instead of sprinkling the magic colon-form through your code:
db, _ := sql.Open("sqlite", sqlite.InMemory)
db, _ := sqlite.Open(sqlite.Config{Path: sqlite.InMemory})
For a quicker no-Config entry, see OpenInMemory. For an in-memory database shared across multiple connections in the same process, pair an empty Path with one of the in-memory VFSes — see gosqlite.org/vfs/memdb / gosqlite.org/vfs/mvcc.
Variables ¶
var ( // ErrorCodeString maps Error.Code() to its string representation. ErrorCodeString = map[int]string{ sqlite3.SQLITE_ABORT: "Callback routine requested an abort (SQLITE_ABORT)", sqlite3.SQLITE_AUTH: "Authorization denied (SQLITE_AUTH)", sqlite3.SQLITE_BUSY: "The database file is locked (SQLITE_BUSY)", sqlite3.SQLITE_CANTOPEN: "Unable to open the database file (SQLITE_CANTOPEN)", sqlite3.SQLITE_CONSTRAINT: "Abort due to constraint violation (SQLITE_CONSTRAINT)", sqlite3.SQLITE_CORRUPT: "The database disk image is malformed (SQLITE_CORRUPT)", sqlite3.SQLITE_DONE: "sqlite3_step() has finished executing (SQLITE_DONE)", sqlite3.SQLITE_EMPTY: "Internal use only (SQLITE_EMPTY)", sqlite3.SQLITE_ERROR: "Generic error (SQLITE_ERROR)", sqlite3.SQLITE_FORMAT: "Not used (SQLITE_FORMAT)", sqlite3.SQLITE_FULL: "Insertion failed because database is full (SQLITE_FULL)", sqlite3.SQLITE_INTERNAL: "Internal logic error in SQLite (SQLITE_INTERNAL)", sqlite3.SQLITE_INTERRUPT: "Operation terminated by sqlite3_interrupt()(SQLITE_INTERRUPT)", sqlite3.SQLITE_IOERR | (1 << 8): "(SQLITE_IOERR_READ)", sqlite3.SQLITE_IOERR | (10 << 8): "(SQLITE_IOERR_DELETE)", sqlite3.SQLITE_IOERR | (11 << 8): "(SQLITE_IOERR_BLOCKED)", sqlite3.SQLITE_IOERR | (12 << 8): "(SQLITE_IOERR_NOMEM)", sqlite3.SQLITE_IOERR | (13 << 8): "(SQLITE_IOERR_ACCESS)", sqlite3.SQLITE_IOERR | (14 << 8): "(SQLITE_IOERR_CHECKRESERVEDLOCK)", sqlite3.SQLITE_IOERR | (15 << 8): "(SQLITE_IOERR_LOCK)", sqlite3.SQLITE_IOERR | (16 << 8): "(SQLITE_IOERR_CLOSE)", sqlite3.SQLITE_IOERR | (17 << 8): "(SQLITE_IOERR_DIR_CLOSE)", sqlite3.SQLITE_IOERR | (2 << 8): "(SQLITE_IOERR_SHORT_READ)", sqlite3.SQLITE_IOERR | (3 << 8): "(SQLITE_IOERR_WRITE)", sqlite3.SQLITE_IOERR | (4 << 8): "(SQLITE_IOERR_FSYNC)", sqlite3.SQLITE_IOERR | (5 << 8): "(SQLITE_IOERR_DIR_FSYNC)", sqlite3.SQLITE_IOERR | (6 << 8): "(SQLITE_IOERR_TRUNCATE)", sqlite3.SQLITE_IOERR | (7 << 8): "(SQLITE_IOERR_FSTAT)", sqlite3.SQLITE_IOERR | (8 << 8): "(SQLITE_IOERR_UNLOCK)", sqlite3.SQLITE_IOERR | (9 << 8): "(SQLITE_IOERR_RDLOCK)", sqlite3.SQLITE_IOERR: "Some kind of disk I/O error occurred (SQLITE_IOERR)", sqlite3.SQLITE_LOCKED | (1 << 8): "(SQLITE_LOCKED_SHAREDCACHE)", sqlite3.SQLITE_LOCKED: "A table in the database is locked (SQLITE_LOCKED)", sqlite3.SQLITE_MISMATCH: "Data type mismatch (SQLITE_MISMATCH)", sqlite3.SQLITE_MISUSE: "Library used incorrectly (SQLITE_MISUSE)", sqlite3.SQLITE_NOLFS: "Uses OS features not supported on host (SQLITE_NOLFS)", sqlite3.SQLITE_NOMEM: "A malloc() failed (SQLITE_NOMEM)", sqlite3.SQLITE_NOTADB: "File opened that is not a database file (SQLITE_NOTADB)", sqlite3.SQLITE_NOTFOUND: "Unknown opcode in sqlite3_file_control() (SQLITE_NOTFOUND)", sqlite3.SQLITE_NOTICE: "Notifications from sqlite3_log() (SQLITE_NOTICE)", sqlite3.SQLITE_PERM: "Access permission denied (SQLITE_PERM)", sqlite3.SQLITE_PROTOCOL: "Database lock protocol error (SQLITE_PROTOCOL)", sqlite3.SQLITE_RANGE: "2nd parameter to sqlite3_bind out of range (SQLITE_RANGE)", sqlite3.SQLITE_READONLY: "Attempt to write a readonly database (SQLITE_READONLY)", sqlite3.SQLITE_ROW: "sqlite3_step() has another row ready (SQLITE_ROW)", sqlite3.SQLITE_SCHEMA: "The database schema changed (SQLITE_SCHEMA)", sqlite3.SQLITE_TOOBIG: "String or BLOB exceeds size limit (SQLITE_TOOBIG)", sqlite3.SQLITE_WARNING: "Warnings from sqlite3_log() (SQLITE_WARNING)", } )
Functions ¶
func ApplyPragmas ¶
ApplyPragmas runs each requested PRAGMA against the given pool via *sql.DB.Exec. Exposed for callers who already have a `sql.Open(dsn)`- opened pool and want the typed PRAGMA surface without rebuilding the DSN:
db, _ := sql.Open("sqlite", "file:x.db")
sqlite.ApplyPragmas(db, sqlite.RecommendedPragmas())
CAVEAT: this path is best-effort for per-connection PRAGMAs (busy_timeout, foreign_keys, cache_size, temp_store, synchronous): database/sql picks any idle connection per Exec, so the setting only sticks on whichever conn the Exec hit. For pool-wide correctness, use Open — it encodes every PRAGMA into the DSN so the driver applies them at each connection open. ApplyPragmas is safe for journal_mode (DB-file attribute, propagates) and for users running with MaxOpenConns=1.
Iteration order is deterministic: declared fields first, then Extra keys in sorted order.
func BuildDSN ¶
BuildDSN renders the full DSN that Open would build for the given Config, including every requested PRAGMA as a `_pragma=` URL flag. Exposed for callers that need the string form (e.g. wiring into a third-party tool that only accepts DSN strings):
dsn := sqlite.BuildDSN(cfg)
db, _ := sql.Open("sqlite", dsn)
New code should prefer Open — it Pings to surface PRAGMA errors eagerly and bundles the encryption VFS lifecycle. BuildDSN exists for the integration case.
Encryption is NOT handled here — pure DSN rendering. Use Open if you need encryption; it owns the crypto.FS lifecycle.
func CompileOptionGet ¶
CompileOptionGet returns the i-th compile-time option (0-based), or ("", false) past the end. Iterate to enumerate the build's feature set.
func CompileOptionUsed ¶
CompileOptionUsed reports whether SQLite was compiled with the given option (the SQLITE_ prefix is optional), e.g. "ENABLE_FTS5".
func Complete ¶
Complete reports whether sql is one or more complete statements — i.e. it ends at a statement boundary (a ; not inside a string/comment/trigger body). Use it to decide whether a REPL has a full statement to execute or needs more input.
func Deserialize ¶
Deserialize is a top-level helper that loads buf into the main database of a pool connection borrowed from db. Note: after Deserialize, subsequent pool connections see the new content only for the same physical connection — for most callers, set db.SetMaxOpenConns(1) before calling Deserialize so the loaded image is the only conn the pool ever returns.
func IsKeyword ¶
IsKeyword reports whether s is a reserved SQL keyword in this build (case- insensitive). An identifier that is a keyword must be quoted.
func KeywordCount ¶
func KeywordCount() int
KeywordCount returns the number of distinct SQL keywords this build of SQLite recognizes.
func KeywordName ¶
KeywordName returns the i-th SQL keyword (0-based), or ("", false) if i is out of range. Iterate 0..KeywordCount()-1 to enumerate the reserved-word set — the authoritative source for identifier quoting, instead of guessing.
func Limit ¶
Limit calls sqlite3_limit, see the docs at https://www.sqlite.org/c3ref/limit.html for details.
To get a sql.Conn from a *sql.DB, use (*sql.DB).Conn(). Limits are bound to the particular instance of 'c', so getting a new connection only to pass it to Limit is possibly not useful above querying what are the various configured default values.
func MustRegisterCollationUtf8 ¶
MustRegisterCollationUtf8 is like RegisterCollationUtf8 but panics on error.
func MustRegisterDeterministicScalarFunction ¶
func MustRegisterDeterministicScalarFunction( zFuncName string, nArg int32, xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), )
MustRegisterDeterministicScalarFunction is like RegisterDeterministicScalarFunction but panics on error.
func MustRegisterFunction ¶
func MustRegisterFunction( zFuncName string, impl *FunctionImpl, )
MustRegisterFunction is like RegisterFunction but panics on error.
func MustRegisterScalarFunction ¶
func MustRegisterScalarFunction( zFuncName string, nArg int32, xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), )
MustRegisterScalarFunction is like RegisterScalarFunction but panics on error.
func Pointer ¶
Pointer wraps v so it can be bound as a SQL parameter and reach the other side of the boundary as a Go value rather than a SQLite primitive. Useful for ferrying slices, maps, or opaque handles into custom UDFs or virtual-table modules without serializing.
Example — bind a Go slice to the ext/array table-valued function:
rows, _ := db.QueryContext(ctx,
`SELECT value FROM array(?) ORDER BY value`,
sqlite.Pointer([]int{10, 20, 30}))
The wrapped value travels through SQLite as a tagged pointer via `sqlite3_bind_pointer` / `sqlite3_value_pointer`. From inside a UDF registered with Conn.RegisterFunc (or a VTab Filter callback), the args slice receives v unchanged — the Go value, not a primitive.
Lifetime: the binding lives until the parameter is rebound or the statement is finalized. SQLite drives the cleanup deterministically via a destructor trampoline — no caller-side Release is needed.
Note: sqlite3_reset does NOT clear bindings (that's sqlite3_clear_bindings). A prepared statement reused via Reset keeps its Pointer binding alive until either the parameter is rebound or the statement is finalized.
func RegisterAutoHook ¶
RegisterAutoHook chains a Register-style hook onto the default driver's [Driver.ConnectHook], preserving any previously-installed hook. The hook fires on every newly-opened connection, after the modernc-style ConnectionHooks and Mattn-style Extensions have run.
This is the recipe the blank-import `ext/<name>/auto` sub-packages use to opt every connection in to a SQL extension without trampling whichever ConnectHook was already there. Composing many /auto imports just chains them in import-graph order — each call captures the previous chain and prepends a run-prior-then-reg trampoline.
func init() {
sqlite.RegisterAutoHook(myext.Register)
}
Concurrency: safe to call from init() (single goroutine) or after. Both the write here and the read in Driver.Open are guarded by d.mu, so concurrent registration and connection-opening compose without races. Pool-wide consistency requires installing all hooks before the first sql.Open, which the blank-import pattern guarantees.
func RegisterCollationUtf8 ¶
RegisterCollationUtf8 makes a Go function available as a collation named zName. impl receives two UTF-8 strings: left and right. The result needs to be:
- 0 if left == right - 1 if left < right - +1 if left > right
impl must always return the same result given the same inputs. Additionally, it must have the following properties for all strings A, B and C: - if A==B, then B==A - if A==B and B==C, then A==C - if A<B, then B>A - if A<B and B<C, then A<C.
The new collation will be available to all new connections opened after executing RegisterCollationUtf8.
func RegisterConnectionHook ¶
func RegisterConnectionHook(fn ConnectionHookFn)
RegisterConnectionHook registers a function to be called after each connection is opened. This is called after all the connection has been set up.
func RegisterDeterministicScalarFunction ¶
func RegisterDeterministicScalarFunction( zFuncName string, nArg int32, xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), ) (err error)
RegisterDeterministicScalarFunction registers a deterministic scalar function named zFuncName with nArg arguments. Passing -1 for nArg indicates the function is variadic. A deterministic function means that the function always gives the same output when the input parameters are the same.
The new function will be available to all new connections opened after executing RegisterDeterministicScalarFunction.
func RegisterFunction ¶
func RegisterFunction( zFuncName string, impl *FunctionImpl, ) error
RegisterFunction registers a function named zFuncName with nArg arguments. Passing -1 for nArg indicates the function is variadic. The FunctionImpl determines whether the function is deterministic or not, and whether it is a scalar function (when Scalar is defined) or an aggregate function (when Scalar is not defined and MakeAggregate is defined).
The new function will be available to all new connections opened after executing RegisterFunction.
func RegisterScalarFunction ¶
func RegisterScalarFunction( zFuncName string, nArg int32, xFunc func(ctx *FunctionContext, args []driver.Value) (driver.Value, error), ) (err error)
RegisterScalarFunction registers a scalar function named zFuncName with nArg arguments. Passing -1 for nArg indicates the function is variadic.
The new function will be available to all new connections opened after executing RegisterScalarFunction.
func Serialize ¶
Serialize is a top-level helper that calls (*Conn).Serialize on a fresh pool connection borrowed from db. It is the simplest way to dump an in-memory DB to bytes without manually using db.Conn().Raw(...).
func StrGlob ¶
StrGlob reports whether s matches the GLOB pattern, using SQLite's exact GLOB semantics (case-sensitive, * and ? wildcards) — the same matching the GLOB operator performs, without running a query.
func StrLike ¶
StrLike reports whether s matches the LIKE pattern (case-insensitive for ASCII, % and _ wildcards). escape is the LIKE ESCAPE character, or 0 for none.
func ValuePointer ¶
ValuePointer is a convenience helper for UDF / vtab implementations that want to verify the value in args came from Pointer. Most code can just type-assert the slot in args directly. ValuePointer returns the wrapped value plus ok=true when v is a non-primitive Go value substituted in by Pointer; returns (v, false) when v is one of the standard driver.Value primitives (int64, float64, string, []byte, bool, time.Time, nil).
Types ¶
type AccessMode ¶
type AccessMode string
AccessMode is the typed enum for SQLite's `mode=` URI parameter. Zero value ModeReadWriteCreate matches the implicit behavior of a bare `file:…` DSN.
const ( // ModeReadWriteCreate creates the file if missing, then opens // read-write. Default. ModeReadWriteCreate AccessMode = "rwc" // ModeReadWrite opens read-write but errors if the file is // missing. ModeReadWrite AccessMode = "rw" // ModeReadOnly opens read-only. ModeReadOnly AccessMode = "ro" // ModeMemory opens a private in-memory database (DSN form // "file:name?mode=memory"); equivalent to ":memory:" for most // callers. ModeMemory AccessMode = "memory" )
type AggregateFunction ¶
type AggregateFunction interface {
// Step is called for each row of an aggregate function's SQL
// invocation. The argument Values are not valid past the return of the
// function.
Step(ctx *FunctionContext, rowArgs []driver.Value) error
// WindowInverse is called to remove the oldest presently aggregated
// result of Step from the current window. The arguments are those
// passed to Step for the row being removed. The argument Values are not
// valid past the return of the function.
WindowInverse(ctx *FunctionContext, rowArgs []driver.Value) error
// WindowValue is called to get the current value of an aggregate
// function. This is used to return the final value of the function,
// whether it is used as a window function or not.
WindowValue(ctx *FunctionContext) (driver.Value, error)
// Final is called after all of the aggregate function's input rows have
// been stepped through. No other methods will be called on the
// AggregateFunction after calling Final. WindowValue returns the value
// from the function.
Final(ctx *FunctionContext)
}
An AggregateFunction is an invocation of an aggregate or window function. See the documentation for aggregate function callbacks and application-defined window functions for an overview.
type ApplyOption ¶
type ApplyOption func(*applyConfig)
ApplyOption configures Conn.ApplyChangeset.
func WithConflictHandler ¶
func WithConflictHandler(h ConflictHandler) ApplyOption
WithConflictHandler sets the conflict-resolution callback.
func WithTableFilter ¶
func WithTableFilter(filter TableFilter) ApplyOption
WithTableFilter restricts the apply to tables for which filter returns true.
type AuthorizerFn ¶
AuthorizerFn is the type for an authorizer callback installed via Conn.RegisterAuthorizer. The function is called for every statement compilation step. Return one of:
- SQLITE_OK: allow the action
- SQLITE_IGNORE: treat the column as NULL or skip the action silently
- SQLITE_DENY: reject the statement compilation with an error
op is one of the SQLITE_* authorizer-action constants (see constants.go). arg1, arg2 are op-specific (e.g. table name, column name). dbName is the schema name (typically "main"). triggerName is the name of the trigger or view causing the access; empty for top-level statements.
Mattn-compatibility note: matches mattn's SQLiteConn.RegisterAuthorizer.
type Backup ¶
type Backup struct {
// contains filtered or unexported fields
}
Backup object is used to manage progress and cleanup an online backup. It is returned by NewBackup or NewRestore.
func (*Backup) Close ¶
Close releases all resources associated with the Backup. It is equivalent to Finish but the dstConn (if any) is not implicitly closed — mirroring the way mattn's SQLiteBackup.Close behaves.
On the factory-built backups (those returned by (*Conn).Backup), dstConn is nil so Close behaves identically to Finish minus the dst.Close() call.
func (*Backup) Commit ¶
Commit releases all resources associated with the Backup object but does not close the destination database connection.
The destination database connection is returned to the caller or an error if raised. It is the responsibility of the caller to handle the connection closure.
Calling Commit followed by Finish (or Close) is safe — Commit zeros the internal backup handle so the follow-up is a no-op rather than a double sqlite3_backup_finish call on the same C handle.
func (*Backup) Finish ¶
Finish releases all resources associated with the Backup object. The Backup object is invalid and may not be used following a call to Finish.
When the Backup was produced by NewBackup or NewRestore, the destination connection it implicitly opened is also closed. When the Backup was produced by (*Conn).Backup (the mattn-compat factory), the destination connection is owned by the caller and is not closed here.
Calling Finish after Close (or vice versa) is a no-op.
func (*Backup) PageCount ¶
PageCount returns the total number of pages in the source database at the most recent completed Step.
Mattn-compatibility API.
func (*Backup) Remaining ¶
Remaining returns the number of pages still to be copied at the most recent completed Step. Returns 0 when the backup is complete.
Mattn-compatibility API.
func (*Backup) Step ¶
Step will copy up to n pages between the source and destination databases specified by the backup object. If n is negative, all remaining source pages are copied. If it successfully copies n pages and there are still more pages to be copied, then the function returns true with no error. If it successfully finishes copying all pages from source to destination, then it returns false with no error. If an error occurs while running, then an error is returned.
type Blob ¶
type Blob struct {
// contains filtered or unexported fields
}
Blob is a handle to a single open BLOB or TEXT value referenced by rowid, returned from Conn.OpenBlob. It exposes incremental binary I/O via sqlite3_blob_read / sqlite3_blob_write, plus zero-allocation re-binding to another row in the same table via Reopen.
A Blob is bound to the connection that opened it and is not safe for concurrent use; callers must serialize access. Like the connection it is drawn from, the Blob must be closed explicitly via Close.
func (*Blob) Close ¶
Close releases the underlying sqlite3_blob handle. Subsequent calls are no-ops and return nil.
func (*Blob) Read ¶
Read implements io.Reader, advancing an internal cursor. The cursor starts at 0 and is reset by Reopen. Mix freely with ReadAt; ReadAt does not advance the cursor.
func (*Blob) ReadAt ¶
ReadAt implements io.ReaderAt. It reads up to len(p) bytes starting at off into p. Reads past the end of the value return io.EOF; reads that straddle the end return the partial bytes plus io.EOF on the next call.
Wraps sqlite3_blob_read: https://sqlite.org/c3ref/blob_read.html
func (*Blob) Reopen ¶
Reopen rebinds the handle to a different rowid in the same database, table, and column without reallocating the underlying handle. Returns an error wrapping SQLITE_ABORT if the rebind fails (e.g. the new row does not exist); the handle is then unusable and should be closed.
Wraps sqlite3_blob_reopen: https://sqlite.org/c3ref/blob_reopen.html
func (*Blob) Size ¶
Size reports the length in bytes of the bound BLOB or TEXT value at the time the handle was opened (or last reopened). The size is fixed for the life of the handle; growing the value requires UPDATEing the row.
func (*Blob) WriteAt ¶
WriteAt implements io.WriterAt. Returns an error if the handle was opened read-only, or if the write would extend past the current value size (BLOB writes cannot grow the row — the row must be sized at INSERT time with zeroblob(N) or via an UPDATE).
Wraps sqlite3_blob_write: https://sqlite.org/c3ref/blob_write.html
type BusyHandler ¶
BusyHandler is called when an operation cannot proceed because the database is locked by another connection. attempts is the number of times it has already been invoked for the current locking event (0 on the first call). Return true to wait and retry, false to give up — in which case the operation fails with SQLITE_BUSY.
The handler runs on the connection's own goroutine while it blocks on the lock; a handler that returns true should sleep first (e.g. an exponential or jittered back-off keyed on attempts), or SQLite will spin retrying immediately. Returning false on the first call makes lock contention fail fast.
type CacheMode ¶
type CacheMode string
CacheMode is the typed enum for SQLite's `cache=` URI parameter. Empty value means "leave at SQLite's default" (per-conn private).
const ( // a single page cache. Critical for multi-conn in-memory databases // (the pattern `file:name?mode=memory&cache=shared`) since without // it each conn would get its own private memory store. See // [OpenShared] for the shortcut. CacheShared CacheMode = "shared" // CachePrivate is the SQLite default — each connection has its // own page cache. Setting this explicitly is rarely useful; leave // empty for the same behavior. CachePrivate CacheMode = "private" )
type CheckpointMode ¶
type CheckpointMode int32
CheckpointMode selects how aggressively Conn.WALCheckpoint runs.
const ( // CheckpointPassive checkpoints as many frames as possible without waiting // for readers or writers; never blocks. CheckpointPassive CheckpointMode = sqlite3.SQLITE_CHECKPOINT_PASSIVE // CheckpointFull waits for writers, then checkpoints all frames. CheckpointFull CheckpointMode = sqlite3.SQLITE_CHECKPOINT_FULL // CheckpointRestart is like Full, then waits for readers so the next write // restarts the WAL from the beginning. CheckpointRestart CheckpointMode = sqlite3.SQLITE_CHECKPOINT_RESTART // CheckpointTruncate is like Restart, then truncates the WAL file to zero. CheckpointTruncate CheckpointMode = sqlite3.SQLITE_CHECKPOINT_TRUNCATE )
type Cipher ¶
Cipher is re-exported from vfs/crypto so consumers of the root package don't need a separate import for the common case. All crypto.Cipher values are usable here.
type ColumnInfo ¶
type ColumnInfo struct {
// Name is the column's name, from sqlite3_column_name.
Name string
// DeclType is the declared column type, from sqlite3_column_decltype.
DeclType string
// DatabaseName is the name of the source database, from sqlite3_column_database_name.
// Empty if the column does not resolve to an unambiguous reference to a single database column,
// such as expressions, function calls, or constants.
DatabaseName string
// TableName is the name of the source table, from sqlite3_column_table_name.
// Empty if the column does not resolve to an unambiguous reference to a single database column,
// such as expressions, function calls, or constants.
TableName string
// OriginName is the name of the source column name, from sqlite3_column_origin_name.
// Empty if the column does not resolve to an unambiguous reference to a single database column,
// such as expressions, function calls, or constants.
OriginName string
}
ColumnInfo describes one output column of a prepared SQL statement.
See https://www.sqlite.org/c3ref/column_database_name.html for more details.
type ColumnMetadata ¶
type ColumnMetadata struct {
DeclType string // declared type, e.g. "INTEGER" ("" for rowid / expressions)
CollSeq string // collation sequence name
NotNull bool // has a NOT NULL constraint
PrimaryKey bool // part of the PRIMARY KEY
AutoInc bool // is INTEGER PRIMARY KEY AUTOINCREMENT
}
ColumnMetadata describes one table column, as reported by sqlite3_table_column_metadata. CollSeq is the declared collation sequence ("BINARY" when none is specified).
type CommitHookFn ¶
type CommitHookFn func() int32
type Config ¶
type Config struct {
// Path is the on-disk file path. Use [InMemory] (or the literal
// ":memory:") for a private per-conn in-memory database. Required.
Path string
// Mode selects the open mode. Zero value is [ModeReadWriteCreate]
// (create the file if missing, then read-write). Use the typed
// constants below.
Mode AccessMode
// Pragmas are applied after open, in struct declaration order
// followed by [Pragmas.Extra] entries. Use [RecommendedPragmas]
// for the production preset (WAL + busy_timeout=5s +
// foreign_keys=on).
Pragmas Pragmas
// Encryption, when non-nil, transparently encrypts the on-disk
// file via [vfs/crypto]. The opened *DB bundles the VFS handle;
// Close releases both the *sql.DB pool AND the VFS.
Encryption *Encryption
// VFS overrides the SQLite VFS name. Set only when you have a
// pre-registered VFS to route through; leave empty otherwise.
// Mutually exclusive with Encryption (which registers its own
// VFS internally).
VFS string
// Cache routes the SQLite `cache=` URI parameter. Use [CacheShared]
// to let multiple connections in the same process see the same
// (possibly in-memory) database; leave empty for SQLite's default
// per-conn private cache.
Cache CacheMode
// MaxOpenConns / MaxIdleConns / ConnMaxLifetime are passed
// through to the underlying *sql.DB via the corresponding
// SetMaxOpenConns / SetMaxIdleConns / SetConnMaxLifetime calls.
// Zero = leave at sql defaults.
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
}
Config is the modern, struct-typed way to describe a SQLite open. Every knob you'd otherwise stuff into a `file:…?_pragma=…&vfs=…` DSN string is a Go field here. Zero-valued fields leave SQLite at its own default; only the values you set fire as PRAGMA statements.
Pass to Open to receive a *DB that bundles the *sql.DB pool with any VFS handles the open registered, so a single Close releases everything in the right order.
The classic DSN-string entry points (`sql.Open("sqlite", dsn)`, `sql.Open("sqlite3", dsn)`) keep working unchanged. Config is the new way, not the only way.
type ConflictAction ¶
type ConflictAction int32
ConflictAction is what a ConflictHandler returns to resolve a conflict.
const ( // ChangesetOmit skips the conflicting change and continues. ChangesetOmit ConflictAction = sqlite3.SQLITE_CHANGESET_OMIT // ChangesetReplace overwrites the conflicting row with the change. Only // valid for ConflictData and ConflictConflict; returning it for other // conflict types makes Apply fail with SQLITE_MISUSE. ChangesetReplace ConflictAction = sqlite3.SQLITE_CHANGESET_REPLACE // ChangesetAbort rolls back the whole apply and returns an error. ChangesetAbort ConflictAction = sqlite3.SQLITE_CHANGESET_ABORT )
type ConflictHandler ¶
type ConflictHandler func(ConflictType) ConflictAction
ConflictHandler decides how to resolve a conflict encountered while applying a changeset. With no handler, conflicts abort the apply.
type ConflictType ¶
type ConflictType int32
ConflictType classifies why applying a change conflicted with the target database, passed to a ConflictHandler.
const ( // ConflictData: a DELETE or UPDATE found a row whose non-PK values differ // from the changeset's expected originals. ConflictData ConflictType = sqlite3.SQLITE_CHANGESET_DATA // ConflictNotFound: a DELETE or UPDATE found no row with the change's PK. ConflictNotFound ConflictType = sqlite3.SQLITE_CHANGESET_NOTFOUND // ConflictConflict: an INSERT found a row with a duplicate PK. ConflictConflict ConflictType = sqlite3.SQLITE_CHANGESET_CONFLICT // ConflictConstraint: applying the change violated a constraint // (UNIQUE/NOT NULL/CHECK). ConflictConstraint ConflictType = sqlite3.SQLITE_CHANGESET_CONSTRAINT // ConflictForeignKey: applying the changeset left foreign-key violations. ConflictForeignKey ConflictType = sqlite3.SQLITE_CHANGESET_FOREIGN_KEY )
func (ConflictType) String ¶
func (t ConflictType) String() string
String renders the conflict type for diagnostics.
type Conn ¶
type Conn = conn
Conn is the SQLite database connection type. It is exposed for use inside ConnectHook callbacks and for low-level operations such as custom function registration, hooks, backup, and serialize/deserialize.
Conn is identical to the underlying connection struct used by the driver; the alias gives the type an exported name without renaming the internal receiver across every method definition.
func (*Conn) AnyCollationNeeded ¶
AnyCollationNeeded satisfies every unknown collation by defining it, the first time it is referenced, as a byte-wise (BINARY-equivalent) comparator. Use it to open / ATTACH / restore / inspect a foreign schema that names collations this process does not implement — DDL and queries then succeed instead of failing with "no such collation sequence".
NOTE: affected columns sort byte-wise, not by the collation's real (e.g. locale-aware) order. When ordering fidelity matters, use Conn.CollationNeeded with a real comparator instead.
func (*Conn) ApplyChangeset ¶
func (c *Conn) ApplyChangeset(changeset []byte, opts ...ApplyOption) error
ApplyChangeset applies a changeset (or patchset) to this connection's database inside a savepoint. Conflicts are resolved by a ConflictHandler (WithConflictHandler); without one, the first conflict aborts and rolls back. WithTableFilter restricts which tables are touched.
func (*Conn) AutoCommit ¶
AutoCommit reports whether the connection is in autocommit mode — true at rest, false while an explicit transaction (BEGIN, or an implicit one held open by a failed COMMIT) is in progress. Useful for savepoint/transaction-nesting logic.
func (*Conn) Backup ¶
Backup creates a backup-handle that copies the database identified by srcSchema on src into the database identified by destSchema on the receiver. Step the returned *Backup to make progress and call Finish (or Close) to release resources.
Mattn-compatibility API: equivalent to SQLiteConn.Backup, which copies schema "main" by default but accepts any attached schema name.
// Typical mattn pattern: backup live DB to a new on-disk file.
destDB, _ := sql.Open("sqlite3", "backup.db")
destConn, _ := destDB.Conn(ctx)
destConn.Raw(func(dc any) error {
dst := dc.(*sqlite.Conn)
bk, err := dst.Backup("main", src, "main")
if err != nil { return err }
for {
done, err := bk.Step(100)
if err != nil { return err }
if !done { break }
}
return bk.Finish()
})
func (*Conn) CacheFlush ¶
CacheFlush flushes any dirty pages in this connection's page cache to disk without committing the open transaction, bounding the dirty-page footprint mid-transaction (useful in long bulk-load transactions). There is no PRAGMA equivalent. It is an error to call this while another connection holds a lock that would block the writes.
func (*Conn) CollationNeeded ¶
CollationNeeded registers fn to be invoked when a statement on this connection references a collating sequence that has not been defined. fn is expected to define it — typically by calling Conn.RegisterCollation with the same name — after which SQLite retries the lookup. If fn does not define it, the original "no such collation sequence" error stands.
This is the lazy companion to Conn.RegisterCollation: register collations on demand (e.g. resolving a locale only when a query first needs it) instead of eagerly up front. Like the other hooks it is per-connection, so pin the pool (see internal/testhelp.OpenPinned) when you need the handler on the connection a later query uses.
func (*Conn) ConcatChangesets ¶
ConcatChangesets returns a single changeset equivalent to applying a then b. The connection is used only for its allocator; the database is not touched.
func (*Conn) CreateEponymousModule ¶
CreateEponymousModule registers a Go-implemented eponymous-only virtual table module: SQLite forbids CREATE VIRTUAL TABLE for the name, and instead instantiates the table via xConnect when the module name appears in a SELECT (e.g. `SELECT … FROM array(?)`). See https://sqlite.org/vtab.html#eponymous_virtual_tables for the contract.
Use this for table-valued functions whose schema is fully determined by the constructor — there's nothing per-instance to persist via CREATE VIRTUAL TABLE. ext/array is the canonical example.
Registration is per-connection; for pool-wide application use a [Driver.ConnectHook].
func (*Conn) CreateModule ¶
CreateModule registers a Go-implemented virtual table module on this connection under name. ctor builds a VTab on each CREATE VIRTUAL TABLE (xCreate) and on subsequent opens of an existing virtual table (xConnect); callers that need to distinguish the two cases can switch on the table argument or stash state in package-level maps.
Registration is per-connection. For pool-wide application, install via a [Driver.ConnectHook] — the `ext/<name>/auto/` blank-import sub-packages do exactly that.
Optional interfaces (VTabUpdater, VTabRenamer, VTabTransactional) are recognized automatically when the returned VTab implements them.
func (*Conn) CreateModuleSplit ¶
CreateModuleSplit registers a Go-implemented virtual table module on this connection under name, using separate create and connect ctors so the module can distinguish "first-time CREATE VIRTUAL TABLE" from "subsequent reopen of an existing vtab via the schema cache".
Use this when the module persists state across sessions (e.g. a shadow storage table) and needs different logic for the first CREATE vs every later open. See ext/bloom and ext/spellfix1 for canonical examples — both maintain a `<vtab>_storage` shadow table that is created on xCreate and merely opened on xConnect.
Modules whose create and connect logic are identical should use the simpler Conn.CreateModule instead. Eponymous tables (table-valued functions) only ever go through xConnect; use Conn.CreateEponymousModule for those.
func (*Conn) CreateSession ¶
CreateSession starts a new change-recording session on the given schema (database) of the connection. Pass schema="" for "main". Attach tables with Session.Attach before making changes.
func (*Conn) DeclareVTab ¶
DeclareVTab calls sqlite3_declare_vtab to describe a virtual table's columns to SQLite. Only callable from inside a VTabCtor; calling it elsewhere returns SQLITE_MISUSE wrapped in a Go error.
func (*Conn) EnableChecksums ¶
EnableChecksums sets reserved_bytes=8 on the named schema ("main" for the primary database) and VACUUMs so every existing page is rewritten with the 8-byte trailer in place. After the call the header's reserved_bytes byte reads 8 and any cksm-flavored VFS wrapping the connection (typically gosqlite.org/vfs/cksm) will start computing + verifying page checksums.
Idempotent — if reserved_bytes is already 8 the call is a no-op. Should be used once after opening a fresh database; on subsequent opens the VFS auto-detects the on-disk format and EnableChecksums does not need to be called again.
Mirrors the same-named convenience on ncruces/go-sqlite3's *Conn.
func (*Conn) EnableLoadExtension ¶
EnableLoadExtension toggles the sqlite3_load_extension C API on or off for this connection. SQLite requires this to be enabled before LoadExtension can be called; it is disabled by default for security.
Mattn compatibility: equivalent to enabling the extension flag before calling LoadExtension.
func (*Conn) ErrorOffset ¶
ErrorOffset returns the byte offset into the most recently prepared SQL text of the token associated with the most recent error, or -1 if the error is not tied to a specific token. Pair it with a caret-pointed diagnostic.
func (*Conn) Filename ¶
Filename returns the on-disk path SQLite associates with the given schema ("main", "temp", or an ATTACHed name; "" means "main"). It returns "" for an in-memory or temporary database, and "" if the schema is unknown.
func (*Conn) GetLimit ¶
GetLimit returns the current value of one of the SQLite per-connection limits (SQLITE_LIMIT_*). It does not modify the limit.
Mattn-compatibility API equivalent to SQLiteConn.GetLimit.
func (*Conn) GetSnapshot ¶
GetSnapshot captures the current state of the schema's database as a Snapshot. The connection must have a read transaction open on the schema, and the database must be in WAL mode. Pass schema="" for "main".
func (*Conn) InvertChangeset ¶
InvertChangeset returns the inverse of a changeset: applying the inverse undoes what the original applies (INSERT↔DELETE, UPDATE reversed). Patchsets cannot be inverted. The connection is used only for its allocator; the database is not touched.
func (*Conn) LoadExtension ¶
LoadExtension loads the SQLite extension at libPath into this connection, optionally calling the named entry point (pass "" for the default). The extension flag must be enabled first via EnableLoadExtension(true) unless the connection was opened by a Driver whose Extensions field was non-empty.
Mattn compatibility: equivalent to mattn's SQLiteConn.LoadExtension.
Platform note: success depends on dynamic-loader support in modernc.org/libc. As of the libc release pinned in `go.mod`, libc's Xdlopen (darwin) and XLoadLibraryW (windows) shims are not implemented and abort the process with "TODOTODO" the moment they are reached — which happens even on the disabled-extensions error path. linux and freebsd are fine. The test suite skips both LoadExtension tests on darwin and windows for that reason; the positive path is platform-dependent.
func (*Conn) OpenBlob ¶
OpenBlob opens a handle to a single BLOB or TEXT value identified by (schema, table, column, rowid). Pass schema="main" for the default database or "" to use SQLite's default. If write is true the handle is opened for read+write; otherwise it is read-only.
The blob handle is valid until Close is called or until the underlying row changes in a way that invalidates the handle (in which case I/O operations return SQLITE_ABORT). Use Reopen to rebind a single handle across many rows in the same column without reallocating, which is materially cheaper than repeated OpenBlob/Close cycles.
Wraps sqlite3_blob_open: https://sqlite.org/c3ref/blob_open.html
func (*Conn) OpenSnapshot ¶
OpenSnapshot starts the next read transaction on schema reading the database as it was when snap was captured. Call it on a connection with no open transaction, immediately before the BEGIN that starts the read. WAL only.
func (*Conn) QueryDBConfig ¶
func (c *Conn) QueryDBConfig(op DBConfigOp) (bool, error)
QueryDBConfig returns the current value of a boolean connection flag without changing it.
func (*Conn) RegisterAggregator ¶
RegisterAggregator registers a Go type with Step and Done methods as a SQLite aggregate function for this connection only.
Mattn-compatibility API: the impl argument must be a function that returns a new instance of an aggregate type. Each invocation of the aggregate at SQL query time creates one instance via impl(), then calls its Step(...) for each row and its Done() at the end. Step's argument types follow the same rules as RegisterFunc; Done returns the aggregate value, optionally with an error.
Setting pure=true marks the aggregate as deterministic.
func (*Conn) RegisterAuthorizer ¶
func (c *Conn) RegisterAuthorizer(fn AuthorizerFn)
RegisterAuthorizer installs an authorization callback consulted for every access to schema objects during statement compilation. Passing a nil callback removes any previously installed authorizer.
Per-connection registration. Mattn-compatibility API.
func (*Conn) RegisterBusyHandler ¶
func (c *Conn) RegisterBusyHandler(handler BusyHandler)
RegisterBusyHandler installs handler as this connection's busy callback, replacing any previous handler. Pass nil to remove it.
This is the programmable alternative to a fixed `busy_timeout`: use it for adaptive / jittered / deadline-aware retry on a high-contention WAL database. Note that SQLite's busy handler and busy_timeout are mutually exclusive — installing one clears the other.
Per-connection, like the other hooks: pin the pool so the handler is on the connection a later query uses.
func (*Conn) RegisterCollation ¶
RegisterCollation registers a Go comparator as a named SQLite collation for this connection only. The comparator must obey the standard sort contract: negative if a < b, zero if a == b, positive if a > b.
Mattn-compatibility API equivalent to SQLiteConn.RegisterCollation.
func (*Conn) RegisterFTS5Tokenizer ¶
func (c *Conn) RegisterFTS5Tokenizer(name string, newTokenizer func(args []string) (FTS5Tokenizer, error)) error
RegisterFTS5Tokenizer registers a Go-implemented FTS5 tokenizer under name on this connection. After registration a table can use it via
CREATE VIRTUAL TABLE docs USING fts5(body, tokenize='name')
newTokenizer is called once per table that references the tokenizer (with the space-separated arguments that follow the name in the tokenize= option) and returns the FTS5Tokenizer that table will use.
The registration is per-connection (the fts5_api is bound to one connection), so create the table on the same connection — pin the pool (see internal/testhelp.OpenPinned). No other pure-Go SQLite driver exposes custom FTS5 tokenizers.
func (*Conn) RegisterFunc ¶
RegisterFunc registers a Go function as a SQLite scalar function for this connection only.
Mattn-compatibility API: the function impl may have any signature whose argument and return types are supported. Supported argument types are int*, uint*, float64, bool, string, []byte, time.Time, and any (which receives the value as the corresponding Go type from the SQLite value). The function may return a single value, or (value, error). The last argument may be variadic.
Setting pure=true marks the function as deterministic (SQLITE_DETERMINISTIC), allowing SQLite to use it inside indexes and to fold its result for repeated invocations with identical arguments.
The function is registered on this connection only, mirroring mattn's per-connection registration model.
func (*Conn) RegisterRTreeGeometry ¶
func (c *Conn) RegisterRTreeGeometry(name string, fn RTreeGeometryFunc) error
RegisterRTreeGeometry registers fn as a custom R-Tree geometry function named name, usable as `WHERE <rtree>.id MATCH name(…)`. See RTreeGeometryFunc.
Wraps sqlite3_rtree_geometry_callback: https://sqlite.org/rtree.html#custom_r_tree_queries
func (*Conn) RegisterRTreeQuery ¶
func (c *Conn) RegisterRTreeQuery(name string, fn RTreeQueryFunc) error
RegisterRTreeQuery registers fn as a custom R-Tree query function named name. It is the second-generation, more expressive form of [RegisterRTreeGeometry]: fn sees the node's tree position and assigns a within-classification plus a visit-order score. See RTreeQueryFunc.
Wraps sqlite3_rtree_query_callback: https://sqlite.org/rtree.html#custom_r_tree_queries
func (*Conn) RegisterUpdateHook ¶
func (c *Conn) RegisterUpdateHook(fn UpdateHookFn)
RegisterUpdateHook installs a callback that fires after every INSERT, UPDATE, or DELETE on a rowid table. Passing a nil callback removes any previously installed hook.
Per-connection registration. Mattn-compatibility API.
func (*Conn) RegisterWALHook ¶
RegisterWALHook installs hook as the post-commit WAL callback. Passing nil removes it and restores the default auto-checkpoint behavior.
Per-connection registration.
func (*Conn) RegisterWindowFunction ¶
func (c *Conn) RegisterWindowFunction(name string, nArg int, constructor func() WindowAccumulator, pure bool) error
RegisterWindowFunction registers a Go window-function implementation on this connection only. Each invocation of the function in SQL creates a fresh accumulator via constructor() and then drives it through SQLite's standard Step / Inverse / Value / Final lifecycle.
Setting pure=true marks the function as deterministic (SQLITE_DETERMINISTIC), enabling SQLite to use it inside indexes and to fold its result for repeated invocations with identical arguments. Most accumulators are pure; pass false if the implementation reads external state (clock, RNG, env).
nArg is the number of arguments the SQL function takes; pass -1 for variadic.
Why nArg is explicit (vs reflective like RegisterAggregator) ¶
Conn.RegisterAggregator infers argument count by reflecting over the Step method's signature: it accepts a typed value (e.g. *myAggregator with `Step(a, b float64)`), so the arity comes from reflect.Type.NumIn(). RegisterWindowFunction can't do that — the constructor returns a WindowAccumulator interface, whose Step method has the fixed signature `Step(*FunctionContext, []driver.Value)`, from which no per-arg information is recoverable. Callers therefore pass nArg explicitly. This is intentional: window functions frequently want variadic / multi-typed arg lists (which reflection couldn't express anyway), and the explicit form keeps the API honest about what SQLite needs.
Example: a running-sum window function. Final is omitted — pure math doesn't need cleanup, and the accumulator is GC'd along with the rest of the query state.
type sumState struct{ total float64 }
func (s *sumState) Step(_ *sqlite.FunctionContext, a []driver.Value) error {
s.total += a[0].(float64)
return nil
}
func (s *sumState) Inverse(_ *sqlite.FunctionContext, a []driver.Value) error {
s.total -= a[0].(float64)
return nil
}
func (s *sumState) Value(_ *sqlite.FunctionContext) (driver.Value, error) {
return s.total, nil
}
conn.RegisterWindowFunction("running_sum", 1,
func() sqlite.WindowAccumulator { return &sumState{} }, true)
func (*Conn) ResetCache ¶
ResetCache discards this connection's page cache for schema (SQLITE_FCNTL_RESET_CACHE), forcing subsequent reads to re-fetch from the VFS. Use it after a lower layer (a wrapping VFS, an external process) has changed the database file out from under SQLite. schema="" means "main".
func (*Conn) SerializeSchema ¶
SerializeSchema returns a serialization of the schema named on this connection. Pass schema = "main" or empty for the main database.
Convenience wrapper around the existing *conn.Serialize method that hides the schema argument from callers who only need the default.
func (*Conn) SetDBConfig ¶
func (c *Conn) SetDBConfig(op DBConfigOp, enable bool) (bool, error)
SetDBConfig sets a boolean connection flag and returns its resulting value. These flags — especially the security ones (DEFENSIVE, TRUSTED_SCHEMA, WRITABLE_SCHEMA) — are reachable only through sqlite3_db_config, not PRAGMA.
func (*Conn) SetFileControlInt ¶
SetFileControlInt issues a file-control op whose argument is a single int, returning the value SQLite leaves in the slot (many such ops are read-modify-write — e.g. SQLITE_FCNTL_CHUNK_SIZE, SQLITE_FCNTL_PERSIST_WAL, SQLITE_FCNTL_POWERSAFE_OVERWRITE). schema="" means "main". It is the generic escape hatch over sqlite3_file_control for the int-argument ops this package does not wrap individually.
func (*Conn) SetLimit ¶
SetLimit sets the given SQLITE_LIMIT_* identifier to newVal and returns the previous value. Pass -1 for newVal to leave the limit unchanged (use GetLimit if that's all you want).
Mattn-compatibility API equivalent to SQLiteConn.SetLimit.
func (*Conn) SetProgressHandler ¶
func (c *Conn) SetProgressHandler(n int, handler ProgressHandler)
SetProgressHandler installs handler, called every n VM instructions while a statement runs — useful for progress reporting and cooperative cancellation (return true to interrupt). Pass n<=0 or a nil handler to remove it. This complements [Conn.IsInterrupted], which polls rather than calls back.
func (*Conn) SetTrace ¶
func (c *Conn) SetTrace(cfg *TraceConfig) error
SetTrace installs (or removes, when cfg.Callback is nil or cfg.EventMask is zero) a tracing callback driven by sqlite3_trace_v2.
Per-connection registration. Mattn-compatibility API.
func (*Conn) SnapshotRecover ¶
SnapshotRecover makes every historical snapshot of the schema reachable by Conn.OpenSnapshot, not just states since the last checkpoint. There must be no read transaction open on the schema.
func (*Conn) Status ¶
Status returns a per-connection runtime counter from sqlite3_db_status: the current value and its high-water mark. Pass reset=true to zero the high-water mark after reading. This is SQLite's own cache/lookaside/memory accounting — distinct from [Conn.StmtCacheStats], which reports our Go-side prepared-statement LRU.
func (*Conn) TableColumnMetadata ¶
func (c *Conn) TableColumnMetadata(schema, table, column string) (ColumnMetadata, error)
TableColumnMetadata returns metadata for a single column without preparing a query. Pass schema="" to search every attached database (main, temp, then attached, in that order). It wraps sqlite3_table_column_metadata; passing column="" with table set is the documented way to check that the table exists and find whether it has a rowid.
func (*Conn) TxnState ¶
TxnState returns the transaction state of the given schema on this connection. schema="" asks for the most advanced state across all schemas.
func (*Conn) WALAutoCheckpoint ¶
WALAutoCheckpoint sets the WAL auto-checkpoint threshold: SQLite runs a PASSIVE checkpoint after a commit that pushes the WAL past frames frames. Pass 0 to disable automatic checkpointing. Default is 1000.
func (*Conn) WALCheckpoint ¶
func (c *Conn) WALCheckpoint(schema string, mode CheckpointMode) (logFrames, checkpointed int, err error)
WALCheckpoint runs a checkpoint on the WAL of the given schema (pass "" for all attached databases). It returns the size of the WAL log in frames and the number of frames checkpointed back into the database — values the `PRAGMA wal_checkpoint` form cannot surface per-schema. Requires WAL mode.
type ConnectionHookFn ¶
type ConnectionHookFn func( conn ExecQuerierContext, dsn string, ) error
ConnectionHookFn function type for a connection hook on the Driver. Connection hooks are called after the connection has been set up.
type Constraint ¶
type Constraint = vtab.Constraint
IndexInfo, Constraint, OrderBy, ConstraintOp are re-exported so a VTab implementation of BestIndex doesn't need a second import.
type ConstraintOp ¶
type ConstraintOp = vtab.ConstraintOp
IndexInfo, Constraint, OrderBy, ConstraintOp are re-exported so a VTab implementation of BestIndex doesn't need a second import.
type DB ¶
DB wraps *sql.DB so the caller can `defer db.Close()` without thinking about the encryption VFS lifecycle. Embedded *sql.DB means every database/sql method works unchanged:
db, err := sqlite.Open(sqlite.Config{Path: "x.db"})
if err != nil { ... }
defer db.Close()
rows, err := db.Query("SELECT ...") // *sql.DB methods
func Open ¶
Open is the modern Go-typed entry point. It builds a DSN that carries every requested PRAGMA as a `_pragma=` URL flag (so the driver applies them at connection open, on every connection in the pool — not just the one database/sql happens to dispatch the first Exec to), opens the underlying *sql.DB, eagerly Pings to surface any PRAGMA error as an Open error, and returns a wrapper that bundles any VFS handles in the Close.
Lifecycle: a single defer db.Close() is sufficient — closing drains the *sql.DB pool first, then unregisters any VFS that Open registered for this database (encryption case).
Backward-compat note: this does not replace `sql.Open("sqlite", dsn)`. Both keep working. Open(Config) is the recommended new path; the DSN form is what BuildDSN produces, exposed for callers integrating with code that already speaks DSN.
func OpenInMemory ¶
OpenInMemory is the shortest path to a private in-memory database: equivalent to Open with Config{Path: InMemory}. Convenient for tests, REPLs, and scratch usage that doesn't need PRAGMAs, encryption, or pool tuning.
db, err := sqlite.OpenInMemory() defer db.Close()
For an in-memory DB shared across multiple connections in the same process, use OpenShared.
func OpenReadOnly ¶
OpenReadOnly opens an existing file-backed database in read-only mode. Refuses to create the file if missing — matches SQLite's `mode=ro`. Equivalent to:
sqlite.Open(sqlite.Config{Path: path, Mode: sqlite.ModeReadOnly})
Typical use: opening a shipped seed database or a read replica without risking accidental writes.
func OpenShared ¶
OpenShared opens (or creates) a named in-memory database that every connection in the same process pointing at the same name shares. Equivalent to:
sqlite.Open(sqlite.Config{Path: name, Mode: sqlite.ModeMemory, Cache: sqlite.CacheShared})
Unlike OpenInMemory / InMemory (which gives each conn its own private store), OpenShared lets multiple *sql.DB handles see the same in-memory rows — the standard SQLite recipe for multi-conn in-memory tests. The shared store lives for the lifetime of the process; opening the same name from a second goroutine re-attaches to it.
For snapshot isolation or richer semantics, use the gosqlite.org/vfs/mvcc or gosqlite.org/vfs/memdb sub-packages.
func OpenWAL ¶
OpenWAL opens a file-backed database with the RecommendedPragmas preset — WAL journaling, 5-second busy timeout, foreign keys enforced. Equivalent to:
sqlite.Open(sqlite.Config{Path: path, Pragmas: sqlite.RecommendedPragmas()})
Most production applications want exactly this. Tune the pool size or other PRAGMAs by reaching for the full Open/Config form.
func (*DB) Close ¶
Close drains the *sql.DB pool and (if Open registered a VFS for encryption) unregisters it. Order matters per vfs/crypto/doc.go: pool first, VFS second. Idempotent.
type DBConfigOp ¶
type DBConfigOp int32
DBConfigOp selects a boolean per-connection configuration flag for Conn.SetDBConfig / Conn.QueryDBConfig.
const ( // DBConfigDefensive disables language features that let a corrupt or // hostile database file harm the application (writable_schema, PRAGMA-driven // schema edits, …). Reachable only here, not via PRAGMA. DBConfigDefensive DBConfigOp = sqlite3.SQLITE_DBCONFIG_DEFENSIVE // DBConfigTrustedSchema controls whether the schema may invoke non-trusted // extension functions; off is the hardened setting. DBConfigTrustedSchema DBConfigOp = sqlite3.SQLITE_DBCONFIG_TRUSTED_SCHEMA // DBConfigWritableSchema allows direct writes to sqlite_schema. DBConfigWritableSchema DBConfigOp = sqlite3.SQLITE_DBCONFIG_WRITABLE_SCHEMA // DBConfigResetDatabase, when enabled then VACUUMed then disabled, resets a // database to empty. DBConfigResetDatabase DBConfigOp = sqlite3.SQLITE_DBCONFIG_RESET_DATABASE // DBConfigForeignKeys toggles foreign-key enforcement (same effect as // PRAGMA foreign_keys). DBConfigForeignKeys DBConfigOp = sqlite3.SQLITE_DBCONFIG_ENABLE_FKEY // DBConfigTriggers toggles trigger execution. DBConfigTriggers DBConfigOp = sqlite3.SQLITE_DBCONFIG_ENABLE_TRIGGER // DBConfigViews toggles view usage. DBConfigViews DBConfigOp = sqlite3.SQLITE_DBCONFIG_ENABLE_VIEW // DBConfigNoCkptOnClose suppresses the checkpoint that normally runs when // the last connection to a WAL database closes. DBConfigNoCkptOnClose DBConfigOp = sqlite3.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE // DBConfigReverseScanOrder reverses the order of unordered scans (a fuzzing // / robustness aid). DBConfigReverseScanOrder DBConfigOp = sqlite3.SQLITE_DBCONFIG_REVERSE_SCANORDER // DBConfigDQSDML controls the double-quoted-string-literal misfeature for // DML; off rejects "string" where 'string' was meant. DBConfigDQSDML DBConfigOp = sqlite3.SQLITE_DBCONFIG_DQS_DML // DBConfigDQSDDL is DBConfigDQSDML for DDL statements. DBConfigDQSDDL DBConfigOp = sqlite3.SQLITE_DBCONFIG_DQS_DDL )
type DBStatus ¶
type DBStatus int32
DBStatus selects a per-connection runtime counter for Conn.Status.
const ( DBStatusLookasideUsed DBStatus = sqlite3.SQLITE_DBSTATUS_LOOKASIDE_USED DBStatusCacheUsed DBStatus = sqlite3.SQLITE_DBSTATUS_CACHE_USED DBStatusSchemaUsed DBStatus = sqlite3.SQLITE_DBSTATUS_SCHEMA_USED DBStatusStmtUsed DBStatus = sqlite3.SQLITE_DBSTATUS_STMT_USED DBStatusLookasideHit DBStatus = sqlite3.SQLITE_DBSTATUS_LOOKASIDE_HIT DBStatusLookasideMissSize DBStatus = sqlite3.SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE DBStatusLookasideMissFull DBStatus = sqlite3.SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL DBStatusCacheHit DBStatus = sqlite3.SQLITE_DBSTATUS_CACHE_HIT DBStatusCacheMiss DBStatus = sqlite3.SQLITE_DBSTATUS_CACHE_MISS DBStatusCacheWrite DBStatus = sqlite3.SQLITE_DBSTATUS_CACHE_WRITE DBStatusCacheSpill DBStatus = sqlite3.SQLITE_DBSTATUS_CACHE_SPILL DBStatusDeferredFKs DBStatus = sqlite3.SQLITE_DBSTATUS_DEFERRED_FKS )
Per-connection status counters (sqlite3_db_status). Each returns a current and a high-water value; some (the CACHE_HIT/MISS/WRITE/SPILL family) only populate the current value.
type Driver ¶
type Driver struct {
// Extensions is a list of SQLite extension shared-library paths to load
// into every new connection via sqlite3_load_extension. Loaded after the
// connection is opened but before user ConnectHook fires. Mattn-compatible.
Extensions []string
// ConnectHook, if non-nil, is invoked once for every newly-opened
// connection, after Extensions are loaded and after the modernc-style
// connection hooks run. Mattn-compatible.
ConnectHook func(*Conn) error
// contains filtered or unexported fields
}
Driver implements database/sql/driver.Driver.
Registration functions and methods must be called before the first call to Open.
For drop-in compatibility with github.com/mattn/go-sqlite3, the type alias SQLiteDriver and the public fields Extensions and ConnectHook are provided so existing mattn code that does
sql.Register("custom", &sqlite3.SQLiteDriver{
Extensions: []string{"my_ext"},
ConnectHook: func(c *sqlite3.SQLiteConn) error { ... },
})
continues to work unchanged with this package.
func DefaultDriver ¶
func DefaultDriver() *Driver
DefaultDriver returns the singleton *Driver the package registers under both "sqlite" and "sqlite3". Use this when a sub-package needs to install a [Driver.ConnectHook] from an init() function — for example, the `ext/<name>/auto/` blank-import sub-packages register their module on every new connection by chaining onto the existing ConnectHook.
Callers MUST preserve any previously-installed hook by invoking the prior value before running their own work. Assigning DefaultDriver().ConnectHook = … without saving and chaining discards the existing hook silently.
func (*Driver) Open ¶
Open returns a new connection to the database. The name is a string in a driver-specific format.
Open may return a cached connection (one previously closed), but doing so is unnecessary; the sql package maintains a pool of idle connections for efficient re-use.
The returned connection is only used by one goroutine at a time.
The name may be a filename, e.g., "/tmp/mydata.sqlite", or a URI, in which case it may include a '?' followed by one or more query parameters. For example, "file:///tmp/mydata.sqlite?_pragma=foreign_keys(1)&_time_format=sqlite". The supported query parameters are:
_pragma: Each value will be run as a "PRAGMA ..." statement (with the PRAGMA keyword added for you). May be specified more than once, '&'-separated. For more information on supported PRAGMAs see: https://www.sqlite.org/pragma.html
_time_format: The name of a format to use when writing time values to the database. The currently supported values are (1) "sqlite" for YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM (format 4 from https://www.sqlite.org/lang_datefunc.html#time_values with sub-second precision and timezone specifier) and (2) "datetime" for YYYY-MM-DD HH:MM:SS (format 3, matching the output of SQLite's datetime() function). If this parameter is not specified, then the default String() format will be used.
_time_integer_format: The name of a integer format to use when writing time values. By default, the time is stored as string and the format can be set with _time_format parameter. If _time_integer_format is set, the time will be stored as an integer and the integer value will depend on the integer format. If you decide to set both _time_format and _time_integer_format, the time will be converted as integer and the _time_format value will be ignored. Currently the supported value are "unix","unix_milli", "unix_micro" and "unix_nano", which corresponds to seconds, milliseconds, microseconds or nanoseconds since unixepoch (1 January 1970 00:00:00 UTC).
_inttotime: Enable conversion of time column (DATE, DATETIME,TIMESTAMP) from integer to time if the field contain integer (int64).
_texttotime: Enable ColumnTypeScanType to report time.Time instead of string for TEXT columns declared as DATE, DATETIME, TIME, or TIMESTAMP.
_timezone: A timezone to use for all time reads and writes, such as "UTC". The value is parsed by time.LoadLocation. Writes will convert to the timezone before formatting as a string; it does not impact _inttotime integer values, as they always use UTC. Reads will interpret timezone-less strings as being in this timezone. Values that are in a known timezone, such as a string with a timezone specifier or an integer with _inttotime (specified to be in UTC), will be converted to this timezone.
_txlock: The locking behavior to use when beginning a transaction. May be "deferred" (the default), "immediate", or "exclusive" (case insensitive). See: https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions
func (*Driver) RegisterConnectionHook ¶
func (d *Driver) RegisterConnectionHook(fn ConnectionHookFn)
RegisterConnectionHook registers a function to be called after each connection is opened. This is called after all the connection has been set up.
type Encryption ¶
type Encryption struct {
// Key is the raw cipher key. Length depends on Cipher: 32 bytes
// for [Adiantum] (default), 64 bytes for [AESXTS]. Use
// [crypto.DeriveKey] to turn a passphrase + salt into the right
// number of bytes.
//
// The caller's slice is defensively copied; you're free to zero
// or mutate it after [Open] returns.
Key []byte
// Cipher selects the encryption mode. Zero value is [Adiantum].
Cipher Cipher
// PageSize must match the database's PRAGMA page_size if the DB
// already exists. Zero = 4096 (SQLite default).
PageSize int
// Recorder receives per-IO observability events (one per xRead /
// xWrite / xSync trampoline). Nil disables. Use
// [crypto.NewSlogRecorder] for an slog-shaped recorder.
Recorder crypto.Recorder
}
Encryption bundles the page-level encryption options. The fields are a thin pass-through to crypto.Options; see that type for per-field semantics. Set [Config.Encryption] to enable.
type ErrNo ¶
type ErrNo int
Mattn-compatible error code aliases (mattn exposes these as ErrNo values). Code that does `if err.Code() == sqlite.ErrConstraintUnique` continues to work after switching imports.
const ( ErrError ErrNo = sqlite3.SQLITE_ERROR ErrInternal ErrNo = sqlite3.SQLITE_INTERNAL ErrPerm ErrNo = sqlite3.SQLITE_PERM ErrAbort ErrNo = sqlite3.SQLITE_ABORT ErrBusy ErrNo = sqlite3.SQLITE_BUSY ErrLocked ErrNo = sqlite3.SQLITE_LOCKED ErrNomem ErrNo = sqlite3.SQLITE_NOMEM ErrReadonly ErrNo = sqlite3.SQLITE_READONLY ErrInterrupt ErrNo = sqlite3.SQLITE_INTERRUPT ErrIoErr ErrNo = sqlite3.SQLITE_IOERR ErrCorrupt ErrNo = sqlite3.SQLITE_CORRUPT ErrNotFound ErrNo = sqlite3.SQLITE_NOTFOUND ErrFull ErrNo = sqlite3.SQLITE_FULL ErrCantOpen ErrNo = sqlite3.SQLITE_CANTOPEN ErrProtocol ErrNo = sqlite3.SQLITE_PROTOCOL ErrEmpty ErrNo = sqlite3.SQLITE_EMPTY ErrSchema ErrNo = sqlite3.SQLITE_SCHEMA ErrTooBig ErrNo = sqlite3.SQLITE_TOOBIG ErrConstraint ErrNo = sqlite3.SQLITE_CONSTRAINT ErrMismatch ErrNo = sqlite3.SQLITE_MISMATCH ErrMisuse ErrNo = sqlite3.SQLITE_MISUSE ErrNoLFS ErrNo = sqlite3.SQLITE_NOLFS ErrAuth ErrNo = sqlite3.SQLITE_AUTH ErrFormat ErrNo = sqlite3.SQLITE_FORMAT ErrRange ErrNo = sqlite3.SQLITE_RANGE ErrNotADB ErrNo = sqlite3.SQLITE_NOTADB ErrNotice ErrNo = sqlite3.SQLITE_NOTICE ErrWarning ErrNo = sqlite3.SQLITE_WARNING )
type ErrNoExtended ¶
type ErrNoExtended int
Extended constraint error code aliases (mattn-compatible).
const ( ErrConstraintCheck ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_CHECK ErrConstraintForeignKey ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY ErrConstraintNotNull ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_NOTNULL ErrConstraintPrimaryKey ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY ErrConstraintTrigger ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_TRIGGER ErrConstraintUnique ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_UNIQUE ErrConstraintRowID ErrNoExtended = sqlite3.SQLITE_CONSTRAINT_ROWID )
func (ErrNoExtended) Error ¶
func (e ErrNoExtended) Error() string
Error makes ErrNoExtended satisfy the error interface so it can be used as a target for errors.Is.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error represents a SQLite library error.
The Code accessor returns the primary SQLite result code (low byte). For the full extended code (e.g. SQLITE_CONSTRAINT_UNIQUE = SQLITE_CONSTRAINT | (8 << 8)), use ExtendedCode.
Mattn-compatibility note: mattn's Error struct exposes Code/ExtendedCode as exported fields of type ErrNo / ErrNoExtended; this struct surfaces them as methods to keep field-level compatibility cross-driver. Code that does `if e.Code() == sqlite.SQLITE_CONSTRAINT` works the same as mattn's `if e.Code == sqlite3.ErrConstraint` (compare against ErrConstraint type-cast).
func (*Error) Code ¶
Code returns the primary SQLite result code for this error (low byte of the extended code). Compare against the SQLITE_* constants.
func (*Error) ExtendedCode ¶
ExtendedCode returns the extended SQLite result code for this error (e.g. SQLITE_CONSTRAINT_UNIQUE). Compare against ErrConstraint* constants or the SQLITE_CONSTRAINT_* family.
type ExecQuerierContext ¶
type ExecQuerierContext interface {
driver.ExecerContext
driver.QueryerContext
}
type FTS5Tokenizer ¶
type FTS5Tokenizer interface {
Tokenize(text string, emit func(token string, start, end int) error) error
}
FTS5Tokenizer splits document and query text into tokens for an FTS5 full-text index. Implementations are registered with Conn.RegisterFTS5Tokenizer and referenced from CREATE VIRTUAL TABLE … USING fts5(…, tokenize='name').
Tokenize is called for both indexing and querying. For each token, call emit with the token text and the [start, end) byte offsets of the source span it came from (offsets into text; used for snippet/highlight). The token text need not be a substring of text — fold case, stem, or transliterate freely. Return emit's error to stop early; returning a non-nil error from Tokenize aborts the operation.
type FileControl ¶
type FileControl interface {
// Set or query SQLITE_FCNTL_PERSIST_WAL, returns set mode or query result
FileControlPersistWAL(dbName string, mode int) (int, error)
// Query SQLITE_FCNTL_DATA_VERSION, returns the pager-cache data version
// for dbName. The value changes whenever the contents of the database
// file change, which makes it suitable for cache-invalidation use cases.
// See
// https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntldataversion.
FileControlDataVersion(dbName string) (uint32, error)
// Query (n<0) or set (n>=0) SQLITE_FCNTL_RESERVE_BYTES for dbName.
// Returns the resulting reserved-bytes count. Reserved bytes are an
// unused area at the end of each page available to extensions like
// the checksum VFS (see gosqlite.org/vfs/cksm).
// Setting the value on a non-empty database does not retroactively
// rewrite existing pages — VACUUM the database after setting it so
// that every page is rebuilt with the new trailer width.
FileControlReserveBytes(dbName string, n int) (int, error)
}
Access to sqlite3_file_control
type FunctionContext ¶
type FunctionContext struct {
// contains filtered or unexported fields
}
FunctionContext represents the context user defined functions execute in. Fields and/or methods of this type may get addedd in the future.
Beyond identifying the invocation it exposes the SQLite function-context substrate: result/argument subtypes (FunctionContext.ResultSubtype / FunctionContext.ValueSubtype) and per-argument auxiliary-data caching (FunctionContext.SetAuxData / FunctionContext.GetAuxData). See function_context.go.
func (*FunctionContext) GetAuxData ¶
func (c *FunctionContext) GetAuxData(i int) (any, bool)
GetAuxData returns the value previously cached against argument i via SetAuxData, or (nil, false) if none is live (never set, or evicted because the argument was not constant).
func (*FunctionContext) ResultSubtype ¶
func (c *FunctionContext) ResultSubtype(subtype uint)
ResultSubtype requests that this function's result value carry the given SQLite subtype — the value a consumer reads back via sqlite3_value_subtype (exposed here as FunctionContext.ValueSubtype). Only the low 8 bits are significant. It is applied by the trampoline after the result value is set, so it may be called anywhere in the scalar or window-function body.
func (*FunctionContext) SetAuxData ¶
func (c *FunctionContext) SetAuxData(i int, data any)
SetAuxData caches data against argument i so a later invocation of the same function for the same constant argument can retrieve it via GetAuxData — the idiom for compiling a pattern / parsing a path once and reusing it per row.
SQLite only preserves the cache while argument i is invariant across rows; otherwise GetAuxData returns (nil, false) and the function must recompute. The cached value is released automatically when SQLite evicts it (a replacing SetAuxData or statement finalize) — do not hold the value past the row unless you own a separate reference.
func (*FunctionContext) ValueSubtype ¶
func (c *FunctionContext) ValueSubtype(i int) uint
ValueSubtype returns the subtype of argument i (0-based) — the tag an upstream function attached via ResultSubtype. It returns 0 when i is out of range or the context carries no arguments (e.g. a window Value/Final call).
type FunctionImpl ¶
type FunctionImpl struct {
// NArgs is the required number of arguments that the function accepts.
// If NArgs is negative, then the function is variadic.
NArgs int32
// If Deterministic is true, the function must always give the same
// output when the input parameters are the same. This enables functions
// to be used in additional contexts like the WHERE clause of partial
// indexes and enables additional optimizations.
//
// See https://sqlite.org/c3ref/c_deterministic.html#sqlitedeterministic
// for more details.
Deterministic bool
// Innocuous marks the function as harmless — no side effects, no access to
// the filesystem or environment, output depends only on its arguments. Such
// functions remain usable from triggers, views, and partial indexes when
// SetDBConfig(DBConfigDefensive, true) or trusted_schema=OFF is in effect,
// where non-innocuous application functions are rejected.
Innocuous bool
// DirectOnly forbids the function from being invoked indirectly via
// triggers, views, or schema-embedded SQL — only from top-level SQL the
// application submits. The conservative default for functions with side
// effects, blocking a malicious schema from invoking them. Mutually
// exclusive in spirit with Innocuous.
DirectOnly bool
// Subtype declares that the function reads the subtype of one or more of its
// arguments via FunctionContext.ValueSubtype. SQLite uses this to keep the
// subtype information flowing through the expression.
Subtype bool
// Scalar is called when a scalar function is invoked in SQL. The
// argument Values are not valid past the return of the function.
Scalar func(ctx *FunctionContext, args []driver.Value) (driver.Value, error)
// MakeAggregate is called at the beginning of each evaluation of an
// aggregate function.
MakeAggregate func(ctx FunctionContext) (AggregateFunction, error)
}
FunctionImpl describes an application-defined SQL function. If Scalar is set, it is treated as a scalar function; otherwise, it is treated as an aggregate function using MakeAggregate.
type HookRegisterer ¶
type HookRegisterer interface {
RegisterPreUpdateHook(PreUpdateHookFn)
RegisterCommitHook(CommitHookFn)
RegisterRollbackHook(RollbackHookFn)
}
type IndexInfo ¶
IndexInfo, Constraint, OrderBy, ConstraintOp are re-exported so a VTab implementation of BestIndex doesn't need a second import.
type JournalMode ¶
type JournalMode string
JournalMode is the typed enum for SQLite's journal_mode pragma. Empty value leaves SQLite at its compile-time default (DELETE).
const ( JournalDelete JournalMode = "DELETE" JournalTruncate JournalMode = "TRUNCATE" JournalPersist JournalMode = "PERSIST" JournalMemory JournalMode = "MEMORY" JournalWAL JournalMode = "WAL" JournalOff JournalMode = "OFF" )
type OrderBy ¶
IndexInfo, Constraint, OrderBy, ConstraintOp are re-exported so a VTab implementation of BestIndex doesn't need a second import.
type Pragmas ¶
type Pragmas struct {
// JournalMode selects the journaling strategy. Use [JournalWAL]
// for production. Empty = leave alone.
JournalMode JournalMode
// BusyTimeout is mapped onto `PRAGMA busy_timeout = <ms>`. Zero =
// leave alone (SQLite default 0 ms = immediate SQLITE_BUSY).
BusyTimeout time.Duration
// Synchronous controls the durability/throughput tradeoff. Use
// [SynchronousNormal] with WAL for typical production. Empty =
// leave alone.
Synchronous Synchronous
// ForeignKeys enables foreign-key enforcement when true. SQLite
// default is OFF; false here means "leave at default".
ForeignKeys bool
// CacheSize: positive = pages, negative = KiB, zero = leave alone.
CacheSize int
// TempStore selects where temporary tables and indices live. Use
// [TempStoreMemory] to avoid disk-resident temp files. Empty =
// leave alone.
TempStore TempStore
// Extra is the escape hatch for Pragmas not in the typed
// surface. Each entry fires `PRAGMA <key> = <value>`.
Extra map[string]string
}
Pragmas maps the most common SQLite knobs to Go fields. Unset values are "leave SQLite alone"; only the values you populate fire as PRAGMA statements at open time.
For Pragmas not surfaced here (there are many), use [Pragmas.Extra].
func RecommendedPragmas ¶
func RecommendedPragmas() Pragmas
RecommendedPragmas returns a production-shaped preset: WAL journaling, 5-second busy timeout, foreign keys enforced. Most consumer applications want exactly this; tune for your workload as needed.
type PreUpdateHookFn ¶
type PreUpdateHookFn func(SQLitePreUpdateData)
type ProgressHandler ¶
type ProgressHandler func() bool
ProgressHandler is invoked roughly every N virtual-machine instructions during a long-running statement (see Conn.SetProgressHandler). Returning true interrupts the statement, which then fails with SQLITE_INTERRUPT.
type RTreeGeometryFunc ¶
RTreeGeometryFunc decides whether an R-Tree bounding box is a candidate for a custom-geometry MATCH query. It is called for every node SQLite visits, internal and leaf.
coords is the node's bounding box as [min0, max0, min1, max1, …] — two values per R-Tree dimension. params holds the arguments passed to the geometry function in SQL: for `WHERE id MATCH mygeom(1, 2, 3)`, params is [1, 2, 3]. Return true if the box overlaps the query region (the subtree or row is a candidate), false to prune it.
type RTreeQueryFunc ¶
type RTreeQueryFunc func(info *RTreeQueryInfo) (within RTreeWithin, score float64, err error)
RTreeQueryFunc classifies a node against the query region and assigns it a score. Nodes are visited in ascending score order, so a smaller score is explored first. Return RTreeNotWithin to prune.
type RTreeQueryInfo ¶
type RTreeQueryInfo struct {
// Coords is the node bounding box as [min0, max0, min1, max1, …].
Coords []float64
// Params are the arguments to the SQL query function (e.g. the radius and
// centre of a circle).
Params []float64
// Level is the current node's height above the leaves; Leaf reports
// whether Level == 0 (a row, not an internal node).
Level int
// MaxLevel is the height of the whole tree.
MaxLevel int
// Rowid is the row identifier; meaningful only at the leaf level.
Rowid int64
// ParentScore is the score the callback assigned to this node's parent.
ParentScore float64
// ParentWithin is the classification the callback gave the parent.
ParentWithin RTreeWithin
}
RTreeQueryInfo is the per-node state passed to an RTreeQueryFunc. It is the richer alternative to RTreeGeometryFunc: the callback sees tree position and parent classification, and assigns both a within-result and a visit-order score.
func (*RTreeQueryInfo) Leaf ¶
func (q *RTreeQueryInfo) Leaf() bool
Leaf reports whether this node is a leaf (a stored row) rather than an internal bounding box.
type RTreeWithin ¶
type RTreeWithin int32
RTreeWithin classifies how a node's bounding box relates to the query region. It is the result an RTreeQueryFunc assigns to each visited node.
const ( // RTreeNotWithin prunes the box: neither it nor its descendants match. RTreeNotWithin RTreeWithin = 0 // RTreePartlyWithin keeps the box as a candidate; children/rows are // re-checked. RTreePartlyWithin RTreeWithin = 1 // RTreeFullyWithin reports the box entirely inside the query region; every // descendant row matches without a further callback. RTreeFullyWithin RTreeWithin = 2 )
type RollbackHookFn ¶
type RollbackHookFn func()
type SQLiteContext ¶
type SQLiteContext = FunctionContext
SQLiteContext is an alias for FunctionContext. mattn-go-sqlite3 uses *SQLiteContext as the receiver for user-defined function callbacks; we use *FunctionContext for the same role. The alias lets mattn UDF code compile after an import-path swap without renaming every callback signature.
type SQLitePreUpdateData ¶
type SQLitePreUpdateData struct {
Op int32
DatabaseName string
TableName string
OldRowID int64
NewRowID int64
// contains filtered or unexported fields
}
func (*SQLitePreUpdateData) Count ¶
func (d *SQLitePreUpdateData) Count() int
Count returns the number of columns in the row
func (*SQLitePreUpdateData) Depth ¶
func (d *SQLitePreUpdateData) Depth() int
Depth returns the source path of the write, see sqlite3_preupdate_depth()
func (*SQLitePreUpdateData) New ¶
func (d *SQLitePreUpdateData) New(dest ...any) error
New populates dest with the replacement row data. This works similar to database/sql's Rows.Scan()
func (*SQLitePreUpdateData) Old ¶
func (d *SQLitePreUpdateData) Old(dest ...any) error
Old populates dest with the row data to be replaced. This works similar to database/sql's Rows.Scan()
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session records changes to one or more tables on the connection it was created from. It is not safe for concurrent use; serialize access. Close it when done.
func (*Session) Attach ¶
Attach starts recording changes to a table. Pass table="" to record changes to every table that has a PRIMARY KEY. Call before the changes are made.
func (*Session) Changeset ¶
Changeset serializes the recorded changes into a changeset blob, which records the full before-and-after of every change (so it can be inverted). Returns nil for an empty session.
func (*Session) Close ¶
Close releases the session. Subsequent calls are no-ops. Closing does not affect already-serialized changesets.
func (*Session) Diff ¶
Diff records, into this session, the differences between the same-named table in fromSchema and the schema the session is recording. It is the "diff two databases" primitive: ATTACH another database, then Diff its table against this one to capture the changeset that would make them equal.
func (*Session) Enable ¶
Enable turns change recording on or off. Sessions start enabled; disabling lets a caller make changes that should not be captured.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is an opaque handle to a historical state of a WAL-mode database, captured by Conn.GetSnapshot. Replay it with Conn.OpenSnapshot to read the database as it was at that point. Free it with Snapshot.Close.
func (*Snapshot) Close ¶
func (s *Snapshot) Close()
Close frees the snapshot handle. Subsequent calls are no-ops.
type StmtCacheStats ¶
type StmtCacheStats struct {
Hits int64 // cached pstmt reused
Misses int64 // SQL not cached, fresh prepare
Evictions int64 // LRU eviction to make room
}
StmtCacheStats is a snapshot of the per-connection prepared-statement cache counters at the moment of the call. Returned by [(*Conn).StmtCacheStats]; the fields are monotonic since connection open.
type StmtStatus ¶
type StmtStatus int32
StmtStatus selects a per-statement counter for [Stmt.Status].
const ( StmtStatusFullscanStep StmtStatus = sqlite3.SQLITE_STMTSTATUS_FULLSCAN_STEP StmtStatusSort StmtStatus = sqlite3.SQLITE_STMTSTATUS_SORT StmtStatusAutoindex StmtStatus = sqlite3.SQLITE_STMTSTATUS_AUTOINDEX StmtStatusVMStep StmtStatus = sqlite3.SQLITE_STMTSTATUS_VM_STEP StmtStatusReprepare StmtStatus = sqlite3.SQLITE_STMTSTATUS_REPREPARE StmtStatusRun StmtStatus = sqlite3.SQLITE_STMTSTATUS_RUN StmtStatusFilterMiss StmtStatus = sqlite3.SQLITE_STMTSTATUS_FILTER_MISS StmtStatusFilterHit StmtStatus = sqlite3.SQLITE_STMTSTATUS_FILTER_HIT StmtStatusMemUsed StmtStatus = sqlite3.SQLITE_STMTSTATUS_MEMUSED )
Per-prepared-statement counters (sqlite3_stmt_status).
type Synchronous ¶
type Synchronous string
Synchronous is the typed enum for SQLite's synchronous pragma. Empty value leaves SQLite at its compile-time default (FULL).
const ( SynchronousOff Synchronous = "OFF" SynchronousNormal Synchronous = "NORMAL" SynchronousFull Synchronous = "FULL" SynchronousExtra Synchronous = "EXTRA" )
type TableFilter ¶
TableFilter decides whether to apply the changes recorded for a table (return true to apply). With no filter, every table is applied.
type TempStore ¶
type TempStore string
TempStore is the typed enum for SQLite's temp_store pragma. Empty value leaves SQLite at its compile-time default (DEFAULT, which usually resolves to FILE).
type TraceConfig ¶
type TraceConfig struct {
// EventMask is an OR'd set of TraceStmt | TraceProfile | TraceRow | TraceClose.
// Pass 0 to disable tracing entirely.
EventMask TraceEvent
// Callback is invoked for every matching event.
Callback TraceFn
// WantExpandedSQL, when true, asks sqlite to expand bound parameters into
// the SQL text passed to the callback. Slightly more expensive.
WantExpandedSQL bool
}
TraceConfig configures Conn.SetTrace.
type TraceEvent ¶
type TraceEvent uint
TraceEvent identifies the kind of event reported to a trace callback.
const ( TraceStmt TraceEvent = sqlite3.SQLITE_TRACE_STMT TraceProfile TraceEvent = sqlite3.SQLITE_TRACE_PROFILE TraceRow TraceEvent = sqlite3.SQLITE_TRACE_ROW TraceClose TraceEvent = sqlite3.SQLITE_TRACE_CLOSE )
Trace event mask constants. OR these together to filter which events fire.
type TraceFn ¶
TraceFn is the signature of a trace callback. Return non-zero from a row-callback to abort the running query (SQLite contract).
type TraceInfo ¶
type TraceInfo struct {
// EventCode is the firing event: TraceStmt, TraceProfile, TraceRow, or
// TraceClose.
EventCode TraceEvent
// Statement is the unexpanded SQL text passed to sqlite3_prepare* for
// stmt/profile events. Empty for row/close events.
Statement string
// ExpandedSQL is the SQL with bound parameters substituted, populated for
// stmt/profile events when the TraceConfig requested it.
ExpandedSQL string
// Duration is the wall-clock execution time captured for profile events.
Duration time.Duration
}
TraceInfo carries a single trace event delivered to a TraceFn.
type TxnState ¶
type TxnState int32
TxnState reports the transaction state of a schema (database) on this connection: TxnNone, TxnRead, or TxnWrite. Pass schema="" for the most advanced state across all attached schemas.
https://sqlite.org/c3ref/txn_state.html
const ( // TxnNone means no transaction is active on the schema. TxnNone TxnState = sqlite3.SQLITE_TXN_NONE // TxnRead means a read transaction is active (no writes yet). TxnRead TxnState = sqlite3.SQLITE_TXN_READ // TxnWrite means a write transaction is active. TxnWrite TxnState = sqlite3.SQLITE_TXN_WRITE )
type UpdateHookFn ¶
UpdateHookFn is the type for an UPDATE/INSERT/DELETE notification hook installed via Conn.RegisterUpdateHook.
op is one of sqlite.SQLITE_INSERT, SQLITE_UPDATE, or SQLITE_DELETE. dbName is the schema name (typically "main"). table is the affected table name. rowid is the rowid of the inserted/updated/deleted row.
Mattn-compatibility note: mattn's callback signature uses int for op.
type VTab ¶
VTab is the interface a Go virtual table must implement. The minimum set is BestIndex + Open + Disconnect + Destroy; modules that also need writes implement VTabUpdater, xRename implements VTabRenamer, and per-table transaction state implements VTabTransactional.
Implementations declare their schema by calling Conn.DeclareVTab from inside the VTabCtor.
type VTabCtor ¶
VTabCtor builds a VTab from CREATE VIRTUAL TABLE arguments. The first three positional values are SQLite's module name, database name (typically "main"), and table name; args are the user's USING name(args...) arguments.
The constructor MUST call Conn.DeclareVTab with the CREATE TABLE statement that describes the table's columns before returning, or SQLite will reject the CREATE.
type VTabCursor ¶
VTabCursor walks the rows a Filter call selected. EOF reports whether the cursor is past the last row (note: lowercase Eof per modernc upstream).
type VTabRenamer ¶
VTabRenamer is optional; modules that implement it handle xRename.
type VTabTransactional ¶
type VTabTransactional = vtab.Transactional
VTabTransactional is optional; modules with per-table transaction state implement it to receive Begin / Sync / Commit / Rollback callbacks.
type VTabUpdater ¶
VTabUpdater is the optional interface a VTab implementation can satisfy to support INSERT / UPDATE / DELETE through xUpdate. Modules that do not implement it are read-only; SQLite returns SQLITE_READONLY on writes.
type Value ¶
Value is the value type ferried between SQLite and Go-implemented virtual table cursors (and the Conn.RegisterFunc surface). It aliases database/sql/driver.Value so consumers don't need a separate import.
type WALHook ¶
WALHook is called after each commit in WAL mode, with the schema name and the total number of frames now in the WAL. Returning a non-nil error makes the commit report an error. A registered hook replaces SQLite's built-in auto-checkpoint hook, so a hook that wants checkpointing must call Conn.WALCheckpoint itself.
type WindowAccumulator ¶
type WindowAccumulator interface {
// Step incorporates one row's args into the accumulator.
Step(ctx *FunctionContext, args []driver.Value) error
// Inverse undoes the contribution of one row that previously went
// through Step. The args match those passed to the original Step.
Inverse(ctx *FunctionContext, args []driver.Value) error
// Value returns the current frame value. Called once per output
// row when the function is invoked as a window function.
Value(ctx *FunctionContext) (driver.Value, error)
}
WindowAccumulator is the interface a window-function implementation satisfies. SQLite calls Step as the engine moves forward through rows, Inverse as the frame's trailing edge moves past a row (so the row's contribution can be removed), and Value to read the current frame value.
All three methods receive a FunctionContext; values are not valid past the return of each call. A fresh WindowAccumulator is created per query via the constructor passed to Conn.RegisterWindowFunction, so per-instance state can be held on the receiver without external synchronization.
For per-instance cleanup at the end of an aggregation, implement WindowFinalizer additionally — the adapter type-asserts and calls Final when present. Implementations without resources to release can omit it.
For a non-window aggregate, implement Inverse as a no-op (or return an error if the function is genuinely non-invertible — SQLite will then fall back to whole-frame recomputation in some plans).
type WindowFinalizer ¶
type WindowFinalizer interface {
Final(ctx *FunctionContext)
}
WindowFinalizer is an optional companion interface a WindowAccumulator can implement to receive a Final callback after the last row of an aggregation. SQLite uses [WindowAccumulator.Value] to read the result; Final exists for any per-instance cleanup. The adapter calls Final only when the accumulator satisfies this interface, so most accumulators (pure-math ones with no external state) can leave it off.
Source Files
¶
- backup.go
- backup_factory.go
- blob.go
- busy.go
- callback_table.go
- collation_needed.go
- compat_convert.go
- compat_register.go
- compat_sqlite3.go
- config.go
- conn.go
- constants.go
- control.go
- convert.go
- doc.go
- driver.go
- dsn.go
- error.go
- extension.go
- fcntl.go
- fts5_tokenizer.go
- function_context.go
- hooks.go
- internal_alloc.go
- introspect.go
- limits.go
- module.go
- mutex.go
- nodmesg.go
- open_config.go
- pointer.go
- pre_update_hook.go
- result.go
- rows.go
- rtree.go
- runtime.go
- session.go
- snapshot.go
- sqlite.go
- stmt.go
- stmt_cache.go
- tx.go
- vtab.go
- wal.go
- windows.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
features/advanced/backup
command
backup: demonstrate (*Conn).Backup (the mattn-compat factory), the top-level sqlite.Serialize / sqlite.Deserialize helpers, and the round-trip path from a live in-memory DB to a snapshot to a fresh in-memory DB.
|
backup: demonstrate (*Conn).Backup (the mattn-compat factory), the top-level sqlite.Serialize / sqlite.Deserialize helpers, and the round-trip path from a live in-memory DB to a snapshot to a fresh in-memory DB. |
|
features/advanced/busy-handler
command
busy-handler: a programmable busy handler — adaptive/back-off retry on lock contention, the callback alternative to a fixed busy_timeout.
|
busy-handler: a programmable busy handler — adaptive/back-off retry on lock contention, the callback alternative to a fixed busy_timeout. |
|
features/advanced/collation-needed
command
collation-needed: define collations on demand.
|
collation-needed: define collations on demand. |
|
features/advanced/hooks
command
hooks: install update / authorizer / commit / trace hooks on a single pinned connection and observe them firing as the connection runs DDL + DML.
|
hooks: install update / authorizer / commit / trace hooks on a single pinned connection and observe them firing as the connection runs DDL + DML. |
|
features/advanced/pcache
command
pcache: bound and observe SQLite's page-cache memory.
|
pcache: bound and observe SQLite's page-cache memory. |
|
features/advanced/session
command
session: capture every change to one database as a changeset and replay it on another — the foundation for offline sync, audit logs, and lightweight replication.
|
session: capture every change to one database as a changeset and replay it on another — the foundation for offline sync, audit logs, and lightweight replication. |
|
features/advanced/sqlitex
command
sqlitex: the ergonomic database/sql helpers — embed.FS migrations, the Transaction commit/rollback wrapper, deferred savepoints, and scalar reads.
|
sqlitex: the ergonomic database/sql helpers — embed.FS migrations, the Transaction commit/rollback wrapper, deferred savepoints, and scalar reads. |
|
features/advanced/udf-context
command
udf-context: the FunctionContext substrate for custom SQL functions — per-argument auxiliary-data caching (compile a regexp once for a constant pattern, reuse it for every row) and result/argument subtypes.
|
udf-context: the FunctionContext substrate for custom SQL functions — per-argument auxiliary-data caching (compile a regexp once for a constant pattern, reuse it for every row) and result/argument subtypes. |
|
features/advanced/window-function
command
window-function example: register a Go window-function on a connection and use it inside SQL.
|
window-function example: register a Go window-function on a connection and use it inside SQL. |
|
features/extensions/array
command
ext-array: bind a Go slice as a SQL table-valued function via the array extension.
|
ext-array: bind a Go slice as a SQL table-valued function via the array extension. |
|
features/extensions/blobio
command
ext-blobio: stream the contents of a pre-sized BLOB column via readblob / writeblob SQL functions.
|
ext-blobio: stream the contents of a pre-sized BLOB column via readblob / writeblob SQL functions. |
|
features/extensions/bloom
command
ext-bloom: probabilistic set-membership with the typed bloom.Filter API.
|
ext-bloom: probabilistic set-membership with the typed bloom.Filter API. |
|
features/extensions/closure
command
ext-closure: parent-child graph walks with the typed closure.Graph API.
|
ext-closure: parent-child graph walks with the typed closure.Graph API. |
|
features/extensions/csv
command
ext-csv: read CSV files as SQL tables with the typed csv.Table API.
|
ext-csv: read CSV files as SQL tables with the typed csv.Table API. |
|
features/extensions/encode
command
ext-encode: encode(data, format) / decode(text, format) for the common binary-to-text codecs SQLite lacks (only hex is built in) — base64, base32, base16, ascii85, url — via the ext/encode scalars.
|
ext-encode: encode(data, format) / decode(text, format) for the common binary-to-text codecs SQLite lacks (only hex is built in) — base64, base32, base16, ascii85, url — via the ext/encode scalars. |
|
features/extensions/extras
command
ext-extras: the new scalar extension families in one place — exact decimal arithmetic, fixed-point money, Go-time helpers, and dynamic SQL via eval().
|
ext-extras: the new scalar extension families in one place — exact decimal arithmetic, fixed-point money, Go-time helpers, and dynamic SQL via eval(). |
|
features/extensions/fileio
command
ext-fileio: read a sandboxed fs.FS via readfile + fsdir, and (with the os-backed variant) walk a real directory.
|
ext-fileio: read a sandboxed fs.FS via readfile + fsdir, and (with the os-backed variant) walk a real directory. |
|
features/extensions/fuzzy
command
ext-fuzzy: approximate string-matching SQL functions — edit distances, Jaro / Jaro-Winkler similarity, and Soundex phonetic codes — via ext/fuzzy.
|
ext-fuzzy: approximate string-matching SQL functions — edit distances, Jaro / Jaro-Winkler similarity, and Soundex phonetic codes — via ext/fuzzy. |
|
features/extensions/hash
command
ext-hash: cryptographic hash SQL functions.
|
ext-hash: cryptographic hash SQL functions. |
|
features/extensions/ipaddr
command
ext-ipaddr: IP / CIDR SQL helpers.
|
ext-ipaddr: IP / CIDR SQL helpers. |
|
features/extensions/lines
command
ext-lines: read a text file as one-row-per-line via the typed lines.Table API.
|
ext-lines: read a text file as one-row-per-line via the typed lines.Table API. |
|
features/extensions/pivot
command
ext-pivot: build a cross-tab via the pivot vtab.
|
ext-pivot: build a cross-tab via the pivot vtab. |
|
features/extensions/regexp
command
ext-regexp: REGEXP operator + regexp_* SQL functions via blank-import auto-registration.
|
ext-regexp: REGEXP operator + regexp_* SQL functions via blank-import auto-registration. |
|
features/extensions/rtree
command
ext-rtree: spatial indexing with the typed rtree.Table API.
|
ext-rtree: spatial indexing with the typed rtree.Table API. |
|
features/extensions/series
command
ext-series: generate_series(start, stop[, step]) integer sequences via the ext/series table-valued function — usable anywhere a table is, including joins and aggregates.
|
ext-series: generate_series(start, stop[, step]) integer sequences via the ext/series table-valued function — usable anywhere a table is, including joins and aggregates. |
|
features/extensions/spellfix1
command
ext-spellfix1: fuzzy spell-correction with the typed spellfix1.Vocab API.
|
ext-spellfix1: fuzzy spell-correction with the typed spellfix1.Vocab API. |
|
features/extensions/statement
command
ext-statement: define a parametrized view via the `statement` vtab.
|
ext-statement: define a parametrized view via the `statement` vtab. |
|
features/extensions/stats
command
ext-stats: statistical aggregates and window functions over a small employees table.
|
ext-stats: statistical aggregates and window functions over a small employees table. |
|
features/extensions/text
command
ext-text: rune-aware string functions SQLite lacks — text_reverse, text_repeat, text_lpad / text_rpad, text_split — via the ext/text scalars.
|
ext-text: rune-aware string functions SQLite lacks — text_reverse, text_repeat, text_lpad / text_rpad, text_split — via the ext/text scalars. |
|
features/extensions/unicode
command
ext-unicode: Unicode-aware string SQL functions + collations.
|
ext-unicode: Unicode-aware string SQL functions + collations. |
|
features/extensions/uuid
command
ext-uuid: RFC 4122 UUID functions.
|
ext-uuid: RFC 4122 UUID functions. |
|
features/extensions/zorder
command
ext-zorder: 2D / 3D Morton encoding for spatial-ish indexing.
|
ext-zorder: 2D / 3D Morton encoding for spatial-ish indexing. |
|
features/gorm/crypto
command
gorm-crypto: a comprehensive end-to-end example wiring every layer you'd realistically want in a production gorm app that needs encryption at rest.
|
gorm-crypto: a comprehensive end-to-end example wiring every layer you'd realistically want in a production gorm app that needs encryption at rest. |
|
features/gorm/ext-scalars
command
gorm-ext-scalars: pair gorm with the scalar / aggregate / collation flavors of ext/.
|
gorm-ext-scalars: pair gorm with the scalar / aggregate / collation flavors of ext/. |
|
features/gorm/ext-vtabs
command
gorm-ext-vtabs: pair gorm with the virtual-table flavors of ext/.
|
gorm-ext-vtabs: pair gorm with the virtual-table flavors of ext/. |
|
features/gorm/fts
command
gorm-fts example: side-by-side pattern for combining gorm-managed schema with FTS5 full-text search.
|
gorm-fts example: side-by-side pattern for combining gorm-managed schema with FTS5 full-text search. |
|
features/gorm/fts-tagged
command
gorm-fts-tagged: the tag-driven flow for combining gorm models with SQLite FTS5.
|
gorm-fts-tagged: the tag-driven flow for combining gorm models with SQLite FTS5. |
|
features/gorm/vec
command
gorm-vec example: side-by-side pattern for combining gorm-managed schema with sqlite-vec virtual tables.
|
gorm-vec example: side-by-side pattern for combining gorm-managed schema with sqlite-vec virtual tables. |
|
features/gorm/vec-tagged
command
gorm-vec-tagged: the tag-driven flow for combining gorm models with sqlite-vec.
|
gorm-vec-tagged: the tag-driven flow for combining gorm models with sqlite-vec. |
|
features/gorm/vfs
command
gorm-vfs example: open a gorm.DB against a SQLite database that lives entirely inside an embed.FS-style read-only filesystem.
|
gorm-vfs example: open a gorm.DB against a SQLite database that lives entirely inside an embed.FS-style read-only filesystem. |
|
features/search/fts-search
command
fts-search example: typed FTS5 API with Porter stemming, BM25 ranking, and snippet/highlight extraction.
|
fts-search example: typed FTS5 API with Porter stemming, BM25 ranking, and snippet/highlight extraction. |
|
features/search/fts-tokenizer
command
fts-tokenizer: a custom Go FTS5 tokenizer.
|
fts-tokenizer: a custom Go FTS5 tokenizer. |
|
features/search/fts-vocab
command
fts-vocab: term-frequency analytics and autocomplete over an FTS5 index via the typed fts.Vocab (an fts5vocab view of the index's term dictionary).
|
fts-vocab: term-frequency analytics and autocomplete over an FTS5 index via the typed fts.Vocab (an fts5vocab view of the index's term dictionary). |
|
features/search/fusion-hybrid
command
fusion-hybrid-search example: combine a vec.KNN semantic ranking with an fts.Search lexical ranking via Reciprocal Rank Fusion.
|
fusion-hybrid-search example: combine a vec.KNN semantic ranking with an fts.Search lexical ranking via Reciprocal Rank Fusion. |
|
features/search/vec-keyed
command
vec-keyed: vector search keyed by a string primary key (UUID / slug) instead of an int64 rowid, via vec.KeyedTable[string].
|
vec-keyed: vector search keyed by a string primary key (UUID / slug) instead of an int64 rowid, via vec.KeyedTable[string]. |
|
features/search/vec-search
command
vec-search example: typed sqlite-vec API.
|
vec-search example: typed sqlite-vec API. |
|
features/vfs/cksm
command
vfs-cksm: register a checksum VFS, build a database through it, corrupt a byte, and observe SQLITE_IOERR_DATA on the next read.
|
vfs-cksm: register a checksum VFS, build a database through it, corrupt a byte, and observe SQLITE_IOERR_DATA on the next read. |
|
features/vfs/crypto
command
vfs-crypto example: open a SQLite database with transparent at-rest encryption.
|
vfs-crypto example: open a SQLite database with transparent at-rest encryption. |
|
features/vfs/custom
command
vfs-custom: implement a SQLite VFS in pure Go on the public vfs.VFS / vfs.File interface, register it, and run a writable database against it through database/sql — no fork, no CGo, no disk.
|
vfs-custom: implement a SQLite VFS in pure Go on the public vfs.VFS / vfs.File interface, register it, and run a writable database against it through database/sql — no fork, no CGo, no disk. |
|
features/vfs/embed
command
vfs-embed example: bundle a SQLite database inside an embed.FS and open it read-only via the vfs sub-package.
|
vfs-embed example: bundle a SQLite database inside an embed.FS and open it read-only via the vfs sub-package. |
|
features/vfs/memdb
command
vfs-memdb: open a SHARED named in-memory DB from two independent *sql.DB handles.
|
vfs-memdb: open a SHARED named in-memory DB from two independent *sql.DB handles. |
|
features/vfs/mvcc
command
vfs-mvcc: open a SHARED named in-memory MVCC DB from two independent *sql.DB handles and observe snapshot semantics — a reader sees its captured view through the lifetime of its transaction, even while a writer commits new rows in between.
|
vfs-mvcc: open a SHARED named in-memory MVCC DB from two independent *sql.DB handles and observe snapshot semantics — a reader sees its captured view through the lifetime of its transaction, even while a writer commits new rows in between. |
|
getting-started/config
command
config: opens a SQLite database via the modern Go-typed sqlite.Config API — no DSN string assembly, no `_pragma=…` URL flags.
|
config: opens a SQLite database via the modern Go-typed sqlite.Config API — no DSN string assembly, no `_pragma=…` URL flags. |
|
getting-started/database-sql
command
database-sql: the modern, idiomatic foundation — plain database/sql on the "sqlite" driver, with no legacy DSN flags.
|
database-sql: the modern, idiomatic foundation — plain database/sql on the "sqlite" driver, with no legacy DSN flags. |
|
getting-started/gorm
command
gorm: opens a gorm.DB via the modern Go-typed sqlite.Config API — same Config shape as the root sqlite.Open, just routed through gorm via sqlitegorm.OpenConfig.
|
gorm: opens a gorm.DB via the modern Go-typed sqlite.Config API — same Config shape as the root sqlite.Open, just routed through gorm via sqlitegorm.OpenConfig. |
|
migrating/from-glebarez
command
from-glebarez: shows the minimal change to migrate from github.com/glebarez/sqlite to gosqlite.org/gorm.
|
from-glebarez: shows the minimal change to migrate from github.com/glebarez/sqlite to gosqlite.org/gorm. |
|
migrating/from-mattn
command
from-mattn: shows that swapping the blank import from "github.com/mattn/go-sqlite3" to "gosqlite.org" needs no other code changes.
|
from-mattn: shows that swapping the blank import from "github.com/mattn/go-sqlite3" to "gosqlite.org" needs no other code changes. |
|
migrating/from-modernc
command
from-modernc: shows that swapping the blank import from "modernc.org/sqlite" to "gosqlite.org" needs no other code changes.
|
from-modernc: shows that swapping the blank import from "modernc.org/sqlite" to "gosqlite.org" needs no other code changes. |
|
ext
|
|
|
array
Package array provides the `array` table-valued SQL function — a way to feed a Go slice into a SQL query as a single-column table.
|
Package array provides the `array` table-valued SQL function — a way to feed a Go slice into a SQL query as a single-column table. |
|
array/auto
Package auto wires the array extension via a sqlite.Driver.ConnectHook so every new connection auto-registers the `array` module.
|
Package auto wires the array extension via a sqlite.Driver.ConnectHook so every new connection auto-registers the `array` module. |
|
blobio
Package blobio exposes SQLite's incremental BLOB I/O API as SQL scalar functions, so callers can stream parts of large BLOBs from SQL without materializing the whole row into memory.
|
Package blobio exposes SQLite's incremental BLOB I/O API as SQL scalar functions, so callers can stream parts of large BLOBs from SQL without materializing the whole row into memory. |
|
blobio/auto
Package auto wires the blobio extension via a sqlite.Driver.ConnectHook so every new connection registers readblob and writeblob.
|
Package auto wires the blobio extension via a sqlite.Driver.ConnectHook so every new connection registers readblob and writeblob. |
|
bloom
Package bloom provides a Bloom filter virtual table — a space-efficient probabilistic structure for set-membership testing.
|
Package bloom provides a Bloom filter virtual table — a space-efficient probabilistic structure for set-membership testing. |
|
bloom/auto
Package auto wires the bloom extension via a sqlite.Driver.ConnectHook so every new connection registers the `bloom` vtab module.
|
Package auto wires the bloom extension via a sqlite.Driver.ConnectHook so every new connection registers the `bloom` vtab module. |
|
closure
Package closure implements the `transitive_closure` virtual table: a parent-child graph walker that returns every descendant of a given node, with optional depth bounds.
|
Package closure implements the `transitive_closure` virtual table: a parent-child graph walker that returns every descendant of a given node, with optional depth bounds. |
|
closure/auto
Package auto wires the transitive_closure extension via a sqlite.Driver.ConnectHook so every new connection registers the vtab.
|
Package auto wires the transitive_closure extension via a sqlite.Driver.ConnectHook so every new connection registers the vtab. |
|
csv
Package csv exposes RFC 4180 comma-separated values as a SQLite virtual table.
|
Package csv exposes RFC 4180 comma-separated values as a SQLite virtual table. |
|
csv/auto
Package auto wires the csv extension via a sqlite.Driver.ConnectHook so every new connection auto-registers the `csv` module with os-backed file access.
|
Package auto wires the csv extension via a sqlite.Driver.ConnectHook so every new connection auto-registers the `csv` module with os-backed file access. |
|
decimal
Package decimal adds exact base-10 arithmetic scalar functions, for workloads where binary floating point's rounding is unacceptable (money, tax, billing).
|
Package decimal adds exact base-10 arithmetic scalar functions, for workloads where binary floating point's rounding is unacceptable (money, tax, billing). |
|
decimal/auto
Package auto wires the decimal_* scalar + aggregate functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the decimal_* scalar + aggregate functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
encode
Package encode adds `encode(data, format)` and `decode(text, format)` scalar functions covering the common binary-to-text codecs SQLite lacks (only hex/quote are built in):
|
Package encode adds `encode(data, format)` and `decode(text, format)` scalar functions covering the common binary-to-text codecs SQLite lacks (only hex/quote are built in): |
|
encode/auto
Package auto wires the encode / decode scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the encode / decode scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
eval
Package eval adds an eval() scalar function that runs dynamic SQL on the calling connection and returns the result as text — sqlean's distinctive "SQL from SQL" capability, which no other pure-Go SQLite driver exposes.
|
Package eval adds an eval() scalar function that runs dynamic SQL on the calling connection and returns the result as text — sqlean's distinctive "SQL from SQL" capability, which no other pure-Go SQLite driver exposes. |
|
eval/auto
Package auto wires the eval() function via a sqlite.Driver.ConnectHook so every new connection registers it.
|
Package auto wires the eval() function via a sqlite.Driver.ConnectHook so every new connection registers it. |
|
fileio
Package fileio exposes SQL functions and a virtual table for reading and walking files.
|
Package fileio exposes SQL functions and a virtual table for reading and walking files. |
|
fileio/auto
Package auto wires the fileio extension via a sqlite.Driver.ConnectHook so every new connection registers readfile, writefile, lsmode, and the fsdir vtab.
|
Package auto wires the fileio extension via a sqlite.Driver.ConnectHook so every new connection registers readfile, writefile, lsmode, and the fsdir vtab. |
|
fuzzy
Package fuzzy adds approximate-string-matching SQL scalar functions — edit distances, the Jaro / Jaro-Winkler similarity, and the Soundex phonetic code:
|
Package fuzzy adds approximate-string-matching SQL scalar functions — edit distances, the Jaro / Jaro-Winkler similarity, and the Soundex phonetic code: |
|
fuzzy/auto
Package auto wires the fuzzy string-matching scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the fuzzy string-matching scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
hash
Package hash provides cryptographic hash SQL functions.
|
Package hash provides cryptographic hash SQL functions. |
|
hash/auto
Package auto wires the hash extension via a sqlite.Driver.ConnectHook so every new connection registers the SQL hash functions.
|
Package auto wires the hash extension via a sqlite.Driver.ConnectHook so every new connection registers the SQL hash functions. |
|
internal/bigdec
Package bigdec is the exact base-10 arithmetic backend shared by ext/decimal and ext/money.
|
Package bigdec is the exact base-10 arithmetic backend shared by ext/decimal and ext/money. |
|
internal/filevtab
Package filevtab holds the file-backed virtual-table scaffolding shared by the file-reading ext modules (ext/csv, ext/lines).
|
Package filevtab holds the file-backed virtual-table scaffolding shared by the file-reading ext modules (ext/csv, ext/lines). |
|
ipaddr
Package ipaddr provides typed IP / CIDR helper functions for SQL queries.
|
Package ipaddr provides typed IP / CIDR helper functions for SQL queries. |
|
ipaddr/auto
Package auto wires the ipaddr extension via a sqlite.Driver.ConnectHook so every new connection registers the IP / CIDR helpers.
|
Package auto wires the ipaddr extension via a sqlite.Driver.ConnectHook so every new connection registers the IP / CIDR helpers. |
|
lines
Package lines exposes a text file as a SQLite virtual table — one row per line.
|
Package lines exposes a text file as a SQLite virtual table — one row per line. |
|
lines/auto
Package auto wires the lines extension via sqlite.Driver.ConnectHook so every new connection registers the `lines` vtab module with os-backed file access.
|
Package auto wires the lines extension via sqlite.Driver.ConnectHook so every new connection registers the `lines` vtab module with os-backed file access. |
|
money
Package money adds fixed-point currency scalar functions over the same exact base-10 backend as ext/decimal.
|
Package money adds fixed-point currency scalar functions over the same exact base-10 backend as ext/decimal. |
|
money/auto
Package auto wires the money_* scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the money_* scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
pivot
Package pivot implements a pivot virtual table — a parametrized cross-tab over three caller-supplied SELECT statements:
|
Package pivot implements a pivot virtual table — a parametrized cross-tab over three caller-supplied SELECT statements: |
|
pivot/auto
Package auto wires the pivot extension via a sqlite.Driver.ConnectHook so every new connection registers the `pivot` vtab.
|
Package auto wires the pivot extension via a sqlite.Driver.ConnectHook so every new connection registers the `pivot` vtab. |
|
regexp
Package regexp provides Go-regexp-syntax SQL functions plus the binary `REGEXP` operator SQLite leaves unimplemented by default.
|
Package regexp provides Go-regexp-syntax SQL functions plus the binary `REGEXP` operator SQLite leaves unimplemented by default. |
|
regexp/auto
Package auto wires the regexp extension via a sqlite.Driver.ConnectHook so every new connection registers the REGEXP operator and the regexp_* SQL function family.
|
Package auto wires the regexp extension via a sqlite.Driver.ConnectHook so every new connection registers the REGEXP operator and the regexp_* SQL function family. |
|
regexp/gorm
Package regexpgorm provides gorm helpers around the ext/regexp extension.
|
Package regexpgorm provides gorm helpers around the ext/regexp extension. |
|
rtree
Package rtree adds ready-made custom geometry callbacks for SQLite's built-in R-Tree module, layered on [gosqlite.org.Conn.RegisterRTreeGeometry].
|
Package rtree adds ready-made custom geometry callbacks for SQLite's built-in R-Tree module, layered on [gosqlite.org.Conn.RegisterRTreeGeometry]. |
|
rtree/auto
Package auto wires the rtree geometry functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the rtree geometry functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
series
Package series implements the `generate_series` table-valued function — an eponymous virtual table that yields a sequence of integers:
|
Package series implements the `generate_series` table-valued function — an eponymous virtual table that yields a sequence of integers: |
|
series/auto
Package auto wires the generate_series table-valued function via a sqlite.Driver.ConnectHook so every new connection registers it.
|
Package auto wires the generate_series table-valued function via a sqlite.Driver.ConnectHook so every new connection registers it. |
|
spellfix1
Package spellfix1 implements a fuzzy-text-matching virtual table inspired by SQLite's spellfix1 extension.
|
Package spellfix1 implements a fuzzy-text-matching virtual table inspired by SQLite's spellfix1 extension. |
|
spellfix1/auto
Package auto wires the spellfix1 extension via a sqlite.Driver.ConnectHook so every new connection registers the `spellfix1` vtab.
|
Package auto wires the spellfix1 extension via a sqlite.Driver.ConnectHook so every new connection registers the `spellfix1` vtab. |
|
statement
Package statement implements a virtual table that turns any SQL statement into a parametrized view.
|
Package statement implements a virtual table that turns any SQL statement into a parametrized view. |
|
statement/auto
Package auto wires the statement extension via a sqlite.Driver.ConnectHook so every new connection registers the `statement` vtab.
|
Package auto wires the statement extension via a sqlite.Driver.ConnectHook so every new connection registers the `statement` vtab. |
|
stats
Package stats provides PostgreSQL-style statistical aggregate and window functions plus two scalar helpers.
|
Package stats provides PostgreSQL-style statistical aggregate and window functions plus two scalar helpers. |
|
stats/auto
Package auto wires the stats extension via a sqlite.Driver.ConnectHook so every new connection registers the statistical aggregate / window function lineup.
|
Package auto wires the stats extension via a sqlite.Driver.ConnectHook so every new connection registers the statistical aggregate / window function lineup. |
|
text
Package text adds Unicode-aware string scalar functions that SQLite's built-ins and ext/unicode don't cover:
|
Package text adds Unicode-aware string scalar functions that SQLite's built-ins and ext/unicode don't cover: |
|
text/auto
Package auto wires the text_* scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the text_* scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
time
Package timeext adds Go-time-backed scalar functions that go beyond SQLite's built-in datetime(): duration arithmetic with Go duration syntax, field extraction, truncation, and unix conversions.
|
Package timeext adds Go-time-backed scalar functions that go beyond SQLite's built-in datetime(): duration arithmetic with Go duration syntax, field extraction, truncation, and unix conversions. |
|
time/auto
Package auto wires the time_* scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them.
|
Package auto wires the time_* scalar functions via a sqlite.Driver.ConnectHook so every new connection registers them. |
|
unicode
Package unicode provides Unicode-aware string SQL functions and collations as an alternative to the SQLite ICU extension.
|
Package unicode provides Unicode-aware string SQL functions and collations as an alternative to the SQLite ICU extension. |
|
unicode/auto
Package auto wires the unicode extension via a sqlite.Driver.ConnectHook so every new connection registers the Unicode-aware scalar functions plus the NOCASE_UNICODE / NOCASE_ACCENT collations.
|
Package auto wires the unicode extension via a sqlite.Driver.ConnectHook so every new connection registers the Unicode-aware scalar functions plus the NOCASE_UNICODE / NOCASE_ACCENT collations. |
|
uuid
Package uuid provides RFC 4122 UUID SQL functions backed by github.com/google/uuid.
|
Package uuid provides RFC 4122 UUID SQL functions backed by github.com/google/uuid. |
|
uuid/auto
Package auto wires the uuid extension via a sqlite.Driver.ConnectHook so every new connection registers the UUID SQL functions.
|
Package auto wires the uuid extension via a sqlite.Driver.ConnectHook so every new connection registers the UUID SQL functions. |
|
zorder
Package zorder provides z-order curve helpers for mapping multi-dimensional integer coordinates to a single ordered scalar (Morton encoding).
|
Package zorder provides z-order curve helpers for mapping multi-dimensional integer coordinates to a single ordered scalar (Morton encoding). |
|
zorder/auto
Package auto wires the zorder extension via a sqlite.Driver.ConnectHook so every new connection registers `zorder` and `unzorder`.
|
Package auto wires the zorder extension via a sqlite.Driver.ConnectHook so every new connection registers `zorder` and `unzorder`. |
|
Package fts is a typed, generics-aware wrapper around SQLite's FTS5 full-text-search virtual table, layered on top of gosqlite.org.
|
Package fts is a typed, generics-aware wrapper around SQLite's FTS5 full-text-search virtual table, layered on top of gosqlite.org. |
|
gorm
Package ftsgorm provides a tag-driven bridge between gorm models and SQLite FTS5 search indexes.
|
Package ftsgorm provides a tag-driven bridge between gorm models and SQLite FTS5 search indexes. |
|
Package fusion implements rank-fusion helpers for combining multiple ranked result sets — most commonly a vec.KNN result and an fts.Search result — into a single merged ranking.
|
Package fusion implements rank-fusion helpers for combining multiple ranked result sets — most commonly a vec.KNN result and an fts.Search result — into a single merged ranking. |
|
Package sqlite provides a gorm Dialector backed by the CGo-free gosqlite.org driver.
|
Package sqlite provides a gorm Dialector backed by the CGo-free gosqlite.org driver. |
|
internal
|
|
|
cabi
Package cabi consolidates the small helpers our packages need for talking to the modernc-transpiled SQLite C ABI.
|
Package cabi consolidates the small helpers our packages need for talking to the modernc-transpiled SQLite C ABI. |
|
gormbridge
Package gormbridge holds the reflect/gorm plumbing shared by the two gorm bridge sub-packages, vecgorm (vec/gorm) and ftsgorm (fts/gorm).
|
Package gormbridge holds the reflect/gorm plumbing shared by the two gorm bridge sub-packages, vecgorm (vec/gorm) and ftsgorm (fts/gorm). |
|
obs
Package obs holds the slog level-dispatch shared by the vec and fts observability wrappers.
|
Package obs holds the slog level-dispatch shared by the vec and fts observability wrappers. |
|
raceskip
Package raceskip exposes a single Enabled bool constant whose value reflects whether the build was produced with -race.
|
Package raceskip exposes a single Enabled bool constant whose value reflects whether the build was produced with -race. |
|
sqlid
Package sqlid implements small SQLite-flavored parsing helpers shared across loadable extensions (ext/closure, ext/pivot, ext/statement, …).
|
Package sqlid implements small SQLite-flavored parsing helpers shared across loadable extensions (ext/closure, ext/pivot, ext/statement, …). |
|
testhelp
Package testhelp consolidates the *sql.DB / *sql.Conn fixture boilerplate shared across the module's tests.
|
Package testhelp consolidates the *sql.DB / *sql.Conn fixture boilerplate shared across the module's tests. |
|
vtabx
Package vtabx holds the small create/drop machinery shared by the typed virtual-table handles in the ext/ sub-packages (bloom.Filter, closure.Graph, csv.Table, lines.Table, rtree.Table, spellfix1.Vocab).
|
Package vtabx holds the small create/drop machinery shared by the typed virtual-table handles in the ext/ sub-packages (bloom.Filter, closure.Graph, csv.Table, lines.Table, rtree.Table, spellfix1.Vocab). |
|
Package pcache installs an application-controlled SQLite page cache — the heap SQLite uses to hold database pages between reads and writes.
|
Package pcache installs an application-controlled SQLite page cache — the heap SQLite uses to hold database pages between reads and writes. |
|
Package sqlitex provides ergonomic helpers over a database/sql SQLite database: deferred savepoints, transaction wrappers, multi-statement scripts, a row-callback query runner, single-row and multi-row scalar reads, and an embed.FS schema-migration runner.
|
Package sqlitex provides ergonomic helpers over a database/sql SQLite database: deferred savepoints, transaction wrappers, multi-statement scripts, a row-callback query runner, single-row and multi-row scalar reads, and an embed.FS schema-migration runner. |
|
Package vec adds first-class vector-search support to gosqlite.org by bundling the sqlite-vec extension and a small Go API layered on top of it.
|
Package vec adds first-class vector-search support to gosqlite.org by bundling the sqlite-vec extension and a small Go API layered on top of it. |
|
gorm
Package vecgorm provides a tag-driven bridge between gorm models and sqlite-vec virtual-table sidecars.
|
Package vecgorm provides a tag-driven bridge between gorm models and sqlite-vec virtual-table sidecars. |
|
Package vfs lets you back a SQLite database with storage you control, in pure Go.
|
Package vfs lets you back a SQLite database with storage you control, in pure Go. |
|
cksm
Package cksm provides a corruption-detection VFS for SQLite.
|
Package cksm provides a corruption-detection VFS for SQLite. |
|
crypto
Package crypto provides a pure-Go encryption-at-rest VFS for SQLite.
|
Package crypto provides a pure-Go encryption-at-rest VFS for SQLite. |
|
internal/memio
Package memio holds page-store helpers shared by the in-memory VFS sub-packages (vfs/mvcc, vfs/memdb).
|
Package memio holds page-store helpers shared by the in-memory VFS sub-packages (vfs/mvcc, vfs/memdb). |
|
memdb
Package memdb implements a plain in-memory SQLite VFS — pages live in a Go-side map per database name, reads and writes hit it directly, and there is no journal, no WAL, and no on-disk representation.
|
Package memdb implements a plain in-memory SQLite VFS — pages live in a Go-side map per database name, reads and writes hit it directly, and there is no journal, no WAL, and no on-disk representation. |
|
mvcc
Package mvcc implements an in-memory SQLite VFS with multi-version concurrency control.
|
Package mvcc implements an in-memory SQLite VFS with multi-version concurrency control. |