dialect

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package dialect is the SQL layer that every SQL store is built on: the Dialect that describes what differs between engines, the unit of work that a context carries over one *sql.DB, the migrator of the modules' migration streams, Store, the handle whose helpers run statements, encode columns, page lists and seal secret columns, and the registration through which the migrator and key rotation reach every module's stream and sealed columns.

Role

platform layer: the SQL dialect, unit of work, migrator, sealing helpers and reseal engine that every module SQL adapter uses. One unit of work spans every module store (decision 0044, "Persistence"), so the platform owns it, with the dialect layer and the migrator. The SQLite and PostgreSQL drivers, platform/sql/sqlite and platform/sql/postgres, each declare a Dialect; the module SQL adapters are built over one Store, call its helpers, and register in a Module each their migration stream, the columns they seal and their hooks. The reseal engine sits beside the keyring because re-sealing opens and seals values, and the keyring never leaves the package. The package imports only the kernel, for its sentinels and paging, and platform/crypt, for the keyring.

Inputs

  • An open *sql.DB and the engine's Dialect: its placeholder style, its row-lock suffix, its query for a table's columns and its test for a unique violation.
  • A *crypt.Keyring for the sealed columns, or nil.
  • Each module's registration, in the canonical module order: its migration stream, the sealed columns its store writes, a hook to run before them and a hook to run after migrating.
  • Statements written with "?" placeholders, which Rebind converts to $1 style for PostgreSQL.
  • Migration files named NNNN_name.sql, with "-- +up" and "-- +down" sections, in a directory per dialect named like the dialect.

Outputs

  • Store and New. The unit of work: Tx, AfterCommit and InTx. Statements: Q, Exec, ExecOne, InsertID, Exists, Rows, Wrap and LockClause. Wrap marks a driver error that is no verdict and no ended context as kernel.ErrStore, the store's own failure, and keeps its text (https://github.com/weaveplatform/artifactweave/issues/1470). Sealed columns: Seal and Unseal. And DB, Dialect and Close.
  • Module registration and key rotation: SealedColumn, FirstKey, Module and Reseal, which re-seals the columns the modules register under the keyring's active version.
  • Statement text: Upsert, InsertIgnore, Insert and Placeholders. Column values: Micros, FromMicros, Millis, FromMillis, ToJSON, MustJSON, FromJSON, RawJSON, FromRaw, NullString and EntBytes. Keyset paging: Keyset, OrderBy, Itoa and LimitOr. Scanning: EntRow, PeersScanner and OpsCols.
  • The migrator: Migration, LoadMigrations, Migrate, Rollback, Version, Applied, StreamVersion and MustSub. Migrate, Rollback and Version take the module list, and Migrate and Rollback can work on one stream.
  • ErrTransaction, ErrMigration, ErrNoKeyring, and the migrator's refusals ErrLegacyHistory, ErrUnknownModule and ErrModuleRequired, which wrap ErrMigration.

