migrate

package
v0.5.5 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 29 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. The
	// error is an [AcknowledgementMismatchError] carrying both tables.
	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")
	// ErrAcceptBlockingNotSupported is returned by [RunDesired] when
	// Options.AcceptBlocking is set: the operator accepts one blocking
	// statement they wrote, and desired-state execution runs statements the
	// plan derived.
	ErrAcceptBlockingNotSupported = errors.New(
		"the accept-blocking acknowledgement applies to the imperative front door only; desired-state execution runs no blocking statement it was not told to")
)
View Source
var (
	// ErrAllowDestructiveMismatch means the destructive acknowledgement
	// named a table other than the statement's resolved target. Nothing has
	// executed. The error is an [AcknowledgementMismatchError] carrying both
	// tables.
	ErrAllowDestructiveMismatch = errors.New("the destructive acknowledgement must name the resolved target table")
	// ErrAllowDestructiveNotSupported is returned by [RunDesired] when
	// Options.AllowDestructive is set: that acknowledgement accepts the
	// loss of a statement the operator wrote, and desired-state execution
	// runs statements its plan derived. A destructive plan runs only through
	// [DesiredRequest.AllowDestructive], bound to a pinned fingerprint.
	ErrAllowDestructiveNotSupported = errors.New(
		"the destructive acknowledgement in the options applies to the imperative front door only; a destructive desired-state " +
			"plan runs only when the request's own acknowledgement names its table and the request pins the reviewed plan's fingerprint")
	// ErrAllowDestructiveNeedsFingerprint is returned by [RunDesired] and
	// [RunDesiredWithRowSecurity] when the request names a table in its
	// destructive acknowledgement without pinning a plan fingerprint:
	// without one nothing says which plan the reviewer read. No database was
	// used and nothing has executed.
	ErrAllowDestructiveNeedsFingerprint = errors.New(
		"the destructive acknowledgement on a desired-state run is valid only with the fingerprint of the plan that was reviewed; nothing was executed")
)
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 ErrBlockWritesMismatch = errors.New("the block-writes acknowledgement must name the resolved target table")

ErrBlockWritesMismatch means the block-writes acknowledgement named a table other than the statement's resolved target. Nothing has executed. The error is an AcknowledgementMismatchError carrying both tables.

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 ErrConnectionRequired = errors.New(
	"Options.Connection must name the database the pool was dialed with; the partitioned index build opens its table lock session from it")

ErrConnectionRequired is returned by Run and RunDesired when a statement is a CREATE INDEX on a partitioned table and Options.Connection is unset. The partitioned index build takes the parent's table lock on a dedicated session of its own, so it 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: RunDesired checks it for the whole plan before its first statement, and Run before the statement's first step.

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 ErrEnumValueAcknowledgement = errors.New("the acknowledgement does not apply to ALTER TYPE ... ADD VALUE")

ErrEnumValueAcknowledgement means an acknowledgement was given for an ALTER TYPE ... ADD VALUE, which none of the table acknowledgements apply to. Nothing has executed.

View Source
var ErrForceMismatch = errors.New("the force acknowledgement must name the resolved target table")

ErrForceMismatch means the force acknowledgement named a table other than the statement's resolved target. Nothing has executed. The error is an AcknowledgementMismatchError carrying both tables.

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.

View Source
var ErrRestartMismatch = errors.New("the restart acknowledgement must name the resolved target table")

ErrRestartMismatch means the restart acknowledgement named a table other than the statement's resolved target. Nothing has executed. The error is an AcknowledgementMismatchError carrying both tables.

View Source
var ErrRestartNotSupported = errors.New(
	"the restart acknowledgement applies to the imperative front door only; desired-state execution resumes a stopped run and never starts one over")

ErrRestartNotSupported is returned by RunDesired when Options.CopySwap.Restart is set. The acknowledgement names one run to discard, but on the declarative front door the derived plan, not the operator, decides which statements take copy-and-swap and so which run the acknowledgement would discard; a value left on an embedder's configuration would throw away a stopped run's checkpoint, shadow, and fence or slot on every later plan, and a plan whose statements route elsewhere would fail on the acknowledgement after an earlier statement committed. Starting a run over belongs on the imperative front door, where the operator names the statement and the table together.

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 a gate refusal that needs the database (GateReadsCatalog names the other). Run does not accept a concurrent form even when this reports true: the passthrough's transaction cannot run it.

func Acknowledgements added in v0.5.4

