sqlite3

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package sqlite3 is a cgo-free binding to real, upstream SQLite.

The library it drives is upstream's own amalgamation, pinned to a version and a checksum in this repository, compiled here with a configuration this repository states in one place (build/flags.sh), and shipped as a platform dylib embedded in the Go package. It is never the operating system's libsqlite3: on macOS that is Apple's fork on a version that moves underneath you with OS updates.

Calls cross into C through github.com/ebitengine/purego, so no consumer of this package needs a C toolchain, and CGO_ENABLED=0 builds and cross-compiles work normally. The cost is a per-call foreign-function overhead that cgo does not pay; see the benchmarks under bench/ for what that costs at a given call rate.

Concurrency

The shipped library is compiled SQLITE_THREADSAFE=2 (multi-thread). SQLite's own mutexes protect its global structures, but a connection object is not guarded, so this package inherits exactly that contract:

  • A Conn, and every Stmt prepared on it, must not be used by more than one goroutine at a time. Serialize them yourself, or give each goroutine its own connection.
  • Separate Conn values may be used concurrently from separate goroutines, including against the same database file. This is the intended shape: one connection per worker, WAL mode, readers that do not block the writer.

Getting started

conn, err := sqlite3.Open("app.db")
if err != nil {
	return err
}
defer conn.Close()

if err := conn.Exec(`PRAGMA journal_mode=WAL`); err != nil {
	return err
}
if err := conn.Exec(`CREATE TABLE IF NOT EXISTS t (k TEXT, v BLOB)`); err != nil {
	return err
}
if err := conn.Exec(`INSERT INTO t VALUES (?, ?)`, "key", []byte{0x00, 0x01}); err != nil {
	return err
}

This package deliberately does not implement database/sql's driver interfaces in v1; see the README for why and for what that would add.

Index

Constants

View Source
const BatchEnv = "PUREGO_SQLITE_BATCH"

BatchEnv names an environment variable that disables the row-batching fast path when set to "0". It exists so the benchmarks can measure both paths against the same library; there is no reason to set it in production.

View Source
const FunctionPathEnv = "PUREGO_SQLITE_FUNCTIONS"

FunctionPathEnv names an environment variable that, when set to "portable", forces application-defined functions onto the per-call path.

View Source
const LibraryPathEnv = "PUREGO_SQLITE_LIBRARY"

LibraryPathEnv names an environment variable that, when set, overrides the embedded library with a path on disk. Intended for testing against a differently-configured SQLite, and for distributions that would rather manage the shared library themselves.

Variables

View Source
var ErrUnsupportedPlatform = errors.New("purego-sqlite: no SQLite library is shipped for " + runtimePlatform)

ErrUnsupportedPlatform is returned when the package is built for a platform this repository does not yet ship a compiled SQLite for. Adding one means adding build/build-<goos>-<goarch>.sh, lib/<goos>_<goarch>/, and the matching embed file -- nothing in this file needs to change.

Functions

func ForcePortableFunctionsForTest

func ForcePortableFunctionsForTest(on bool)

ForcePortableFunctionsForTest switches subsequent CreateFunction calls onto the portable path. It exists so a test can compare the two implementations in one process, which is the only way to compare them at all: the environment variable is read once, at library load.

func HasExtension

func HasExtension(e Extension) (bool, error)

HasExtension reports whether the named extension is compiled in and registered.

func LoadedLibraryPath

func LoadedLibraryPath() string

LoadedLibraryPath reports the file the SQLite library was loaded from, which is a cache directory when the embedded library is in use. It returns "" if the library has not been loaded yet.

func RowBatchingActive

func RowBatchingActive() (bool, error)

RowBatchingActive reports whether the loaded library provides the row-batching shim and it is in use. False means correct results at a higher per-row cost, which is what a stock system SQLite gives you.

func SetLibraryPath

func SetLibraryPath(path string) error

SetLibraryPath directs the package at a SQLite shared library on disk instead of the embedded one. It must be called before any other function in this package; once the library is loaded the choice is fixed for the lifetime of the process.

func SourceID

func SourceID() (string, error)