Invariants

  • The unit of work is keyed to one *sql.DB. A context carries at most one transaction, and only stores over its pool join it, so every module store is built over the same Store: a store over another pool writes outside the transaction and does not roll back with it.
  • A nested Tx joins the outer transaction, and an error its function returns fails the outer transaction even when the outer function drops it. platform/tx/memtx commits in that case, as tx.Runner records, so callers return inner errors.
  • AfterCommit runs its functions in order once the transaction has committed, never after a rollback or a failed commit, and at once outside a transaction.
  • The keyring never leaves the package: stores seal and open values only through Seal and Unseal, which bind each value to its column's purpose and its row (decision 0017), and Reseal re-seals them under the same binding, which it takes from the column's registration.
  • Every sealed column belongs to exactly one module registration. Reseal reaches only registered columns, so the values of a column left out stay under a retired key and no longer open once that key leaves the configuration. Reseal takes the modules in the canonical module order (decision 0044, "Persistence"), and each module's hook before its columns. TestAccSealedColumnsComplete matches every Seal call in the repository against the registrations, and fails on a purpose registered twice.
  • A store that embeds *Store gets its methods promoted, and a method the store declares under the same name hides the promoted one without a compile error. So Store exports no method named like an accessor of a composite store (Keys, Items, Repos, ...) other than Tx, AfterCommit and Close, or like a method an embedding store declares, such as Reseal, which is why the layer's Reseal is a function. TestUnitDialectStoreShadowsNoAccessor checks it.
  • Every SQL adapter keeps the schema conventions of research 15, section 4. Times are BIGINT Unix microseconds, NULL for a zero time (Micros), and durations BIGINT milliseconds (Millis): integers compare and sort alike on every engine, which keeps keyset paging exact. Documents are TEXT (ToJSON), so they round-trip byte for byte, and empty values are NULL (NullString, RawJSON, EntBytes). A sealed value has a BLOB (BYTEA) column of its own, never a place inside a document (Seal). Text columns that lists sort by are byte-ordered (COLLATE "C" on PostgreSQL), and a cursor binds the parts of integer columns as integers (Keyset), so a cursor means the same position on every store, the in-memory ones included.
  • Each module's migrations are recorded in schema_migrations under the module's name, keyed by (module, version), and every stream numbers its versions from 1 on its own. Migrate applies the streams in the order of the module list, the canonical module order (decision 0044, "Persistence"), and Rollback reverts them in the reverse order, so a table is created before any later stream's and dropped after it.
  • A schema_migrations table without a module column predates the streams. Migrate, Rollback and Version refuse it with ErrLegacyHistory before writing anything, through the dialect's Columns query: there is no upgrade path, and such a database is recreated.
  • The SQL text the helpers render is observed by the engines, and error and panic texts reach operators and logs, the "sqlcommon:" prefix of the sentinels and panics included. They stay byte-identical, except the migrator's step errors, which name the module because every stream has a 1_baseline.

References

  • Decision 0004: docs/research/decisions/0004-storage-sql-metadata-and-blobs.md ("Metadata": SQL stores over SQLite and PostgreSQL through one dialect layer, with embedded migrations per dialect).
  • Decision 0017: docs/research/decisions/0017-sealed-columns-and-master-key.md (sealed columns, with the purpose and the row identity as additional authenticated data).
  • Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md ("Persistence": per-module migration streams in the canonical module order, refused legacy histories, one unit of work for every module store, one *sql.DB with platform/sql/dialect; "Names the migration introduces").
  • Research 15: docs/research/15-data-model.md, section 4 (the derived storage model and its column conventions).
  • Target layout: docs/research/architecture-options/5-modular-monolith.md, lines 130 and 131 (platform/sql/dialect), line 483 and line 583 (its files), line 579 (the platform owns the dialect layer, the unit of work and the migrator), lines 624 to 633 (one migration stream per module, recorded by module), line 917 (Tx opens the unit of work through it), line 1042 (the mapping row) and lines 1091 to 1094 (the unit of work is platform-level and context-carried).
  • Plan: docs/implementation/plan.md#p2-stores, task 2, and #p9d-modular-monolith-migration, epic STO (https://github.com/weaveplatform/artifactweave/issues/939).
  • https://github.com/weaveplatform/artifactweave/issues/992
  • https://github.com/weaveplatform/artifactweave/issues/993
  • https://github.com/weaveplatform/artifactweave/issues/994

Status

Implemented P2: the dialects, the unit of work, the migrator, the store handle and its helpers, sealed columns included (pull request 3). In the v0.1.0 release InsertIgnore gained the form without a conflict target, for the property tables, whose unique indexes differ between the dialects (issue 338, pull request 339). Moved here in P9d: the scanner helpers were gathered into one file (issue 959, pull request 1122), and the layer leaves the SQL stores' shared package for this one, exported for the module SQL adapters (issue 992). The reseal engine joins the keyring here, and each module registers its sealed columns (issue 993). Each module registers its own migration stream, which replaces the global history, and the migrator records the streams by module and refuses an older history (issue 994).

