migrate

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 13 Imported by: 1 module, 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 migrate applies the platform's OWN schema to the admin store (§2.9), from numbered .sql files.

Only the admin store is migrated here. A caller's Storage is their database and their schema; the platform never touches it.

The rules, in one place:

  • A migration is a file named "NNNN_what_it_does.sql". Filename order is apply order.
  • A file that has been released is never edited. Its checksum is recorded when it runs, and a later mismatch is an error, because a database that no longer matches the code is exactly the thing an operational store is supposed to tell you about.
  • 0001 is the schema as it stood before this package existed, written so that running it against a database already holding those tables changes nothing. That is what lets an existing install pick the migrator up without a separate baseline step, and what repairs one that stopped on an older release.

Index

Constants

View Source
const Timeout = 2 * time.Minute

Timeout is how long the background migration may take before it gives up. Generous: it is one pass of DDL, and a database slow enough to exceed this has a bigger problem than the schema.

Variables

View Source
var Postgres = Dialect{
	Name: "postgres",
	Ledger: `CREATE TABLE IF NOT EXISTS agentic_migrations (
	  version TEXT PRIMARY KEY, checksum TEXT NOT NULL,
	  "appliedAt" TIMESTAMPTZ NOT NULL DEFAULT now())`,
	Insert: `INSERT INTO agentic_migrations (version, checksum) VALUES ($1, $2)`,

	Lock:        `SELECT pg_advisory_xact_lock(4171939288)`,
	Placeholder: "$1",
}

Postgres takes a transaction-scoped advisory lock, so several workers starting at once queue rather than racing on the same DDL. The key is arbitrary and constant: it only has to be the same in every process.

View Source
var SQLite = Dialect{
	Name: "sqlite",
	Ledger: `CREATE TABLE IF NOT EXISTS agentic_migrations (
	  version TEXT PRIMARY KEY, checksum TEXT NOT NULL, appliedAt INTEGER NOT NULL)`,
	Insert: `INSERT INTO agentic_migrations (version, checksum, appliedAt)
	         VALUES (?, ?, CAST(strftime('%s','now') AS INTEGER) * 1000)`,
	Placeholder: "?",
	Begin:       "BEGIN IMMEDIATE",
}

SQLite needs no lock: the database takes one writer at a time, and BEGIN IMMEDIATE makes a second process wait for it.

Functions

func Gated

func Gated(inner ports.AdminStore, gate *Gate) ports.AdminStore

Gated is an AdminStore that waits for the schema before it does anything.

The wrapper lives here rather than in each store so that every admin store, including one added later, gets the same behaviour for free.

func Run

func Run(ctx context.Context, db *sql.DB, d Dialect, ms []Migration) error

Run applies every migration the ledger does not already carry, in order. Safe to call from several processes at once.

The whole run is ONE transaction, taken under the dialect's lock: the ledger, the repair step and every file commit together or not at all. Both databases roll DDL back with the transaction, so a run that fails part way leaves nothing behind to confuse the next attempt.

The lock has to cover the ledger too. Postgres's CREATE TABLE IF NOT EXISTS is not atomic against another session creating the same table: both see it missing, both create it, and one gets a duplicate-type error. Two workers starting together is the normal case here, so that is not a rare race.

One consequence worth knowing: a migration that cannot run inside a transaction (CREATE INDEX CONCURRENTLY, say) does not belong in a file here.

func Statements

func Statements(sqlText string) []string

Statements splits a migration into the statements to run one at a time, because neither driver reliably takes several at once.

Line comments are stripped BEFORE the split, so a semicolon inside one cannot cut a statement in half. A semicolon inside a string literal still would: migrations must not contain one.

Types

type Dialect

type Dialect struct {
	Name string
	// Ledger creates the table recording what has run.
	Ledger string
	// Insert records one applied migration, with two bind parameters.
	Insert string
	// Applied reads the ledger back: version and checksum. Empty reads
	// agentic_migrations.
	Applied string
	// Lock is run first inside each migration's transaction so two workers
	// starting together cannot both apply the same file. Empty for a
	// database that serialises writers by itself.
	Lock string
	// Placeholder is how this database spells a bind parameter.
	Placeholder string
	// Skipped is told about an Optional step that failed and was left for
	// the next start. Nil ignores it.
	Skipped func(version string, err error)
	// Begin opens the migration's transaction. SQLite's is BEGIN IMMEDIATE:
	// a plain BEGIN takes the write lock only at the first write, so two
	// processes that both read the ledger first both fail with SQLITE_BUSY
	// instead of one waiting for the other.
	Begin string
	// Repair runs once BEFORE the migration files, inside their transaction. It exists for the one
	// thing portable SQL cannot express: SQLite has no ADD COLUMN IF NOT
	// EXISTS, so a database left behind by an older release needs a PRAGMA
	// check instead.
	//
	// Before, not after, because the baseline creates indexes over columns
	// that such a database may not have yet — and an index on a column that
	// does not exist is an error, not a no-op.
	//
	// It must be idempotent, and it must tolerate a database where none of
	// the tables exist: on a fresh one it runs before anything is created.
	Repair func(context.Context, Execer) error
}

Dialect is the little that differs between databases.

type Execer

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

Execer is the part of a database handle a repair step needs. Both *sql.DB and *sql.Tx satisfy it.

type Gate

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

Gate is the "schema is ready" signal (§2.9). SetupAgentCore returns as soon as the store is OPEN, and the schema is brought up to date behind it, so a service starts at the same speed whether or not it has migrating to do. Any admin call made in that window waits here rather than meeting a table that does not exist yet.

func NewGate

func NewGate() *Gate

NewGate returns a gate nobody has opened yet.

func Start

func Start(ctx context.Context, db *sql.DB, d Dialect, ms []Migration, log *slog.Logger) *Gate

Start applies the migrations on a goroutine and returns the gate that speaks for them.

The context is detached from the caller's: SetupAgentCore's own context is usually finished the moment it returns, and a migration cancelled half way through is exactly what nobody wants.

func (*Gate) Open

func (g *Gate) Open(err error)

Open releases everything waiting, with the migration's outcome. Called once.

func (*Gate) Wait

func (g *Gate) Wait(ctx context.Context) error

Wait blocks until the schema is ready, and reports what happened. It returns the caller's own error if they give up first.

type Migration

type Migration struct {
	Version  string
	SQL      string
	Checksum string
	// Optional marks a step that may fail on data it cannot change, such as
	// a unique index over rows an older release left duplicated. It runs
	// under a savepoint: a failure is rolled back and reported to
	// Dialect.Skipped, the rest of the run goes on, and the step is tried
	// again on the next start.
	Optional bool
	// Equivalent are other checksums this step is known to be the same as:
	// the same SQL, recorded under a different text by the TS runtime. A
	// database migrated by either runtime is then accepted by both.
	Equivalent []string
}

Migration is one versioned step, named by its file without the extension.

func Load

func Load(fsys fs.FS, dir string) ([]Migration, error)

Load reads every .sql file in dir, in filename order. Nested directories are ignored: one flat directory per dialect keeps apply order obvious.

func NewMigration added in v0.4.0

func NewMigration(version string, statements ...string) Migration

NewMigration is a migration built in code rather than read from a file, for a schema whose names are only known at run time (a table prefix).

func PostgresMigrations

func PostgresMigrations() ([]Migration, error)

PostgresMigrations are the admin migrations for Postgres, in apply order.

func SQLiteMigrations

func SQLiteMigrations() ([]Migration, error)

SQLiteMigrations are the admin migrations for SQLite, in apply order.

Jump to

Keyboard shortcuts

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