migrate

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 26 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 is the imperative front door as a library: one parsed statement in — gate, resolve, introspect, classify, route, execute — and exactly one verdict out. The CLI's migrate command and orchestrators embedding pg-sprite share this one pipeline, so a verdict means the same thing no matter which caller produced it.

RunDesired is the declarative execution loop on the same pipeline: one parsed desired-state schema in, the convergence plan derived through diffplan.Plan, and every planned statement executed back through Run — per-statement verdicts, committed-prefix semantics, stop at the first refusal or failure. Both entry points share Options, the executors, and the verdict contract; the desired loop adds only plan admission and sequencing.

Callers own the boundary concerns: parse the statement through statement.ParseOne (or the desired schema through statement.ParseDesired; a parse failure surfaces at the caller) and build the connection through dbconn.NewPool. Gate is exported so a caller can refuse an unsupported statement kind before dialing; Run re-checks it, so a caller that skips the early gate still cannot execute a gated kind.

Run takes the concrete pgxpool.Pool that dbconn.NewPool returns — a deliberate concrete dependency, not an oversight: the execution paths need the full pool surface (dedicated sessions for concurrent builds, per-step transactions), a narrower interface would admit handles those paths cannot use, and it is the same handle the declarative front door (diffplan.Plan) takes, so the two front doors embed identically.

Before a v1 module tag the Go API carries no compatibility promise: the JSON verdict.Verdict is the stability boundary, the Go API follows at v1 (see docs/architecture.md).

Example (Run)

Example_run is the full library flow an orchestrator embeds: parse the statement, gate it before dialing, connect, and drive the imperative pipeline to exactly one verdict. It is compile-checked but not executed — Run needs a live PostgreSQL database.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/block/pg-sprite/pkg/dbconn"
	"github.com/block/pg-sprite/pkg/migrate"
	"github.com/block/pg-sprite/pkg/statement"
	"github.com/block/pg-sprite/pkg/verdict"
)

func main() {
	ctx := context.Background()

	// Parse failures surface here, at the boundary where the embedder can
	// render them.
	st, err := statement.ParseOne("ALTER TABLE users ALTER COLUMN email SET NOT NULL")
	if err != nil {
		log.Print(err)
		return
	}

	// Gate needs no database: an unsupported statement kind refuses before
	// dialing. Run re-checks it, so skipping this early gate is safe —
	// only slower.
	if v, refused := migrate.Gate(st); refused {
		fmt.Println(v.Reason, v.Detail)
		return
	}

	pool, err := dbconn.NewPool(ctx, dbconn.Config{URL: "postgres://engine@localhost:5432/app"})
	if err != nil {
		log.Print(err)
		return
	}
	defer pool.Close()

	// The zero Options is not a runnable policy — Run rejects it.
	// DefaultOptions is the sanctioned starting point (the CLI's flag
	// defaults); tune it per table: a large table needs more generous
	// concurrent-build and validate bounds, a hot table a tighter lock
	// budget.
	opts := migrate.DefaultOptions()

	// The verdict-and-error contract has three shapes: a refusal returns
	// the verdict with a nil error; an execution failure returns the
	// failed verdict (the stable code and the committed prefix) together
	// with the operational error; an error with a zero verdict means the
	// pipeline stopped before executing anything.
	v, err := migrate.Run(ctx, pool, st, opts)
	if err != nil {
		log.Print(err)
	}
	switch v.Outcome {
	case verdict.OutcomeExecuted:
		fmt.Println(v.ExecutedSQL)
	case verdict.OutcomeRefused:
		fmt.Println(v.Reason, v.Detail)
	case verdict.OutcomeFailed:
		fmt.Println(v.Code, v.ExecutedSQL)
	}
}
Example (RunDesired)

Example_runDesired is the declarative execution flow: parse the desired-state schema, connect, and converge the live table onto it — the engine derives the plan and drives every planned statement through the same pipeline Run uses. It is compile-checked but not executed — RunDesired needs a live PostgreSQL database.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/block/pg-sprite/pkg/dbconn"
	"github.com/block/pg-sprite/pkg/migrate"
	"github.com/block/pg-sprite/pkg/statement"
	"github.com/block/pg-sprite/pkg/verdict"
)