SourceID reports the loaded library's upstream check-in identifier: the date and hash of the exact SQLite source it was compiled from.

func ThreadSafeMode

func ThreadSafeMode() (int, error)

ThreadSafeMode reports the SQLITE_THREADSAFE mode the loaded library was compiled with: 0 single-thread, 1 serialized, 2 multi-thread. This repository ships 2.

func UseMarshaledFunctions

func UseMarshaledFunctions() (bool, error)

UseMarshaledFunctions reports whether application-defined functions take the C-marshaling fast path. False means the loaded library has no marshaling trampoline, or it was disabled by FunctionPathEnv.

func Version

func Version() (string, error)

Version reports the SQLite version string of the loaded library, for example "3.53.4". It is the version this repository pins, unless the library was overridden with SetLibraryPath or LibraryPathEnv.

func VersionNumber

func VersionNumber() (int, error)

VersionNumber reports the loaded library's version as the integer (major*1000000 + minor*1000 + patch) that SQLite itself uses.

Types

type Accumulation

type Accumulation struct {
	// Count is how many non-NULL values were seen. SQL aggregates ignore
	// NULL, and so does this one.
	Count int64
	// Sum is the running total as floating point.
	Sum float64
	// Min and Max are the extremes of the numeric interpretation. They are
	// meaningless when Count is zero.
	Min, Max float64
	// IntSum is the exact integer total, valid only when AllInt is true --
	// float accumulation loses precision that a coordination-plane rollup over
	// counters usually cannot afford to lose.
	IntSum int64
	// AllInt reports that every value seen was an integer.
	AllInt bool
}

Accumulation is what C summarised while walking the rows, handed to a Go aggregate once at the end.

The narrowness is the point. A scalar function crosses the boundary per row; an aggregate that accumulates in C crosses once per query. What C can summarise without knowing what the answer means is a small set, and that set is this. An aggregate needing every individual row is not this feature -- that is an ordinary query with a loop around it.

type AggregateFunc

type AggregateFunc func(ctx *FuncContext, acc Accumulation)

AggregateFunc is a Go implementation of a SQL aggregate's final step. It is called once per group, with what C accumulated.

type Backup

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

Backup is an online copy from one open database to another, running incrementally so a large database can be copied without holding a read lock for the whole of it.

func (*Backup) Close

func (b *Backup) Close() error

Close finishes the backup, releasing its resources. It is safe to call more than once, and it reports any error the copy accumulated.

func (*Backup) PageCount

func (b *Backup) PageCount() int

PageCount is the total size of the source database in pages, as of the last Step.

func (*Backup) Remaining

func (b *Backup) Remaining() int

Remaining is the number of pages still to copy, as of the last Step.

func (*Backup) Step

func (b *Backup) Step(pages int) (done bool, err error)

Step copies up to pages pages, or all remaining pages when pages is negative. It reports done when the whole database has been copied.

type CheckpointMode

type CheckpointMode int32

CheckpointMode selects how hard a WAL checkpoint tries, mirroring SQLITE_CHECKPOINT_*.

const (
	// CheckpointPassive copies what it can without blocking anyone.
	CheckpointPassive CheckpointMode = 0
	// CheckpointFull waits for writers, then copies the whole WAL.
	CheckpointFull CheckpointMode = 1
	// CheckpointRestart is CheckpointFull, then waits for readers so the next
	// writer starts the WAL from its beginning.
	CheckpointRestart CheckpointMode = 2
	// CheckpointTruncate is CheckpointRestart, then truncates the WAL file to
	// zero bytes.
	CheckpointTruncate CheckpointMode = 3
)

type Code

type Code int32

Code is a SQLite result code. Both primary codes (SQLITE_BUSY) and extended codes (SQLITE_BUSY_SNAPSHOT) are represented; the low 8 bits of an extended code are its primary code.

Code implements error, so it can be used directly with errors.Is against an error returned by this package:

if errors.Is(err, sqlite3.Busy) { ... }

Matching is deliberately asymmetric in the useful direction: a primary code matches any of its extended codes, an extended code matches only itself.