Testing

  • The metadata store's contract suite on SQLite and PostgreSQL (TestAccContractFile, TestAccContractMemory and TestAccContract), the SQL stores' fault tests, TestAccKeyRotation and TestAccMigrationsUpDownUp run every helper through the SQL stores. TestAccSchemaGolden, TestAccLegacyHistoryRefused and TestAccStreamsMigrateAlone run the migrator over the modules' streams on the real engines.
  • TestUnitWrapMarksTheStoresOwnFailures: a statement the database fails to run is kernel.ErrStore with its text kept; a verdict and an ended context are not.
  • TestAccTxDroppedInnerErrorFailsOuter covers the nested case that the contract suite leaves out, and TestAccTxJoinsTheTransactionOfItsPool the pool the unit of work is keyed to.
  • TestAccMigratorStopsAtAFailingStep, TestAccMigratorRecordsEachStepInItsTransaction, TestAccMigratorReportsAnUnreadableVersionTable, TestAccMigratorFollowsTheModuleOrder, TestAccMigratorMovesOneStream, TestAccMigratorLeavesOtherModulesAlone and TestAccMigratorRefusesALegacyHistory run the migrator over streams in memory on SQLite, through modernc.org/sqlite, which the test package registers.
  • TestUnitLoadMigrationsReadsSections and TestUnitLoadMigrationsRejectsMalformedFiles parse migrations from file systems in memory, TestUnitMustSubPanicsOnInvalidDirectory checks MustSub's refusal, TestUnitMigratorChecksItsArguments the refusals that come before the database is touched, and TestUnitAppliedString the form the migrate command prints.
  • TestUnitTxReportsCommitFailure, TestUnitMigratorReportsDriverFaults, TestUnitMigratorReportsUnreadableMigrations and TestUnitStoreReportsDriverFaults use a database/sql driver whose named steps fail, for the failures SQLite cannot produce on demand.
  • TestUnitResealNeedsAKeyring, TestAccResealFollowsTheModuleOrder, TestAccResealStopsAtTheFirstError, TestUnitResealReportsAnUnscannableRow, TestAccResealKeepsAValueChangedSinceItsRead and TestAccResealReadsByteKeysAsText run Reseal over tables of their own, for the order, the failures and the concurrent write that TestAccKeyRotation leaves out.
  • TestUnitSealReportsTheKeyringsRefusal, TestUnitUpsertOfKeyColumnsOnlyDoesNothing and TestAccMustJSONPanicsOnUnencodable cover the rest, and a test file checks at compile time that *Store implements tx.Runner.

Index

Constants

This section is empty.

Variables

View Source
var ErrLegacyHistory = fmt.Errorf(
	"%w: database history predates per-module migrations; not upgraded", ErrMigration)

ErrLegacyHistory reports a database whose schema_migrations table has no module column: its history predates the per-module streams, so its versions cannot be matched to them. The migrator refuses it before writing anything, and there is no upgrade path (decision 0044, "Persistence"): such a database is recreated. It wraps ErrMigration.

View Source
var ErrMigration = errors.New("sqlcommon: migration")

ErrMigration reports a malformed or failing migration.

View Source
var ErrModuleRequired = fmt.Errorf("%w: a target version other than 0 needs a module", ErrMigration)

ErrModuleRequired reports a rollback to a version other than 0 with no module: each stream numbers its versions on its own, so a version names a point in one stream only. It wraps ErrMigration.

View Source
var ErrNoKeyring = errors.New("sqlcommon: value is sealed but no keyring is configured")

ErrNoKeyring reports a sealed value read by a store opened without a keyring: the server was started without the master key that sealed it.

View Source
var ErrTransaction = errors.New("sqlcommon: transaction failed")

ErrTransaction reports a transaction that could not begin or commit.