func main() {
	ctx := context.Background()

	// One desired file describes one table: exactly one CREATE TABLE plus
	// its indexes. Parse failures surface here, at the boundary where the
	// embedder can render them.
	desired, err := statement.ParseDesired(`CREATE TABLE users (id bigint PRIMARY KEY, email text);
CREATE INDEX users_email_idx ON users (email);`)
	if err != nil {
		log.Print(err)
		return
	}

	pool, err := dbconn.NewPool(ctx, dbconn.Config{URL: "postgres://engine@localhost:5432/app"})
	if err != nil {
		log.Print(err)
		return
	}
	defer pool.Close()

	// The result-and-error contract mirrors Run's three shapes: a refusal
	// (at plan admission or on a mid-plan statement) returns the result
	// with a nil error; an execution failure returns the failed result
	// together with the operational error; an error with a zero result
	// means nothing was planned or executed. Verdicts[i] is the verdict of
	// Plan.Statements[i] — fewer verdicts than planned statements means
	// execution stopped there.
	res, err := migrate.RunDesired(ctx, pool, migrate.DesiredRequest{
		Schema:  "public",
		Desired: desired,
		// ExpectedFingerprint pins a reviewed plan: leave it empty to run
		// whatever plan the live table needs now.
	}, migrate.DefaultOptions())
	if err != nil {
		log.Print(err)
	}
	switch res.Outcome {
	case verdict.OutcomeExecuted:
		fmt.Println(len(res.Plan.Statements), "statements converged")
	case verdict.OutcomeRefused:
		fmt.Println(res.Reason, res.Detail)
	case verdict.OutcomeFailed:
		fmt.Println(res.Detail)
	}
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrAcceptBlockingMismatch means the acknowledgement named a table other
	// than the one the accepted statement locks. Nothing has executed.
	ErrAcceptBlockingMismatch = errors.New("the accept-blocking acknowledgement must name the table the statement locks")
	// ErrAcceptBlockingRelationNotFound means the index or table the
	// accepted statement names does not exist or is not visible on the
	// session search_path, so there is no table to acknowledge. Nothing has
	// executed.
	ErrAcceptBlockingRelationNotFound = errors.New("the accepted statement names a relation that does not exist")
	// ErrAcceptBlockingWrongRelationKind means the accepted statement names a
	// relation that exists but is not what the statement operates on — a
	// table where DROP INDEX / REINDEX INDEX needs an index, or an index
	// where REINDEX TABLE needs a table — so there is no lock to
	// acknowledge. Nothing has executed.
	ErrAcceptBlockingWrongRelationKind = errors.New("the accepted statement names a relation of the wrong kind")
)
View Source
var (
	// ErrAllowDestructiveMismatch means the destructive acknowledgement
	// named a table other than the statement's resolved target. Nothing has
	// executed.
	ErrAllowDestructiveMismatch = errors.New("the destructive acknowledgement must name the resolved target table")
	// ErrAllowDestructiveNotSupported is returned by [RunDesired] when
	// Options.AllowDestructive is set: desired-state execution refuses a
	// destructive plan whole and has no acknowledgement for it.
	ErrAllowDestructiveNotSupported = errors.New(
		"the destructive acknowledgement applies to the imperative front door only; desired-state execution refuses a destructive plan whole")
)
View Source
var (
	// ErrRenamedIndexNotFound means the relation an ALTER INDEX ... RENAME
	// TO names is not an index visible on the session search_path, so
	// there is no table to plan or preflight. Nothing has executed.
	ErrRenamedIndexNotFound = errors.New("the renamed index is not an index visible on the session search_path")
	// ErrIndexRenameAcknowledgement means an acknowledgement was given for
	// an ALTER INDEX ... RENAME TO, which neither the force nor the
	// copy-and-swap restart acknowledgement applies to. Nothing has
	// executed.
	ErrIndexRenameAcknowledgement = errors.New("the acknowledgement does not apply to ALTER INDEX ... RENAME TO")
)
View Source
var ErrBlockWritesNotSupported = errors.New(
	"the block-writes acknowledgement applies to the imperative front door only; desired-state execution never takes a table offline for writes")

ErrBlockWritesNotSupported is returned by RunDesired when Options.CopySwap.BlockWrites is set. The acknowledgement names a table, but on the declarative front door the derived plan, not the operator, decides which statements take copy-and-swap and so how many fenced copies refuse the table's writes and for how long; a value left on an embedder's configuration would take the table offline for every later plan. Offline mode belongs on the imperative front door, one statement the operator wrote at a time.

View Source
var ErrCopySwapConnectionRequired = errors.New(
	"Options.CopySwap.Connection must name the database the pool was dialed with; the copy-and-swap route opens dedicated sessions from it")

