sqlite

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package sqlite provides the SQLite store.Store: it opens the database, applies its PRAGMAs, runs migrations, and builds the shared SQL store (internal/store/sqlstore) over its pools with the SQLite dialect. It also holds the operations only SQLite has: Ping, backup and WAL checkpointing.

Usage

opts := sqlite.DefaultOptions()
s, err := sqlite.Open(ctx, "/path/to/sqi.db", opts)
if err != nil {
    log.Fatal(err)
}
defer s.Close()

The returned *Store satisfies store.Store in full. It can be passed wherever a store.Store is expected, or used directly for the [Ping] method that is not part of the public interface (used by health checks).

Concurrency

The store keeps two connection pools over the same database file.

Writes go through a pool opened with sql.DB.SetMaxOpenConns(1), which serializes every write through a single SQLite connection. That prevents write-write conflicts and avoids SQLITE_BUSY between concurrent goroutines.

Reads go through a second pool of up to [readPoolMaxConns] connections. WAL mode lets readers proceed alongside a writer, so a read does not queue behind one. A single large [Store.CreateJobSubmission] holds the write connection while it inserts every task, which takes seconds at the job sizes this server accepts; with one shared pool every other database user in the process, the health checker included, would stall for that long.

The shared store routes by statement, not by call site: anything whose SQL begins with SELECT is a read, everything else is a write. Several writes are INSERT/UPDATE/DELETE ... RETURNING issued through QueryRow, so classifying by Go method would be wrong. Misclassifying a read as a write only serializes it; misclassifying a write as a read puts it on a multi-connection pool, so anything ambiguous (a CTE, say) stays on the write pool.

Transactions always run on the write pool.

Correctness under concurrent writers is not left to the single write connection: every multi-row invariant is a single store operation (see "Store invariants" in docs/architecture.md), and most of them name their anchor rows via Dialect.LockAnchors, which the SQLite dialect leaves a no-op because the one write connection already serializes every write transaction. The PostgreSQL dialect, which has concurrent writers, locks those rows instead (see "Anchor rows" in docs/architecture.md). Single-row writes carry their own precondition in their WHERE clause on either kind of store.

An in-memory or temporary database gets one pool for both roles: a second sql.Open on ":memory:" would open a different, empty database.

Migrations

When Options.AutoMigrate is true (the default), Open applies every pending migration through a goose provider over the embedded SQLite migration set (migrations.NewProvider) before returning. A caller that must open an existing database without changing its schema sets AutoMigrate to false; "sqi-server migrate up" applies migrations explicitly.

Index

Constants

This section is empty.

Variables

View Source
var ErrServerLockHeld = fslock.ErrHeld

ErrServerLockHeld means another sqi-server, or a command that must not run beside one (restore, store copy, migrate up), holds the database's lock file.

Functions

func AcquireLock added in v0.4.0

func AcquireLock(dbPath string) (*fslock.Lock, error)

AcquireLock takes the single-server lock for the database at dbPath.

func BackupPath added in v0.4.0

func BackupPath(ctx context.Context, dbPath, destPath string) error

BackupPath creates a consistent, online copy of the database at dbPath in destPath using SQLite's VACUUM INTO statement, without opening the store, so it works on a schema this binary is too old for (the backup taken before rolling a binary back). The source database remains fully available for reads and writes during the operation.

VACUUM INTO is the SQL-level equivalent of the SQLite C online backup API (sqlite3_backup_*): it produces a clean, fully checkpointed snapshot of the live database in a single atomic operation. The modernc.org/sqlite driver does not expose the C backup API directly, so VACUUM INTO is the idiomatic replacement.

destPath must not already exist. The copy holds password hashes, API-key hashes and session tokens, so destPath is created first, empty and restricted to the writing user (fsutil.CreateSecretExclusive), and VACUUM INTO, which accepts an empty file, writes into it; left to SQLite, the file would get the process's default permissions. On failure the file is removed.

func DSN added in v0.4.0

func DSN(path string) (string, error)

DSN returns the name to hand the driver for the database at path. The driver reads everything after a name's first "?" as its own query, so a path holding one is opened by its FileURI, which escapes it. Any other path is handed over unchanged — the driver reads no other character specially in a plain name — as are a "file:" URI the caller wrote and an in-memory or temporary database.

func FileURI added in v0.4.0

func FileURI(path string, readOnly bool) (string, error)

FileURI returns a file: URI DSN for the database at path, with sqi's busy_timeout, read-only (mode=ro) when readOnly is set. The path is made absolute and percent-escaped by url.URL, so a "?", "#", "%" or space in it stays part of the name (handed to the driver raw, "?" would start the query and open, or create, a truncated name), and a Windows drive path becomes file:///C:/..., the form SQLite reads as that drive.