View Source
var ErrUnknownModule = fmt.Errorf("%w: unknown module", ErrMigration)

ErrUnknownModule reports a module name that none of the modules passed to the migrator has. The error names it. It wraps ErrMigration.

Functions

func EntBytes

func EntBytes(b []byte) any

EntBytes stores an empty byte slice as NULL.

func FirstKey

func FirstKey(k []string) string

FirstKey is the RowID of a column whose row id is the value of its first key column, such as a table keyed by name alone.

func FromJSON

func FromJSON(doc sql.NullString, into any) error

FromJSON decodes a document column; NULL leaves into untouched.

func FromMicros

func FromMicros(v sql.NullInt64) time.Time

FromMicros reads a time column Micros wrote, in UTC; NULL reads as the zero time.

func FromMillis

func FromMillis(ms int64) time.Duration

FromMillis reads a duration column Millis wrote.

func FromRaw

func FromRaw(doc sql.NullString) []byte

FromRaw reads an opaque document column RawJSON wrote; NULL reads as nil.

func Insert

func Insert(table string, cols []string) string

Insert renders an INSERT with one placeholder per column.

func InsertIgnore

func InsertIgnore(table string, cols, key []string) string

InsertIgnore renders INSERT ... ON CONFLICT (key) DO NOTHING, or ON CONFLICT DO NOTHING for any unique index when key is empty: a target must name a unique index's exact columns, and the property tables' differ between dialects (the PostgreSQL artifacts baseline keys a digest of the value, SQLite the whole value).

func Itoa

func Itoa(n int64) string

Itoa formats an integer cursor part.

func Keyset

func Keyset(p kernel.Page, cols []string, ints map[string]bool, desc bool) (string, []any, error)

Keyset is the condition that continues a list after the cursor in p, for a sort over cols (ascending, or descending when desc). Columns sorted as integers must be listed in ints so their cursor parts bind as integers. It returns "1 = 1" for the first page, and an error that wraps kernel.ErrInvalidCursor for a cursor that does not fit cols and ints.

func LimitOr

func LimitOr(limit int) int

LimitOr applies the default limit for "at most limit" queries: kernel.DefaultLimit for zero or less, and never more than kernel.MaxLimit.

func Micros

func Micros(t time.Time) any

Micros is a time column value: Unix microseconds, NULL for a zero time.

func Millis

func Millis(d time.Duration) int64

Millis is a duration column value in milliseconds.

func MustJSON

func MustJSON(v any) any

MustJSON is ToJSON for documents built from the domain types, which are structs, slices and string-keyed maps of plain values that encoding/json cannot fail to encode. An error therefore means a field of an unsupported kind was added to a type, a programming mistake that must fail loudly: storing NULL instead would lose the document without a trace.

func MustSub

func MustSub(fsys fs.FS, dir string) fs.FS

MustSub returns the sub-tree dir of fsys. The migrator reads a module's stream for a dialect through it, from the directory named like the dialect, and a dialect's name is fixed when its driver is built, so a name that is not a valid path is a programming error rather than a run-time one. It panics when fs.Sub refuses dir, as it does a path that is not valid; a directory that does not exist surfaces as the error LoadMigrations returns.

func NullString

func NullString(v string) any

NullString stores "" as NULL, for optional foreign keys and unique columns where an empty value must not collide.

func OpsCols

func OpsCols(list string) []string

OpsCols splits a column list written as "a, b, c".

func OrderBy

func OrderBy(cols []string, desc bool) string

OrderBy renders ORDER BY cols in one direction.

func Placeholders

func Placeholders(n int) string

Placeholders returns "?, ?, ?" for n values.

func RawJSON

func RawJSON(b []byte) any

RawJSON stores an opaque JSON (or other) document given as bytes; empty stores as NULL.

func Reseal

func Reseal(ctx context.Context, s *Store, mods []Module) (int, error)