ErrCopySwapConnectionRequired is returned by Run and RunDesired when a statement routes to the copy-and-swap backend and Options.CopySwap.Connection is unset. The route opens dedicated sessions of its own and needs the connection the pool was dialed with, not the pool alone; a library caller that builds Options by hand wires it, the CLI always does. It is a sentinel so an embedder can tell the missing wiring apart from an operational failure with errors.Is; nothing has been executed when it is returned. A connection that is set but reaches another database is the other wiring error, CopySwapConnectionMismatchError.

View Source
var ErrForceNotSupported = errors.New(
	"the force acknowledgement applies to the imperative front door only; desired-state execution never runs a submitted form blind")

ErrForceNotSupported is returned by RunDesired when Options.Force is set: the force acknowledgement applies to the imperative front door only — desired-state execution never runs a submitted form blind. It is a sentinel so an embedder can tell the unsupported option apart from an operational failure with errors.Is.

View Source
var ErrNotConverged = errors.New("every planned statement committed but the table still differs from the desired schema")

ErrNotConverged is returned by RunDesired when every planned statement committed but a plan derived again from the live table afterwards is not empty: the table still differs from the desired schema, so the run cannot report it converged. The committed statements stay in effect; the error names the statements a rerun would plan.

Functions

func AcceptedRefusal added in v0.4.0

func AcceptedRefusal(ack string, v verdict.Verdict) (verdict.Refusal, bool)

AcceptedRefusal returns the refusal's in-process proof when the acknowledgement applies to it: the caller supplied one and the proof is in the eligible set. Ineligible refusals — and a verdict whose proof does not validate, which this build's gate cannot produce — stand exactly as they would without the acknowledgement. Run makes this decision itself; it is exported so a front door that refuses gated statements before dialing can tell the one gate refusal that needs the database.

func AdmitDestructive added in v0.4.0

func AdmitDestructive(st statement.Statement, schema string, rs router.Statement, ack string) (verdict.Verdict, bool, error)

AdmitDestructive is the destructive-change gate a dry run applies to the statement it routed, with the result Run reaches for the same statement and acknowledgement: the refusal verdict when the routed statement rs discards live data or structure and ack is empty, or the mismatch error when ack does not name the resolved target table. The boolean is false when the statement discards nothing or ack names its table.

schema is the schema st's table resolved to on the session's search_path, as the dry run's live facts read it; a qualified st ignores it. An unqualified st's verdict names the table and statement the way Run's does, qualified.

func AdmitRoutedSteps added in v0.4.0

func AdmitRoutedSteps(st statement.Statement, schema string, steps []string) (verdict.Verdict, bool, error)

AdmitRoutedSteps runs the sequence executor's static admission over the steps a dry run would execute for st, and returns the refusal verdict Run ends in when that admission refuses the same steps. It is how a dry run learns a refusal that is decided from the statement's shape alone — an unnamed or IF NOT EXISTS index build, a DETACH PARTITION substituted to its unsupported concurrent form — instead of reporting a plan the apply turns down. The verdict is the apply's only when admission is the apply's first refusal: the checks that need live facts — the size guard, the partitioned-parent and privilege preflights — run before admission in Run and are not part of this function, so a dry run does not claim them.

The boolean is false when every step is admitted. A non-nil error is not a refusal: the steps could not be parsed, or admission failed for a reason outside the refusal contract, exactly where Run would return an operational error.

schema is the schema st's table resolved to on the session's search_path, as the dry run's live facts read it. Run resolves an unqualified table before its executor admits the steps, so an unqualified st has its steps qualified with schema before admission, and its refusal names the table and statement the way Run's does: the table in schema, and the statement re-emitted qualified. A qualified st ignores schema.

func CopySwapMinConns added in v0.4.0

func CopySwapMinConns(o copier.Options) int32

CopySwapMinConns is the smallest pool the copy-and-swap route admits for a copy sized by o: one connection per copy worker, with zero workers meaning copier.DefaultWorkers, and two beside them. Each worker holds a pool connection while it copies a chunk, so a pool of only the workers leaves a live run's catch-up flushes waiting behind the copy while the slot's lag grows. A host that builds its own pool sizes it with this (dbconn.Config.MaxConnsFloor); Run and RunDesired refuse a smaller one. A worker count no pool size can hold answers math.MaxInt32 rather than wrapping to a number every pool would pass.

func Gate