const (
	OK         Code = 0
	ErrorCode  Code = 1
	Internal   Code = 2
	Perm       Code = 3
	Abort      Code = 4
	Busy       Code = 5
	Locked     Code = 6
	NoMem      Code = 7
	ReadOnly   Code = 8
	Interrupt  Code = 9
	IOErr      Code = 10
	Corrupt    Code = 11
	NotFound   Code = 12
	Full       Code = 13
	CantOpen   Code = 14
	Protocol   Code = 15
	Empty      Code = 16
	Schema     Code = 17
	TooBig     Code = 18
	Constraint Code = 19
	Mismatch   Code = 20
	Misuse     Code = 21
	NoLFS      Code = 22
	Auth       Code = 23
	Format     Code = 24
	Range      Code = 25
	NotADB     Code = 26
	Notice     Code = 27
	Warning    Code = 28
	Row        Code = 100
	Done       Code = 101
)

Primary result codes.

const (
	BusyRecovery          Code = Busy | (1 << 8)
	BusySnapshot          Code = Busy | (2 << 8)
	BusyTimeout           Code = Busy | (3 << 8)
	ConstraintCheck       Code = Constraint | (1 << 8)
	ConstraintForeignKey  Code = Constraint | (3 << 8)
	ConstraintNotNull     Code = Constraint | (5 << 8)
	ConstraintPrimaryKey  Code = Constraint | (6 << 8)
	ConstraintTrigger     Code = Constraint | (7 << 8)
	ConstraintUnique      Code = Constraint | (8 << 8)
	ConstraintRowID       Code = Constraint | (10 << 8)
	ReadOnlyRollback      Code = ReadOnly | (1 << 8)
	CantOpenNotempdir     Code = CantOpen | (1 << 8)
	IOErrWrite            Code = IOErr | (3 << 8)
	IOErrFsync            Code = IOErr | (4 << 8)
	NoticeRecoverWAL      Code = Notice | (1 << 8)
	NoticeRecoverRollback Code = Notice | (2 << 8)
)

Extended result codes this package's users are most likely to branch on. Any extended code SQLite returns is preserved on Error; these are named for convenience, not as an exhaustive list.

func (Code) Error

func (c Code) Error() string

Error makes a bare Code usable as an error, so that a sentinel like Busy can be both the thing you compare against with errors.Is and the thing you return.

func (Code) IsExtended

func (c Code) IsExtended() bool

IsExtended reports whether c carries extended detail beyond its primary code.

func (Code) Primary

func (c Code) Primary() Code

Primary returns the primary result code underlying c. For a primary code it returns c unchanged.

func (Code) String

func (c Code) String() string

String returns SQLite's own text for the code, from sqlite3_errstr, with the numeric value appended when the code is an extended one — SQLite's strings for extended codes are not always distinct from their primary code's.

type ColumnType

type ColumnType int32

ColumnType is the storage class of a result column, mirroring SQLITE_* datatype codes. It is the type of the value actually stored, not the column's declared type.

const (
	TypeInteger ColumnType = 1 // signed integer, 1 to 8 bytes as stored
	TypeFloat   ColumnType = 2 // IEEE 754 double
	TypeText    ColumnType = 3 // text in the database encoding, UTF-8 here
	TypeBlob    ColumnType = 4 // bytes, stored and returned exactly as given
	TypeNull    ColumnType = 5 // SQL NULL
)

The five storage classes SQLite has. A column's ColumnType is decided per row by the value stored in it, so the same column can report different types on different rows.

func (ColumnType) String

func (t ColumnType) String() string

String returns SQLite's own name for the storage class — "INTEGER", "FLOAT", "TEXT", "BLOB", "NULL" — or "UNKNOWN" for a value that is none of them.

type Conn

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

Conn is a connection to a SQLite database.

A Conn and every Stmt prepared on it belong to one goroutine at a time; see the package documentation on concurrency. Separate Conn values are safe to use concurrently, which is how this package expects to be used under load: one connection per worker.

func Open

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

Open opens (creating if necessary) the database at path for reading and writing, with extended result codes enabled.

The special path ":memory:" gives a private in-memory database. Note that SQLite's URI forms are not interpreted unless OpenURI is passed to OpenFlags.

