Documentation
¶
Overview ¶
Package sqlite is a SQLite driver for database/sql that needs no cgo.
Open opens a database with what a server needs already chosen:
db, err := sqlite.Open("app.db")
The driver also registers itself as "sqlite", and sql.Open("sqlite", "app.db") opens the same database with the pool of database/sql (OptimizePool gives it the pool of Open). modernc.org/sqlite and github.com/glebarez/go-sqlite register the same name, so a program that imports one of them as well panics at start.
What the driver chooses ¶
A database opened with nothing but its name is not as SQLite alone would open it. The driver chooses when a call waits and where the bytes go, never what a statement returns or whether a commit is on the disk:
- The file is put in WAL mode (PRAGMA journal_mode=WAL), where readers and the writer do not wait for each other. Not when the DSN has a _pragma=journal_mode of its own (_pragma=journal_mode(delete) for a rollback journal, _pragma=journal_mode to leave the file as it is), and not on a connection that only reads (mode=ro, a file that cannot be written, _pragma=query_only). A file that cannot be put in WAL mode as a connection opens is opened in the mode it has.
- A transaction starts with BEGIN IMMEDIATE: it waits its turn for the write lock, so one that reads and then writes does not fail halfway with "database is locked". Start a transaction that only reads with sql.TxOptions{ReadOnly: true}, or it holds the write lock while it reads, and the writers that wait for it longer than the busy timeout fail. _txlock=deferred starts transactions as SQLite does, and so does a connection that cannot write (mode=ro, PRAGMA query_only).
- A connection waits 5 seconds for a lock (busy_timeout).
synchronous is SQLite's FULL, and foreign keys are off, as in SQLite.
The data source name ¶
A file name, ":memory:", or a URI ("file:app.db?mode=ro"), which SQLite reads itself (https://sqlite.org/uri.html). These parameters are the driver's and SQLite does not see them:
- _pragma=name(value): a PRAGMA run on every new connection, in order. It may be given more than once. Not optimize, which may write: run it with Exec once the database is open.
- _txlock=immediate, deferred or exclusive: how BEGIN starts a transaction (immediate by default, see above). A read-only transaction always starts deferred, and so does every transaction of a connection SQLite opened read-only, unless _txlock is given.
- _time_format=sqlite: how a time.Time is written. The only format, and the default, is "2006-01-02 15:04:05.999999999-07:00".
- _wal_limit=bytes: the length of the WAL past which the driver starts it over, waiting up to 100 ms for the readers that still use it. In WAL mode, reads that overlap without a gap otherwise let the WAL grow as long as they last. 67108864 (64 MiB) by default, 0 for no limit.
In WAL mode the driver runs the automatic checkpoints of its connections: one each time the WAL has grown by wal_autocheckpoint frames, where SQLite runs one after every commit once the WAL is that long. PRAGMA wal_autocheckpoint reads and sets it as before.
Foreign keys in a migration ¶
PRAGMA foreign_keys does nothing inside a transaction (https://sqlite.org/pragma.html#pragma_foreign_keys). So with _pragma=foreign_keys(1), a migration that rebuilds a table as SQLite describes (https://sqlite.org/lang_altertable.html#otheralter) inside a transaction runs with foreign keys on, also when it runs PRAGMA foreign_keys=OFF itself. Its DROP TABLE then deletes, without an error, every row of another table that refers to the table with ON DELETE CASCADE. Migration tools such as goose and golang-migrate run each file in a transaction by default. Turn foreign keys off on a connection of its own before BEGIN, check them before COMMIT, and close that connection so that the pool never hands it out:
conn, err := db.Conn(ctx)
if err != nil {
return err
}
// Returning driver.ErrBadConn closes conn and takes it out of the pool.
defer conn.Raw(func(any) error { return driver.ErrBadConn })
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=OFF"); err != nil {
return err
}
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// The migration, then PRAGMA foreign_key_check with tx: any row it
// gives is a reference the migration broke, so return before Commit.
return tx.Commit()
Index ¶
- Constants
- Variables
- func Open(dsn string, opts ...Option) (*sql.DB, error)
- func OptimizePool(db *sql.DB) error
- func Register(opts ...Option)
- type Aggregate
- type Connector
- type ConsumeStats
- type Driver
- type Error
- type ErrorStats
- type FileStats
- type Func
- type FuncFlag
- type IndexConstraint
- type IndexInfo
- type IndexOp
- type IndexOrderBy
- type IndexUsage
- type MemoryStats
- type ModuleFlag
- type Option
- func Join(opts ...Option) Option
- func WithAggregate(name string, nArg int, newAggregate func() Aggregate, flags ...FuncFlag) Option
- func WithCollation(name string, cmp func(a, b string) int) Option
- func WithFunction(name string, nArg int, fn Func, flags ...FuncFlag) Option
- func WithModule(name string, connect func(args []string) (VTable, error), flags ...ModuleFlag) Option
- func WithWindow(name string, nArg int, newWindow func() Window, flags ...FuncFlag) Option
- type QueueStats
- type QueueSubStats
- type ReplicaStats
- type Report
- type StatementStats
- type VCursor
- type VSavepointer
- type VTable
- type VTransactor
- type VUpdater
- type WALStats
- type Window
- type WriteStats
Examples ¶
Constants ¶
const ( ERROR = 1 INTERNAL = 2 PERM = 3 ABORT = 4 BUSY = 5 LOCKED = 6 NOMEM = 7 READONLY = 8 INTERRUPT = 9 IOERR = 10 CORRUPT = 11 NOTFOUND = 12 FULL = 13 CANTOPEN = 14 PROTOCOL = 15 EMPTY = 16 SCHEMA = 17 TOOBIG = 18 CONSTRAINT = 19 MISMATCH = 20 MISUSE = 21 NOLFS = 22 AUTH = 23 FORMAT = 24 RANGE = 25 NOTADB = 26 NOTICE = 27 WARNING = 28 )
Primary result codes.
const ( ERROR_MISSING_COLLSEQ = ERROR | 1<<8 ERROR_RETRY = ERROR | 2<<8 ERROR_SNAPSHOT = ERROR | 3<<8 ERROR_RESERVESIZE = ERROR | 4<<8 ERROR_KEY = ERROR | 5<<8 ERROR_UNABLE = ERROR | 6<<8 IOERR_READ = IOERR | 1<<8 IOERR_SHORT_READ = IOERR | 2<<8 IOERR_WRITE = IOERR | 3<<8 IOERR_FSYNC = IOERR | 4<<8 IOERR_DIR_FSYNC = IOERR | 5<<8 IOERR_TRUNCATE = IOERR | 6<<8 IOERR_FSTAT = IOERR | 7<<8 IOERR_UNLOCK = IOERR | 8<<8 IOERR_RDLOCK = IOERR | 9<<8 IOERR_DELETE = IOERR | 10<<8 IOERR_BLOCKED = IOERR | 11<<8 IOERR_NOMEM = IOERR | 12<<8 IOERR_ACCESS = IOERR | 13<<8 IOERR_CHECKRESERVEDLOCK = IOERR | 14<<8 IOERR_LOCK = IOERR | 15<<8 IOERR_CLOSE = IOERR | 16<<8 IOERR_DIR_CLOSE = IOERR | 17<<8 IOERR_SHMOPEN = IOERR | 18<<8 IOERR_SHMSIZE = IOERR | 19<<8 IOERR_SHMLOCK = IOERR | 20<<8 IOERR_SHMMAP = IOERR | 21<<8 IOERR_SEEK = IOERR | 22<<8 IOERR_DELETE_NOENT = IOERR | 23<<8 IOERR_MMAP = IOERR | 24<<8 IOERR_GETTEMPPATH = IOERR | 25<<8 IOERR_CONVPATH = IOERR | 26<<8 IOERR_VNODE = IOERR | 27<<8 IOERR_AUTH = IOERR | 28<<8 IOERR_BEGIN_ATOMIC = IOERR | 29<<8 IOERR_COMMIT_ATOMIC = IOERR | 30<<8 IOERR_ROLLBACK_ATOMIC = IOERR | 31<<8 IOERR_DATA = IOERR | 32<<8 IOERR_CORRUPTFS = IOERR | 33<<8 IOERR_IN_PAGE = IOERR | 34<<8 IOERR_BADKEY = IOERR | 35<<8 IOERR_CODEC = IOERR | 36<<8 LOCKED_SHAREDCACHE = LOCKED | 1<<8 LOCKED_VTAB = LOCKED | 2<<8 BUSY_RECOVERY = BUSY | 1<<8 BUSY_SNAPSHOT = BUSY | 2<<8 BUSY_TIMEOUT = BUSY | 3<<8 CANTOPEN_NOTEMPDIR = CANTOPEN | 1<<8 CANTOPEN_ISDIR = CANTOPEN | 2<<8 CANTOPEN_FULLPATH = CANTOPEN | 3<<8 CANTOPEN_CONVPATH = CANTOPEN | 4<<8 CANTOPEN_DIRTYWAL = CANTOPEN | 5<<8 CANTOPEN_SYMLINK = CANTOPEN | 6<<8 CORRUPT_VTAB = CORRUPT | 1<<8 CORRUPT_SEQUENCE = CORRUPT | 2<<8 CORRUPT_INDEX = CORRUPT | 3<<8 READONLY_RECOVERY = READONLY | 1<<8 READONLY_CANTLOCK = READONLY | 2<<8 READONLY_ROLLBACK = READONLY | 3<<8 READONLY_DBMOVED = READONLY | 4<<8 READONLY_CANTINIT = READONLY | 5<<8 READONLY_DIRECTORY = READONLY | 6<<8 ABORT_ROLLBACK = ABORT | 2<<8 CONSTRAINT_CHECK = CONSTRAINT | 1<<8 CONSTRAINT_COMMITHOOK = CONSTRAINT | 2<<8 CONSTRAINT_FOREIGNKEY = CONSTRAINT | 3<<8 CONSTRAINT_FUNCTION = CONSTRAINT | 4<<8 CONSTRAINT_NOTNULL = CONSTRAINT | 5<<8 CONSTRAINT_PRIMARYKEY = CONSTRAINT | 6<<8 CONSTRAINT_TRIGGER = CONSTRAINT | 7<<8 CONSTRAINT_UNIQUE = CONSTRAINT | 8<<8 CONSTRAINT_VTAB = CONSTRAINT | 9<<8 CONSTRAINT_ROWID = CONSTRAINT | 10<<8 CONSTRAINT_PINNED = CONSTRAINT | 11<<8 CONSTRAINT_DATATYPE = CONSTRAINT | 12<<8 NOTICE_RECOVER_WAL = NOTICE | 1<<8 NOTICE_RECOVER_ROLLBACK = NOTICE | 2<<8 NOTICE_RBU = NOTICE | 3<<8 WARNING_AUTOINDEX = WARNING | 1<<8 AUTH_USER = AUTH | 1<<8 )
Extended result codes.
Variables ¶
var ErrUnusablePlan = errors.New("sqlite: no usable plan for the virtual table")
ErrUnusablePlan is what BestIndex returns when the scan cannot work with the constraints it was given.
Functions ¶
func Open ¶ added in v0.2.0
Open opens the database dsn names, as sql.Open("sqlite", dsn) does, sets up its pool as OptimizePool does, and connects once: a name that cannot be opened fails here and not at the first query.
db, err := sqlite.Open("app.db")
opts are the options NewConnector takes.
func OptimizePool ¶ added in v0.2.0
OptimizePool sets up the pool of db, a database of this driver that something else opened, as Open does:
- At most 128 connections, all of them kept when idle. database/sql keeps 2 and has no limit: with more goroutines than that it closes and opens connections all the time, and a burst of requests opens a connection each, with a page cache each.
- A connection idle for 5 minutes is closed, so the memory of a burst comes back.
- A database that lives in one connection (":memory:", a temporary database) gets a pool of one connection that is never closed, so that every call sees the same database. A call made while another holds the connection (rows not yet closed, a transaction) waits for it: use the rows or the transaction for it.
- No connection is closed for its age (SetConnMaxLifetime).
It connects once to see which database db is, and waits for a connection when the program holds all of them. What the program sets on db afterwards holds. A db whose connections are wrapped by another package (one that traces calls, say) gives an error: OptimizePool cannot see the database behind them.
Types ¶
type Aggregate ¶
Aggregate is the state of one group of an aggregate function written in Go. Step runs for each row of the group, with arguments as a Func gets them, then Final once, with a result as a Func gives it. An error or a panic in either is the error of the statement.
type Connector ¶
type Connector struct {
// contains filtered or unexported fields
}
Connector opens connections to one database.
func NewConnector ¶
NewConnector parses dsn, for sql.OpenDB. Its connections get what Register gave, then opts.
type ConsumeStats ¶ added in v0.5.0
type ConsumeStats struct {
// Path is the database file of the queue, as SQLite named it when the
// driver first opened it. Table and Queue are the table of its
// messages, as given to queue.Table, and the name of the queue.
Path, Table, Queue string
// Sub is the subscription it handles, "" for the default one, and Dead
// says it hands out dead messages (queue.Dead).
Sub string
Dead bool
// Workers is how many workers it has. StuckWorkers is how many of them
// are held by a handler that ran past MaxRun and has not returned 30
// seconds after its context was cancelled. When the two are equal, it
// takes no message. A gauge.
Workers, StuckWorkers int64
// LastError is the last error of the database it met since it started,
// nil before the first, and kept once the database works again: in
// JSON, its text, or null. LastErrorAt is when it came, and Errors
// counts the statements of the database that failed for it, also those
// whose error OnError did not get, and the give-backs of messages taken
// and not run that failed (queue.MessageError.NotGivenBack). A Consume
// whose Errors grows between two reports cannot reach its database, and
// tries again by itself.
LastError error
LastErrorAt time.Time
Errors int64
}
ConsumeStats is how a Consume of a queue of package queue stands now.
type Driver ¶
type Driver struct{}
Driver is the database/sql driver.
type Error ¶ added in v0.1.5
Error is an error SQLite gave, with its result code. Read it with errors.As:
var e *sqlite.Error
if errors.As(err, &e) && e.Code() == sqlite.CONSTRAINT {
// a constraint failed
}
Code is the primary result code (CONSTRAINT), ExtendedCode the extended one (CONSTRAINT_UNIQUE), as listed in codes.go and at https://sqlite.org/rescode.html. Unwrap gives the error under it when there is one: the panic of a Go collation, or for ABORT_ROLLBACK under group commit, the error that rolled the batch back.
A statement stopped by its context gives the context's error instead.
type ErrorStats ¶ added in v0.3.1
type ErrorStats struct {
// Full counts SQLITE_FULL, a full disk.
Full int64
// IO counts SQLITE_IOERR, a file that could not be read or written.
IO int64
// Corrupt counts SQLITE_CORRUPT, a database file that is damaged.
Corrupt int64
// Constraint counts SQLITE_CONSTRAINT: a UNIQUE, NOT NULL, CHECK or
// FOREIGN KEY constraint that failed.
Constraint int64
// Other counts every other code. OtherCodes says which, by the name of
// the code as in codes.go ("BUSY", "ERROR"), with only the codes seen.
Other int64
OtherCodes map[string]int64
}
ErrorStats counts the errors of SQLite that calls on a file returned to the program, by their primary result code (Error.Code). The error of a context that ended is not counted, nor an error of the driver itself, as for a transaction that already ended or an argument it cannot bind.
type FileStats ¶ added in v0.3.1
type FileStats struct {
// Path is the file, as SQLite named it when the driver first opened it.
Path string
// Writes is how the writes of the process go.
Writes WriteStats
// WAL is the checkpoints the driver runs, and the length of the WAL.
WAL WALStats
// Errors counts the errors of SQLite that calls on the file returned.
Errors ErrorStats
// Statements counts how often a query or a write found its statement
// kept by its connection.
Statements StatementStats
// Queues are the queues of package queue that this process opened on
// the file with a database (sql.DB) that has a connection to it now,
// sorted by Table and then Name. A queue that two of them opened is
// listed once, with the later count.
Queues []QueueStats
// Replica is how replication of the file stands, nil when this process
// does not replicate it.
Replica *ReplicaStats
}
FileStats is the numbers of one database file.
type Func ¶
Func is a SQL function written in Go.
Its arguments are copies, each an int64, float64, string, []byte or nil, so it may keep them. It returns a value database/sql can bind (an integer, float, bool, string, []byte, time.Time, nil or a driver.Valuer), or an error, which becomes the error of the statement. A panic in it is recovered and becomes the error of the statement too: the connection stays good.
It may run on any connection of its connector, and from several goroutines at once. It must not use the database: it runs in the middle of a statement. It may also run more than once for the same row: SQLite does not promise how often it calls a function. Group commit never runs a statement twice. A statement that called a function not marked Innocuous ends its batch and commits right away, so that a failure of a later statement cannot roll back what it wrote after the function acted.
type FuncFlag ¶
type FuncFlag int
FuncFlag tells SQLite how a function behaves.
const ( // Deterministic: the same arguments always give the same result, so // SQLite may compute it once, and use it in indexes and generated // columns. Deterministic FuncFlag = csqlite.FuncDeterministic // DirectOnly: the function may be called only from SQL the program // runs, never from a trigger, view, index or generated column of the // schema. Give it to a function with side effects, so that a database // file someone else made cannot call it. DirectOnly FuncFlag = csqlite.FuncDirectOnly // Innocuous: the function has no side effects and reveals nothing, so // it is safe wherever SQL comes from. A write that calls only such // functions merges with others: one that calls a Go function without // this flag ends its group commit batch. Innocuous FuncFlag = csqlite.FuncInnocuous )
type IndexConstraint ¶ added in v0.1.3
IndexConstraint is a term of the WHERE clause: column Op value. A constraint that is not Usable may not get an ArgvIndex.
type IndexInfo ¶ added in v0.1.3
type IndexInfo struct {
Constraints []IndexConstraint
OrderBy []IndexOrderBy
// ColUsed has bit i set when the statement uses column i, and bit 63
// for any column from 63 up.
ColUsed uint64
// Usage is as long as Constraints, one for each.
Usage []IndexUsage
// IdxNum and IdxStr name the plan for Filter.
IdxNum int
IdxStr string
// OrderByConsumed says the scan gives its rows in the order of OrderBy.
OrderByConsumed bool
EstimatedCost float64
EstimatedRows int64
// Unique says the scan gives at most one row.
Unique bool
}
IndexInfo is the question BestIndex answers. Constraints, OrderBy and ColUsed are the question. The rest is the answer, with SQLite's defaults in EstimatedCost and EstimatedRows.
type IndexOp ¶ added in v0.1.3
type IndexOp int
IndexOp is the operator of a constraint.
const ( IndexEQ IndexOp = csqlite.IndexEQ IndexGT IndexOp = csqlite.IndexGT IndexLE IndexOp = csqlite.IndexLE IndexLT IndexOp = csqlite.IndexLT IndexGE IndexOp = csqlite.IndexGE IndexMatch IndexOp = csqlite.IndexMatch IndexLike IndexOp = csqlite.IndexLike IndexGlob IndexOp = csqlite.IndexGlob IndexRegexp IndexOp = csqlite.IndexRegexp IndexNE IndexOp = csqlite.IndexNE IndexIsNot IndexOp = csqlite.IndexIsNot IndexIsNotNull IndexOp = csqlite.IndexIsNotNull IndexIsNull IndexOp = csqlite.IndexIsNull IndexIs IndexOp = csqlite.IndexIs IndexLimit IndexOp = csqlite.IndexLimit IndexOffset IndexOp = csqlite.IndexOffset )
The operators of IndexConstraint.
type IndexOrderBy ¶ added in v0.1.3
IndexOrderBy is a term of the ORDER BY clause.
type IndexUsage ¶ added in v0.1.3
IndexUsage is what BestIndex says of a constraint. ArgvIndex > 0 hands its value to Filter, at args[ArgvIndex-1]: give each used constraint its own number from 1 up. Omit says the scan only gives rows that meet it, so SQLite need not check them again.
type MemoryStats ¶ added in v0.3.1
type MemoryStats struct {
// InUseBytes is what the heap holds now. A gauge.
InUseBytes int64
// HighWaterBytes is the most it held since the process started.
HighWaterBytes int64
}
MemoryStats is the memory SQLite takes from the system for its heap: the pages it caches, its statements and the rest of what it allocates. Blocks it freed are counted while the heap keeps them for reuse. The stacks of the connections are not counted.
type ModuleFlag ¶ added in v0.1.3
type ModuleFlag int
ModuleFlag tells SQLite how a module behaves.
const ( // EponymousOnly: the module is only used by its name, as a function // whose arguments are its hidden columns (a table-valued function such // as generate_series). CREATE VIRTUAL TABLE with it fails. Without the // flag, the module serves only CREATE VIRTUAL TABLE. EponymousOnly ModuleFlag = csqlite.ModEponymousOnly // ModuleDirectOnly: its tables may be used only by SQL the program // runs and by temp triggers and views, never by a trigger or a view // stored in a database. Give it to a module that reaches // outside the database, such as one that reads files, so that a // database file someone else made cannot use it. It cannot go with // ModuleInnocuous: a table has one of the two. ModuleDirectOnly ModuleFlag = csqlite.ModDirectOnly // ModuleInnocuous: the module has no side effects and reveals nothing, // so its tables are safe wherever SQL comes from. ModuleInnocuous ModuleFlag = csqlite.ModInnocuous // ModuleWritable: its tables take INSERT, UPDATE and DELETE when they are // VUpdaters. Those statements never merge with others in group commit: // the table's own transaction is outside what a merged batch can undo. // It cannot go with EponymousOnly. ModuleWritable ModuleFlag = csqlite.ModWritable )
type Option ¶
type Option struct {
// contains filtered or unexported fields
}
An Option adds something to the connections of a connector: give it to NewConnector, or to Register for the connectors sql.Open makes.
func Join ¶
Join makes one Option of several, applied in order: how a package of functions hands them over.
func WithAggregate ¶
WithAggregate makes an aggregate function name of nArg arguments: for each group, newAggregate makes a state. A group of no rows gets one too, for Final alone.
func WithCollation ¶
WithCollation makes cmp the collation name, for COLLATE name in queries and in the schema. cmp returns a negative number, 0 or a positive number as a sorts before, with or after b, and must be a total order. It must have no side effects: SQLite calls it as often and in the order its plan needs. A panic in cmp fails the statement with the panic, and SQLite undoes it as it does when memory runs out: it rolls back the statement, or the whole transaction. When the whole transaction is gone, the next statements of it and its Commit fail, and so do the statements merged before it (SQLITE_ABORT_ROLLBACK). The connection stays good.
func WithFunction ¶
WithFunction makes fn the SQL function name of nArg arguments (-1 for any number) on every connection of the connector. A later option of the same name and nArg replaces an earlier one.
Give a function with no side effects the flag Innocuous. Without it, a write that calls the function is the last of its group commit batch and commits right away, so many writers that call it commit one by one. The same holds for WithAggregate and WithWindow.
Example ¶
//go:build ((linux || darwin) && (amd64 || arm64)) || (windows && (amd64 || arm64))
package main
import (
"database/sql"
"database/sql/driver"
"fmt"
"strings"
"github.com/liustack/sqlite"
)
type longest struct{ s string }
func (l *longest) Step(args []driver.Value) error {
if s, ok := args[0].(string); ok && len(s) > len(l.s) {
l.s = s
}
return nil
}
func (l *longest) Final() (driver.Value, error) { return l.s, nil }
func main() {
reverse := func(args []driver.Value) (driver.Value, error) {
s, _ := args[0].(string)
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r), nil
}
c, err := sqlite.NewConnector(":memory:",
sqlite.WithFunction("reverse", 1, reverse, sqlite.Deterministic),
sqlite.WithAggregate("longest", 1, func() sqlite.Aggregate { return &longest{} }),
sqlite.WithCollation("nocase_go", func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
}))
if err != nil {
panic(err)
}
db := sql.OpenDB(c)
defer db.Close()
var r, l, first string
err = db.QueryRow(`
WITH w(word) AS (VALUES ('Banana'), ('apple'), ('cherry'))
SELECT reverse('stressed'), longest(word),
(SELECT word FROM w ORDER BY word COLLATE nocase_go LIMIT 1)
FROM w`).Scan(&r, &l, &first)
if err != nil {
panic(err)
}
fmt.Println(r, l, first)
}
Output: desserts Banana apple
func WithModule ¶ added in v0.1.3
func WithModule(name string, connect func(args []string) (VTable, error), flags ...ModuleFlag) Option
WithModule makes a virtual table module name on every connection of the connector. connect makes a table for CREATE VIRTUAL TABLE t USING name(args...), and when a connection first uses such a table, or, for an EponymousOnly module, for its name used as a table, with no args. args are the arguments as SQL wrote them, without quotes taken off. A later option of the same name replaces an earlier one.
type QueueStats ¶ added in v0.3.1
type QueueStats struct {
// Table is the table of its messages, as given to queue.Table.
Table string
// Name is the name of the queue.
Name string
// AsOf is when Subs was counted, the zero time until a round has.
AsOf time.Time
// Subs is how the messages of each subscription stood, by its name: of
// the default subscription when the queue has no named one.
Subs []QueueSubStats
}
QueueStats is a queue of package queue. Its numbers are those the last round of cleanup of the queue in this process counted, once a minute at most: q.Stats(ctx) counts them now.
type QueueSubStats ¶ added in v0.3.1
type QueueSubStats struct {
Sub string
Waiting, Delayed, Held, Dead int64
OldestWaitTime time.Duration
}
QueueSubStats is how the messages of a subscription stood at AsOf, as queue.SubStats says. Each count is a gauge.
type ReplicaStats ¶ added in v0.3.1
type ReplicaStats struct {
// StagedTXID is the last TXID in the staging folder.
StagedTXID uint64
// UploadedTXID is the last TXID in the replica.
UploadedTXID uint64
// PendingBytes is what is staged and not uploaded yet. A gauge.
PendingBytes int64
// UploadError is the error of the last upload, "" once one succeeds.
UploadError string
}
package replica says.
type Report ¶ added in v0.3.1
type Report struct {
// Memory is SQLite's memory, of the whole process.
Memory MemoryStats
// Files has a FileStats for each database file the driver has open now,
// sorted by Path. A file drops out once its last connection closes and
// no replicator runs on it, its numbers with it: opened again, it starts
// from zero. Open's pool closes a connection idle for 5 minutes, so a
// database no one used for that long is not listed.
Files []FileStats
// Consumes has how each Consume of package queue that runs in this
// process stands, in the order they started. It is apart from Files:
// a Consume is listed while it runs, also while its database fails and
// its file has no connection open.
Consumes []ConsumeStats
}
Report is what Stats gives: the numbers of the driver in this process, for a status page. It is plain data, for encoding/json as it is.
A counter counts from the start of the process and never goes back, while its file stays open. A gauge, marked as such, is a value of now. Each field is read on its own as Stats runs, so the fields are not of one instant: a commit that ends while Stats runs may be in Commits and not yet in Merged. On windows the clock the times are read on moves in steps of the system's timer, up to 15.6ms: one commit, wait or checkpoint can be off by up to a step (a short one often reads 0), and only a sum over many is close.
func Stats ¶ added in v0.3.1
func Stats() Report
Stats gives the numbers of the driver in this process. It runs no SQL and waits for no write: what it reads is counted with atomics as the driver runs, and the list of files is held only while a connection opens or closes. The numbers of a queue come from its last round of cleanup, and those of a Consume from what it holds as it runs.
A program puts it on its status page as it is, as JSON for example:
json.NewEncoder(w).Encode(sqlite.Stats())
type StatementStats ¶ added in v0.3.1
type StatementStats struct {
// Hits counts those that found their statement kept by their
// connection.
Hits int64
// Misses counts those that did not, and so prepared it.
Misses int64
}
StatementStats counts the queries (QueryContext) and writes (ExecContext) of the connections of a file, by whether their connection kept their statement (docs/query-cache.md). The statements a program prepares itself (Prepare) are not counted.
type VCursor ¶ added in v0.1.3
type VCursor interface {
// Filter starts the scan with the plan BestIndex chose: idxNum and
// idxStr as it set them, and args the values of the constraints it gave
// an ArgvIndex, args[ArgvIndex-1] for each. The values are copies, as
// a Func gets them. Filter may run again on the same cursor, to start
// over.
Filter(idxNum int, idxStr string, args []driver.Value) error
// Next goes to the next row.
Next() error
// EOF says the scan is past its last row. It runs after Filter and
// after each Next.
EOF() bool
// Column is column i of the row, a value as a Func returns.
Column(i int) (driver.Value, error)
// RowID is the rowid of the row.
RowID() (int64, error)
Close() error
}
VCursor is a scan of a VTable.
type VSavepointer ¶ added in v0.1.3
VSavepointer is a VTransactor that keeps savepoints, so that a statement that fails inside a transaction is undone in the table too: Savepoint(n) marks the state, RollbackTo(n) goes back to the state at savepoint n, and Release(n) forgets the marks from n on. A table that joined the transaction after savepoint n was opened has no mark for it: RollbackTo(n) then goes back to the state at Begin.
type VTable ¶ added in v0.1.3
type VTable interface {
// Schema is the CREATE TABLE statement of its columns, such as
// "CREATE TABLE x(value, start HIDDEN)". The name of the table in it
// is not used. A HIDDEN column is not in SELECT *, and when the module
// is used by its name as a function, its arguments give the hidden
// columns, in order: they reach BestIndex as constraints of EQ.
Schema() string
// BestIndex chooses how to scan the table under the constraints of
// info, and says what the scan costs. SQLite may ask several times
// with different constraints and runs the cheapest. It returns
// ErrUnusablePlan when the scan cannot work with the constraints that
// are usable, such as when an argument it needs is missing.
BestIndex(info *IndexInfo) error
// Open makes a cursor for a scan.
Open() (VCursor, error)
// Disconnect ends the table on its connection.
Disconnect() error
}
VTable is a table of a virtual table module, written in Go, on one connection. It only reads, unless its module is ModuleWritable and it is also a VUpdater.
Each connection connects a table of its own, and uses it from one goroutine at a time. Something the tables of several connections share is used from several goroutines at once. Like a Func, a table must not use the database. A statement that reads a table never merges with others in group commit, so it always reads the table of its own connection.
type VTransactor ¶ added in v0.1.3
VTransactor is a VUpdater that takes part in the transactions of its connection. Begin runs before the first write of the table in a transaction, and as CREATE VIRTUAL TABLE makes the table. Sync, then Commit, run at the commit, or Rollback at the rollback. A failed Sync fails the commit. Commit runs after the database committed, so its error is lost: write what must last in Sync. Without VTransactor, a statement that fails leaves what it wrote to the table.
type VUpdater ¶ added in v0.1.3
type VUpdater interface {
// Insert adds a row of the values cols. rowid is nil when the
// statement gave none, and Insert chooses one. It returns the rowid of
// the row, which last_insert_rowid() and LastInsertId give. In a table
// declared WITHOUT ROWID, rowid is always nil, the key is in cols, and
// the number returned only goes to last_insert_rowid().
Insert(rowid driver.Value, cols []driver.Value) (int64, error)
// Update changes the row oldRowid to newRowid and cols.
Update(oldRowid, newRowid driver.Value, cols []driver.Value) error
Delete(rowid driver.Value) error
}
VUpdater is a VTable that takes INSERT, UPDATE and DELETE, of a module made with ModuleWritable. A rowid is an int64, or in a table declared WITHOUT ROWID the value of its PRIMARY KEY. Column values come as a Func's arguments. The table does not learn the statement's ON CONFLICT clause: an error fails the statement, also in INSERT OR IGNORE.
type WALStats ¶ added in v0.3.1
type WALStats struct {
// Checkpoints counts the checkpoints the driver ran on the file, those
// that failed too: those it runs each wal_autocheckpoint pages, and
// those that start the WAL over past _wal_limit. Not counted: those of
// a replicated file, which its replicator runs, those SQLite runs for
// a connection with an attached database, and a program's own PRAGMA
// wal_checkpoint.
Checkpoints int64
// CheckpointTime is the time they took, the writers of the file
// waiting meanwhile.
CheckpointTime time.Duration
// SizeBytes is the length of the WAL as the last write of the process
// left it, 0 once the driver started it over, and 0 before the process
// first wrote to the file in WAL mode. A gauge. A checkpoint of the
// replicator shows at the next write, and a file that leaves WAL mode
// keeps its last length. The -wal file on the disk can be longer:
// SQLite writes it from the start again once it starts over.
SizeBytes int64
}
WALStats is the WAL of a file.
type Window ¶ added in v0.1.3
type Window interface {
Aggregate
Value() (driver.Value, error)
Inverse(args []driver.Value) error
}
Window is the state of one partition of an aggregate window function written in Go, used with OVER. As the frame moves, Step adds a row that came into it and Inverse takes out a row that left it, with the arguments Step had for that row. Value gives the result for the rows in the frame, and may be asked when the frame has no rows. Final runs once at the end of the partition, and gives the result when the function is used without OVER.
type WriteStats ¶ added in v0.3.1
type WriteStats struct {
// Commits counts the transactions that changed rows and committed:
// each batch of group commit, and each write or transaction that ran on
// its own. One that changed only the schema is not counted. Rows are
// those SQLite counts for the connection (total_changes()), which tells
// neither the database they are in nor whether a ROLLBACK TO undid
// them: a transaction that wrote only temporary tables counts, and so
// does one whose rows a ROLLBACK TO all undid.
Commits int64
// Merged counts the writes that ran without an error in the batches of
// group commit that Commits counts.
Merged int64
// CommitTime is the time those commits took: the COMMIT of a batch, of
// a sql.Tx or of a transaction run with Exec, and the whole of a write
// that ran alone, as its commit is part of it. A write run with Query
// commits inside Query or the reading of its rows (a COMMIT in Query
// itself, an INSERT ... RETURNING as its rows are read to the end or
// close), and counts once its rows close, without its time. Divided by
// Commits it is about what a commit costs.
CommitTime time.Duration
// LockWaits counts the times a write, a transaction or the replicator
// found the write lock of the file held, and waited.
LockWaits int64
// LockWaitTime is the time they waited: until the lock was theirs, or
// a batch took their write, or they gave up.
LockWaitTime time.Duration
// Busy counts the calls that returned SQLITE_BUSY, "database is
// locked": a lock stayed held past the busy timeout, or SQLite gave up
// at once, as with a busy timeout of 0 (docs/database-is-locked.md).
// Errors counts them too, under Other.
Busy int64
}
WriteStats is how the writes of the process to a file go.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
ext
|
|
|
csv
Package csv gives SQLite the csv virtual table of SQLite's csv extension (ext/misc/csv.c), ported to Go:
|
Package csv gives SQLite the csv virtual table of SQLite's csv extension (ext/misc/csv.c), ported to Go: |
|
hash
Package hash gives SQLite hash functions:
|
Package hash gives SQLite hash functions: |
|
internal/arg
Package arg reads the arguments of the functions of ext/.
|
Package arg reads the arguments of the functions of ext/. |
|
internal/sqltest
Package sqltest runs the queries of the tests of ext/.
|
Package sqltest runs the queries of the tests of ext/. |
|
regexp
Package regexp gives SQLite the REGEXP operator and regexp functions, with Go's regexp syntax (RE2: no backreferences, and time linear in the text).
|
Package regexp gives SQLite the REGEXP operator and regexp functions, with Go's regexp syntax (RE2: no backreferences, and time linear in the text). |
|
series
Package series gives SQLite generate_series, the table-valued function of SQLite's series extension (ext/misc/series.c), ported to Go:
|
Package series gives SQLite generate_series, the table-valued function of SQLite's series extension (ext/misc/series.c), ported to Go: |
|
stats
Package stats gives SQLite the variance and the standard deviation as aggregate functions:
|
Package stats gives SQLite the variance and the standard deviation as aggregate functions: |
|
unicode
Package unicode gives SQLite case rules for every script, where SQLite's own upper, lower and NOCASE know only ASCII:
|
Package unicode gives SQLite case rules for every script, where SQLite's own upper, lower and NOCASE know only ASCII: |
|
uuid
Package uuid gives SQLite the functions of SQLite's own uuid extension:
|
Package uuid gives SQLite the functions of SQLite's own uuid extension: |
|
vec
Package vec gives SQLite vector functions, for similarity search over vectors kept in ordinary tables:
|
Package vec gives SQLite vector functions, for similarity search over vectors kept in ordinary tables: |
|
internal
|
|
|
extapi
Package extapi gives the packages of ext/ what the driver does not offer its users.
|
Package extapi gives the packages of ext/ what the driver does not offer its users. |
|
goasm/gen/cmd/engine
command
|
|
|
goasm/gen/cmd/gen
command
|
|
|
goversion
Package goversion stops a build with a Go newer than the one the engine was checked with.
|
Package goversion stops a build with a Go newer than the one the engine was checked with. |
|
powerloss
Package powerloss builds the files a power loss could leave in a directory, for the tests that play one.
|
Package powerloss builds the files a power loss could leave in a directory, for the tests that play one. |
|
queuehook
Package queuehook gives the queue (package queue) what it needs of the driver and the driver does not offer its users.
|
Package queuehook gives the queue (package queue) what it needs of the driver and the driver does not offer its users. |
|
replhook
Package replhook gives the replicator (replica/internal/capture) what it needs of the driver and the driver does not offer its users.
|
Package replhook gives the replicator (replica/internal/capture) what it needs of the driver and the driver does not offer its users. |
|
vfs
Package vfs is the operating system layer of SQLite, in Go: the files, locks and shared memory that os_unix.c gives a normal build.
|
Package vfs is the operating system layer of SQLite, in Go: the files, locks and shared memory that os_unix.c gives a normal build. |
|
Package queue keeps queues of messages in a SQLite database opened with github.com/liustack/sqlite: work a request should not wait for, or should only start once its own writes are committed.
|
Package queue keeps queues of messages in a SQLite database opened with github.com/liustack/sqlite: work a request should not wait for, or should only start once its own writes are committed. |
|
Package replica copies a database of the driver to S3 (AWS S3, Cloudflare R2, MinIO and the other stores that speak its API) as it changes, so that it can be restored after the machine is lost.
|
Package replica copies a database of the driver to S3 (AWS S3, Cloudflare R2, MinIO and the other stores that speak its API) as it changes, so that it can be restored after the machine is lost. |
|
internal/capture
Package capture copies each change of a database in WAL mode into LTX files in a local staging folder, from which the replicator uploads them, and runs the database's checkpoints, so that no frame is checkpointed before it is copied.
|
Package capture copies each change of a database in WAL mode into LTX files in a local staging folder, from which the replicator uploads them, and runs the database's checkpoints, so that no frame is checkpointed before it is copied. |
|
internal/s3
Package s3 is the small client of the S3 protocol the replicator uses: PUT, multipart upload, ranged GET, ListObjectsV2 and DELETE, signed with SigV4, against AWS S3 and the stores that speak its protocol (Cloudflare R2, MinIO and the like).
|
Package s3 is the small client of the S3 protocol the replicator uses: PUT, multipart upload, ranged GET, ListObjectsV2 and DELETE, signed with SigV4, against AWS S3 and the stores that speak its protocol (Cloudflare R2, MinIO and the like). |
|
internal/s3test
Package s3test gives tests an S3 store:
|
Package s3test gives tests an S3 store: |