Gate is the statement-type gate: ALTER TABLE, CREATE INDEX, and ALTER INDEX ... RENAME TO proceed to classification (a blocking CREATE INDEX is substituted with its concurrent build, a submitted concurrent build is driven directly); the index-maintenance forms the executor cannot drive yet are pointed at their concurrent idiom, everything else is unsupported. Refused statements are never executed. Gate needs no database, so a caller can refuse before dialing; Run re-checks it regardless.

func ResolvedSchema

func ResolvedSchema(st statement.Statement) string

ResolvedSchema is the schema the engine plans against: the statement's qualification, or public — the default the engine introspects — when a table-targeted statement leaves it unqualified. A report carries the resolved name, never the submitted one: a stored plan must not depend on the reader's search_path to say which table it describes.

func RowSecurityRefusal added in v0.4.0

func RowSecurityRefusal(err error) (verdict.Refusal, bool)

RowSecurityRefusal classifies typed admission failures from the atomic RLS executor. Operational errors are not refusals. Privilege causes take priority over the general admission sentinel they also wrap.

func Run

Run drives one schema change end to end: gate the statement type, resolve the target, classify and route the statement exactly as a dry run would, execute the routed SQL — the planner's safer native sequence by default when the submitted form blocks — and end in exactly one verdict.

The verdict-and-error contract has three shapes. A refusal returns the refusal verdict and a nil error; the caller maps it to its refusal exit path. An execution failure returns the failed verdict — the stable executor code plus the committed prefix — together with the operational error; the verdict is the error's machine-readable twin. An error with a zero verdict means the pipeline stopped before reaching a verdict (a resolution, introspection, or acknowledgement error) and nothing was executed. A fourth outcome exists only under Options.AcceptBlocking: an eligible gate refusal the operator acknowledged commits as verdict.OutcomeExecutedWithoutOnlineSafety with a nil error, and the caller maps it to its own exit path — never the online-safe one. A statement the router assigns to the copy-and-swap backend runs through the shadow table under Options.CopySwap and commits as verdict.OutcomeExecutedViaCopyAndSwap; a failure on that path leaves a checkpoint row the next Run over the same statement resumes from.

A statement that discards live data or structure — a dropped column, constraint, NOT NULL, or (on the accepted blocking path) index — is refused with reason destructive-change before any route runs it, unless Options.AllowDestructive names its table; an acknowledged run's verdict carries AllowedDestructive.

A bare table name resolves on the pool's own search_path, so two pools with different paths can address different tables from the same statement text. Run's own catalog reads — the resolve and the accept-blocking lookup — are pg_catalog-qualified whatever that path lists; a pool from dbconn.NewPool also drops a shadowing pg_catalog entry on every session, which the engine's other reads rely on (CO-9, docs/schemabot-integration.md).

Run does not close the pool; one pool serves any number of calls.

Types

type Convergence added in v0.4.0

type Convergence struct {
	// Status is what the fresh plan found.
	Status ConvergenceStatus `json:"status"`
	// Remaining is the fresh plan, what a rerun would execute; present
	// exactly when Status is not-converged.
	Remaining *plan.Report `json:"remaining,omitempty"`
}

Convergence is the outcome of deriving the plan again after every planned statement committed.

type ConvergenceStatus added in v0.4.0

type ConvergenceStatus string

ConvergenceStatus is what the plan derived again after a desired-state run's last commit found.

const (
	// ConvergenceVerified means the fresh plan is empty: the table matches
	// the desired schema.
	ConvergenceVerified ConvergenceStatus = "converged"
	// ConvergenceRemaining means the fresh plan is not empty: the table
	// still differs, and Convergence.Remaining is what a rerun would run.
	ConvergenceRemaining ConvergenceStatus = "not-converged"
	// ConvergenceUnverifiable means the fresh plan could not be derived, so
	// the run can prove neither outcome.
	ConvergenceUnverifiable ConvergenceStatus = "unverifiable"
)

type CopySwapConnectionMismatchError added in v0.4.0

type CopySwapConnectionMismatchError struct {
	// PoolCluster and PoolDatabase identify the database the pool reaches.
	PoolCluster  string
	PoolDatabase string
	// ConnectionCluster and ConnectionDatabase identify the database
	// Options.CopySwap.Connection reaches.
	ConnectionCluster  string
	ConnectionDatabase string
}