Reseal re-seals the sealed columns of mods under the keyring's active version and returns how many values changed. It takes the modules in order and, for each, runs BeforeReseal, when it is set, and then its columns in order. Values already under the active version are left alone, and values stored before a keyring was configured are sealed for the first time, so running it again is harmless. Each value is replaced only if it still holds the bytes that were read, so a concurrent write is never overwritten with a stale secret. Without a keyring it returns ErrNoKeyring and runs nothing. Otherwise it stops at the first error, from a hook, a statement or a value the keyring cannot open, and returns it with the number of values changed before it. Reseal opens no transaction of its own: its statements run in the one ctx carries, if any. It is a function, not a method of Store, because a store that embeds *Store and declares a Reseal method would hide one of that name without a compile error.

func ToJSON

func ToJSON(v any) (any, error)

ToJSON encodes a document column; nil and empty values store as NULL.

func Upsert

func Upsert(table string, cols, key []string) string

Upsert renders INSERT ... ON CONFLICT (key) DO UPDATE SET col = excluded.col for every non-key column; SQLite and PostgreSQL share the syntax. When every column is a key column it renders DO NOTHING instead, because neither engine accepts a SET with nothing to set.

Types

type Applied

type Applied struct {
	Module  string
	Version int
}

Applied names one migration of one stream: the Module whose stream holds it and its Version.

func Migrate

func Migrate(
	ctx context.Context,
	db *sql.DB,
	d Dialect,
	mods []Module,
	only string,
) ([]Applied, error)

Migrate applies every pending migration of each module's stream, the streams in the order of mods and each stream by version, and returns the migrations applied. When only is set it applies that module's stream alone, and a name that no module has fails with ErrUnknownModule. Each migration runs in its own transaction with the row that records it. On a failure it returns the migrations applied before it and an error that wraps ErrMigration and names the module, the migration and the first line of a failing statement.

Like Rollback and Version, it first loads every stream and then reads the history table's columns: a table with no module column fails with ErrLegacyHistory, and nothing has been written to the database. Only then does it create the history table when it is absent.

func Rollback

func Rollback(
	ctx context.Context,
	db *sql.DB,
	d Dialect,
	mods []Module,
	module string,
	target int,
) ([]Applied, error)

Rollback reverts the applied migrations of module's stream that are newer than target, newest first, and returns the migrations reverted. With no module it reverts every stream, the streams in the reverse order of mods, and accepts only target 0: any other target fails with ErrModuleRequired. A module that none of mods has fails with ErrUnknownModule. Each migration is reverted in its own transaction with the removal of its row. On a failure it returns the migrations reverted before it and an error that wraps ErrMigration. It refuses a legacy history as Migrate does.

func (Applied) String

func (a Applied) String() string

String returns the module and the version as "module:version", the form the migrate command prints, such as "platform:1".

type Dialect

type Dialect struct {
	// Name is used in errors.
	Name string
	// Dollar selects $1-style placeholders (PostgreSQL); otherwise "?".
	Dollar bool
	// ForUpdate is appended to row-locking SELECTs inside transactions, or
	// empty when the engine serialises writers (SQLite).
	ForUpdate string
	// Columns is a query that lists the column names of the table its one
	// "?" parameter names, in the current schema only, so the migrator can
	// tell a history table that predates the per-module streams from a
	// missing one without writing anything (ErrLegacyHistory). Rebind
	// converts its placeholder.
	Columns string
	// IsUniqueViolation reports whether err is the engine's unique or
	// primary-key constraint error, so the store returns kernel.ErrConflict
	// instead of a driver error when two writers race for one key.
	IsUniqueViolation func(error) bool
}

Dialect describes what differs between SQL engines. Each driver declares one value and passes it to New and to the migrator.

func (Dialect) Rebind

func (d Dialect) Rebind(query string) string

Rebind converts "?" placeholders to the dialect's form. A "?" inside a single-quoted literal is left alone.

type EntRow

type EntRow interface{ Scan(dest ...any) error }