func Acknowledgements() []string

Acknowledgements returns the name of every typed acknowledgement the engine takes, in the order RunDesired rejects them: "force", "accept-blocking", "allow-destructive", "restart", "block-writes", and any added later. Each name is also the migrate command's flag for it, so renaming a flag changes this list; before v1 it carries no compatibility promise. An orchestrator that maps its own approval switches onto the engine's acknowledgements can assert every one is reachable. Each call returns a fresh slice, so changing it changes nothing else.

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 AdmitPartitionedIndexRequest added in v0.5.5

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

AdmitPartitionedIndexRequest is AdmitRoutedSteps for a statement routed to the partitioned index build, whose one step is the CREATE INDEX itself: it runs the build's own static admission, so an unnamed or IF NOT EXISTS index is refused in the dry run as it is in the run.

func AdmitPartitionedUniqueIndex added in v0.5.5

func AdmitPartitionedUniqueIndex(ctx context.Context, pool *pgxpool.Pool, st statement.Statement, schema string, steps []string) (verdict.Verdict, bool, error)

AdmitPartitionedUniqueIndex is the catalog half of the partitioned index build's admission, for a statement AdmitPartitionedIndexRequest admitted: a unique index whose plain key columns do not contain the partition key of the target and of every sub-partitioned partition is refused, read from the live catalog on pool, as the build refuses it under its table lock before it creates anything. A host that plans through the library calls it with a pool from pkg/dbconn to learn that refusal without running the build. The verdict, the boolean, and the error mean what they mean for AdmitRoutedSteps.

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 CheckDesiredAllowDestructiveTable added in v0.5.5

func CheckDesiredAllowDestructiveTable(allow string, report plan.Report) error

CheckDesiredAllowDestructiveTable is the check a desired-state run makes on its destructive acknowledgement once the plan is derived and before anything runs: it must name the table report converges, whether or not the plan drops anything, so an acknowledgement left on a script cannot reach another table. A caller that previews a run calls it first so the preview fails the way the run would. The error is an AcknowledgementMismatchError matching ErrAllowDestructiveMismatch.

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: schemachange.MinPoolConns, the size the Runner itself holds every run to, named here so a host that builds its pool for Run or RunDesired (dbconn.Config.MaxConnsFloor) sizes it from the package it calls. Run and RunDesired refuse a smaller pool before the preflight.

func DesiredFileRefusal added in v0.5.5

func DesiredFileRefusal(err error, sql string) (verdict.Verdict, bool)

DesiredFileRefusal reports whether err is a refusal of the desired file itself, returned by statement.ParseDesiredFile before anything is planned, by the planner while it builds the desired table, or by the diff for a change it does not derive, and returns the refusal verdict for it. sql is the refused statement when err does not name one (the file's CREATE TABLE for a planner refusal); a parse refusal that names its statement reports that one instead. ok is false for every other error, including a syntax error, which is an input error and not a refusal.

func Gate

Gate is the statement-type gate without the catalog; for a single-index DROP INDEX its verdict is provisional, and the final one comes from GateWithCatalog. 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 — except for the statements GateReadsCatalog names, whose refusal GateWithCatalog completes from the catalog; Run re-checks it regardless.

func GateReadsCatalog added in v0.5.5

func GateReadsCatalog(st statement.Statement) bool

GateReadsCatalog reports whether Gate's refusal of st is provisional until the catalog is read: a DROP INDEX of exactly one index, plain or CONCURRENTLY. Whether its concurrent idiom exists depends on the index — PostgreSQL has no concurrent drop for an index of a partitioned table, and will not drop an index attached under a parent index on its own — and only the catalog says which kind of index the name resolves to. A front door that refuses gated statements before dialing must dial for this one and take its refusal from GateWithCatalog (which Run calls) instead.

func GateWithCatalog added in v0.5.5

func GateWithCatalog(ctx context.Context, pool *pgxpool.Pool, st statement.Statement) (verdict.Verdict, bool, error)

GateWithCatalog is Gate with the catalog read GateReadsCatalog calls for. For a single-index DROP INDEX it reads the named index on the pool's search_path: an index attached under a parent index is refused as a drop PostgreSQL never runs, naming the root partitioned index to drop instead; a partitioned index is refused without the concurrent idiom PostgreSQL rejects for it, naming the bounded plain drop. Every other statement, a plain index, and a name that resolves to no index keep Gate's verdict. It executes nothing.

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 executors, including the creation proofs and create-path admission of a table created with its row security. Operational errors are not refusals. Privilege causes take priority over the general admission sentinel they also wrap. The executor builds the declaration on the same scratch schema as RunDesired, so a desired-file shape refusal is classified the same way on both paths.

func Run

func Run(ctx context.Context, pool *pgxpool.Pool, st statement.Statement, opts Options) (v verdict.Verdict, err error)

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, the kind of an index a DROP INDEX names, 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).