CopySwapConnectionMismatchError is returned by Run and RunDesired when Options.CopySwap.Connection reaches a database other than the one the pool handed to Run was dialed with. The route takes its table lock on a session opened from the connection and runs every other statement on the pool. An advisory lock excludes only sessions of the database it was taken in, so a lock taken in another database does not keep a correctly wired second run off the table, and a working transaction on another cluster cannot confirm it at all. The check runs before the preflight, so nothing has been executed when it is returned; it is a wiring mistake that no retry corrects, so match it with errors.As and fix the wiring rather than routing it as an outcome. The error carries both clusters' system identifiers, a stable fingerprint of each server, so a caller that posts results to a shared surface logs the fields and shows a fixed line rather than the raw text.

A database is told from another by the cluster's system identifier, minted by initdb, together with the database name, which is unique only within a cluster. A physical copy of a cluster (a standby, or a server restored from a base backup or a snapshot) keeps its source's system identifier and database names, so the check does not tell such a copy from its source; a run wired across that pair still stops, later, when its first working transaction finds no lock to confirm.

func (*CopySwapConnectionMismatchError) Error added in v0.4.0

Error implements the error interface.

type CopySwapOptions added in v0.4.0

type CopySwapOptions struct {
	// Connection is the database the pool handed to Run was dialed with.
	// The route's dedicated sessions are opened from it. Before the
	// preflight the route proves the two reach one database on one
	// cluster, and stops with a CopySwapConnectionMismatchError when they
	// do not.
	Connection dbconn.Config

	// FreeDiskBytes is the free space the operator reports on the volume
	// the table lives on; the preflight refuses the run when the shadow and
	// its indexes would not fit. Zero means no space, and refuses.
	FreeDiskBytes int64

	// KeepOld leaves the retained source under its derived _old name after
	// the swap, for a rollback window the operator ends by hand. False
	// drops it before the run reports done.
	KeepOld bool

	// BlockWrites, when set, declares that nothing writes the table while the
	// run lasts. The run then takes the write fence instead of a
	// replication slot and needs no logical decoding from the server; every
	// write that reaches the fence fails, so the table is offline for
	// writes until the swap. It must name the resolved target table as
	// SCHEMA.TABLE, the same way Restart does, so the declaration cannot be
	// left on a script and fence another table by accident. Empty runs the
	// live path: slot, stream, and catch-up. Run takes it; RunDesired
	// rejects any value with ErrBlockWritesNotSupported.
	BlockWrites string

	// Restart, when set, is the operator's acknowledgement that the run on
	// the table is to start over: whatever an earlier run left — its
	// checkpoint row, its shadow, its write fence or replication slot —
	// is discarded under the run's own lock session before a fresh shadow
	// is built (schemachange.RunOptions.Restart). It must name the
	// resolved target table as SCHEMA.TABLE, the same way Options.Force
	// does, so the acknowledgement cannot be left on a script by accident.
	// A leftover whose swap already committed is not discarded: the
	// change is past the point of starting over, and the run is refused
	// so it can be finished without the acknowledgement. Empty resumes a
	// leftover, as every run does.
	Restart string

	// Copier sizes the copy: its workers, the chunk sizes and the chunk
	// time they are throttled toward, the budgets of each chunk
	// transaction, and the progress tracker the copier reports to while it
	// runs. Zero values take the copier's defaults. A value the copier
	// would refuse is a wiring error refused before the preflight, like a
	// negative CheckpointInterval. The workers set the pool size the route
	// admits: CopySwapMinConns(Copier).
	//
	// Copier.Tracker is the one source of rows copied; OnCheckpoint
	// carries a key position, not a count. The host builds the tracker and
	// calls its Start before Run, since Start and StartStep drop the
	// tracker's work source and so, called while the copy runs, stop the
	// counters. The copier is the work source from the copy's first chunk
	// until just before the copy returns: the tracker reports no work
	// before the copy, after it, or through the verification pass and a
	// live run's catch-up, whose phases reach the host through
	// OnCheckpoint alone; the verdict's detail reports the rows the
	// verification pass covered. Rows copied counts this run's rows only,
	// and rows total is the source's catalog estimate, zero for a table
	// never analyzed, so a host treats a zero total as unknown and a ratio
	// over one as possible. A tracker serves one run: two runs handed one
	// tracker each make it their source, and the first to finish drops the
	// source the other still reports to.
	Copier copier.Options

	// CheckpointInterval is how often a copy in progress saves its landed
	// watermark to the checkpoint row, which is how far a run that stops
	// mid-copy resumes from, and how often OnCheckpoint hears from the
	// copy. Zero means the Runner's default; a negative value is refused
	// before anything is read.
	CheckpointInterval time.Duration

	// OnCheckpoint, when set, is the run's progress signal: it is called
	// after every successful save of the checkpoint row with the row as
	// saved — the phase it entered, the watermark the copy has landed, the
	// position a live run has applied through — so a host can record where
	// a run that may last hours stands. Two saves are not shown: a live
	// run that reconciles a lost slot writes its reconciling marker and
	// the resumed row straight to the store, and the hook is handed the
	// row the reconcile leaves once. The row is the row as written, so its
	// UpdatedAt is zero; a host that wants a save time uses its own clock.
	// Its ShadowProof bytes are shared with the run, so a hook that keeps
	// the row treats it as read-only. The slot, publication, and applied
	// position it carries are PostgreSQL's; an adapter that forwards the
	// row to an engine-neutral record maps them into generic metadata.
	//
	// The hook runs on the run's own goroutines and holds the run up while
	// it runs: the phase saves call it on the goroutine that called Run,
	// with the table's lock session held and, for a quiesced run, the
	// source fenced against writes; the periodic watermark saves call it
	// on the copy's saving goroutine, every CheckpointInterval rather than
	// as the copy lands rows, and a slow call there delays the next save.
	// It must be safe to call from either goroutine and should return
	// promptly. An error it returns stops the run there, as a failed
	// verdict with the row as that save left it, and the next run resumes
	// from the row — except at the done save, after which there is nothing
	// left to stop: the verdict is executed and its detail names the
	// error.
	OnCheckpoint func(ctx context.Context, cp checkpoint.Checkpoint) error
}

