Documentation
¶
Overview ¶
Package sqlitekit holds the SQLite settings and routines that every application using a SQLite file should share: a connection string that turns on the settings SQLite has off (DSN), a startup check that the driver really applied them (Check), and dated online backups with retention (Backups).
MigrationLock serialises schema migration across processes that open the same database.
The package uses only the standard library and imports no driver. It builds connection strings in the syntax of modernc.org/sqlite (driver name "sqlite"); the application imports the driver itself.
The subpackage goosestrict adapts github.com/pressly/goose/v3 to SQLite STRICT tables and is the only part of the module that depends on goose.
Index ¶
- Constants
- func Check(ctx context.Context, db *sql.DB, o Options) error
- func DSN(path string, o Options) (string, error)
- func MigrationLock(ctx context.Context, dbPath string) (release func() error, err error)
- type BackupFile
- type BackupLoop
- type BackupResult
- type BackupSchedule
- type Backups
- type Options
Constants ¶
const DefaultBusyTimeout = 5 * time.Second
DefaultBusyTimeout is the busy timeout used when Options.BusyTimeout is 0.
const MigrationLockSuffix = ".migrate-lock"
MigrationLockSuffix is appended to the database path to name the lock file.
Variables ¶
This section is empty.
Functions ¶
func Check ¶
Check verifies, on one connection from db, that the settings DSN asks for are in effect, and returns an error naming each one that is not. Call it right after opening the database: a driver that ignores a parameter would otherwise run for months with foreign keys off or without WAL, and nothing would say so.
Each setting is per connection and DSN applies it to every connection, so one connection stands for the pool. secure_delete is checked only when o.SecureDelete is set; left unset, it is not required to be off.
Check cannot see _txlock: it is a driver option, not a SQLite setting, and no query reveals it. The package's tests prove it instead, by showing that a second connection cannot write while a transaction opened through database/sql is in progress.
func DSN ¶
DSN returns the data source name for the SQLite file at path, in the syntax of modernc.org/sqlite:
db, err := sql.Open("sqlite", dsn)
The path is made absolute and escaped as a file: URL, so a space, "?" or "#" in it is part of the file name and never becomes driver configuration. The settings are passed as _pragma parameters, which the driver runs on every connection it opens, so each connection in the pool has them:
foreign_keys(1) SQLite enforces no foreign key without it busy_timeout(ms) wait for a lock instead of failing at once journal_mode(WAL) readers do not block the writer secure_delete(1) only when Options.SecureDelete is set
plus _txlock=immediate, so a transaction takes the write lock at BEGIN, where the busy timeout applies, instead of failing when it first writes. path is a file path: ":memory:" and file: URLs are not supported.
func MigrationLock ¶
MigrationLock takes an exclusive lock that serialises schema migration across every process that opens the database at dbPath, and returns the function that releases it. It waits until the lock is free or ctx is done; in the second case it returns ctx.Err(), wrapped.
Why it exists. Goose works out which migrations are pending before it takes SQLite's write lock, and does not read the recorded version again inside the transaction. Two processes opening one database at once (two replicas started together, or a restart that overlaps its predecessor) can therefore both decide that migration 2 is pending and both apply it. The second fails, for instance with "duplicate column name", or worse, succeeds twice. Holding this lock across the whole migration step makes the second process wait, and then find nothing pending.
Take it before the first query on the database, Check included. The busy timeout does not cover the very first open of a fresh database: while the file is being created and switched to WAL, concurrent first queries can fail at once with SQLITE_BUSY. sql.Open itself does not connect, so it may come before or after the lock; the first query must come after.
Hold it across everything that must not overlap with another process's migration: goosestrict.Adopt, building the goose provider (which creates the version table on a fresh database) and its Up, and any application-specific check or data fix that follows a migration. Release it before serving.
release, err := sqlitekit.MigrationLock(ctx, path)
if err != nil { return err }
defer release()
db, err := sql.Open("sqlite", dsn) // does not connect
// ... sqlitekit.Check, Adopt if needed, goosestrict.NewProvider,
// p.Up(ctx), post-checks ...
The lock is an flock(2) exclusive lock on the file dbPath + ".migrate-lock", created with mode 0600 next to the database if missing and never deleted: removing a lock file that another process may hold or be about to open is a race. The kernel drops the lock if the process dies, so a crash cannot keep it held. release is idempotent; the first call returns the error from unlocking, later calls return nil.
Scope. It works between processes, including containers, that share the same directory on one host. It does not work across hosts or on network filesystems, where flock is unreliable and SQLite itself is unsafe anyway. dbPath must be the path every process opens; use an absolute path, since a relative one is made absolute against the current directory. The lock file is found by name: a symlink to the database file is a different lock file, while a symlinked directory is fine. The lock file is created by whichever user opens it first, like the database file itself, so run every process as the same user.
It is supported on Linux, macOS and the BSDs. Elsewhere it returns an error.
Types ¶
type BackupFile ¶
BackupFile describes one backup in Backups.Dir.
type BackupLoop ¶
type BackupLoop struct {
// contains filtered or unexported fields
}
BackupLoop is a running schedule. Its zero value represents a stopped loop.
func (*BackupLoop) Done ¶
func (l *BackupLoop) Done() <-chan struct{}
Done is closed once the loop has returned (Stop, or ctx done). A nil or zero loop returns a closed channel.
func (*BackupLoop) Stop ¶
func (l *BackupLoop) Stop()
Stop ends the loop and waits until its goroutine has returned, including a run or Report in progress (the run's context is canceled). Call it before closing db. Safe to call more than once, concurrently, and on a nil or zero loop.
type BackupResult ¶
type BackupResult struct {
Path string // today's backup; empty when Err is set
Made bool // this run wrote it
Err error
Next time.Duration // wait before the next run (Interval or Retry)
}
BackupResult is the outcome of one scheduled run.
type BackupSchedule ¶
type BackupSchedule struct {
// Interval is the wait after a run that succeeded. Zero means one hour.
// Run makes at most one backup per day, so an hourly check costs a stat
// and a prune.
Interval time.Duration
// Retry is the wait after a run that failed. Zero means 15 minutes or
// Interval, whichever is shorter. It must not exceed Interval or one
// hour, so a failure is always retried within the hour.
Retry time.Duration
// Timeout bounds one run, including the wait for LockPath. Zero means
// 5 minutes. A run that fails at the deadline reports an error wrapping
// [context.DeadlineExceeded].
Timeout time.Duration
// LockPath, if set, names the flock file taken around each run. Sharing
// it lets overlapping processes take turns instead of racing on the
// same temporary backup. Use a separate file outside the backup folder,
// never the database file or its -wal or -shm files.
// It is created with mode 0600 if missing and never deleted. It must not
// end in [MigrationLockSuffix], so backups do not hold up migrations.
// It has the same platform and filesystem requirements as [MigrationLock].
// Start rejects a non-empty LockPath on platforms without flock.
LockPath string
// Now picks the day. Nil means [time.Now].
Now func() time.Time
// Report receives the outcome of every run that was not cut short by the
// loop stopping. Nil reports nothing. It runs on the loop's goroutine,
// after the lock is released, and Stop waits for it. It must not call
// Stop or wait on Done: the loop cannot return until Report returns.
Report func(BackupResult)
}
BackupSchedule says when Backups.Start runs Backups.Run.
type Backups ¶
type Backups struct {
// Dir holds the backups. It must be a folder the process owns and that
// holds only this application's backups: it is created if missing and set
// to mode 0700 on every [Backups.Run], and Run fails if it cannot do that.
Dir string
// Prefix starts every backup's name, e.g. "notes-". It must not contain a
// path separator.
Prefix string
// Layout is the [time] layout of the date in the name, e.g. "2006-01-02"
// or "20060102". It must identify a day. A file is a backup only if the
// text between Prefix and ".db" parses as a date in this layout.
Layout string
// Keep is how many of the newest backups to keep. Values below 1 are
// treated as 1: a backup that has just been made is never pruned.
Keep int
// Location decides which calendar day "today" is. Nil means UTC.
Location *time.Location
}
Backups takes one dated copy of a database per day into Dir and keeps the newest few. A copy is a complete, ordinary database file made with VACUUM INTO.
Run must not be called concurrently for the same Dir and Prefix; use a single caller. A concurrent call can fail, and the backup under today's name stays good.
Backups are for mistakes and corruption. They sit next to the database, so they do not survive the loss of the disk; copy them elsewhere for that.
func (Backups) List ¶
func (b Backups) List() ([]BackupFile, error)
List returns the backups in Dir, newest first. A missing directory means no backups. Only files named Prefix + <a date in Layout> + ".db" are listed.
func (Backups) Run ¶
func (b Backups) Run(ctx context.Context, db *sql.DB, now time.Time) (path string, made bool, err error)
Run writes today's backup, unless it already exists, then prunes. now picks the day (in Location). It returns the path of today's backup and whether this call made it.
The copy is written under a hidden temporary name, created with mode 0600 before SQLite writes to it, and renamed into place, so a crash never produces a half-written file under a name that looks like the day's backup. Temporary files left by earlier crashes are removed. Dir is set to mode 0700. A symlink or other non-regular file with today's name is an error.
VACUUM INTO reads inside one transaction, so the copy is the database at one instant even while other connections write; copying the file with cp is not safe for a WAL database, which keeps recent commits in a separate -wal file.
func (Backups) Start ¶
func (b Backups) Start(ctx context.Context, db *sql.DB, s BackupSchedule) (*BackupLoop, error)
Start checks b and s, then runs b.Run at once and on schedule in one goroutine until ctx is done or Stop is called. The single goroutine is the one caller Run requires. An invalid Backups or schedule is returned as an error and nothing is started.
type Options ¶
type Options struct {
// BusyTimeout is how long a connection waits for a lock held by another
// connection before failing with SQLITE_BUSY. Zero means
// [DefaultBusyTimeout]. Negative, below one millisecond or above
// 2^31-1 milliseconds (SQLite's limit) is an error.
BusyTimeout time.Duration
// SecureDelete overwrites deleted content with zeros, so deleted rows do
// not linger in free pages of the file or of a backup. It costs some write
// speed; turn it on only where deleted data must not survive.
SecureDelete bool
}
Options are the choices left to the application. Foreign keys, WAL and immediate transactions are always on: each one guards against a failure that is silent when it is missing, so none of them is an option.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package goosestrict runs github.com/pressly/goose/v3 migrations against SQLite databases whose tables are all STRICT, version table included, and refuses to guess when a database does not match its migrations.
|
Package goosestrict runs github.com/pressly/goose/v3 migrations against SQLite databases whose tables are all STRICT, version table included, and refuses to guess when a database does not match its migrations. |