func LockPath added in v0.4.0

func LockPath(dbPath string) (string, error)

LockPath is the lock file guarding the database at dbPath: the database file's own path, symlinks resolved, plus ".lock". Every symlinked name for one database, including a link to one not created yet, gives the same lock file, so two servers cannot each hold a lock on it. A hard link is a name the filesystem cannot tell from the original, and gets a lock file of its own.

func ResolvePath added in v0.4.0

func ResolvePath(path string) (string, error)

ResolvePath is the absolute path, symlinks resolved, of the database file SQLite opens for path. When nothing exists there yet, a dangling link is followed to the file SQLite would create through it; otherwise only the directory is resolved. An in-memory database has no file and keeps its name.

Commands resolve a configured path once, so the server and a backup or restore given another name for the database all work on one file: SQLite on Windows names the -wal and -shm files after the name it is given, and restore moves aside and replaces whatever file the path names.

func SchemaVersion added in v0.4.0

func SchemaVersion(ctx context.Context, db *sql.DB) (int64, error)

SchemaVersion returns the highest applied goose version, or 0 when the database has never been migrated. It creates nothing.

Types

type Options

type Options struct {
	// AutoMigrate controls whether Open applies any pending migrations (via
	// [migrations.NewProvider]) before returning. Default: true. A caller
	// that must not change the schema sets it to false.
	AutoMigrate bool

	// ServerLock takes the single-server lock file (LockPath) for the store's
	// life. The server sets it; backup and the worker-token commands do not.
	// Ignored for an in-memory or temporary database, which no second process
	// can open.
	ServerLock bool
}

Options configures Open.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns an Options with recommended defaults.

type Store

type Store struct {
	*sqlstore.Store
	// contains filtered or unexported fields
}

Store is the SQLite state store: the shared SQL store over a single write connection and a read pool, plus SQLite's own operations.

func Open

func Open(ctx context.Context, path string, opts Options) (*Store, error)

Open opens (or creates) the SQLite database at path, applies connection pragmas, optionally runs pending migrations, prepares all statements, and returns a ready-to-use *Store.

Open returns an error and releases all resources if any step fails.

func (*Store) Checkpoint

func (s *Store) Checkpoint(ctx context.Context) (walPages, checkpointed int, err error)

Checkpoint runs a WAL checkpoint in PASSIVE mode, copying whatever committed WAL frames it can back into the main database file without ever waiting. It returns the number of WAL log pages and the number successfully checkpointed, and is the mode the periodic checkpointer uses.

The periodic checkpoint must not be TRUNCATE. Reads run on their own connection pool (see the Concurrency section of the package doc), so a reader holding a WAL snapshot blocks a truncating checkpoint, which invokes SQLite's busy handler and waits out the whole busy_timeout (5s) on the write connection before giving up, still without truncating. That stalls job submission, lease grants and every task-status write for five seconds on each tick, the write stall the separate read pool exists to remove.

PASSIVE never invokes the busy handler: it transfers what it can and returns. A reader means fewer frames move this tick and the next one takes them. Pinned by TestCheckpoint_DoesNotBlockOnAReader.

The checkpoint runs on the write pool, which is still a single connection, so two checkpoints can never overlap.

func (*Store) CheckpointTruncate added in v0.3.0

func (s *Store) CheckpointTruncate(ctx context.Context) (walPages, checkpointed int, err error)

CheckpointTruncate runs a WAL checkpoint in TRUNCATE mode, which additionally truncates the WAL to zero bytes once every frame is transferred.

It is for shutdown, where a WAL left at zero is worth waiting for and there is no next tick to finish the job. It can block for up to busy_timeout if a reader still holds a snapshot, which is acceptable once on the way down. Do not call it on a timer; see Store.Checkpoint.

func (*Store) Close

func (s *Store) Close() error

Close releases the server lock, if held, and closes the store. Safe to call more than once.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping verifies the database connection is still alive. Health checks use it.

It pings the read pool, not the write pool. Readiness reports whether the database is reachable, and a large job submission holds the sole write connection for seconds at a time; a ping queued behind it would turn a normal write into a failed health check.

func (*Store) StartCheckpointer

func (s *Store) StartCheckpointer(ctx context.Context, interval time.Duration, logger *slog.Logger) <-chan struct{}

StartCheckpointer launches a background goroutine that calls [Checkpoint] every interval. The goroutine exits when ctx is canceled, running one final checkpoint before returning so the WAL is fully flushed before the store is closed.

The returned channel closes after the final checkpoint; the server waits on it before closing the store.

Errors are logged but do not stop the loop; transient checkpoint failures are not fatal. The caller does not need to wrap this in a goroutine; it manages its own.

Jump to

Keyboard shortcuts

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