func OpenFlags

func OpenFlags(path string, flags OpenFlag, vfs string) (*Conn, error)

OpenFlags opens a database with an explicit SQLITE_OPEN_* flag set and an optional VFS name. An empty vfs selects SQLite's default.

func (*Conn) BackupFrom

func (c *Conn) BackupFrom(dstName string, src *Conn, srcName string) (*Backup, error)

BackupFrom starts a backup that copies the src connection's srcName database into this connection's dstName database. An empty name means "main".

The destination must be a different connection than the source. Call Backup.Step until it reports done, then Backup.Close.

func (*Conn) BackupTo

func (c *Conn) BackupTo(dst *Conn) error

BackupTo copies this connection's main database into dst's main database, running the copy to completion in one call.

func (*Conn) BusyTimeout

func (c *Conn) BusyTimeout(d time.Duration) error

BusyTimeout makes a blocked connection retry for up to d before returning Busy. Zero disables the wait and fails immediately.

The shipped library is compiled with HAVE_USLEEP, so sub-second timeouts are honoured at their stated resolution rather than rounded up to whole seconds.

func (*Conn) Changes

func (c *Conn) Changes() int64

Changes counts the rows modified by the most recently completed statement.

func (*Conn) Close

func (c *Conn) Close() error

Close finalizes any statements still open on the connection and closes it.

Statements are finalized first on purpose: sqlite3_close_v2 would otherwise return success while leaving the connection alive as a zombie holding file locks until the last statement is finalized, which reads as "closed" and behaves as "still open".

func (*Conn) Closed

func (c *Conn) Closed() bool

Closed reports whether Close has been called.

func (*Conn) CreateAggregate

func (c *Conn) CreateAggregate(name string, nArg int, flags FunctionFlag, fn AggregateFunc) error

CreateAggregate registers a Go implementation of a SQL aggregate whose per-row accumulation happens in C.

The Go function runs once per group rather than once per row, which is the whole reason to prefer an aggregate here: a scalar function over a million rows pays a million boundary crossings, this pays one.

It requires the marshaling shim; without it there is no accumulator to batch into and the call returns an error rather than silently falling back to something with different cost.

func (*Conn) CreateFunction

func (c *Conn) CreateFunction(name string, nArg int, flags FunctionFlag, fn ScalarFunc) error

CreateFunction registers a Go implementation of a SQL scalar function on this connection.

nArg is the argument count, or -1 for variadic. The function is visible only to this connection, which is SQLite's model: there is no global registry.

The Go function is called on whatever thread SQLite is running the query on, which for this package is the goroutine that called Step. It must not use the connection it was called from.

Answering a SQL function in Go crosses the C boundary once per invocation. See the package benchmarks for what that costs; it is fine for functions called thousands of times and wrong for ones called millions.

func (*Conn) EnableLoadExtension

func (c *Conn) EnableLoadExtension(on bool) error

EnableLoadExtension turns SQLite's runtime extension loading on or off for this connection.

It is off by default in SQLite and this package does not change that: a connection that can load a shared library from a path is a connection that can execute arbitrary code, and whether that is acceptable is the application's call, not a binding's.

Enabling affects the C API only. SQL's load_extension() stays disabled unless the application also turns on SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION's SQL half, which this package deliberately does not expose -- a SQL string that can load a dylib is a much larger blast radius than a Go call that can.

func (*Conn) Exec

func (c *Conn) Exec(sql string, args ...any) error

Exec runs SQL that returns no rows.

With no arguments the whole string is executed, so it may contain several statements separated by semicolons -- the shape a schema migration takes. With arguments it must be a single statement, which is prepared, bound, run to completion, and finalized.

func (*Conn) Filename

func (c *Conn) Filename(dbName string) string

Filename is the full path SQLite resolved for the named attached database, "main" being the one opened by Open.

func (*Conn) InTransaction

func (c *Conn) InTransaction() bool

InTransaction reports whether an explicit transaction is open, which is the inverse of SQLite's autocommit flag.

func (*Conn) Interrupt

func (c *Conn) Interrupt()