With Options.Progress set, Run reports to it as a run of one step: it starts the tracker with operation admitting while it gates, resolves, routes, and preflights, reports the statement as step 1 once it executes, and finishes the tracker as it returns — finished for an executed verdict, failed for a refusal or a failure. While the step runs the detail names what is executing now: each statement of a safer sequence in turn with its own operation, a concurrent index build with the server's build counters, and for a copy-and-swap the copy, a live run's catch-up, and the verification pass, each with its counters.

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

func WithServerError added in v0.5.1

func WithServerError(v verdict.Verdict, err error) verdict.Verdict

WithServerError records on a failed verdict the server error that failed it: the SQLSTATE and primary message of the first *pgconn.PgError in err's chain, the same text the returned error prints. A verdict that did not fail, or a failure that was not a server error, is returned unchanged. Run and RunDesired apply it to their own verdicts; a caller that builds a failed verdict itself, such as the CLI's row-security path, applies it after classifying refusals.

Types

type AcknowledgementMismatchError added in v0.5.4

type AcknowledgementMismatchError struct {
	// Acknowledgement is the acknowledgement's name as [Acknowledgements]
	// spells it, such as "force".
	Acknowledgement string
	// Table is the table the acknowledgement must name — the resolved
	// target, or for "accept-blocking" the table the statement locks — in
	// the engine's flat SCHEMA.TABLE spelling: an unquoted name folded to
	// lower case, a quoted one kept as written, with no quoting added, so it
	// is what the operator must type and cannot be split back into schema
	// and table. It is empty for a statement that names no table, which no
	// acknowledgement value matches.
	Table string
	// Given is the value the acknowledgement carried.
	Given string
	// LockingStatement is, for "accept-blocking", the kind of the statement
	// whose lock the acknowledgement accepts, which the message names; it is
	// the zero Kind for every other acknowledgement.
	LockingStatement statement.Kind
}

AcknowledgementMismatchError is the usage error Run returns when a typed acknowledgement names a table other than the one it must name. Nothing has executed. It unwraps to the acknowledgement's own sentinel — ErrForceMismatch, ErrAcceptBlockingMismatch, ErrAllowDestructiveMismatch, ErrRestartMismatch, or ErrBlockWritesMismatch — so errors.Is answers that sentinel and no other. An adapter that asks whether an error is any wrong-table acknowledgement uses errors.As once, and one that shows the operator what they gave and what the target is reads the fields rather than the message.

The engine builds it; a value built elsewhere, such as in an adapter's tests, behaves the same only when Acknowledgement is spelled exactly as Acknowledgements returns it, and for "accept-blocking" sets LockingStatement.

func (*AcknowledgementMismatchError) Error added in v0.5.4

Error implements the error interface.

func (*AcknowledgementMismatchError) Unwrap added in v0.5.4

func (e *AcknowledgementMismatchError) Unwrap() error