CopySwapOptions is the policy for a statement the router assigns to the copy-and-swap backend. The zero value is not runnable: the route opens dedicated sessions of its own — the table lock, the copy workers, the replication stream — so it needs the connection the pool was built from, not the pool alone.

A table that already carries the done row of an earlier copy-and-swap is run again without ceremony: the route replaces the row inside its own lock session (schemachange.RunOptions.ReplaceDone), so a second type change on a table — the next planned statement, or next month's — needs no step between the two runs. The one done row the route will not replace is one whose retained source still stands under its _old name (KeepOld): that is an open rollback window, and the run is refused until the operator ends it.

type DesiredRequest

type DesiredRequest struct {
	// Schema is the target schema the desired table lives in.
	Schema string
	// Desired is the parsed desired-state schema for the table.
	Desired statement.DesiredSchema
	// ExpectedFingerprint optionally pins the plan: when set, the plan
	// derived at execution time must carry exactly this fingerprint
	// (plan.Report.Fingerprint) or nothing runs. It is how a caller that
	// had a plan reviewed enforces that the plan the reviewer approved is
	// the plan that executes; empty skips the check.
	ExpectedFingerprint string
}

DesiredRequest names the inputs to RunDesired. Zero-value fields are invalid: the schema must be set, and the desired state must come from statement.ParseDesired — the zero DesiredSchema is refused.

type DesiredResult

type DesiredResult struct {
	// Plan is the convergence plan derived at execution time; empty
	// Plan.Statements means the live table already matched the desired
	// schema.
	Plan plan.Report `json:"plan"`
	// Verdicts are the per-statement verdicts, in plan order, one per
	// attempted statement.
	Verdicts []verdict.Verdict `json:"verdicts,omitempty"`
	// Outcome is what happened overall: executed when every planned
	// statement committed and, for an existing table, a plan derived
	// again afterwards is empty (or there was nothing to run), refused
	// when the plan or one of its statements was refused and execution
	// stopped, failed when execution stopped on an operational error. A failed result whose stopping
	// statement has no verdict means the pipeline stopped before reaching
	// one — nothing about that statement was executed; a failed verdict
	// means the statement was attempted and failed. A failed result with
	// an executed verdict for every planned statement means everything
	// committed but convergence could not be verified. Detail says which.
	Outcome verdict.Outcome `json:"outcome"`
	// Reason is the typed refusal cause; empty unless Outcome is refused.
	Reason verdict.Reason `json:"reason,omitempty"`
	// Class identifies how a consumer routes a refusal; empty unless
	// Outcome is refused.
	Class verdict.Class `json:"class,omitempty"`
	// Owner identifies who owns work with no online-safety problem; present
	// exactly when Class is no-online-safety-problem.
	Owner verdict.Owner `json:"owner,omitempty"`
	// Detail is the human explanation: why refused, what committed, or
	// that there was nothing to do.
	Detail string `json:"detail,omitempty"`
	// Convergence is what the plan derived again after the last commit
	// found; present exactly when every planned statement for an existing
	// table committed, so a failed result carrying it committed everything
	// and a converged one proved it.
	Convergence *Convergence `json:"convergence,omitempty"`
}