Interrupt aborts any query running on this connection. It is the one method safe to call from another goroutine while the connection is in use, which is what makes it useful for cancellation.

func (*Conn) LastInsertRowID

func (c *Conn) LastInsertRowID() int64

LastInsertRowID is the rowid of the most recent successful insert on this connection.

func (*Conn) LoadExtension

func (c *Conn) LoadExtension(path, entry string) error

LoadExtension loads a SQLite extension from a shared library at runtime.

entry may be empty, in which case SQLite derives the entry point from the filename. Conn.EnableLoadExtension must have been called first.

This is the escape hatch for extensions this repository has not compiled in: it costs a file on disk that has to match the platform and the SQLite ABI, which is exactly the deployment problem the embedded library exists to avoid. Prefer compiling an extension in when it is one you always want.

func (*Conn) Path

func (c *Conn) Path() string

Path is the filename the connection was opened with.

func (*Conn) Prepare

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

Prepare compiles a single SQL statement. The caller owns the result and must Close it. Text after the first statement is an error, so that a typo'd semicolon cannot silently drop half the query.

func (*Conn) PrepareFlags

func (c *Conn) PrepareFlags(sql string, flags PrepareFlag) (*Stmt, error)

PrepareFlags is Prepare with SQLITE_PREPARE_* flags. Pass PreparePersistent for a statement that will be reused for the life of the connection, which is the normal case for a polling reader.

func (*Conn) PrepareTail

func (c *Conn) PrepareTail(sql string) (*Stmt, string, error)

PrepareTail compiles the first statement in sql and returns the unconsumed remainder, so a caller can walk a multi-statement script one statement at a time. A nil Stmt with a nil error means the text held only whitespace or comments.

func (*Conn) TotalChanges

func (c *Conn) TotalChanges() int64

TotalChanges counts the rows modified since the connection was opened.

func (*Conn) WALAutoCheckpoint

func (c *Conn) WALAutoCheckpoint(pages int) error

WALAutoCheckpoint sets how many WAL pages may accumulate before SQLite checkpoints on its own. Zero disables automatic checkpointing, leaving it to the caller -- which is what a process that wants checkpoints off the write path will do.

func (*Conn) WALCheckpoint

func (c *Conn) WALCheckpoint(dbName string, mode CheckpointMode) (walPages, checkpointed int, err error)

WALCheckpoint runs a write-ahead-log checkpoint on the named database and reports how large the WAL was, in frames, and how many of those frames were moved into the database file. An empty dbName means "main".

Two behaviours surprise people, both of them SQLite's:

  • CheckpointRestart and CheckpointTruncate report zero for both counts on success, because SQLite reads the counters out of the WAL header after the reset that those modes perform.
  • A busy return is not an error in the usual sense: a checkpoint that could not move everything reports Busy with the counts still filled in, describing how far it got.

type Error

type Error struct {
	Code     Code   // primary result code
	Extended Code   // extended result code; equals Code when SQLite had no detail
	Message  string // sqlite3_errmsg text
	SQL      string // statement text, when the failure came from one
}

Error is a failed SQLite call: the codes SQLite reported, the message it produced, and the SQL in flight when the call failed, where this package knows it.

func (*Error) Error

func (e *Error) Error() string

Error renders the failure as "sqlite3: <code>[extended]: <message> (in <sql>)", omitting each part SQLite did not supply. The SQL is truncated so that a generated statement cannot turn one log line into a page.

func (*Error) Is

func (e *Error) Is(target error) bool

Is lets errors.Is match an *Error against a bare Code. A primary code matches when the error's primary code is equal; an extended code matches only the identical extended code.

type Extension

type Extension string

Extension names an optional SQLite extension this repository can compile into the shipped library.

const (
	// ExtSQLiteVec is asg017/sqlite-vec: vector storage and KNN search through
	// vec0 virtual tables. Pinned in build/extensions.lock, built by
	// `WITH_SQLITE_VEC=1 make build`.
	ExtSQLiteVec Extension = "sqlite-vec"
)

func CompiledExtensions

func CompiledExtensions() ([]Extension, error)

CompiledExtensions reports the extensions built into the loaded library and successfully registered for every new connection.