EntRow is a *sql.Row or *sql.Rows, so that one scan function reads a row of either.

type Migration

type Migration struct {
	Version int
	Name    string
	Up      []string
	Down    []string
}

Migration is one parsed migration file: the version and name its file name gives, and the statements of its up and down sections.

func LoadMigrations

func LoadMigrations(fsys fs.FS) ([]Migration, error)

LoadMigrations parses every NNNN_name.sql file at the top of fsys, sorted by version. A statement ends with a semicolon at the end of a line, the last one of a section may leave it out, and comment and blank lines are dropped. It fails with ErrMigration for a directory or file it cannot read, a malformed file name, a version below 1, a version defined twice and a file with no up statements.

type Module

type Module struct {
	Name         string
	Migrations   fs.FS
	Sealed       []SealedColumn
	BeforeReseal func(ctx context.Context, s *Store) (int, error)
	AfterMigrate func(ctx context.Context, s *Store) error
}

Module is one module's registration with the SQL layer. Name is one of the canonical module names, and keys the module's rows in the migration history. Migrations is the module's migration stream: a directory per dialect, named like the dialect ("sqlite", "postgres"), of NNNN_name.sql files, or nil for a module with no tables. Sealed lists the sealed columns its store writes. BeforeReseal, when it is set, runs before the module's columns in Reseal, for work such as a backfill that seals values first; the count it returns is added to Reseal's. AfterMigrate, when it is set, runs after Migrate each time the store opens with migrations, for work DDL cannot do: a conversion that seals values with the configured keyring, because DDL never sees key material (decision 0017), or one that needs Go rather than the engine to fold text (decision 0043). The module SQL adapters register each module once, in the canonical module order (decision 0044, "Persistence"): platform, artifacts, access, notifications, retention, federation, releases, workers. Migrate, Rollback, Version and Reseal take the modules in that order.

type PeersScanner

type PeersScanner interface{ Scan(dest ...any) error }

PeersScanner is a *sql.Row or *sql.Rows, as EntRow is; the peer and outbox stores scan with it.

type Queryer

type Queryer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Queryer is what Store.Q returns: the pool, or the transaction a context carries on it. *sql.DB and *sql.Tx implement it.

type SealedColumn

type SealedColumn struct {
	Table, Column, Purpose string
	Keys                   []string
	RowID                  func(key []string) string
}

SealedColumn is one column that holds sealed values (decision 0017): the Table and Column, the Purpose its values are sealed under, the Keys columns that identify a row, and RowID, which builds a row's id from the values of those columns, read as strings. Purpose and RowID must give exactly what the module's store passes to Seal for the same row, because both are authenticated with the value: Reseal fails on a sealed value that does not open under them, and would seal a plain value under a binding the store cannot open. A module registers every column it seals, because Reseal reaches only registered columns: `artifactweave keys rotate` would leave the values of a missing one under the old key, and once that key is removed from the configuration they no longer open.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the handle every SQL store is built over: one pool, its dialect and the keyring that seals secret columns. It runs the unit of work and the helpers the SQL adapters share. The transaction a context carries belongs to the pool, so every store built over one Store shares it. A Store is safe for concurrent use.

func New

func New(db *sql.DB, d Dialect, keys *crypt.Keyring) *Store

New wraps an open, migrated pool for one dialect. keys seals secret columns; with nil, Seal stores values as given and Unseal refuses a sealed one with ErrNoKeyring.

func (*Store) AfterCommit

func (*Store) AfterCommit(ctx context.Context, fn func())

AfterCommit queues fn until the transaction ctx carries commits, and runs it at once outside a transaction. Queued functions run in order after the commit, and never after a rollback or a failed commit.

func (*Store) Close

func (s *Store) Close() error

Close closes the pool, and with it every store built over it; an error names the dialect.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the pool, for tests and the migrate command.

func (*Store) Dialect

func (s *Store) Dialect() Dialect

Dialect returns the store's dialect.

func (*Store) Exec

