Documentation
¶
Overview ¶
Package store opens the application's local SQLite database.
The database is opened with database/sql over the pure-Go modernc.org/sqlite driver, so it builds without CGO; no other package imports the driver. Every pooled connection runs in write-ahead-logging mode with foreign keys on and a busy timeout, and begins its transactions IMMEDIATE, so a transaction that reads and then writes waits for the write lock up front instead of failing part way. Open then brings the schema up to date with the checksummed migrations in the migrate package, backing up a migrated database before it changes it. The schema comes from those migrations alone.
The store owns no table. Each table's owner package queries it through code sqlc generates from the owner's SQL, on the pool Open returns or in a transaction from InTx; the store gives every owner DBTX, the JSON column codecs, and IsForeignKeyViolation.
Timestamps are written as UTC text in one sortable format, "2006-01-02 15:04:05.999999999+00:00", whatever a time.Time's location, so the database orders and compares them as text in time order. DATETIME columns read back as time.Time values in UTC.
Before the pool connects, Open reads the migration history over a connection that writes nothing, so a database it refuses or sets aside has not been changed by the attempt. It recovers from a database it cannot use, so the app starts whenever it safely can:
- A file that is not a database or is damaged, a schema the migrations did not create, or a migration history this build disagrees with is set aside: once Open has shown that no other connection has the file open, the file and its -wal and -shm files are renamed to <path>.broken-<UTC stamp>, a fresh database is created in its place, and Opened.Reset says what happened. When the fresh database cannot be created either, the files are put back and the error is returned.
- A database a newer build migrated is refused with ErrNewerSchema, whose message asks the user to update the app, and is left exactly as it is.
- Anything else, such as a database another process has open, a permission error, a full disk, or a migration that failed after its backup, is returned as an error, and the file is never moved.
A database the app could use may be set aside too, when the user asks to start over: OpenFresh renames it, with its -wal and -shm files, to <path>.reset-<UTC stamp> once no other connection has it open, waiting a few seconds for a copy of the app that is still quitting, and starts a fresh database in its place, which Opened.Reset says with ResetRequested. PruneResetCopies keeps the newest few of those.
Backup takes a backup of the open database whenever asked, as the app does before it installs an update, named and pruned as the migrations' own backups are, and RestoreBackup puts one of those backups back in the database's place, setting the database there aside as one Open could not use, so an older build can go back to the data from before a newer one migrated it.
Index ¶
- Constants
- Variables
- func Backup(ctx context.Context, db *sql.DB, path string) (string, error)
- func ConvertRows[R, T any](rows []R, convert func(R) (T, error)) ([]T, error)
- func DecodeJSON[T any](text string) (T, error)
- func Deref[T any](p *T) T
- func EncodeJSON(v any) (string, error)
- func InTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error
- func IsBusy(err error) bool
- func IsForeignKeyViolation(err error) bool
- func LatestSchema() (int, error)
- func PruneResetCopies(path string) error
- func RestoreBackup(ctx context.Context, path, backup string) (string, error)
- type DBTX
- type Opened
- type Reset
- type ResetReason
- type Row
- func (r Row) Bool(column string) *bool
- func (r Row) Has(column string) bool
- func (r Row) Int(column string) (int64, bool)
- func (r Row) StringLists(column string) map[string][]string
- func (r Row) StringMap(column string) map[string]string
- func (r Row) Strings(column string) []string
- func (r Row) Text(column string) string
- func (r Row) Time(column string) string
- type Snapshot
- type SnapshotFile
- type SnapshotKind
Constants ¶
const ( // KeepResetCopies is how many of the databases OpenFresh set aside PruneResetCopies // keeps: the newest. KeepResetCopies = 3 )
Variables ¶
var ( // ErrNoTable is returned when a snapshot has no table of the name asked for. ErrNoTable = errors.New("the database has no such table") // ErrNotIdentifier is returned for a table or column name that is not a plain SQL // identifier. ErrNotIdentifier = errors.New("not a plain SQL identifier") // ErrNotAFile is returned when a snapshot's path is not a regular file. ErrNotAFile = errors.New("not a file") )
var ( // ErrEmptyPath is returned when no database path is given. ErrEmptyPath = errors.New("database path is empty") // ErrInvalidPath is returned for a path the driver cannot open as a plain file name. ErrInvalidPath = errors.New("database path must not contain '?'") // ErrNewerSchema is returned when a newer build of the app has migrated the database. // Its message asks the user to update the app; the database is left as it is. ErrNewerSchema = migrate.ErrNewerSchema )
var ErrNoAsideName = errors.New("no free name to set the database aside under")
ErrNoAsideName is returned when every name a database could be set aside under is taken.
var ErrNotABackup = errors.New("not a backup of the database")
ErrNotABackup is returned by RestoreBackup for a file that isn't one of the database's own backups: not beside it, not named as one, not a regular file, or not a database.
Functions ¶
func Backup ¶ added in v0.3.1
Backup copies the open database db, whose file is path, to a backup beside it, named and pruned as the backups taken before migrations are: <path>.backup-<UTC stamp>-v<schema>, schema being the newest migration the database has, with the newest three of those kept, the migrations' and these together, so Snapshots lists it as a SnapshotBackup. It returns the backup's path. The copy is taken with VACUUM INTO, a whole database whatever is written meanwhile, readable only by the user.
func ConvertRows ¶ added in v0.2.0
ConvertRows converts each of an owner's query rows with convert, in order, into a list that is never nil, so a bound result holding it carries [] rather than null. It stops at the first row convert refuses and returns convert's error as it is, for the owner to word.
func DecodeJSON ¶ added in v0.2.0
DecodeJSON decodes the text of a JSON column into a T. On an error it returns T's zero value.
func Deref ¶ added in v0.2.0
func Deref[T any](p *T) T
Deref returns what p points to, or T's zero value when p is nil: what a nullable column, or one from a LEFT JOIN whose row is missing, reads as.
func EncodeJSON ¶ added in v0.2.0
EncodeJSON encodes v as the text of a JSON column. A nil slice is stored as [] and a nil map as {}, never as null, so a column that holds a list or an object always holds one.
func InTx ¶ added in v0.2.0
InTx runs fn in a transaction on db and commits it when fn returns nil. When fn returns an error, the transaction is rolled back and that error is returned as it is. When fn panics, the transaction is rolled back before the panic carries on, so the connection goes back to the pool without holding the write lock.
func IsBusy ¶ added in v0.2.0
IsBusy reports whether err is SQLite finding the database locked by another connection or process, such as another copy of the app, past the wait every connection allows.
func IsForeignKeyViolation ¶ added in v0.2.0
IsForeignKeyViolation reports whether err, from a statement, is SQLite refusing it because it would break a foreign key: deleting a row that another table's RESTRICT key still names, or naming a row that is not there. An owner maps it to its own error, such as a record still in use.
func LatestSchema ¶ added in v0.3.1
LatestSchema returns the newest migration this build has. A database whose own newest is newer was saved by a newer build, which Open refuses (ErrNewerSchema); a backup whose schema (SnapshotFile.Schema) is no newer opens here, brought up to date.
func PruneResetCopies ¶ added in v0.3.0
PruneResetCopies deletes the databases OpenFresh set aside beside the database at path, with their -wal and -shm files, but the newest KeepResetCopies, so a reset the user asks for again and again never fills the disk. The databases Open set aside, as ones it could not use, are never deleted: the user may still want what they hold. A file it cannot delete is named in the error, and the rest are still deleted.
func RestoreBackup ¶ added in v0.3.1
RestoreBackup puts backup, one of the backups beside the database at path (a SnapshotBackup, as Backup and the migrations take), in the database's place. The backup is first copied, not moved, into a temporary file beside the database, so the backup stays as it was and the slow part changes nothing; only then is the database there now, with its -wal and -shm files, set aside under the name Open gives one it can't use, <path>.broken-<UTC stamp>, and kept until the user removes it, and the copy renamed into its place. It returns where the database was set aside, or "" when there was none.
Nothing may have the database open: it waits a moment for another connection to let go, as a copy of the app that is quitting, and fails otherwise, moving nothing. When the rename fails, the database is put back. Whatever fails, the copy is removed. The next Open opens the restored database and brings it up to date with the migrations.
Types ¶
type DBTX ¶ added in v0.2.0
type DBTX interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
DBTX is what a query runs on: the pool, a transaction, or a single connection. It matches the interface sqlc generates, so generated queries accept any of the three.
type Opened ¶ added in v0.2.0
type Opened struct {
// DB is the database's connection pool. The caller closes it.
DB *sql.DB
// Reset is set when the database at the path was set aside for a fresh, empty one:
// Open could not use it, or OpenFresh set it aside as the user asked. It is nil
// otherwise.
Reset *Reset
}
Opened is an open, migrated database.
func Open ¶
Open opens (creating if needed) the database at path and applies pending migrations, backing up a migrated database first. A database it cannot use is set aside for a fresh one, which Opened.Reset reports; see the package documentation for which failures that covers. The caller closes Opened.DB.
func OpenFresh ¶ added in v0.3.0
OpenFresh starts over, as the user asked: it sets the database at path aside as <path>.reset-<UTC stamp>, with its -wal and -shm files, and opens a fresh, migrated one in its place, which Opened.Reset reports with ResetRequested and no error. It moves nothing while another connection has the database open, waiting about five seconds for one that is letting go, as a copy of the app that is quitting does, and then returns an error IsBusy tells apart; it puts the files back when the fresh database cannot be opened. With no database at path there is nothing to set aside, and it opens one as Open does. The caller closes Opened.DB.
type Reset ¶ added in v0.2.0
type Reset struct {
// Path is where the database is now. Its -wal and -shm files, when it had them, sit
// beside it under the same name with those suffixes, so SQLite still opens it whole.
Path string
// Reason says why it was set aside.
Reason ResetReason
// Err is the error opening or migrating it returned, or nil for a reset the user
// asked for.
Err error
}
Reset reports a database set aside: one Open could not use, or one OpenFresh set aside as the user asked. The database was renamed, with its -wal and -shm files, and a fresh one was created at the original path.
type ResetReason ¶ added in v0.2.0
type ResetReason string
ResetReason says why a database was set aside: Open could not use it, or the user asked for a fresh one (OpenFresh).
const ( // ResetCorrupt means the file is not an SQLite database, or it is damaged. ResetCorrupt ResetReason = "corrupt" // ResetUnmanaged means the database holds tables the app's migrations did not // create. ResetUnmanaged ResetReason = "unmanaged" // ResetHistory means the database's migration history disagrees with this build's: // a migration it records has changed since it ran, or one older than its newest // never ran. ResetHistory ResetReason = "history" // ResetRequested means the user asked to start over: the database could be used, and // OpenFresh set it aside for a fresh one. ResetRequested ResetReason = "requested" )
type Row ¶ added in v0.2.0
Row is one row a Snapshot read, by column name, each value as the driver read it: int64, float64, string, []byte, time.Time for a DATETIME column, or nil for NULL. A column the table lacks is missing, and each accessor gives it its empty value, so a caller reads a backup any build wrote the same way.
func (Row) Bool ¶ added in v0.2.0
Bool returns a boolean column, stored as 0 or 1, or nil for NULL, a missing column, or any other value.
func (Row) Has ¶ added in v0.2.0
Has reports whether the row holds column: whether the table it was read from has it.
func (Row) StringLists ¶ added in v0.2.0
StringLists returns a JSON object of string arrays, or an empty map when the column holds none.
func (Row) StringMap ¶ added in v0.2.0
StringMap returns a JSON object of strings, or an empty map when the column holds none.
func (Row) Strings ¶ added in v0.2.0
Strings returns a JSON array of strings, or an empty list when the column holds none.
type Snapshot ¶ added in v0.2.0
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is a read-only view of a database file the app keeps but no longer opens as its own: one Open set aside, a backup taken before migrations, or a copy the user kept. Any build may have written it, older or newer than this one, so Rows reads only the columns it is asked for that the file has.
Reading one changes nothing on disk. A file with no write-ahead log beside it is read in place, immutable; one with a log is copied, with its log, to a scratch directory that Close removes, so SQLite never writes beside the original.
func OpenSnapshot ¶ added in v0.2.0
OpenSnapshot opens the database file at path for reading. It returns an error for a path that is not a regular file, or a file that is not a database or is damaged. The caller closes the snapshot.
func (*Snapshot) Close ¶ added in v0.2.0
Close closes the snapshot and removes its scratch copy, if it has one.
func (*Snapshot) DB ¶ added in v0.2.0
DB returns the snapshot's read-only connection pool, for an owner whose own queries read a table every build has kept the same, such as the prefs table.
type SnapshotFile ¶ added in v0.2.0
type SnapshotFile struct {
// Path is the file.
Path string
// Kind says how it came to be.
Kind SnapshotKind
// At is when it was set aside or backed up, read from its name, in UTC.
At time.Time
// Schema is the newest migration a backup holds, read from its name's -v<schema>, or 0
// for a file that names none: one set aside, or a backup of a database no migration
// had touched.
Schema int
}
SnapshotFile is a database file kept beside the app's own.
func Snapshots ¶ added in v0.2.0
func Snapshots(path string) ([]SnapshotFile, error)
Snapshots lists the databases kept beside the database at path, the newest first: the ones Open set aside, which are kept until the user removes them, the ones OpenFresh set aside as the user asked, and the backups taken before migrations, of which the newest few of each are kept. A missing directory holds none.
type SnapshotKind ¶ added in v0.2.0
type SnapshotKind string
SnapshotKind says how a database kept beside the app's own came to be.
const ( // SnapshotSetAside is a database Open could not use and set aside. SnapshotSetAside SnapshotKind = "set-aside" // SnapshotBackup is a copy taken before migrations changed the database. SnapshotBackup SnapshotKind = "backup" // SnapshotReset is a database OpenFresh set aside when the user asked to start over. SnapshotReset SnapshotKind = "before-reset" )