An empty result is the normal case: extensions are opt-in at build time.

type FuncContext

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

FuncContext is where an application-defined function writes its answer.

On the marshaled path the answer is written into a buffer that C reads after the call returns; on the portable path it goes straight to SQLite. Callers see neither difference.

func (*FuncContext) ResultBlob

func (c *FuncContext) ResultBlob(v []byte)

ResultBlob returns bytes.

func (*FuncContext) ResultError

func (c *FuncContext) ResultError(msg string)

ResultError aborts the query with a message.

func (*FuncContext) ResultFloat

func (c *FuncContext) ResultFloat(v float64)

ResultFloat returns a floating-point value.

func (*FuncContext) ResultInt64

func (c *FuncContext) ResultInt64(v int64)

ResultInt64 returns an integer.

func (*FuncContext) ResultNull

func (c *FuncContext) ResultNull()

ResultNull returns SQL NULL.

func (*FuncContext) ResultText

func (c *FuncContext) ResultText(v string)

ResultText returns a string.

type FunctionFlag

type FunctionFlag int32

FunctionFlag controls how SQLite may use an application-defined function, mirroring the text-encoding and optimization bits of sqlite3_create_function.

const (
	// Deterministic promises the function returns the same answer for the same
	// arguments within a single query, which lets SQLite factor it out of
	// loops and use it in indexes on expressions. Promise it falsely and you
	// get wrong answers, not slow ones.
	Deterministic FunctionFlag = 0x000000800
	// DirectOnly forbids use from triggers, views and schema structures --
	// the right default for anything touching the outside world.
	DirectOnly FunctionFlag = 0x000080000
	// Innocuous declares the function harmless to run on hostile input.
	Innocuous FunctionFlag = 0x000200000
)

type OpenFlag

type OpenFlag int32

OpenFlag values for OpenFlags. These mirror SQLITE_OPEN_*.

const (
	// OpenReadOnly opens an existing database for reading only. Writes fail
	// with [ReadOnly], and the database is not created if it is absent.
	OpenReadOnly OpenFlag = 0x00000001
	// OpenReadWrite opens for reading and writing, falling back to read-only
	// when the file permissions do not allow writing.
	OpenReadWrite OpenFlag = 0x00000002
	// OpenCreate creates the database if it does not exist. Meaningful only
	// alongside OpenReadWrite.
	OpenCreate OpenFlag = 0x00000004
	// OpenURI interprets the filename as a URI, which is what enables
	// "file:name?mode=memory&cache=shared" and the other query parameters.
	OpenURI OpenFlag = 0x00000040
	// OpenMemory opens a private in-memory database, ignoring the filename.
	OpenMemory OpenFlag = 0x00000080
	// OpenNoMutex asks for multi-thread mode. Inert here; see above.
	OpenNoMutex OpenFlag = 0x00008000
	// OpenFullMutex asks for serialized mode. Inert here; see above.
	OpenFullMutex OpenFlag = 0x00010000
	// OpenSharedCache enables shared-cache mode, which upstream discourages
	// for new code and which WAL mode makes largely unnecessary.
	OpenSharedCache OpenFlag = 0x00020000
	// OpenPrivateCache disables shared-cache mode even where it is the default.
	OpenPrivateCache OpenFlag = 0x00040000
	// OpenNoFollow refuses to open the database if the path is a symbolic link.
	OpenNoFollow OpenFlag = 0x01000000
	// OpenExResCode makes the connection report extended result codes, so a
	// constraint failure says which constraint. Part of [OpenDefault].
	OpenExResCode OpenFlag = 0x02000000

	// OpenDefault is what [Open] uses: create if absent, read and write, and
	// report extended result codes so a constraint violation says which kind.
	OpenDefault = OpenReadWrite | OpenCreate | OpenExResCode
)

The open flags, each the value of the SQLITE_OPEN_* constant it is named for. Combine them with | and pass them to OpenFlags.

OpenNoMutex and OpenFullMutex select a connection's threading mode, and both are inert here: the shipped library is compiled SQLITE_THREADSAFE=2, in which SQLite honours neither. The contract is the one described in the package documentation — one goroutine per connection at a time — whatever is passed.