DesiredResult is the aggregate report for one desired-state execution: the plan that was derived, the verdict of every statement that was attempted, and the overall outcome.

Verdicts[i] is the verdict of Plan.Statements[i]; fewer verdicts than planned statements means execution stopped and the remaining statements were never attempted. The committed prefix is read from the verdicts: every executed verdict committed in full, and a failed verdict's own ExecutedSQL discloses the committed steps inside the statement that failed. Whether anything changed is read from the plan: an executed outcome with empty Plan.Statements is the no-op signal — the live table already matched the desired schema and nothing ran.

func RunDesired

func RunDesired(ctx context.Context, pool *pgxpool.Pool, req DesiredRequest, opts Options) (DesiredResult, error)

RunDesired converges one live table onto its desired-state schema: derive the convergence plan with diffplan.Plan, admit the plan as a whole, then execute each planned statement back through the full Run pipeline — fresh introspection, classification, and routing per statement, so a statement that became unsafe after planning refuses instead of running — stopping at the first refusal or failure.

A table that does not exist yet takes the greenfield create path instead: the plan is the desired schema itself, and after the same whole-plan admission the executor's create path verifies the name is free and the role can create in the schema, then runs the CREATE TABLE and the index builds as brief bounded steps. An occupied name is a typed verdict.ReasonCreateCollision refusal — the caller re-derives the plan against the live catalog rather than assuming the occupant's shape.

Plan-time admission is all-or-nothing: a plan that contains a destructive statement, routes any statement away from execution, or does not match the pinned fingerprint is refused before anything runs, and so is a plan that routes a statement through copy-and-swap when that route's preflight refuses the table or the server as they stand now. Execution-time semantics are committed-prefix: once statements start running, an executed statement stays committed even when a later one refuses or fails, and the result's verdicts disclose exactly how far convergence got.

Convergence of an existing table is verified, not assumed: after the last statement commits, the plan is derived again from the live table, and the run is executed only when that plan is empty. A non-empty plan returns the failed result with ErrNotConverged, naming what a rerun would plan; a failure to derive it returns the failed result with that error. Either way every statement stays committed. The greenfield path is not re-planned: deriving a plan for an existing table builds the desired side in a scratch schema, which needs CREATE on the database, and a create needs only CREATE in its own schema. A create runs the desired file's own statements and verifies every name it claims before it reports, which is its proof instead.

The result-and-error contract mirrors Run's three shapes. A refusal — at plan admission or on a mid-plan statement — returns the result with a nil error. An execution failure returns the failed result together with the operational error. An error with a zero result means the pipeline stopped before planning or executing anything.

Options.Force, Options.AllowDestructive and Options.CopySwap.BlockWrites are rejected: the declarative front door never runs a submitted form blind, refuses a destructive plan whole, and never takes a table offline for writes. A destructive, force-worthy or offline change belongs on the imperative front door where the operator states it explicitly.

Every planned statement runs back through Run, so Run's note on the pool's search_path applies to the pool passed here.

RunDesired does not close the pool; one pool serves any number of calls.

type Facts

type Facts struct {
	// Classifier feeds [planner.Classify]. Statements without a single
	// table target (index drops, REINDEX) and missing tables classify
	// with zero facts — a strictly more conservative plan.
	Classifier planner.Facts

	// Target carries the preflight facts (partitioning, server major)
	// for plan-time partition checks; zero whenever Classifier is.
	Target preflight.TargetFacts

	// Schema is the schema the facts describe: the statement's
	// qualification, or the schema an unqualified table resolves to on the
	// session search_path, the one Run resolves it to. An unqualified table
	// the search_path does not show is looked up in public, and reported
	// missing; a statement without a single table target carries its own
	// qualification.
	Schema string

	// Table is the table the facts describe: the statement's target, or,
	// for an ALTER INDEX ... RENAME TO, which names no table, the table
	// that owns the renamed index; empty for a statement without a single
	// table target.
	Table string

	// TableExists mirrors the introspection outcome for a plan report:
	// true when the table was found, false when it was looked up and
	// missing, nil when the statement has no single table target to
	// introspect.
	TableExists *bool
}

Facts is one introspection pass over the statement's target table. Both Run and a dry-run plan classify from one Facts value, so execution and its plan describe the same live state.

func LiveFacts