func (s *Store) Exec(ctx context.Context, op, q string, args ...any) (int64, error)

Exec runs a statement written with "?" placeholders, in the transaction ctx carries if any, and returns the number of rows it changed. Errors come through Wrap.

func (*Store) ExecOne

func (s *Store) ExecOne(ctx context.Context, op, q string, args ...any) error

ExecOne runs a statement, as Exec does, that is meant to change one row, and returns kernel.ErrNotFound, prefixed with op, when it changed none.

func (*Store) Exists

func (s *Store) Exists(ctx context.Context, op, q string, args ...any) (bool, error)

Exists reports whether q (a SELECT 1 ...) returns a row. Errors other than no row come through Wrap.

func (*Store) InTx

func (s *Store) InTx(ctx context.Context) bool

InTx reports whether ctx carries a transaction on the store's pool, which a statement through Q joins.

func (*Store) InsertID

func (s *Store) InsertID(ctx context.Context, op, q string, args ...any) (int64, error)

InsertID runs an INSERT written with "?" placeholders, adding RETURNING id, and returns the new row's id. Errors come through Wrap.

func (*Store) LockClause

func (s *Store) LockClause(ctx context.Context) string

LockClause returns the row-lock suffix for a SELECT inside a transaction, or "" outside one and on engines that serialise writers.

func (*Store) Q

func (s *Store) Q(ctx context.Context) Queryer

Q returns the transaction ctx carries on the store's pool, or the pool, so that a statement joins the unit of work when there is one.

func (*Store) Rows

func (s *Store) Rows(
	ctx context.Context,
	op, q string,
	args []any,
	scan func(*sql.Rows) error,
) error

Rows runs a query and calls scan for each row, stopping at the first error scan returns. Every error comes through Wrap.

func (*Store) Seal

func (s *Store) Seal(purpose, rowID, plain string) ([]byte, error)

Seal seals a secret for one column of one row under the store's keyring: purpose names the column and rowID the row, and both are authenticated (decision 0017). "" is stored as NULL, and without a keyring the value is stored as given. On an error it returns nothing to store.

func (*Store) Tx

func (s *Store) Tx(ctx context.Context, fn func(context.Context) error) error

Tx runs fn in a transaction on the store's pool. When fn fails, Tx rolls back and returns an error that wraps fn's. When the transaction cannot begin, as when ctx has already ended, or cannot commit, Tx returns an error that wraps ErrTransaction. Engines whose dialect sets ForUpdate run it at read committed, the others at their default level. Called with a context that already carries a transaction on the pool, Tx runs fn in it at once, and an error fn returns fails that transaction even if the outer function drops it.

func (*Store) Unseal

func (s *Store) Unseal(purpose, rowID string, stored []byte) (string, error)

Unseal opens a value Seal stored, with the same purpose and rowID; NULL reads as "". A value stored before a keyring was configured is returned as it is, and a sealed value read without a keyring fails with ErrNoKeyring.

func (*Store) Wrap

func (s *Store) Wrap(op string, err error) error

Wrap maps a driver error onto the kernel sentinels and names the operation: sql.ErrNoRows becomes kernel.ErrNotFound and a unique violation the dialect recognises kernel.ErrConflict, each prefixed with op; any other error is prefixed with the dialect's name and op and also marked kernel.ErrStore, the store's own failure, unless its context ended. nil stays nil.

type StreamVersion

type StreamVersion struct {
	Module          string
	Current, Latest int
}

StreamVersion is one module's stream: the highest version its history records, Current (0 when none), and the highest version the stream holds, Latest, so a caller can report a pending schema.

func Version

func Version(ctx context.Context, db *sql.DB, d Dialect, mods []Module) ([]StreamVersion, error)

Version returns every module's stream in the order of mods, with the highest version its history records and the highest it holds. It refuses a legacy history as Migrate does, and its errors wrap ErrMigration.

Jump to

Keyboard shortcuts

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