type PrepareFlag

type PrepareFlag uint32

PrepareFlag is a statement preparation flag for Conn.PrepareFlags, mirroring SQLITE_PREPARE_*.

const (
	// PreparePersistent tells SQLite the statement will be reused many times,
	// so it should not be aggressively reclaimed from the statement cache.
	PreparePersistent PrepareFlag = 0x01
	// PrepareNoVTab refuses to prepare the statement if it would use a virtual
	// table. Useful as a guard where a virtual table would mean the schema is
	// not the one the caller expects.
	PrepareNoVTab PrepareFlag = 0x04
)

type ScalarFunc

type ScalarFunc func(ctx *FuncContext, args []Value)

ScalarFunc is a Go implementation of a SQL scalar function. Write the answer through ctx; returning without doing so yields SQL NULL.

type Stmt

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

Stmt is a compiled SQL statement.

Parameter indexes are 1-based and column indexes are 0-based, because that is what SQLite's own documentation says. Translating one of them here would only mean every reader has to translate it back.

func (*Stmt) Bind

func (s *Stmt) Bind(args ...any) error

Bind binds every argument positionally, starting at parameter 1.

Supported: nil, bool, the sized and unsized integer types, float32, float64, string, and []byte. A uint64 above math.MaxInt64 is rejected rather than wrapped to a negative integer, because SQLite has no unsigned type and a silent wrap is a corrupted value.

time.Time is deliberately absent: SQLite stores time as whatever the application decides -- Unix seconds, Julian day, or ISO-8601 text -- and a binding that picked one for you would be picking your schema.

func (*Stmt) BindBlob

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

BindBlob binds a byte slice. A nil slice binds SQL NULL; a non-nil empty slice binds a zero-length blob, which is a distinct value.

func (*Stmt) BindBool

func (s *Stmt) BindBool(i int, v bool) error

BindBool binds a boolean as SQLite's 0 or 1, which is how SQLite represents truth: it has no boolean type.

func (*Stmt) BindCount

func (s *Stmt) BindCount() int

BindCount is the number of parameters in the statement.

func (*Stmt) BindFloat

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

BindFloat binds a floating-point value to the 1-based parameter i.

func (*Stmt) BindIndex

func (s *Stmt) BindIndex(name string) int

BindIndex is the 1-based index of a named parameter, or 0 if there is no such parameter. The name includes its prefix, as in ":id" or "@id".

func (*Stmt) BindInt64

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

BindInt64 binds an integer to the 1-based parameter i.

func (*Stmt) BindName

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

BindName is the name of the parameter at a 1-based index, or "" for a positional parameter.

func (*Stmt) BindNull

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

BindNull binds SQL NULL.

func (*Stmt) BindText

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

BindText binds a string. The string may contain NUL bytes and any UTF-8 sequence; the length is passed explicitly rather than inferred from a terminator.

func (*Stmt) BindZeroBlob

func (s *Stmt) BindZeroBlob(i, n int) error

BindZeroBlob binds a blob of n zero bytes without materializing it, for reserving space to be filled in later.

func (*Stmt) Busy

func (s *Stmt) Busy() bool

Busy reports whether the statement is mid-execution: it has returned at least one row and has neither run to completion nor been reset.

func (*Stmt) ClearBindings

func (s *Stmt) ClearBindings() error

ClearBindings sets every parameter back to NULL.

func (*Stmt) Close

func (s *Stmt) Close() error

Close finalizes the statement. It is safe to call more than once.

func (*Stmt) ColumnBlob

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

ColumnBlob reads column i as a byte slice, copied into Go memory. It returns nil for SQL NULL and a non-nil empty slice for a zero-length blob.

func (*Stmt) ColumnBool

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

ColumnBool reads column i as a boolean: false for zero, true otherwise.

func (*Stmt) ColumnBytes

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

ColumnBytes is the byte length of column i as text or blob.

func (*Stmt) ColumnCount

func (s *Stmt) ColumnCount() int

ColumnCount is the number of columns in the result set, available as soon as the statement is prepared.

func (*Stmt) ColumnDeclType

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