func LiveFacts(ctx context.Context, pool *pgxpool.Pool,
	st statement.Statement) (Facts, error)

LiveFacts introspects the statement's target table for classifier facts. For an ALTER TABLE that retypes or drops a column it reads which views depend on each column (preflight.ColumnDependentViews), and for one that adds columns, has the server prove whether each one rewrites the table (preflight.AddColumnRewrites). For one that adds an unnamed CHECK or FOREIGN KEY it also reads the constraint names the schema already uses, so the safer sequence names the constraint as the server would.

type Options

type Options struct {
	// CreateOwner is the role greenfield tables are created as. Empty means
	// create as the connected role.
	CreateOwner string

	// Force is the typed acknowledgement to run the submitted form as-is,
	// overriding a safer-sequence substitution or a rewrite-required /
	// backend-unavailable refusal. It must name the resolved
	// schema-qualified target table exactly; empty means the engine's
	// routing decides. Planner refusals (no known safe path) and gated
	// statement kinds cannot be forced.
	Force string

	// AcceptBlocking is the typed acknowledgement to run one eligible
	// refused statement as-is, without online safety, under the engine-owned
	// lock and statement budgets in Budget.Brief: today a plain
	// single-relation DROP INDEX, REINDEX INDEX, or REINDEX TABLE the
	// statement-kind gate refuses. It must name the schema-qualified table
	// whose lock the operator accepts — the index's owning table, resolved
	// from the catalog — exactly; empty means every refusal stands.
	// Ineligible refusals stand regardless. Force and AcceptBlocking are
	// mutually exclusive: a statement reaches one routing decision, and
	// one acknowledgement names it. An accepted DROP INDEX also needs
	// AllowDestructive: accepting the lock is not accepting the loss.
	AcceptBlocking string

	// AllowDestructive is the typed acknowledgement that the statement may
	// discard live data or structure: a dropped column, constraint, NOT
	// NULL, or index. Without it such a statement is refused before
	// anything runs, with reason destructive-change, on every route it
	// could take. It must name the resolved schema-qualified target table
	// exactly — for a DROP INDEX, the index's owning table; empty means
	// destructive statements are refused. It acknowledges only the loss:
	// the statement still meets every other gate, so a statement that also
	// needs Force or AcceptBlocking needs both. [RunDesired] rejects it.
	AllowDestructive string

	// MaxTableSizeBytes is the threshold above which a blind bounded
	// attempt of the submitted form is refused, measured as the table's
	// full on-disk footprint: heap, indexes, and TOAST, all partitions.
	// Substituted safer sequences and planner-proven online idioms are not
	// size-guarded — long work on large tables is their purpose.
	MaxTableSizeBytes int64

	// Budget bounds every executed step: brief steps under lock and
	// statement timeouts, concurrent index builds and constraint
	// validation under their overall bounds.
	Budget executor.SequenceBudget

	// Retry is the bounded retry policy when native DDL exceeds its lock
	// budget. The zero value uses [executor.DefaultRetryPolicy]; a
	// partially configured policy is rejected by the executor.
	Retry executor.RetryPolicy

	// CopySwap is the policy for a statement the router assigns to the
	// copy-and-swap backend. A statement the router keeps on the native
	// backend never reads it; a statement routed to copy-and-swap cannot
	// run without CopySwap.Connection.
	CopySwap CopySwapOptions

	// Logger receives decision diagnostics (routing, preflight, execution
	// transitions); nil discards them.
	Logger *slog.Logger

	// Audit receives the force-override audit record; nil discards it.
	// The verdict's Forced field is the machine-readable record and is
	// always set, so the run's outcome never depends on this logger; the
	// CLI wires an always-on stderr handler here so an operator's
	// deliberate safety override is visible even without diagnostics.
	Audit *slog.Logger
}

Options carries the execution policy for one Run: the safety budgets, the retry policy, the size guard, and the operator's force acknowledgement. The zero value is not a runnable policy: callers set the budgets and the size guard deliberately — DefaultOptions is the sanctioned starting point (the same policy the CLI's flag defaults wire), an embedding orchestrator tunes from there.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions is the sanctioned starting point for an embedding caller: the same budgets, size guard, and retry policy the CLI's flag defaults wire. These are defaults to tune, not a recommendation — a large table needs a more generous concurrent-build and validate bound, a hot table a tighter lock budget. Force, AllowDestructive, Logger, and Audit stay zero: overriding safety and receiving diagnostics are always deliberate choices.

Jump to

Keyboard shortcuts

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