Unwrap returns the acknowledgement's own mismatch sentinel, or nil when Acknowledgement is not one Acknowledgements returns.

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 {
	// Enabled opens the copy-and-swap route. The route is in preview: it
	// has not been exercised under production-like load, so a caller opts
	// into it deliberately, per run, rather than reaching it by default
	// whenever the router assigns a statement to the backend. While it is
	// false, a statement the router assigns to copy-and-swap is refused
	// with reason copy-and-swap-refused and cause
	// copy-and-swap-not-enabled before the route's preflight runs or
	// anything is written, on both front doors (target resolution and
	// planning still read the catalog ahead of the gate); Options.Force
	// still runs the statement natively, as it does with the route open.
	// The CLI sets it from --copy-and-swap.
	Enabled bool

	// 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, or, for a live run, when they and
	// SlotLagCeilingBytes of retained WAL would not fit together. A run
	// that resumes a stopped one is asked only for what is left to grow:
	// the shadow the stopped run built and the WAL its slot retains, both
	// read from the server, are subtracted, since the measured free space
	// already excludes them. 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; a value naming
	// any other table returns [ErrBlockWritesMismatch], an [AcknowledgementMismatchError]. 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 value naming any other table returns [ErrRestartMismatch], an [AcknowledgementMismatchError]. 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. Run takes it; RunDesired rejects any
	// value with ErrRestartNotSupported.
	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; so is a Copier.Pace, which a live run
	// sets itself from its stream's lag. The workers set the pool size the
	// route admits: CopySwapMinConns(Copier).
	//
	// Options.Progress is the way to observe the whole run: it reports the
	// copy, a live run's catch-up, and the verification pass, each as the
	// statement's step with its own counters, and Copier.Tracker must then
	// be left nil. Without it, 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

	// SlotLagCeilingBytes is the WAL, in bytes, a live run's replication
	// slot may hold before the catch-up stops the run with a
	// *decode.SlotLagExceededError, leaving the slot and the checkpoint row
	// for the next run to resume from (applier.CatchupOptions.SlotLagCeiling).
	// Zero takes decode.DefaultSlotLagCeiling, one GiB; a negative value is
	// refused before anything is read. The preflight counts the ceiling,
	// the default included, against FreeDiskBytes beside the shadow. A run
	// that blocks writes holds no slot and does not read it. A live run
	// needs a ceiling above about a release interval and a catch-up cycle
	// of the cluster's WAL, with margin, or it stops wal-retained while its
	// stream keeps up. The CLI sets it from --slot-lag-ceiling.
	SlotLagCeilingBytes int64

	// 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 keeps the route closed: Enabled is the opt-in, and a statement that reaches the closed route is refused. An opened route needs the connection the pool was built from, not the pool alone, because it opens dedicated sessions of its own — the table lock, the copy workers, the replication stream.

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
	// AllowDestructive lets a plan that drops live structure run: it names
	// the desired table, schema-qualified. It is valid only with
	// ExpectedFingerprint, so it covers the destructive statements of the
	// reviewed plan and no others: without a fingerprint the request fails
	// with [ErrAllowDestructiveNeedsFingerprint] before any database work,
	// and another table fails with [ErrAllowDestructiveMismatch] before
	// anything runs. Each destructive statement then runs through [Run] with
	// the acknowledgement it needs, so Run's per-statement gate, audit
	// record, and AllowedDestructive verdict apply unchanged; a dropped index
	// runs as DROP INDEX CONCURRENTLY. It is separate from
	// Options.AllowDestructive, which desired-state execution still rejects.
	AllowDestructive 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"`
	// Cause narrows the refusal reason to its typed discriminator, the
	// same token the statement verdict would carry: the copy-and-swap
	// gate or preflight cause of a whole-plan refusal at admission, or the
	// cause of the statement verdict that stopped execution. Empty when
	// the reason has none or Outcome is not refused.
	Cause verdict.Cause `json:"cause,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 AdmitPlan added in v0.5.5

func AdmitPlan(req DesiredRequest, report plan.Report) (DesiredResult, bool)

AdmitPlan is the all-or-nothing plan-time admission: it refuses the whole plan — before anything runs — when the plan cannot converge the table as a unit. The checks run from the caller's contract outward: the pinned fingerprint first (the caller's approval is void whatever else holds), then the destructive guard, then the routed dispositions. An empty (already-converged) plan never reaches admission: the caller resolves it first, because it carries no plan identity for the pin to verify and nothing would run anyway.

A plan holding destructive statements is admitted only when the request names the desired table in AllowDestructive; the pin check above has already bound that acknowledgement to the reviewed plan. A partitioned parent's index drop and a destructive statement that carries no definition of what it drops are refused even when the run is acknowledged: the first so the operator gets its specific guidance, the second so the refusal comes before any statement runs.

func CheckPlanPin added in v0.5.5

func CheckPlanPin(expected string, report plan.Report) (DesiredResult, bool)

CheckPlanPin is the pin check every desired-state run makes before anything else: when expected is set, report must be the plan it pins, or it returns the run's refusal and false. An empty plan has no identity to verify and always passes. A dry run calls it to report a stale pin as the run would.

func RunDesired

func RunDesired(ctx context.Context, pool *pgxpool.Pool, req DesiredRequest, opts Options) (result DesiredResult, err 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 without the request's destructive acknowledgement, 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. A plan that builds an index on a partitioned table stops whole, with ErrConnectionRequired or a PartitionedIndexConnectionMismatchError, when Options.Connection is unset or reaches another database than the pool. 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.

Every typed acknowledgement in the options — Options.Force, AcceptBlocking, AllowDestructive, CopySwap.Restart and CopySwap.BlockWrites — is rejected with its own sentinel, the first set in that order when several are, before the policy is validated: each accepts a loss for one statement the operator wrote, and the declarative front door runs statements the plan derived. A blocking, force-worthy, restarted or offline change belongs on the imperative front door where the operator states it explicitly. Options.WithoutAcknowledgements is the policy with all of them cleared.

The one acknowledgement desired-state execution takes is DesiredRequest.AllowDestructive, which is valid only with ExpectedFingerprint; each destructive statement of the pinned plan then runs through Run with the acknowledgement it needs.

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

With Options.Progress set, RunDesired reports to it as a run whose steps are the planned statements: the tracker stays pending while the plan is derived, starts with operation admitting for as many steps as the plan has statements, reports planned statement N as step N while it executes — with the detail Run reports for a statement of its own — and finishes as RunDesired returns: finished for an executed result, failed for a refused or failed one. A create reports each statement of the desired file as its step.

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

func RunDesiredEnumType added in v0.5.5

func RunDesiredEnumType(ctx context.Context, pool *pgxpool.Pool, req EnumTypeRequest, opts Options) (result DesiredResult, err error)

RunDesiredEnumType converges one live enum type onto its desired file: derive the plan with diffplan.PlanEnumType, admit it as a whole, then run each planned ALTER TYPE ... ADD VALUE back through the full Run pipeline, which resolves the type, checks the role may alter it, and confirms before each commit that the label reached that type. Each label commits on its own; a later refusal or failure leaves the earlier labels added, and the verdicts say how far the run got.

A missing type, a name that holds another kind of type, and a file that drops or reorders a live label are refused before anything runs, as is a plan whose fingerprint is not the pinned one. Convergence is verified, not assumed: after the last label commits, the plan is derived again and the run is executed only when it is empty.

The result-and-error contract, the rejection of every acknowledgement, and the progress reporting are RunDesired's. RunDesiredEnumType does not close the pool.

func RunDesiredWithRowSecurity added in v0.5.1

func RunDesiredWithRowSecurity(ctx context.Context, pool *pgxpool.Pool, req RowSecurityRequest, opts Options) (result DesiredResult, err error)

RunDesiredWithRowSecurity converges an existing table onto a desired file that declares row security when the live row security already matches the file and only the table definition differs. It runs the table definition's plan through RunDesired, so every statement keeps RunDesired's admission, per-statement gates, and committed-prefix semantics, and it never changes the table's row security.

The row security is checked before and after. Before: the plan is derived with diffplan.PlanWithRowSecurity, and a file whose row security differs from the live table is refused before anything runs. A file that changes only the row security is converged by executor.ExecuteDesiredRowSecurity instead, which replaces it in one transaction; a file that changes both is refused on either path. A table that does not exist is refused too: the executor creates it with its row security in one transaction. After: the run is executed only when the same comparison, derived again after the last commit, is empty. Another session can change the policies while the table plan runs; the run then reports that the row security no longer matches rather than claiming convergence, and every table statement stays committed. The comparison is made again even when the delegated run found nothing to do, since the table can change between the two plans. The delegated run only converges a table that exists: if the table is dropped before it plans, it is refused, so it is never created without its row security.

The result-and-error contract is RunDesired's, and so is the progress Options.Progress receives; the tracker finishes once the row security has been compared again.

type EnumTypeRequest added in v0.5.5

type EnumTypeRequest struct {
	// Schema is the schema the enum type lives in.
	Schema string
	// Desired is the parsed desired enum type.
	Desired statement.DesiredEnumType
	// ExpectedFingerprint optionally pins the plan, as
	// DesiredRequest.ExpectedFingerprint does.
	ExpectedFingerprint string
}

EnumTypeRequest names the inputs to RunDesiredEnumType. Zero-value fields are invalid: the schema must be set, and the desired state must come from statement.ParseDesiredFile.

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 and policies depend on each column (preflight.ReadColumnDependents), and for one that adds columns, has the server prove whether each one rewrites the table (preflight.AddColumnRewrites), and for each of those with no DEFAULT of its own whether it is NOT NULL, as spelled or through its domain or an inline PRIMARY KEY, and the table holds a row it would be NULL in (preflight.NullFilledColumns). 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. A value naming any other table returns
	// [ErrForceMismatch], an [AcknowledgementMismatchError]. 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. A
	// value naming any other table returns [ErrAcceptBlockingMismatch], an [AcknowledgementMismatchError].
	// 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. A value naming any other table
	// returns [ErrAllowDestructiveMismatch], an [AcknowledgementMismatchError]. 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 is
	// refused unless CopySwap.Enabled opens the route, and cannot run
	// without CopySwap.Connection.
	CopySwap CopySwapOptions

	// Connection is the connection target the run opens dedicated sessions
	// from when a statement needs one the pool cannot supply: a CREATE INDEX
	// on a partitioned table takes the parent's table lock on a session of its
	// own. It must reach the database the pool was dialed with, which the run
	// proves before it opens anything; a run that needs it and finds it unset
	// returns [ErrConnectionRequired]. The CLI always sets it. A statement
	// that needs no dedicated session never reads it.
	Connection dbconn.Config

	// Logger receives decision diagnostics (routing, preflight, execution
	// transitions) at Debug; nil discards them. A copy-and-swap's catch-up
	// also writes Info and Warn records here when it requeues a batch
	// (applier.CatchupOptions.Logger lists 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

	// Progress, when set, is the tracker the whole call reports to, for the
	// caller to poll from another goroutine while the call runs; nil
	// reports nothing. The call owns the tracker's lifecycle: it calls
	// Start and Finish, and one tracker serves one call at a time. See
	// [Run] and [RunDesired] for the steps each reports. It replaces
	// CopySwap.Copier.Tracker, which must be left nil when it is set.
	Progress *progress.Tracker
}

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.

func (Options) Acknowledgements added in v0.5.4

func (o Options) Acknowledgements() []string

Acknowledgements returns the name, as Acknowledgements spells it, of every typed acknowledgement o carries, in the same order, or nil when o carries none. An adapter calls it before Options.WithoutAcknowledgements to learn which of an operator's acknowledgements the desired-state view sets aside. Each call returns a fresh slice.

func (Options) WithoutAcknowledgements added in v0.5.1

func (o Options) WithoutAcknowledgements() Options

WithoutAcknowledgements returns a copy of o with every typed acknowledgement cleared — Force, AcceptBlocking, AllowDestructive, CopySwap.Restart, CopySwap.BlockWrites, and any added later — and every other field unchanged. It is the desired-state front door's view of a policy: an adapter that builds one Options for both front doors passes RunDesired o.WithoutAcknowledgements(), which RunDesired never rejects for an acknowledgement. o itself is not modified. The view drops an operator's consent without reporting it: an adapter that must not lose one calls Options.Acknowledgements on o first, which names every acknowledgement the view sets aside, and the desired-state door's own refusals still apply.

type PartitionedIndexConnectionMismatchError added in v0.5.5

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

PartitionedIndexConnectionMismatchError is returned by Run and RunDesired when Options.Connection reaches a database other than the one the pool was dialed with. The build 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 would not keep a second run off the table. Nothing has been executed when it is returned; it is a wiring mistake that no retry corrects, so match it with errors.AsType and fix the wiring rather than routing it as an outcome. A database is told from another by the cluster's system identifier together with the database name, which is unique only within a cluster. Both identifiers are stable fingerprints of a server, so a caller that posts results to a shared surface logs the fields and shows a fixed line rather than the raw text.

func (*PartitionedIndexConnectionMismatchError) Error added in v0.5.5

Error implements the error interface.

type RowSecurityRequest added in v0.5.1

type RowSecurityRequest struct {
	// Schema is the target schema the desired table lives in.
	Schema string
	// Desired is the parsed desired file, table definition and row security.
	Desired statement.DesiredWithRowSecurity
	// ExpectedFingerprint optionally pins the plan, as
	// DesiredRequest.ExpectedFingerprint does. The plan is the table
	// definition's plan, so it is the fingerprint
	// diffplan.PlanWithRowSecurity reported.
	ExpectedFingerprint string
	// AllowDestructive names the desired table, schema-qualified, to let
	// the table definition's destructive statements run, exactly as
	// DesiredRequest.AllowDestructive does for a table file: valid only with
	// ExpectedFingerprint, and applying to the table definition's plan alone.
	// It never reaches the row security, which this path does not change.
	AllowDestructive string
}

RowSecurityRequest is a desired file that declares row security, for RunDesiredWithRowSecurity.

Jump to

Keyboard shortcuts

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