ColumnDeclType is the declared type of column i in the CREATE TABLE that defined it, or "" for an expression.

func (*Stmt) ColumnFloat

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

ColumnFloat reads column i as a float, converting per SQLite's rules.

func (*Stmt) ColumnInt

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

ColumnInt reads column i as a Go int.

func (*Stmt) ColumnInt64

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

ColumnInt64 reads column i as an integer, converting per SQLite's rules.

func (*Stmt) ColumnIsNull

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

ColumnIsNull reports whether column i of the current row holds SQL NULL.

func (*Stmt) ColumnName

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

ColumnName is the name of column i, as SQLite assigned it: the AS alias when there is one, otherwise something unspecified that should not be relied on.

func (*Stmt) ColumnRawBlob

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

ColumnRawBlob returns column i as a slice aliasing SQLite's own memory, with no copy.

The slice is valid only until the next Step, Reset, Close, or any column accessor on this statement that forces a type conversion. Write to it and you are writing into SQLite's buffer. Use Stmt.ColumnBlob unless the copy is measurably the problem.

func (*Stmt) ColumnRawText

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

ColumnRawText returns column i's UTF-8 bytes aliasing SQLite's own memory, under the same lifetime rules as Stmt.ColumnRawBlob.

func (*Stmt) ColumnText

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

ColumnText reads column i as a string, copied into Go memory. Text containing NUL bytes survives intact: the length comes from SQLite, not from scanning for a terminator.

func (*Stmt) ColumnType

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

ColumnType is the storage class of the value in column i of the current row.

func (*Stmt) DataCount

func (s *Stmt) DataCount() int

DataCount is the number of values in the current row, which is zero unless the last Step returned a row.

func (*Stmt) ExpandedSQL

func (s *Stmt) ExpandedSQL() string

ExpandedSQL is the statement text with its bound parameters substituted in, which is what belongs in a log line about a failing query.

func (*Stmt) ReadOnly

func (s *Stmt) ReadOnly() bool

ReadOnly reports whether the statement makes no direct changes to the database.

func (*Stmt) Reset

func (s *Stmt) Reset() error

Reset returns the statement to its pre-execution state. Bindings survive a reset; use Stmt.ClearBindings to drop them.

Reset reports the error of the statement's most recent execution, so an error already returned by Step will surface here a second time. That is SQLite's behaviour and hiding it would hide errors that only Reset can see.

func (*Stmt) Run

func (s *Stmt) Run() error

Run executes a statement that returns no rows and resets it, ready to be bound and run again. It is the shape a prepared insert is used in.

func (*Stmt) SQL

func (s *Stmt) SQL() string

SQL is the text this statement was compiled from.

func (*Stmt) Step

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

Step advances the statement, returning true when a row is available and false when the statement has run to completion.

A statement that returns false, or an error, has stopped; call Reset before running it again.

type Value

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

Value is one argument to an application-defined function. It is only valid for the duration of the call.

The layout mirrors fn_value in build/shim.c exactly, because on the fast path the argument slice aliases a buffer C filled in on its own stack. The raw handle travels alongside the cached data so that reading an argument as a type it is not stored as still goes to SQLite for the conversion -- the same refusal to reimplement SQLite's rules that the row batcher makes.

func (Value) Blob

func (v Value) Blob() []byte

Blob reads the argument as bytes, copied into Go memory. It returns nil for SQL NULL.

func (Value) Float

func (v Value) Float() float64

Float reads the argument as a float, converting per SQLite's rules.

func (Value) Int64

func (v Value) Int64() int64

Int64 reads the argument as an integer, converting per SQLite's rules.

func (Value) RawBlob

func (v Value) RawBlob() []byte

RawBlob returns the argument's bytes without copying, aliasing SQLite's own memory. Valid only until the function returns. Use Value.Blob unless the copy is measurably the problem.

func (Value) Text

func (v Value) Text() string

Text reads the argument as a string, copied into Go memory. Embedded NUL bytes survive: the length comes from SQLite.

func (Value) Type

func (v Value) Type() ColumnType

Type is the storage class of the argument.

Jump to

Keyboard shortcuts

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