Documentation
¶
Overview ¶
Package sqlitestore implements storage.Adapter on SQLite via modernc.org/sqlite (pure Go, no CGO).
Connection model: the store keeps two pools over the same database file in WAL mode — a single-connection writer and a multi-connection reader. WAL lets any number of readers run concurrently with the one writer, so reads (pull, query, the Subscribe streams' seq checks) do not queue behind a write burst. The single writer connection still serializes writes, which is exactly the per-workspace write mutual exclusion the storage contract requires, granted for free. An in-memory database (":memory:") is private to its connection and cannot be shared across pools, so it falls back to one shared connection; use a temp file to exercise the split.
Locking: write transactions BEGIN IMMEDIATE (the writer DSN's _txlock=immediate), so they take SQLite's write lock up front instead of upgrading at their first write statement. A deferred upgrade that loses a race fails outright with SQLITE_BUSY_SNAPSHOT, which busy_timeout does not wait out and this adapter does not retry; taking the lock at BEGIN turns that failure back into a wait. Read transactions pass ReadOnly, which keeps them on a plain deferred BEGIN and off the write lock entirely.
Re-entrancy: reads may be nested, but only up to the reader pool — a nested read holds its outer read's connection while it waits for one of its own, so depth times concurrency has to stay under WithReadConnections or the pool hands out its last connection to an outer read and nothing can finish. The engine's own read paths do not nest (each is one short transaction), and pgstore's pool is bounded the same way, so this bounds app code handed a read view rather than anything internal. Writes are stricter: they serialize on the one writer connection, so opening a write transaction from inside another write transaction on the same store deadlocks outright — the inner BeginTx waits forever for the connection the outer tx holds. This is intrinsic to SQLite's single-writer model, not the pool size. The server rejects re-entrant Mutate/Invoke/CollectGarbage with an error rather than letting them hang (see package engine/server); direct adapter callers must likewise never nest write transactions.
Never open the same database file twice in one process: two writer pools each holding their own connection contend for the one write lock, so a write that outlives the other pool's busy_timeout fails with SQLITE_BUSY. To serve several apps from one file, open one Store and partition it with prefixstore.
Tuning: the defaults suit a server rather than an embedded library, and each has an Option to move it — WithCacheSize (page cache, charged per connection), WithMmapSize (how much of the file is read through a shared memory mapping instead of a syscall), WithReadConnections (reader pool ceiling, and with it the store's memory ceiling), WithWALSizeLimit (how large the -wal sidecar is left after a checkpoint) and WithOptimizeInterval (how often query-planner statistics are refreshed; see maintain). The rest is fixed: synchronous is NORMAL, the WAL default, which trades the last commits before a power loss or kernel panic — not a process crash — for not paying an fsync per transaction. Each connection also holds a prepared statement per distinct SQL text the store has run on it — a bounded set, but one that counts against the same per-connection budget as the page cache.
Index ¶
- type Option
- type Store
- func (s *Store) Close() error
- func (s *Store) CursorStateStore() cursorstate.Store
- func (s *Store) DeleteCatalogEntry(ctx context.Context, id string) error
- func (s *Store) Leases() lease.Locker
- func (s *Store) ListCatalogEntries(ctx context.Context) ([]storage.CatalogEntry, error)
- func (s *Store) ListCollectableWorkspaceIDs(ctx context.Context, cutoffs storage.GCCutoffs, rng storage.Range, limit int) ([]string, error)
- func (s *Store) ListCompactableWorkspaceIDs(ctx context.Context, minPurged int, rng storage.Range, limit int) ([]string, error)
- func (s *Store) ListPendingWorkspaceIDs(ctx context.Context, consumer string, rng storage.Range, limit int) ([]string, error)
- func (s *Store) ListStaleIndexWorkspaceIDs(ctx context.Context, mark string, rng storage.Range, limit int) ([]string, error)
- func (s *Store) ListWorkspaceIDs(ctx context.Context, rng storage.Range) ([]string, error)
- func (s *Store) PutCatalogEntry(ctx context.Context, id string, payload []byte, revision string) error
- func (s *Store) WithReadTx(ctx context.Context, workspaceID string, fn func(storage.ReadTx) error) error
- func (s *Store) WithWriteTx(ctx context.Context, workspaceID string, fn func(storage.WriteTx) error) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option func(*config)
Option configures Open.
func WithCacheSize ¶
WithCacheSize sets SQLite's page cache in bytes. It is charged per connection, so the store's worst case is this times one writer plus every reader connection — raise it together with, not independently of, WithReadConnections. Zero leaves SQLite's own default.
func WithMmapSize ¶
WithMmapSize caps how much of the database file each connection may read through a memory mapping rather than a read syscall, in bytes. A mapped page is read straight out of the operating system's page cache, with no syscall and no copy into the connection's own cache, and the mapping is backed by pages the operating system already holds — so unlike WithCacheSize it costs address space rather than memory, and every connection shares one copy. Zero disables mapping and puts every page read back on a syscall.
The caveat is the one SQLite documents for mmap: an I/O error on a mapped page reaches the process as a signal (SIGBUS) rather than an error code the call can return. A database on storage that can fail out from under a running process — a network mount, a removable disk — is a reason to pass zero.
func WithOptimizeInterval ¶
WithOptimizeInterval sets how often the store refreshes query-planner statistics (see maintain). Zero disables the background pass; Open and Close still run one, so a process that never reaches an interval is not left planning against no statistics at all.
func WithReadConnections ¶
WithReadConnections caps the reader pool, which bounds both read concurrency and the page cache the store can hold (see WithCacheSize), and with it how deeply reads may nest (see the package comment). Idle readers are kept rather than churned, because a fresh connection starts with a cold cache and re-runs every pragma. Zero leaves the pool unbounded, which is database/sql's default; the writer pool is always exactly one connection.
func WithWALSizeLimit ¶
WithWALSizeLimit caps the -wal sidecar in bytes. Zero lets it grow to its high-water mark and stay there, which is SQLite's default.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store implements storage.Adapter. read and write are the same handle for an in-memory database.
func Open ¶
Open opens (creating if necessary) a SQLite database at path. Use ":memory:" only for single-connection tests; prefer a temp file.
Open a given file at most once per process: see the package comment. Use prefixstore to multiplex several applications over one Store.
An empty path is created at the current schema; an existing database is brought up to it. A database that is not a syncplane store, or belongs to a schema lineage this binary cannot read, is refused with an error rather than opened — it has to be re-created, which costs every client of the workspaces it held a re-bootstrap.
func (*Store) CursorStateStore ¶
func (s *Store) CursorStateStore() cursorstate.Store
CursorStateStore returns a cursorstate.Store backed by this database, making the adapter a cursorstate.Provider: a server constructed on this store gets cursors that reference their membership sets instead of restating them, and the entries survive restarts with the rest of the database. Entries are pruned on write (see the constants above); a client presenting a pruned entry is reset, exactly as one below the tombstone horizon is.
func (*Store) DeleteCatalogEntry ¶
func (*Store) Leases ¶
Leases returns a process-local lease.Locker, making the adapter a lease.Provider: a server constructed on this store dedups its background work with no configuration. Process-local is the whole lease space this adapter can have — a database file is opened by at most one process (see the package comment), so there is no other node to exclude.
func (*Store) ListCatalogEntries ¶
func (*Store) ListCollectableWorkspaceIDs ¶
func (s *Store) ListCollectableWorkspaceIDs(ctx context.Context, cutoffs storage.GCCutoffs, rng storage.Range, limit int) ([]string, error)
ListCollectableWorkspaceIDs answers "which workspaces hold something this pass would reclaim" as a single query: the workspace scan is in primary-key order, and each row probes the _gc indexes of the four collectable tables on their own (workspace_id, updated_at) prefix. Each probe stops at the first match, so a workspace with nothing collectable costs four index descents and no transaction at all.
The entity purges are the exception. Live rows of an aging entity are found on rows_by_entity_version's (workspace_id, entity) prefix with updated_at left as a filter, so a workspace whose entity has no expired row reads that entity's entries to say so — the same range PurgeEntityRows walks to delete them, read instead of written.
func (*Store) ListCompactableWorkspaceIDs ¶
func (s *Store) ListCompactableWorkspaceIDs(ctx context.Context, minPurged int, rng storage.Range, limit int) ([]string, error)
ListCompactableWorkspaceIDs compares two columns of the workspace row and reads nothing else. Whether a row is worth compacting is a question only decoding its text can answer, so the query does not ask it: it asks the cheaper question of whether the sweep has fallen behind the delta prune, which is the one the mark already records.
Like ListStaleIndexWorkspaceIDs this scans the workspaces table rather than an index, for the same reason — the predicate compares two columns to each other, which no btree serves — and against the same alternative, which was scanning every text-bearing entity of every workspace to find out.
func (*Store) ListPendingWorkspaceIDs ¶
func (s *Store) ListPendingWorkspaceIDs(ctx context.Context, consumer string, rng storage.Range, limit int) ([]string, error)
ListPendingWorkspaceIDs answers "which workspaces owe this consumer work" as a single indexed query: the workspace scan is in primary-key order, and each row probes consumer_positions on its own primary key prefix (workspace_id, consumer). A workspace with no position row for the consumer is pending by the LEFT JOIN — a first run has acted on nothing.
The cost is one probe per workspace, which is a scan the engine runs once per poll rather than the per-workspace read transaction it replaces. It is still linear in workspaces; an adapter with a cheaper answer (a dirty set maintained on write) may substitute one, as long as it stays complete.
A non-empty entity or key is pending whatever the sequence says: that is a sub-position inside a same-sequence group, so the group has changes after it even when the sequence has reached the head. Only a clean boundary — the cursor a drained pass records — means caught up.
func (*Store) ListStaleIndexWorkspaceIDs ¶
func (s *Store) ListStaleIndexWorkspaceIDs(ctx context.Context, mark string, rng storage.Range, limit int) ([]string, error)
ListStaleIndexWorkspaceIDs scans the workspaces table and compares one column. There is no index for it — a btree cannot serve `<>` — and none is wanted: the scan is one row per workspace, which is what replaces the point read per (workspace × entity × index) the pass did to learn the same thing.
func (*Store) ListWorkspaceIDs ¶
func (*Store) PutCatalogEntry ¶
func (s *Store) PutCatalogEntry(ctx context.Context, id string, payload []byte, revision string) error
PutCatalogEntry upserts an entry into the server-global catalog. It runs on the writer connection.