executor

package
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 20 Imported by: 2 modules, 1 package

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 executor runs schema changes against the database. It holds the optimistic front door — attempt the change directly under a tight lock_timeout and statement_timeout so it can only succeed if it is effectively an instant / in-place change; a budget overrun cancels the statement cleanly, nothing is executed, and a typed BudgetError surfaces for the caller to turn into a not-native-safe verdict — and the native executors for the classified safe idioms, starting with the concurrent index build (BuildIndexConcurrently). The files of the concurrent index creation path — the build, its budget, its typed refusals, the backend inspection, and the invalid-index outcome — carry the cic_ prefix.

This is a safety-critical core package: see SAFETY.md. It never trusts the caller's classification — its own protections are the budget, applied with SET LOCAL inside the attempt's transaction regardless of session defaults, and the statement binding: it accepts only a parsed statement.Statement (exactly one statement by construction) whose target matches the preflighted table (invariant ST-7).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidBlockingBudget means an accepted-blocking bound would be
	// disabled, cannot be represented by PostgreSQL, or is not longer than
	// the lock bound it is meant to outlast.
	ErrInvalidBlockingBudget = errors.New("invalid accepted-blocking budget")
	// ErrUnsupportedAcceptedBlocking means the statement is not one of the
	// single-relation blocking index forms this executor admits, the server
	// will not run it inside the engine-owned transaction, or it drops a
	// replica identity index. Retrying the same statement reproduces it;
	// the outcome is permanent.
	ErrUnsupportedAcceptedBlocking = errors.New("statement is not an accepted blocking index statement")
)
View Source
var (
	// ErrNotConcurrentIndexBuild is returned when the statement is not a
	// single CREATE INDEX ... CONCURRENTLY.
	ErrNotConcurrentIndexBuild = errors.New("statement is not a CREATE INDEX CONCURRENTLY")
	// ErrUnnamedIndex is returned when the concurrent build does not name
	// its index: without a deterministic identity there is no idempotent
	// way to find and recover the invalid leftover of a failed build.
	ErrUnnamedIndex = errors.New("concurrent index build must name its index")
	// ErrUnqualifiedTable is returned when the target table is not
	// schema-qualified. The post-failure catalog verdict re-resolves the
	// table on another session, where search_path cannot be proven
	// identical to the build session's — an unqualified name could resolve
	// to a different table and turn the verdict into a false clean.
	ErrUnqualifiedTable = errors.New("concurrent index build must schema-qualify its table")
	// ErrIfNotExistsUnsupported is returned for any CREATE ... IF NOT
	// EXISTS. The clause checks only the name: it succeeds as a no-op
	// while an unrelated relation — or, for a concurrent build, an
	// invalid index — owns that name, so an executor could report
	// success over a relation it cannot vouch for.
	ErrIfNotExistsUnsupported = errors.New(CreateShapeIfNotExists.Description())
	// ErrInvalidIndexBuildInFlight is returned (inside an *InvalidIndexError
	// carrying the builder's PID) when the invalid index under the
	// requested name is another backend's concurrent build still in
	// progress: pg_stat_progress_create_index reports a live command on
	// that exact index OID. A concurrent build is invalid until it
	// finishes, so the entry may be healthy and hours in; nothing here may
	// touch it, and the build refuses because the name is occupied. The
	// answer is to wait for the builder to finish or fail (see
	// docs/invalid-index-recovery.md).
	ErrInvalidIndexBuildInFlight = errors.New("an invalid index with this name is another backend's concurrent build still in progress")
	// ErrAbandonedInvalidIndex is returned (inside an *InvalidIndexError)
	// when an invalid index under the requested name sits on the target
	// table with no backend building it: the debris of an earlier failed
	// build, this executor's or anyone's. It cannot become valid on its
	// own, so the build refuses — the name is occupied — but the state is
	// recoverable: RebuildAbandonedIndex proves the abandonment under lock,
	// removes the entry, and builds the requested index.
	ErrAbandonedInvalidIndex = errors.New("an abandoned invalid index with this name already exists on the target table")
	// ErrInvalidIndexOnOtherTable is returned (inside an *InvalidIndexError)
	// when the invalid index under the requested name sits on a different
	// table in the target schema, with no backend building it. A failed
	// build's debris carries the requested name whatever table it ended up
	// on, so the build refuses; but another table's debris is not this
	// change's to remove — the recovery refuses it too, and that table's
	// own change recovers it.
	ErrInvalidIndexOnOtherTable = errors.New("an invalid index with this name exists on a different table in the target schema")
	// ErrInvalidIndexNotDroppable is returned (inside an *InvalidIndexError)
	// when the invalid index under the requested name sits on the target
	// table but is not an index DROP INDEX CONCURRENTLY can remove: a
	// partitioned table's index (invalid by design until every partition
	// has an attached index, the documented CREATE INDEX ... ON ONLY
	// workflow), an index partition attached to such a parent, or an index
	// backing a constraint. None of these is the debris of a failed
	// concurrent build whatever its validity flag says, and no recovery
	// here can be proven through to a removal, so the build refuses and
	// the recovery leaves the entry exactly as it found it — only an
	// operator who knows what the index is can decide.
	ErrInvalidIndexNotDroppable = errors.New("an invalid index with this name exists on the target table and is not a droppable index: it is a partitioned table's index, an index partition, or backs a constraint")
	// ErrInvalidIndexBuilderUnobservable is returned (inside an
	// *InvalidIndexError) when an invalid index under the requested name
	// sits on the target table, no backend is visibly building it, and
	// this session cannot vouch for that silence: pg_stat_progress_create_index
	// withholds every column but the PID and database of another role's
	// command from a reader without pg_read_all_stats, and records nothing
	// at all for a session running with track_activities off. The entry may
	// be abandoned or may be a build in progress that this role cannot see,
	// so the build refuses without claiming either. The state is still
	// recoverable: RebuildAbandonedIndex proves abandonment under the table
	// lock every concurrent index command holds, which no visibility rule
	// can hide. An operator with pg_read_all_stats can classify it exactly.
	ErrInvalidIndexBuilderUnobservable = errors.New("an invalid index with this name exists on the target table and this role cannot observe whether a backend is building it")
	// ErrBuildLeftInvalidIndex is returned (inside an *InvalidIndexError)
	// when this executor's own build left an invalid catalog entry behind:
	// after a failure, once the build's backend provably stopped, or after
	// a reported success whose validity verification found the entry
	// invalid. The build never removes it in the same call: PostgreSQL
	// drops by name, not identity, so a drop without a fresh ownership
	// proof could destroy another actor's index registered under the same
	// name in the same window. The recovery is RebuildAbandonedIndex, which
	// carries that proof, or the operator's explicit DROP INDEX
	// CONCURRENTLY (see docs/invalid-index-recovery.md). A build that
	// failed on its rows is not recoverable until they are corrected
	// ((*InvalidIndexError).Recoverable).
	ErrBuildLeftInvalidIndex = errors.New("the build left an invalid index behind")
	// ErrAbandonmentUnproven is returned (inside an *InvalidIndexError)
	// when a recovery could not carry its proof through to the removal:
	// the entry changed name or identity between two verification points,
	// or the drop left it in place. Nothing was destroyed; the state is
	// indeterminate and fails closed, and a later recovery starts over.
	ErrAbandonmentUnproven = errors.New("the invalid index could not be proven abandoned through to its removal")
	// ErrTargetIdentityChanged is returned (inside an *InvalidIndexError)
	// when the target table no longer resolves to the OID the build was
	// admitted against: it was dropped, replaced, or renamed while the
	// build ran. The catalog can no longer prove whether the failed build
	// left debris — the verdict is indeterminate, and indeterminate fails
	// closed.
	ErrTargetIdentityChanged = errors.New("the target table was dropped or replaced during the build: the catalog cannot prove whether the failed build left an invalid index")
	// ErrTableNotFound is returned when the statement's qualified table
	// resolves to nothing before the build starts; it distinguishes a
	// missing table from an inspection failure so callers can branch with
	// errors.Is instead of matching message text.
	ErrTableNotFound = errors.New("table not found")
	// ErrPoolTooSmall is returned at admission when the pool cannot hold
	// every session the operation needs at once — for a build, the build
	// session and the verdict session (buildMinConns); for a rebuild
	// recovery, its own session on top of those (recoveryMinConns); for a
	// drop-only recovery, its own session and one drop session
	// (dropRecoveryMinConns). The message names the sessions the refused
	// operation holds at its peak. The verdict is a correctness
	// dependency, not a nicety: without a reserved connection, every
	// failed build would resolve indeterminate, and a pool one connection
	// short would not fail but wait on itself for as long as the caller's
	// context allows. Like an unbounded budget, an unusable pool is
	// refused by construction. The copy-and-swap front door
	// (pkg/migrate) wraps it too, for a pool that cannot hold the copy's
	// workers beside the catch-up's flushes and the checkpoint saves.
	ErrPoolTooSmall = errors.New("the pool cannot hold every session the operation needs at once")
	// ErrCallerOwnedNeedsCancellableContext is returned when caller-owned
	// mode has no cancellation signal to bound the statement.
	ErrCallerOwnedNeedsCancellableContext = errors.New("a caller-owned build needs a cancellable context: with statement_timeout disabled the context is the statement's only bound")
	// ErrCallerOwnedOverallBudget is returned when a caller-owned budget
	// also carries a server deadline: the two bounds would contradict each
	// other, so the combination is refused before any session is acquired.
	ErrCallerOwnedOverallBudget = errors.New("a caller-owned build has no server deadline: Overall must be zero")
	// ErrUnboundedBudget is returned when the overall budget would leave
	// the statement without a working statement_timeout.
	ErrUnboundedBudget = errors.New("the overall budget would leave the statement unbounded")
	// ErrCancelledByCaller is returned when the build's statement was
	// cancelled because the caller's own context ended — cancelled or past
	// its deadline — while the statement ran. The cancellation reaches the
	// executor in one of two forms, the server's SQLSTATE 57014 or the
	// client's context error, and both are typed the same way: the cause is
	// the caller, in either budget mode — with one precedence in bounded
	// mode: a 57014 arriving once the overall budget has elapsed is the
	// budget's statement_timeout firing and is typed *BudgetError even if
	// the caller's context ended in the same instant, so the server's 57014
	// is the caller's only below the budget. An orchestrator reads this
	// error as its own lease lapsing, not as an operator's intervention
	// (ErrCancelledExternally).
	ErrCancelledByCaller = errors.New("the build was cancelled by its caller's context")
	// ErrCancelledExternally is returned when the build's statement was
	// cancelled (SQLSTATE 57014) while the caller's context was still live
	// and, in bounded mode, before its overall budget elapsed: neither the
	// caller nor the executor's statement_timeout can have done it, so the
	// cancellation came from outside — an operator's pg_cancel_backend, an
	// administrative tool. In caller-owned mode there is no server deadline,
	// so every 57014 under a live context is external. It is deliberately
	// not a *BudgetError: a budget exhaustion invites escalation to a
	// heavier strategy, while a deliberate cancel usually means the change
	// should be left alone.
	ErrCancelledExternally = errors.New("the build was cancelled from outside the executor")
)

Typed admission refusals for the concurrent index build. The executor re-verifies the statement shape itself — a caller's classification is a request, not a proof (see SAFETY.md).

View Source
var (
	// ErrCreateCollision is returned when a claimed name is already taken.
	// A catalog probe after admission checks the desired file's explicit
	// index names and first-choice constraint-index and sequence names before
	// the first step executes, refusing the whole set with no *SequenceStepError;
	// duplicate-name SQLSTATEs backstop time-of-check races for explicit
	// names and arrive wrapped in one. Server-chosen names have no such
	// backstop. The remedy is on the desired file's side — drop or rename the
	// occupant, name a constraint's index explicitly, or for a sequence use
	// an explicitly named sequence or a non-serial column —
	// then re-diff; a re-plan alone reproduces the refusal.
	ErrCreateCollision = errors.New("a name the create path needs is already taken")
	// ErrDuplicateCreateName is returned when the desired set claims the
	// same relation name twice — two indexes under one name, or an index
	// named after the table. The conflict is decidable before anything
	// runs, so admission refuses the whole set rather than letting a
	// mid-run step fail after a prefix committed.
	ErrDuplicateCreateName = errors.New(CreateShapeDuplicateName.Description())
	// ErrPartitionOfUnsupported is returned for CREATE TABLE ... PARTITION
	// OF: attaching a partition takes a lock on the partitioned parent,
	// an existing table the absence proof says nothing about.
	ErrPartitionOfUnsupported = errors.New(CreateShapePartitionOf.Description())
	// ErrUnsupportedCreateStep is returned when a desired statement is not
	// a shape the create path can run: a plain CREATE TABLE or a plain
	// CREATE INDEX on the new table. CONCURRENTLY is refused deliberately —
	// the table is born this run with no traffic to protect, and a plain
	// build cannot leave an INVALID index behind a failure.
	ErrUnsupportedCreateStep = errors.New("statement is not a shape the create path can run")
	// ErrCreateNameMismatch is returned when the CREATE TABLE committed but
	// the table does not own a first-choice relation name the desired file
	// claimed. PostgreSQL never raises a duplicate-name error for a
	// constraint index or column-owned sequence whose first choice is taken
	// — it appends a numeric suffix — so an occupant that took the name
	// between the catalog probe and the step is visible only afterwards,
	// in the names the table actually owns. The run stops at the CREATE
	// TABLE with the table left in place: dropping a table this executor
	// just created is a destructive action the create path never takes.
	// The error arrives wrapped in a *SequenceStepError at step 1 as a
	// *CreateNameMismatchError naming the claimed names the table lacks
	// and the names it owns instead. The remedy is an operator's: free the
	// first-choice name and rename the owned relation to it, or drop the
	// table, then re-diff.
	ErrCreateNameMismatch = errors.New("the CREATE TABLE committed but the table does not own a first-choice relation name the desired file claims")
	// ErrCreateNamesUnverified is returned when the CREATE TABLE committed
	// but the read of the relation names the table owns did not complete,
	// so whether every first-choice claim was honoured is unknown. It wraps
	// the read's own error as the cause — a cancelled context, a lost
	// connection, a table no longer at its name — and arrives in a
	// *SequenceStepError at step 1 under its own code, with the table left
	// in place; an unproven name set is not a passing one, and the executor
	// never drops a table it has just created.
	ErrCreateNamesUnverified = errors.New("the CREATE TABLE committed but the relation names the table owns could not be read")
	// ErrCreateOwnerMismatch is returned when the committed table's catalog
	// owner differs from the creation-role proof. The executor never repairs
	// this invariant with ALTER OWNER.
	ErrCreateOwnerMismatch = errors.New("the CREATE TABLE committed with an unexpected owner")
	// ErrCreateOwnerUnverified is returned when the committed table's owner
	// could not be read back. The table is committed either way, and an
	// unproven owner is not a passing one.
	ErrCreateOwnerUnverified = errors.New("the CREATE TABLE committed but its owner could not be read")
)

Typed refusals and failures for the create path. Admission covers every desired statement before the first executes, so a creation this executor cannot finish is never started.

View Source
var (
	// ErrDetachDefaultPartition is the admission refusal of a concurrent
	// detach from a table that has a DEFAULT partition, which PostgreSQL
	// rejects in every supported version. Nothing is executed.
	ErrDetachDefaultPartition = errors.New("PostgreSQL cannot detach a partition concurrently from a table that has a DEFAULT partition")
	// ErrDetachInterrupted is returned when a concurrent detach stopped
	// after its first transaction committed. The partition is detach-pending:
	// queries through the table no longer read it and rows can no longer be
	// routed into it, but it is still in the partition tree until DETACH
	// PARTITION ... FINALIZE runs. Running the same step again finishes it.
	ErrDetachInterrupted = errors.New("the concurrent detach stopped after its first transaction committed, so the partition is detach-pending")
)

Typed outcomes of a DETACH PARTITION ... CONCURRENTLY step.

View Source
var (
	// ErrNotCreateIndex is returned when the statement is not a single
	// CREATE INDEX.
	ErrNotCreateIndex = errors.New("statement is not a CREATE INDEX")
	// ErrNotPartitionedTable is returned when the target is not a partitioned
	// table, at admission or when the catalog is read under the table lock. A
	// plain table's index is the concurrent build's job.
	ErrNotPartitionedTable = errors.New("the target is not a partitioned table")
	// ErrPartitionedIndexNameTaken is returned when a name the build needs is
	// held by a relation that is not the requested index: another kind of
	// relation, an index of another definition, or an index on another table.
	// The build never chooses another name and never drops what it did not
	// create, so the occupant is left for an operator.
	ErrPartitionedIndexNameTaken = errors.New("an index name the build needs is held by a relation that is not the requested index")
	// ErrForeignTablePartition is returned when the partition tree holds a
	// foreign table. It cannot carry an index, so the parent's index would
	// never become valid; the build refuses the whole tree before it creates
	// anything.
	ErrForeignTablePartition = errors.New("the partition tree holds a foreign table, which cannot carry an index")
	// ErrUniqueIndexPartitionKey is returned for a unique index that does not
	// contain the partition key of every partitioned table in the tree as
	// plain key columns. PostgreSQL checks each partitioned table on its
	// own, so the build refuses the whole tree before it creates anything
	// rather than fail at the first level that does not match.
	ErrUniqueIndexPartitionKey = errors.New("a unique index must contain the partition key of every partitioned table in the tree")
	// ErrTableLockUnconfirmed is returned when the pool's role cannot see
	// when the session holding the build's table lock started. The build
	// identifies that session by its PID and start time, so it refuses
	// before any step rather than accept a PID that another server could
	// share. Nothing was created.
	ErrTableLockUnconfirmed = errors.New("the pool cannot confirm that the build's own session holds the table lock")
	// ErrPartitionedIndexTablespace is returned when the statement has a
	// TABLESPACE clause. A partition's index is built from the definition the
	// server prints for the parent's index, and that definition never names a
	// tablespace, so the clause would place the parent's index and leave every
	// partition's index in the default tablespace. The build refuses the
	// statement before it creates anything.
	ErrPartitionedIndexTablespace = errors.New("a partitioned index build does not support a TABLESPACE clause")
	// ErrPartitionDetachPending is returned when the partition tree holds a
	// partition whose DETACH PARTITION CONCURRENTLY did not finish. The
	// server leaves that partition out when it attaches an index, so the
	// parent's index could never become valid, and out of a parent's column
	// drop, so it would keep its copy of the column; and a table detaches
	// one partition at a time, so a concurrent detach of another of its
	// partitions would fail. An operator finishes the detach with FINALIZE.
	ErrPartitionDetachPending = errors.New("the partition tree holds a partition whose detach has not finished")
	// ErrPartitionedIndexUnsettled is returned when partitions kept appearing
	// without an attached index for as long as the build's bounded number of
	// passes. What the build finished stays attached.
	ErrPartitionedIndexUnsettled = errors.New("partitions kept appearing without an index until the build ran out of passes")
)

Typed refusals for the partitioned index build. Each says what the catalog or the statement decided, so a caller branches on the cause, not on text.

View Source
var (
	// ErrPartitionedKeyNameTaken is returned when the name the step derives
	// for a leaf's index and constraint is held by something that is not the
	// requested key: another kind of relation, an index of another
	// definition or on another table, an index already attached to a
	// partitioned index or backing a constraint, or a constraint that is not
	// the requested key.
	ErrPartitionedKeyNameTaken = errors.New("the name the key constraint needs on a partition is held by something that is not the requested key")
	// ErrPartitionedKeyConflict is returned when the leaf already carries a
	// key constraint the step cannot reconcile with the requested one: two
	// constraints that each match it, a constraint on the same columns that
	// differs in kind or definition or is DEFERRABLE, one already attached to
	// a parent's constraint, or, for a primary key, a primary key on other
	// columns. The parent's constraint could adopt the wrong one, or the
	// server would refuse a second primary key, so the step adds nothing.
	ErrPartitionedKeyConflict = errors.New("the partition already has a key constraint that conflicts with the requested one")
	// ErrPartitionedKeyNullableColumn is returned when a primary key is
	// requested over a column the leaf allows to be NULL, including one whose
	// not-null constraint is NOT VALID (PostgreSQL 18). Adding the primary
	// key would set NOT NULL, which scans the whole partition while it holds
	// ACCESS EXCLUSIVE, so the step refuses before it builds anything.
	ErrPartitionedKeyNullableColumn = errors.New("a primary key column of the partition allows NULL, and setting NOT NULL would scan it under ACCESS EXCLUSIVE")
)

Typed refusals for giving a leaf partition the key constraint a partitioned parent's PRIMARY KEY or UNIQUE constraint adopts. Each says what the catalog decided, so a caller branches on the cause, not on text. The step never drops or renames an object it did not create, so each one leaves the leaf as it found it.

View Source
var (
	// ErrEmptySequence is returned for a sequence with no steps: reporting
	// success over nothing executed would be a false proof.
	ErrEmptySequence = errors.New("sequence has no steps")
	// ErrUnsupportedSequenceStep is returned when a step is not one of the
	// shapes this executor can run safely: an ALTER TABLE step, a lone
	// DETACH PARTITION ... CONCURRENTLY, or a CREATE INDEX CONCURRENTLY
	// step. The concurrent forms of other statements are refused
	// deliberately — a DROP INDEX CONCURRENTLY or REINDEX CONCURRENTLY is
	// not driven yet.
	ErrUnsupportedSequenceStep = errors.New("step is not a shape the sequence executor can run safely")
	// ErrUnsupportedPartitionedParent is returned when the target is a
	// partitioned parent and the admitted sequence is not supported there.
	ErrUnsupportedPartitionedParent = errors.New("sequence is not supported on a partitioned parent")
)

Typed admission refusals for the sequence executor. Admission covers the whole sequence before the first step executes, so a sequence that cannot be finished is never started.

View Source
var ErrAdoptedIndexDrift = errors.New("the index the constraint takes over changed after planning")

ErrAdoptedIndexDrift means the index a planned ADD CONSTRAINT ... USING INDEX takes over no longer has the definition the plan matched it against, read again under the table's lock: it was dropped, replaced under the same name, or left invalid after planning. Nothing was attached. The outcome is permanent: re-plan against the index as it stands.

View Source
var ErrAnalyzeForeignChild = errors.New("an inheritance child is a foreign table, which ANALYZE may skip")

ErrAnalyzeForeignChild means a table the refresh covers is a foreign table. Whether ANALYZE can sample one depends on its foreign-data wrapper, and a wrapper that cannot is skipped with only a warning, so the refresh refuses rather than report statistics it may never have refreshed. Nothing was analyzed.

View Source
var ErrAnalyzeNotPermitted = errors.New("the role cannot act as the table's owner, so ANALYZE would skip it")

ErrAnalyzeNotPermitted means the connected role cannot act as the owner of a table the refresh covers, so ANALYZE would skip it with only a warning and leave its statistics as they were. Nothing was analyzed.

View Source
var ErrDroppedColumnPartitionDependent = errors.New("the column the plan drops has an unreviewed dependent on a partition")

ErrDroppedColumnPartitionDependent means a reviewed column drop on a partitioned table would also remove an object a partition carries of its own and that uses the partition's copy of the column — an index, a CHECK or foreign key, a statistics object, an owned sequence, or any other object with a dependency on the column — read under the locks of the whole partition tree. The plan reviewed the parent's column and the parent's objects only, so nothing was dropped. Objects a partition holds as copies of the parent's — attached indexes, inherited constraints, cloned triggers — are the parent's reviewed objects and do not refuse. The outcome is permanent: drop or change the partition's own object first, then re-plan.

View Source
var ErrDroppedColumnPartitionKey = errors.New("the column the plan drops is part of a partition key")

ErrDroppedColumnPartitionKey means a reviewed column drop names a column that is part of the partition key of the partitioned table or of a sub-partitioned partition below it, read under the table's lock. PostgreSQL refuses to drop a partition key column at any level of the tree, so the drop cannot run; nothing was dropped. The outcome is permanent.

View Source
var ErrDroppedIndexDrift = errors.New("the index the plan drops changed after planning")

ErrDroppedIndexDrift means the index a reviewed plan drops is no longer the plain, valid index of the plan's table with the definition the plan carried: it is gone, belongs to another table, is invalid, is a partitioned table's index or an index partition, now backs a constraint, or is another index that took over its name. It is returned only from the read before the drop, so nothing was dropped. The outcome is permanent: re-plan and review the new plan.

View Source
var ErrDroppedIndexReplaced = errors.New("the drop removed an index the plan did not review")

ErrDroppedIndexReplaced means a drop that passed its pre-drop read dropped an index the plan did not review: another session gave the name to a different index in the round trip between the read and the drop, and the index that was read is still in the catalog. Unlike ErrDroppedIndexDrift, something was dropped; the operator inspects the table's indexes and recreates the one that was dropped if it should stay. The outcome is permanent.

View Source
var ErrDroppedObjectDrift = errors.New("the object the plan drops changed after planning")

ErrDroppedObjectDrift means the column, constraint, NOT NULL, or table a reviewed plan drops no longer has the definition the plan carried for it, read again under the table's lock: it is gone, or the name now stands for another object (a column dropped and added again, a constraint replaced under its name, a table whose shape changed). Nothing was dropped. The outcome is permanent: re-plan against the table as it stands and review the new plan.

View Source
var ErrDroppedObjectHasDescendants = errors.New("the object the plan drops also reaches tables below it")

ErrDroppedObjectHasDescendants means a reviewed drop would reach tables below the named one, read under the table's lock. A column, constraint, or NOT NULL drop is refused on a table that has inheritance children, and a NOT NULL drop on a partitioned table that has partitions: a column drop would remove the children's copies of the column and anything on them, a constraint drop their copies of the constraint, and a NOT NULL drop would clear it on their copies. A column or constraint drop on a partitioned table whose every descendant is a declarative partition is not refused here: see refusePartitionedDrop. A table drop is refused on a partitioned table or an inheritance parent, since it would drop the tables below. The plan reviewed only the named table's object and its dependents, so nothing was dropped. The outcome is permanent.

View Source
var ErrDroppedTableHasDependents = errors.New("other objects depend on the table the plan drops")

ErrDroppedTableHasDependents means PostgreSQL refused the reviewed table drop because another object depends on the table, such as a view or a foreign key of another table. The drop never says CASCADE, so the server refuses rather than remove objects the plan did not review. Nothing was dropped. The outcome is permanent until the dependent objects are removed or changed.

View Source
var ErrDroppedTableHasParent = errors.New("the table the plan drops is a partition or an inheritance child")

ErrDroppedTableHasParent means a reviewed table drop names a partition or an inheritance child, read under the table's lock. Its rows are also rows of the table above it, so dropping it changes what that table holds, which the plan did not review. Nothing was dropped. The outcome is permanent.

View Source
var ErrEnumLabelExists = errors.New("the enum type already carries the label the ADD VALUE adds")

ErrEnumLabelExists means the enum type the engine checked already carries the label an ALTER TYPE ... ADD VALUE without IF NOT EXISTS adds: another change added it after the statement was planned. Nothing was added. The outcome is permanent: the same statement meets the same label on every attempt, so plan again against the catalog as it stands.

View Source
var ErrEnumNeighborMissing = errors.New("the enum type no longer carries the label the ADD VALUE places its value next to")

ErrEnumNeighborMissing means the enum type the engine checked no longer carries the label an ALTER TYPE ... ADD VALUE places its value BEFORE or AFTER: another change renamed or removed it after the statement was planned. Nothing was added. The outcome is permanent: the same statement meets the same missing label on every attempt, so plan again against the catalog as it stands.

View Source
var ErrEnumTypeDrift = errors.New("the ADD VALUE reached a type other than the enum type the engine checked")

ErrEnumTypeDrift means an ALTER TYPE ... ADD VALUE changed a type other than the enum type the engine resolved and checked: another session moved the type's name to a different type before the statement ran, so the name reached that type instead. Nothing was added. The outcome is permanent: plan again against the catalog as it stands.

View Source
var ErrInvariantViolation = dbconn.ErrInvariantViolation

ErrInvariantViolation aliases dbconn's fail-closed error class for breaches of the registry in docs/invariants.md. It is never a warning and never retried.

View Source
var ErrPolicyRecursion = errors.New("a policy cannot read a table whose policies read this table back")

ErrPolicyRecursion refuses policies that read a table whose own policies, directly or through other tables and views, read the target table back. PostgreSQL accepts such policies, then fails every query on the table that they apply to with "infinite recursion detected in policy".

View Source
var ErrRenamedIndexDrift = errors.New("the index the rename names is no longer a plain index on the preflighted table")

ErrRenamedIndexDrift means the relation an ALTER INDEX ... RENAME TO names is no longer a plain index on the preflighted table, read again under the table's lock: it is gone, it is not an index (PostgreSQL's ALTER INDEX ... RENAME also renames a table), it belongs to another table, or it now backs a primary-key, unique, or exclusion constraint, which the rename would rename with it. It also means another session moved the name to a different relation between that check and the rename, so the rename reached a relation other than the one checked. Nothing was renamed. The outcome is permanent: re-plan against the catalog as it stands.

View Source
var ErrReplicaIdentityDrop = errors.New("the drop removes what a replica identity index is built on")

ErrReplicaIdentityDrop means a native drop would remove what a replica identity index of the table, or of a table below it, is built on. The planner refuses such a drop from the facts it read; this is the same answer read again under the table's lock, so it fires when the identity moved onto the dropped object after planning. Nothing was dropped. The outcome is permanent: point REPLICA IDENTITY elsewhere, then re-plan.

View Source
var ErrRowSecurityDatabaseCreateRequired = errors.New("grant CREATE on the database to the execution role for scratch inspection")

ErrRowSecurityDatabaseCreateRequired identifies the grant needed for scratch inspection.

View Source
var ErrRowSecurityOwnerRequired = errors.New("connect as the table owner or a role inheriting its privileges")

ErrRowSecurityOwnerRequired identifies a missing table-ownership privilege.

View Source
var ErrRowSecurityPlanChanged = errors.New("row security SQL differs from reviewed plan")

ErrRowSecurityPlanChanged means the locked SQL sequence differs from review. No target RLS statements have executed. Preview and review the new plan.

View Source
var ErrRowSecurityPrivileges = errors.New("insufficient row security privileges")

ErrRowSecurityPrivileges identifies a missing grant, distinct from unsupported declarations.

View Source
var ErrRowSecurityRefused = errors.New("row security change refused")

ErrRowSecurityRefused means the declaration, target shape, or privileges must change before retrying. Wrapped causes retain the specific admission failure.

View Source
var ErrValidatedConstraintDrift = errors.New("the constraint the validation checks changed after planning")

ErrValidatedConstraintDrift means the constraint a planned VALIDATE CONSTRAINT validates no longer has the definition the plan matched it against, read again under the table's lock: it was dropped, or replaced under the same name. Nothing was validated. The outcome is permanent: re-plan against the constraint as it stands.

Functions

func AdmitDetachPartition added in v0.5.6

func AdmitDetachPartition(ctx context.Context, pool *pgxpool.Pool, sql string) error

AdmitDetachPartition is the catalog half of the admission of a DETACH PARTITION ... CONCURRENTLY step: it refuses with ErrDetachDefaultPartition, before anything executes, when the table has a DEFAULT partition. Any other statement is admitted. The table must be schema-qualified. pool must come from pkg/dbconn.

func AdmitPartitionedIndexShape added in v0.5.5

func AdmitPartitionedIndexShape(sql string) error

AdmitPartitionedIndexShape is the statement-shape half of the partitioned index build's admission: exactly one named CREATE INDEX, without IF NOT EXISTS or TABLESPACE, on a schema-qualified table. It needs no connection, so a dry run learns the refusals the build would return before it runs anything. The refusals are the build's own, typed.

func AdmitPartitionedUniqueIndex added in v0.5.5

func AdmitPartitionedUniqueIndex(ctx context.Context, pool *pgxpool.Pool, sql string) error

AdmitPartitionedUniqueIndex is the catalog half of the partitioned index build's admission, for a statement AdmitPartitionedIndexShape 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 with the build's own *UniqueIndexPartitionKeyError, which the build returns under its table lock before it creates anything. A dry run calls it to learn that refusal without running the build. It only reads the catalog, in bounded transactions on the pool that always roll back; the pool must come from pkg/dbconn. A non-unique index is admitted without a read.

func AdmitSequenceShape added in v0.4.0

func AdmitSequenceShape(steps []string) error

AdmitSequenceShape runs the statement-shape half of the sequence executor's admission over steps — every step re-parsed and classified — without the preflight-dependent target check, so a caller holding no preflight proof (a dry run) learns the shape refusals RunSequence would return before it executes anything. The refusals and their step-position wrapping are exactly those of RunSequence's admission. Every step must be schema-qualified: a concurrent index build is refused otherwise, because the executor proves its target by schema.

func AttemptSearchPath added in v0.5.1

func AttemptSearchPath(schema string, extensions []string) []string

AttemptSearchPath is the search_path an attempt on a table in schema runs under: the schema, then public, where extension types live, then each extension schema the desired file resolves names against that the path does not already list (see statement.DesiredSchema.WithExtensionSchemas).

func CreateShapeRefusals added in v0.3.0

func CreateShapeRefusals(schema string, ds statement.DesiredSchema) ([]error, error)

CreateShapeRefusals checks the connection-free create-path rules in desired statement order. A nil entry is admitted; a non-nil entry identifies the shape refusal for that statement. Parse failures and violated DesiredSchema invariants are returned separately because no positional plan is safe.

func ExecuteDropTable added in v0.5.6

func ExecuteDropTable(ctx context.Context, pool *pgxpool.Pool, schema, table, definition string, b Budget, retry RetryPolicy) error

ExecuteDropTable drops one reviewed table with DROP TABLE, without CASCADE, in a single transaction under the budget b, retrying a lock timeout under retry. A caller has already admitted the drop as destructive; definition is the one its plan recorded with schemadiff.DroppedTableDefinition.

Each attempt takes the table's ACCESS EXCLUSIVE lock, which the drop takes anyway, before reading anything, and holds it until the drop commits, so the table cannot change between the check and the drop. Under the lock it reads the table again and refuses, dropping nothing:

  • when the table no longer exists (ErrTableNotFound);
  • when its definition differs from the reviewed one, or the name now stands for another kind of relation (ErrDroppedObjectDrift);
  • when it is a partitioned table or has inheritance children, which the drop would remove too (ErrDroppedObjectHasDescendants);
  • when it is a partition or an inheritance child (ErrDroppedTableHasParent).

A view, another table's foreign key, or any other object that depends on the table makes the server refuse the drop (ErrDroppedTableHasDependents). A COMMIT that does not return success reports *CommitOutcomeUnknownError: the table may be gone, so the caller inspects the catalog before retrying.

func ExecuteEnumValueAdd added in v0.5.1

func ExecuteEnumValueAdd(ctx context.Context, pool *pgxpool.Pool, et preflight.EnumTarget, st statement.Statement, b Budget, retry RetryPolicy) error

ExecuteEnumValueAdd runs an ALTER TYPE ... ADD VALUE as bounded attempts under transaction-local budgets, retrying only lock_timeout failures, bounded by retry. The statement locks only the type, never a table that uses it, and waits only on another session altering the same type.

It accepts only an EnumTarget minted for the type name the statement spells, and pins each attempt's search_path to the target's schema alone, so a bare name resolves only there. The statement names a type, not a table, so the ST-7 binding is checked in the catalog against the target's OID. The type's lock does not hold its name still, since ALTER TYPE ... RENAME does not wait for it, so after the statement runs, and before the commit, the attempt confirms that every enum label the transaction wrote belongs to the target, that the target carries the label, and, when the statement wrote nothing, that the name still resolves to the target, and rolls back with ErrEnumTypeDrift otherwise.

A statement the server rejects because the type already carries the label, or lacks the label BEFORE or AFTER names, returns ErrEnumLabelExists or ErrEnumNeighborMissing when the target, read by OID, shows that fact, and ErrEnumTypeDrift when it does not, since the statement then reached a different type.

func ExecuteIndexRename added in v0.4.0

func ExecuteIndexRename(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy) error

ExecuteIndexRename runs a plain ALTER INDEX ... RENAME TO as bounded attempts under transaction-local budgets, retrying only lock_timeout failures, bounded by retry. The statement names an index, not a table, so the ST-7 binding is checked in the catalog instead of on the statement's text. Each attempt pins its search_path to the proof's schema alone, so the name the statement carries resolves only there (an index's schema is always its table's), then locks the preflighted table alone in SHARE UPDATE EXCLUSIVE, which conflicts with every ALTER TABLE that could attach a constraint to an index of it, and refuses with ErrRenamedIndexDrift unless the name resolves to an index on that table that backs no primary-key, unique, or exclusion constraint.

ALTER INDEX ... RENAME locks the index it renames, never its table, so the table's lock does not hold the name still: another session can rename the checked index away and give its name to another index before the statement resolves it. After the statement runs, and before the commit, the attempt therefore confirms that the relation now carrying the new name in the proof's schema is the index it checked, and rolls back with ErrRenamedIndexDrift otherwise. The rename holds that index's lock until the commit, so nothing renames it in between.

func ExecuteIndexRenameWithProgress added in v0.5.2

func ExecuteIndexRenameWithProgress(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy, tracker *progress.Tracker) (err error)

ExecuteIndexRenameWithProgress runs ExecuteIndexRename, with the same checks and the same ErrRenamedIndexDrift refusal, while updating tracker as one optimistic step. The caller may poll tracker concurrently with this blocking call.

func ExecuteNative

func ExecuteNative(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy) error

ExecuteNative runs transactional native DDL under transaction-local budgets and retries only lock_timeout failures, bounded by retry. The table must have passed preflight and the statement must target it — both proofs make the unsafe call unrepresentable: a statement.Statement can only come from ParseOne (exactly one statement, parsed by the real grammar), and a target mismatch is refused before anything executes, so a proof for one table cannot smuggle SQL against another. Each attempt is a new transaction, so neither an aborted transaction nor its settings can leak through the pool. When the proof carries a schema, each attempt runs with search_path pinned to that schema then public, so the statement's unqualified secondary names resolve in the target schema — the same resolution the create path and the introspection read path use. On success the change is committed: it was effectively instant. If the lock budget is exhausted across all bounded attempts, a *BudgetError carrying the attempt count is returned. Statement timeouts and all other failures return immediately: repeating work that exceeded its execution budget is not a lock-acquisition strategy.

func ExecuteNativeAdoptingWithProgress added in v0.5.2

func ExecuteNativeAdoptingWithProgress(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy, adopts schemadiff.IndexAdoption, tracker *progress.Tracker) error

ExecuteNativeAdoptingWithProgress is ExecuteNativeWithProgress for a planned ADD CONSTRAINT ... USING INDEX (schemadiff.Change.Adopts): each attempt first checks, under the table's lock and in the same transaction, that adopts.Index is still valid and still has adopts.Def, and refuses with ErrAdoptedIndexDrift when it is not — the check RunSequenceAdopting runs on its adopting step. A statement that does not take over adopts.Index is refused as an invariant violation before anything runs.

func ExecuteNativeAsStep added in v0.5.2

func ExecuteNativeAsStep(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy, at RunStep) error

ExecuteNativeAsStep is ExecuteNative reported to the run step at: the attempt is step at.Step with operation progress.OperationOptimistic and its retry attempts recorded. A zero at runs exactly as ExecuteNative.

func ExecuteNativeValidatingWithProgress added in v0.5.2

func ExecuteNativeValidatingWithProgress(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy, validates schemadiff.ConstraintValidation, tracker *progress.Tracker) error

ExecuteNativeValidatingWithProgress is ExecuteNativeWithProgress for a planned VALIDATE CONSTRAINT (schemadiff.Change.Validates): each attempt first checks, under the validation's own SHARE UPDATE EXCLUSIVE lock and in the same transaction, that validates.Constraint still has validates.Def, and refuses with ErrValidatedConstraintDrift when it does not — the check RunSequenceValidating runs on its validating step. A statement that does not validate validates.Constraint is refused as an invariant violation before anything runs. The validation scan is bounded by b.StatementTimeout, so size it as a sequence sizes ValidateBudget.Overall; the tracker reports the step as a constraint-validation scan, as the sequence executor does.

func ExecuteNativeWithProgress

func ExecuteNativeWithProgress(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, st statement.Statement, b Budget, retry RetryPolicy, tracker *progress.Tracker) error

ExecuteNativeWithProgress runs an optimistic native attempt while updating tracker. The caller may poll tracker concurrently with this blocking call.

func RefreshTableStatistics added in v0.4.0

func RefreshTableStatistics(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, b Budget) (string, error)

RefreshTableStatistics runs ANALYZE on the preflighted table and on every table that inherits from it, in one transaction under transaction-local budgets. It returns the ANALYZE it ran, or, with an error, the one an operator still has to run.

ALTER COLUMN TYPE deletes the column's planner statistics, for a catalog relabel as much as for a rewrite, and nothing restores them until autovacuum's change threshold trips. On a table that changes slowly that can be a long time, and until then the planner estimates every predicate on the column from defaults. ANALYZE samples rather than scans, and its SHARE UPDATE EXCLUSIVE lock blocks neither reads nor writes; it waits only behind another ANALYZE, VACUUM, or DDL on the table, which the lock budget bounds.

The whole table is analyzed rather than the retyped columns alone: the server computes expression-index statistics only for a whole-table ANALYZE, and an extended statistics object only when every column it covers is sampled, and a type change can rebuild or invalidate either. A type change on an inheritance parent recurses into its children and deletes their statistics too, while ANALYZE on the parent does not analyze them, so each child is named; a partitioned table's partitions need no naming, since ANALYZE on the parent recurses into them itself.

The server skips a table whose owner the role cannot act as with only a warning, so a refresh that completed proves nothing on its own. The refresh checks ownership of every table it covers first, in the same transaction, and returns ErrAnalyzeNotPermitted rather than report statistics it never refreshed. Ownership is the privilege every native step on the table needs anyway; a role ANALYZE admits on other grounds is refused here, which costs a manual ANALYZE and never a false report.

Types

type BlockingBudget added in v0.3.3

type BlockingBudget struct {
	LockTimeout      time.Duration
	StatementTimeout time.Duration
}

BlockingBudget bounds one operator-accepted blocking statement.

func (BlockingBudget) Validate added in v0.5.6

func (b BlockingBudget) Validate() error

Validate reports whether the budget can bound an accepted blocking statement: both limits non-zero and representable, and the statement limit longer than the lock limit. A caller that runs several statements checks it before the first, so a budget the blocking one would refuse stops the run before anything commits.

type BlockingExecutionError added in v0.3.3

type BlockingExecutionError struct{ Err error }

BlockingExecutionError reports a PostgreSQL failure after the accepted statement was submitted. Err retains the server SQLSTATE.

func (*BlockingExecutionError) Error added in v0.3.3

func (e *BlockingExecutionError) Error() string

func (*BlockingExecutionError) Unwrap added in v0.3.3

func (e *BlockingExecutionError) Unwrap() error

type BlockingIndexDrop added in v0.5.6

type BlockingIndexDrop struct {
	Schema, Table, Index string
	// IndexOID is the OID of the partitioned index that was dropped.
	IndexOID uint32
	// PartitionIndexes are the attached partition indexes the drop removed
	// with the parent's, schema-qualified, in catalog order.
	PartitionIndexes []string
	Duration         time.Duration
}

BlockingIndexDrop records a committed blocking drop of a partitioned table's index: the index, the attached partition indexes PostgreSQL dropped with it, and how long the transaction ran.

func ExecuteBlockingPartitionedIndexDrop added in v0.5.6

func ExecuteBlockingPartitionedIndexDrop(ctx context.Context, pool *pgxpool.Pool, schema, table, index, definition string, b BlockingBudget) (BlockingIndexDrop, error)

ExecuteBlockingPartitionedIndexDrop drops one reviewed index of the partitioned table schema.table with the plain DROP INDEX, the only drop PostgreSQL has for a partitioned index. The caller has admitted the drop as destructive and accepted its blocking lock; definition is the one the plan carried (schemadiff.DroppedObject.Definition).

It runs in one engine-owned transaction under b's lock_timeout and statement_timeout and the search_path the plan's definition was read under, the schema then public. The table's ACCESS EXCLUSIVE lock is requested first, as a statement of its own, which reaches every partition: an exhausted lock budget is a *BudgetError with CauseLock and nothing was submitted. Under that lock the index is read again and the drop refused, dropping nothing, with ErrDroppedIndexDrift unless schema.index is still the partitioned index (relkind 'I') of schema.table, not attached under another index, with the planned definition; a drop that would remove a replica identity index is refused with ErrUnsupportedAcceptedBlocking. The DROP INDEX then removes the parent's index and every attached partition index, and before the commit the transaction reads back that none of them is left; a name another session moved in between rolls the drop back as ErrDroppedIndexDrift. A statement-budget cancellation is a *BudgetError with CauseStatement, any other server error a *BlockingExecutionError, both rolled back, and a commit the client cannot confirm a *BlockingOutcomeUnknownError.

type BlockingOutcomeUnknownError added in v0.3.3

type BlockingOutcomeUnknownError struct{ Err error }

BlockingOutcomeUnknownError means the client cannot establish whether the transaction committed; the catalog must be inspected before retrying.

func (*BlockingOutcomeUnknownError) Error added in v0.3.3

func (*BlockingOutcomeUnknownError) Unwrap added in v0.3.3

func (e *BlockingOutcomeUnknownError) Unwrap() error

type BlockingReport added in v0.3.3

type BlockingReport struct {
	SQL              string        `json:"sql"`
	LockTimeout      time.Duration `json:"lock_timeout_ns"`
	StatementTimeout time.Duration `json:"statement_timeout_ns"`
	Duration         time.Duration `json:"duration_ns"`
}

BlockingReport records a committed accepted-blocking statement and its engine-owned bounds.

func ExecuteAcceptedBlocking added in v0.3.3

func ExecuteAcceptedBlocking(ctx context.Context, pool *pgxpool.Pool, sql string, table pgx.Identifier, b BlockingBudget) (BlockingReport, error)

ExecuteAcceptedBlocking runs one admitted blocking index statement in one engine-owned transaction with explicit lock and statement bounds.

table, when non-nil, is the schema-qualified table the statement locks, as the caller resolved it from the catalog. The executor requests that table's ACCESS EXCLUSIVE lock as a statement of its own before the DDL, so the whole lock wait happens where only the lock budget can end it and nothing has been submitted; the DDL's own lock requests are then granted at once and its statement budget measures the work. A nil table leaves the statement to acquire its locks itself — the caller's choice when the relation is one LOCK TABLE cannot name, such as a materialized view — and a statement cancellation then cannot distinguish a lock wait from work.

type Budget

type Budget struct {
	// LockTimeout bounds how long the attempt may wait in the lock queue.
	LockTimeout time.Duration
	// StatementTimeout bounds how long the statement may run once started.
	StatementTimeout time.Duration
}

Budget bounds one optimistic attempt. Both limits must be at least minBudget: an unbounded attempt is exactly the stall the front door exists to prevent.

type BudgetCause

type BudgetCause int

BudgetCause says which budget the optimistic attempt exceeded.

const (
	// CauseLock means the lock was not granted within lock_timeout: the
	// table is too contended for a blind attempt right now.
	CauseLock BudgetCause = iota + 1
	// CauseStatement means the statement ran past statement_timeout: the
	// change is doing real work (a rewrite), not an in-place catalog change.
	CauseStatement
)

The two budgets an attempt runs under.

func (BudgetCause) String

func (c BudgetCause) String() string

String returns the human-readable budget name.

type BudgetError

type BudgetError struct {
	// Cause is the budget that was exceeded.
	Cause BudgetCause
	// Budget is the configured limit for that cause.
	Budget time.Duration
	// Attempts is the number of bounded transactions tried. It is greater
	// than one when lock acquisition retries were exhausted.
	Attempts int
	// contains filtered or unexported fields
}

BudgetError reports that an execution attempt exceeded one of its budgets and was cancelled cleanly by the server: the statement did not take effect. It is a refusal input, not an operational failure.

func (*BudgetError) Code

func (e *BudgetError) Code() Code

Code returns the budget outcome's stable code. A budget error whose cause carries an invariant breach reports the breach, as OutcomeCode does.

func (*BudgetError) Error

func (e *BudgetError) Error() string

Error implements the error interface.

func (*BudgetError) Unwrap added in v0.3.0

func (e *BudgetError) Unwrap() error

Unwrap exposes the server error behind the budget verdict.

type Code

type Code string

Code is the stable string identity of one executor outcome; automation branches on it, never on error text. Codes are part of the report contract: existing values never change meaning, new outcomes add new codes.

const (
	// CodeBudgetLockExceeded: the lock was not granted within
	// lock_timeout; nothing was executed.
	CodeBudgetLockExceeded Code = "budget-lock-exceeded"
	// CodeBudgetStatementExceeded: the statement ran past
	// statement_timeout and was cancelled; the change does real work.
	CodeBudgetStatementExceeded Code = "budget-statement-exceeded"
	// CodeRowSecurityPlanChanged requires a fresh preview and SQL review before retry.
	CodeRowSecurityPlanChanged Code = "row-security-plan-changed"
	// CodeRowSecurityRefused requires a declaration, target, or privilege change.
	CodeRowSecurityRefused Code = "row-security-refused"
	// CodeRowSecurityOutcomeUnknown requires catalog inspection before retry.
	CodeRowSecurityOutcomeUnknown Code = "row-security-outcome-unknown"
	// CodeBlockingOutcomeUnknown requires catalog inspection before retry.
	CodeBlockingOutcomeUnknown Code = "blocking-outcome-unknown"
	// CodeCommitOutcomeUnknown requires catalog inspection before retry: a
	// bounded attempt's COMMIT did not return success and may have landed.
	CodeCommitOutcomeUnknown Code = "commit-outcome-unknown"
	// CodeDropOutcomeUnknown requires catalog inspection before retry: a
	// reviewed index drop completed, but the check of which index it
	// dropped failed.
	CodeDropOutcomeUnknown Code = "drop-outcome-unknown"
	// CodeInvalidBlockingBudget identifies an unrepresentable or disabled bound.
	CodeInvalidBlockingBudget Code = "invalid-blocking-budget"
	// CodeUnsupportedAcceptedBlocking identifies a statement outside this narrow path.
	CodeUnsupportedAcceptedBlocking Code = "unsupported-accepted-blocking"
	// CodeCancelledByCaller: the build's statement was cancelled because
	// the caller's own context ended while it ran.
	CodeCancelledByCaller Code = "cancelled-by-caller"
	// CodeCancelledExternally: the build's statement was cancelled from
	// outside the executor — not by its caller, not by its budget.
	CodeCancelledExternally Code = "cancelled-externally"
	// CodeInvalidIndexOwnLeftover: the failed build's own invalid index
	// remains and is proven this run's leftover; the recovery runbook
	// applies. A build that failed on its rows reports CodeDataFault
	// instead, with the leftover still on its Cleanup.
	CodeInvalidIndexOwnLeftover Code = "invalid-index-own-leftover"
	// CodeInvalidIndexBuildInFlight: the invalid index under the requested
	// name is another backend's concurrent build still in progress; wait.
	CodeInvalidIndexBuildInFlight Code = "invalid-index-build-in-flight"
	// CodeInvalidIndexAbandoned: an abandoned invalid index under the
	// requested name sits on the target table with no builder;
	// RebuildAbandonedIndex recovers it.
	CodeInvalidIndexAbandoned Code = "invalid-index-abandoned"
	// CodeInvalidIndexOtherTable: an invalid index under the requested name
	// sits on a different table in the target schema; this change refuses
	// and does not remove it.
	CodeInvalidIndexOtherTable Code = "invalid-index-other-table"
	// CodeInvalidIndexNotDroppable: the invalid index under the requested
	// name sits on the target table but is a partitioned table's index, an
	// index partition, or a constraint's index — not the debris of a
	// failed concurrent build, and not removable by DROP INDEX
	// CONCURRENTLY; this change leaves it in place for an operator.
	CodeInvalidIndexNotDroppable Code = "invalid-index-not-droppable"
	// CodeInvalidIndexBuilderUnobservable: an invalid index under the
	// requested name sits on the target table and this role cannot observe
	// whether a backend is building it; RebuildAbandonedIndex proves the
	// state under the table lock, or a role with pg_read_all_stats can
	// classify it.
	CodeInvalidIndexBuilderUnobservable Code = "invalid-index-builder-unobservable"
	// CodeInvalidIndexUnproven: an invalid index may remain but the
	// catalog state could not be proven; an operator must inspect.
	CodeInvalidIndexUnproven Code = "invalid-index-unproven"
	// CodeNotCreateIndex: the statement handed to the partitioned index
	// build is not a CREATE INDEX.
	CodeNotCreateIndex Code = "not-create-index"
	// CodeNotPartitionedTable: the target of a partitioned index build is
	// not a partitioned table.
	CodeNotPartitionedTable Code = "not-partitioned-table"
	// CodePartitionedIndexNameTaken: a name the partitioned index build
	// needs is held by a relation that is not the requested index; the
	// occupant is left for an operator.
	CodePartitionedIndexNameTaken Code = "partitioned-index-name-taken"
	// CodeForeignTablePartition: the partition tree holds a foreign table,
	// which cannot carry an index; nothing was created.
	CodeForeignTablePartition Code = "foreign-table-partition"
	// CodeUniqueIndexPartitionKey: a unique index does not contain the
	// partition key of every partitioned table in the tree; nothing was
	// created.
	CodeUniqueIndexPartitionKey Code = "unique-index-partition-key"
	// CodeTableLockUnconfirmed: the pool's role cannot see when the session
	// holding the build's table lock started, so the build cannot confirm
	// the lock is its own; nothing was created.
	CodeTableLockUnconfirmed Code = "table-lock-unconfirmed"
	// CodePartitionDetachPending: the partition tree holds a partition
	// whose concurrent detach did not finish, so no index can be attached
	// for it.
	CodePartitionDetachPending Code = "partition-detach-pending"
	// CodeDetachDefaultPartition: a DETACH PARTITION ... CONCURRENTLY on a
	// table that has a DEFAULT partition, which PostgreSQL rejects; nothing
	// was executed.
	CodeDetachDefaultPartition Code = "detach-default-partition"
	// CodeDetachInterrupted: a DETACH PARTITION ... CONCURRENTLY stopped
	// after its first transaction committed, leaving the partition
	// detach-pending; running the same statement again finishes it.
	CodeDetachInterrupted Code = "partition-detach-interrupted"
	// CodePartitionedIndexTablespace: the partitioned index statement has a
	// TABLESPACE clause, which would reach the parent's index and not the
	// partitions' indexes; nothing was created.
	CodePartitionedIndexTablespace Code = "partitioned-index-tablespace"
	// CodePartitionedIndexUnsettled: partitions kept appearing without an
	// index until the build ran out of passes; a rerun resumes.
	CodePartitionedIndexUnsettled Code = "partitioned-index-unsettled"
	// CodePartitionedKeyNameTaken: the name a partitioned key constraint
	// needs on a partition is held by something that is not the requested
	// key; the occupant is left for an operator.
	CodePartitionedKeyNameTaken Code = "partitioned-key-name-taken"
	// CodePartitionedKeyConflict: a partition already has a key constraint
	// that conflicts with the requested one; nothing was added to it.
	CodePartitionedKeyConflict Code = "partitioned-key-conflict"
	// CodePartitionedKeyNullableColumn: a primary key was requested over a
	// column a partition allows to be NULL; nothing was built.
	CodePartitionedKeyNullableColumn Code = "partitioned-key-nullable-column"
	// CodeEmptySequence: the sequence had no steps to run.
	CodeEmptySequence Code = "empty-sequence"
	// CodeUnsupportedSequenceStep: a step is not a shape the sequence
	// executor can run safely.
	CodeUnsupportedSequenceStep Code = "unsupported-sequence-step"
	// CodeUnsupportedPartitionedParent identifies partitioned-parent
	// admission refusals.
	CodeUnsupportedPartitionedParent Code = "unsupported-partitioned-parent"
	// CodeNotConcurrentIndexBuild: the statement handed to the concurrent
	// build executor is not a CREATE INDEX CONCURRENTLY.
	CodeNotConcurrentIndexBuild Code = "not-concurrent-index-build"
	// CodeUnnamedIndex: the concurrent build does not name its index, so
	// its outcome could not be verified.
	CodeUnnamedIndex Code = "unnamed-index"
	// CodeUnqualifiedTable: the target table is not schema-qualified at
	// the library boundary.
	CodeUnqualifiedTable Code = "unqualified-table"
	// CodeIfNotExistsUnsupported: CREATE ... IF NOT EXISTS cannot prove
	// what its no-op would mean.
	CodeIfNotExistsUnsupported Code = "if-not-exists-unsupported"
	// CodeCreateCollision: a name the create path needs is already taken
	// on the server; the caller re-diffs the live catalog rather than
	// assuming the occupant's shape.
	CodeCreateCollision Code = "create-collision"
	// CodeCreateNameMismatch: the CREATE TABLE committed but the table does
	// not own a first-choice constraint-index or sequence name the desired
	// file claimed — an occupant took it inside the catalog probe's window
	// and the server chose a suffixed name instead; the table remains for an
	// operator to rename the relation or drop, then re-diff.
	CodeCreateNameMismatch Code = "create-name-mismatch"
	// CodeCreateNamesUnverified: the CREATE TABLE committed but the read of
	// the relation names the table owns did not complete, so whether every
	// first-choice claim was honoured is unknown; the table remains for an
	// operator to compare its names against the desired file, then re-diff.
	// The read's own failure is the cause in the error text, never the code:
	// the code names the state the step left, and that state is a standing
	// table whose names are unproven.
	CodeCreateNamesUnverified Code = "create-names-unverified"
	// CodeCreateOwnerMismatch: the CREATE TABLE committed but the table's
	// catalog owner is not the create owner the proof named; the table
	// remains as committed for an operator to inspect, transfer, or drop —
	// the executor never repairs ownership with ALTER ... OWNER TO.
	CodeCreateOwnerMismatch Code = "create-owner-mismatch"
	// CodeCreateOwnerUnverified: the CREATE TABLE committed but the read of
	// its catalog owner did not complete, so whether it was born under the
	// named owner is unknown; the table remains for an operator to compare
	// its owner against the configured one. As with the unverified names,
	// the read's own failure is the cause in the error text, never the code.
	CodeCreateOwnerUnverified Code = "create-owner-unverified"
	// CodeDuplicateCreateName: the desired set claims the same relation
	// name twice; the conflict is decidable at admission and refused
	// before anything runs.
	CodeDuplicateCreateName Code = "duplicate-create-name"
	// CodePartitionOfUnsupported: CREATE TABLE PARTITION OF locks the
	// partitioned parent, which the absence proof does not cover.
	CodePartitionOfUnsupported Code = "partition-of-unsupported"
	// CodeUnsupportedCreateStep: a desired statement is not a shape the
	// create path can run.
	CodeUnsupportedCreateStep Code = "unsupported-create-step"
	// CodePoolTooSmall: the pool cannot hold every session the operation
	// needs at once — the build session and the verdict connection, or a
	// copy-and-swap run's copy workers and the two connections beside them.
	CodePoolTooSmall Code = "pool-too-small"
	// CodeReplicaIdentityDrop: a native drop would remove what a replica
	// identity index is built on, read again under the table's lock;
	// nothing was dropped. Point REPLICA IDENTITY elsewhere, then re-plan.
	CodeReplicaIdentityDrop Code = "replica-identity-drop"
	// CodeAdoptedIndexDrift: the index a planned ADD CONSTRAINT ... USING
	// INDEX takes over was dropped, replaced, or left invalid after
	// planning, read again under the table's lock; nothing was attached.
	// Re-plan against the index as it stands.
	CodeAdoptedIndexDrift Code = "adopted-index-drift"
	// CodeDroppedIndexDrift: the index a reviewed plan drops is no longer
	// the plain, valid index of the plan's table that the plan named, read
	// again on the session that drops it; nothing was dropped. Re-plan
	// against the catalog as it stands and review the new plan.
	CodeDroppedIndexDrift Code = "dropped-index-drift"
	// CodeDroppedIndexReplaced: a drop that passed its pre-drop read removed
	// an index the plan did not review, because another session gave the
	// name to a different index in the round trip between the read and the
	// drop. Unlike the drift codes, something was dropped: inspect the
	// table's indexes and recreate the dropped one if it should stay.
	CodeDroppedIndexReplaced Code = "dropped-index-replaced"
	// CodeDroppedObjectDrift: the column, constraint, NOT NULL, or table a
	// reviewed plan drops no longer has the definition the plan carried,
	// read again under the table's lock; nothing was dropped. Re-plan
	// against the table as it stands and review the new plan.
	CodeDroppedObjectDrift Code = "dropped-object-drift"
	// CodeDroppedObjectHasDescendants: a reviewed column, constraint, or
	// NOT NULL drop names a table with inheritance children, or a NOT NULL
	// drop (or any drop with ONLY) names a partitioned table with
	// partitions, and the drop would reach their copies too; or a reviewed
	// table drop names a partitioned table or an inheritance parent, which
	// would drop the tables below it. The plan did not review that, so
	// nothing was dropped.
	CodeDroppedObjectHasDescendants Code = "dropped-object-has-descendants"
	// CodeDroppedColumnPartitionKey: a reviewed column drop names a column
	// in the partition key of the partitioned table or of a
	// sub-partitioned partition below it, which PostgreSQL never drops;
	// nothing was dropped.
	CodeDroppedColumnPartitionKey Code = "dropped-column-partition-key"
	// CodeDroppedColumnPartitionDependent: a reviewed column drop on a
	// partitioned table would also remove an object a partition carries of
	// its own on the column (an index, constraint, statistics object, or
	// sequence that is not a copy of the parent's), which the plan did not
	// review; nothing was dropped. Drop or change that object first, then
	// re-plan.
	CodeDroppedColumnPartitionDependent Code = "dropped-column-partition-dependent"
	// CodeDroppedTableHasParent: a reviewed table drop names a partition or
	// an inheritance child, whose rows the table above it also holds;
	// nothing was dropped.
	CodeDroppedTableHasParent Code = "dropped-table-has-parent"
	// CodeDroppedTableHasDependents: the server refused a reviewed table
	// drop because a view, another table's foreign key, or another object
	// depends on the table; nothing was dropped.
	CodeDroppedTableHasDependents Code = "dropped-table-has-dependents"
	// CodeValidatedConstraintDrift: the constraint a planned VALIDATE
	// CONSTRAINT validates was dropped or replaced after planning, read
	// again under the table's lock; nothing was validated. Re-plan against
	// the constraint as it stands.
	CodeValidatedConstraintDrift Code = "validated-constraint-drift"
	// CodeRenamedIndexDrift: the relation an ALTER INDEX ... RENAME TO
	// names is no longer a plain index on the preflighted table, read
	// again under the table's lock — gone, not an index, on another table,
	// or now backing a constraint; nothing was renamed. Re-plan against the
	// catalog as it stands.
	CodeRenamedIndexDrift Code = "renamed-index-drift"
	// CodeEnumTypeDrift: an ALTER TYPE ... ADD VALUE reached a type other
	// than the enum type the engine checked, because another session gave
	// the name to a different type; nothing was added. Plan again against
	// the catalog as it stands.
	CodeEnumTypeDrift Code = "enum-type-drift"
	// CodeEnumLabelExists: the enum type the engine checked already
	// carries the label an ALTER TYPE ... ADD VALUE without IF NOT EXISTS
	// adds, because another change added it after planning; nothing was
	// added. Plan again against the catalog as it stands.
	CodeEnumLabelExists Code = "enum-label-exists"
	// CodeEnumNeighborMissing: the enum type the engine checked no longer
	// carries the label an ALTER TYPE ... ADD VALUE places its value
	// BEFORE or AFTER, because another change renamed or removed it after
	// planning; nothing was added. Plan again against the catalog as it
	// stands.
	CodeEnumNeighborMissing Code = "enum-neighbor-missing"
	// CodeTableNotFound: the statement's qualified table does not exist.
	CodeTableNotFound Code = "table-not-found"
	// CodeDataFault: the server rejected the table's rows as the statement
	// would shape them (SQLSTATE class 22, a value the new type or an index
	// expression will not take; class 23, a constraint the rows break, such
	// as duplicate values under a unique index). The code names the fault,
	// not what was left behind: any rerun meets the same rows until the data
	// or the statement is corrected. A copy-and-swap run tries to abandon
	// itself — shadow, hold on the source, and checkpoint row discarded —
	// and returns *schemachange.AbandonedError only when that finished,
	// which the verdict reports as Abandoned; when the abandon did not
	// finish, start it over with the restart acknowledgement, as the
	// verdict's detail says. A concurrent index build returns an
	// *InvalidIndexError whose Recoverable is false and whose Cleanup
	// still says what it left: its own invalid index occupies the name,
	// so correct the rows, drop the leftover concurrently, and run the
	// change again.
	CodeDataFault Code = "data-fault"
	// CodeInvariantViolation: a breach of the invariant registry; never a
	// retry candidate.
	CodeInvariantViolation Code = "invariant-violation"
	// CodeExecutionFailed: the fallback for a failure outside the typed
	// set — a server error surfaced as-is, a connection failure, a
	// context cancellation. Consumers treat it as an operational error to
	// investigate, not a refusal to branch on.
	CodeExecutionFailed Code = "execution-failed"
)

The codes an executor outcome can carry.

func Codes added in v0.2.0

func Codes() []Code

Codes returns the closed set of outcome codes. It is part of the report contract: adapters enumerate it to know every outcome they must render, and the docs test pins every code into the execution-model page so the documented vocabulary cannot drift from this one.

func OutcomeCode

func OutcomeCode(err error) Code

OutcomeCode maps an error returned by this package to its stable code. A nil error has no outcome code and maps to the empty Code. A *SequenceStepError carries its failed step's own cause, so it maps to that underlying code — the step position and committed prefix ride on the struct itself, not the vocabulary. An error outside the typed set maps to CodeExecutionFailed.

An error that carries ErrInvariantViolation maps to CodeInvariantViolation whichever typed failure wraps it, so the fail-closed code outranks every other one. Each typed error's own Code method applies the same rule, so the two never disagree.

func (Code) Permanent added in v0.3.0

func (c Code) Permanent() bool

Permanent reports whether the outcome is decided by the statement, the caller's configuration, or the standing catalog: retrying the same call unchanged reproduces it, and no executor entry point changes it — an author or operator has to act first. It is the floor an adapter's retry policy stands on, not its ceiling: a code that is not permanent may still be one a particular adapter declines to retry (a statement budget it sized as a lease, for one), but a permanent code retried unchanged loops for ever. The invalid-index family splits on exactly this line: an entry RebuildAbandonedIndex can prove abandoned, a build to wait out, or a proof to re-take is not permanent; an entry on another table or one the server will not drop concurrently is. The empty code (no error) is not permanent.

type CommitOutcomeUnknownError added in v0.4.0

type CommitOutcomeUnknownError struct{ Err error }

CommitOutcomeUnknownError means a bounded attempt's COMMIT did not return success, and the client cannot establish whether the server applied it: the connection may have dropped before the reply, the server may have failed over, or the caller's context may have ended while the COMMIT was in flight. The change may or may not be in the catalog, so a caller must inspect the catalog before retrying — never read it as the rollback an attempt that failed before COMMIT gets. Err keeps the cause for errors.Is and errors.As.

func (*CommitOutcomeUnknownError) Error added in v0.4.0

func (e *CommitOutcomeUnknownError) Error() string

func (*CommitOutcomeUnknownError) Unwrap added in v0.4.0

func (e *CommitOutcomeUnknownError) Unwrap() error

type ConcurrentBudget

type ConcurrentBudget struct {
	// Overall bounds the whole statement, waits included, via
	// statement_timeout. It must be at least one millisecond (PostgreSQL's
	// granularity); expect index builds on large tables to need a generous
	// value.
	Overall time.Duration
	// CallerOwned makes the caller's cancellable context the statement's only
	// bound: the session runs with statement_timeout disabled and Overall must
	// be zero. The executor refuses a context that cannot be cancelled.
	CallerOwned bool
}

ConcurrentBudget bounds one CONCURRENTLY statement (index build or drop).

CONCURRENTLY statements get their own wait policy instead of the blanket per-lock timeout: their waits for other transactions' snapshots are lock waits by implementation, so a session lock_timeout would cancel a healthy build mid-wait — and that cancellation is exactly what creates the invalid index this executor exists to prevent. The statement therefore runs with lock_timeout disabled and one bound on the whole statement: a server deadline, or in caller-owned mode the caller's cancellable context. That is safe with respect to the lock queue: the SHARE UPDATE EXCLUSIVE lock a concurrent build waits for does not block normal reads or writes queued behind it.

type CreateNameMismatchError added in v0.3.2

type CreateNameMismatchError struct {
	Schema    string
	Table     string
	Missing   []string
	Unclaimed []string
}

CreateNameMismatchError reports the owned relation names that differ from the create path's first-choice claims after the CREATE TABLE committed. Missing lists the claimed constraint-index and sequence names the table does not own; Unclaimed lists the names it owns that no claim predicted — the server's suffixed replacements. Both are sorted.

func (*CreateNameMismatchError) Error added in v0.3.2

func (e *CreateNameMismatchError) Error() string

Error names the committed table, the claimed names it lacks, and the names it owns instead, so an operator can rename the relation to its first choice once the occupant is gone or drop the table and re-diff.

func (*CreateNameMismatchError) Unwrap added in v0.3.2

func (e *CreateNameMismatchError) Unwrap() error

Unwrap exposes the sentinel boundary for errors.Is callers.

type CreateOwnerMismatchError added in v0.3.3

type CreateOwnerMismatchError struct{ Expected, Actual string }

CreateOwnerMismatchError reports the expected and catalog-resolved owner.

func (*CreateOwnerMismatchError) Error added in v0.3.3

func (e *CreateOwnerMismatchError) Error() string

func (*CreateOwnerMismatchError) Unwrap added in v0.3.3

func (e *CreateOwnerMismatchError) Unwrap() error

type CreateShapeCause added in v0.3.1

type CreateShapeCause string

CreateShapeCause is the stable identity of why the create path refuses a desired statement's shape. Automation branches on it, never on error text. Existing values never change meaning; new refusals add new values.

const (
	// CreateShapePartitionOf refuses attaching a partition because it locks
	// the partitioned parent, which the absence proof does not cover.
	CreateShapePartitionOf CreateShapeCause = "partition-of"
	// CreateShapeInherits refuses binding to an existing parent because the
	// absence proof does not cover it.
	CreateShapeInherits CreateShapeCause = "inherits"
	// CreateShapeLike refuses reading an existing source table because the
	// absence proof does not cover it.
	CreateShapeLike CreateShapeCause = "like"
	// CreateShapeOfType refuses binding to an existing composite type because
	// the absence proof does not cover it.
	CreateShapeOfType CreateShapeCause = "of-type"
	// CreateShapeIfNotExists refuses a name-only no-op because it cannot prove
	// the existing relation has the requested shape or is valid.
	CreateShapeIfNotExists CreateShapeCause = "if-not-exists"
	// CreateShapeConcurrently refuses a concurrent build because a table born
	// this run has no traffic to protect and a plain build cannot leave an
	// invalid index behind a failure.
	CreateShapeConcurrently CreateShapeCause = "concurrently"
	// CreateShapeDuplicateName refuses a desired set that claims the same
	// relation name twice before any statement runs.
	CreateShapeDuplicateName CreateShapeCause = "duplicate-name"
	// CreateShapeMultipleOperations refuses a statement when the statement and
	// operation parse boundaries disagree about its operation count.
	CreateShapeMultipleOperations CreateShapeCause = "multiple-operations"
	// CreateShapeUnsupportedKind refuses a statement kind outside the plain
	// CREATE TABLE and CREATE INDEX shapes the create path can run.
	CreateShapeUnsupportedKind CreateShapeCause = "unsupported-kind"
)

The causes for which the create path can refuse a desired statement.

func CreateShapeCauseOf added in v0.3.1

func CreateShapeCauseOf(err error) CreateShapeCause

CreateShapeCauseOf returns the create-shape cause carried by err, or the empty cause when err is nil or carries no create-shape refusal. Wrappers, including a *SequenceStepError naming the failed step, are read through.

func CreateShapeCauses added in v0.3.1

func CreateShapeCauses() []CreateShapeCause

CreateShapeCauses returns the closed set of create-shape refusal causes.

func (CreateShapeCause) Class added in v0.4.0

func (c CreateShapeCause) Class() refusal.Class

Class is the routing class of the cause, from docs/refusal-classes.md: what kind of boundary the consumer is looking at. A shape outside the absence proof — a partition, an inheritance parent, a LIKE source, a composite type — and a statement kind the create path does not run are a capability boundary: proofs and routes the engine could mint later. A name-only IF NOT EXISTS, a desired set that claims a name twice, and a concurrent build on a table born this run are by design: permanent decisions whose Description names the deliberate path. Two parse boundaries disagreeing about a statement's operation count is an invariant violation: a state this build should not produce, which no retry changes. The class is a triage decision; the cause's row in the document decides what the consumer does next. An unknown cause has no class.

func (CreateShapeCause) Description added in v0.3.1

func (c CreateShapeCause) Description() string

Description returns the human-facing sentence for a create-shape cause.

type CreateShapeError added in v0.3.1

type CreateShapeError struct {
	Cause CreateShapeCause
	Name  string
}

CreateShapeError identifies a create-shape refusal. Name is populated only when Cause is CreateShapeDuplicateName.

func (*CreateShapeError) Error added in v0.3.1

func (e *CreateShapeError) Error() string

Error renders the create-shape refusal for a human reader.

func (*CreateShapeError) Unwrap added in v0.3.1

func (e *CreateShapeError) Unwrap() error

Unwrap exposes the existing sentinel boundary for errors.Is callers.

type DropOutcomeUnknownError added in v0.5.5

type DropOutcomeUnknownError struct {
	Schema, Table, Index string
	// IndexOID is the OID of the index the pre-drop read checked. If it is
	// no longer in the catalog, the reviewed index is the one dropped.
	IndexOID uint32
	Err      error
}

DropOutcomeUnknownError means DROP INDEX CONCURRENTLY returned success, so an index was dropped, but the lookup that confirms it was the reviewed one failed: the connection dropped or the caller's context ended right after the drop. Whether the reviewed index or one that took its name in between was dropped is unknown, so a caller must inspect the table's indexes before retrying. A rerun alone does not settle it: once the name is gone, it reports dropped-index-drift whichever index was dropped. Err keeps the cause for errors.Is and errors.As.

func (*DropOutcomeUnknownError) Error added in v0.5.5

func (e *DropOutcomeUnknownError) Error() string

func (*DropOutcomeUnknownError) Unwrap added in v0.5.5

func (e *DropOutcomeUnknownError) Unwrap() error

type DroppedIndex added in v0.3.0

type DroppedIndex struct {
	// Schema is the schema the entry lived in.
	Schema string `json:"schema"`
	// Index is the entry's name at drop time — its identity-derived
	// quarantine name, not the name the failed build gave it.
	Index string `json:"index"`
	// IndexOID is the removed entry's catalog identity.
	IndexOID uint32 `json:"index_oid"`
	// Duration is the wall-clock time of the DROP INDEX CONCURRENTLY
	// statement itself. It encodes as integer nanoseconds.
	Duration time.Duration `json:"duration_ns"`
}

DroppedIndex records one abandoned invalid index the recovery removed.

func ExecuteDropIndexConcurrently added in v0.5.5

func ExecuteDropIndexConcurrently(ctx context.Context, pool *pgxpool.Pool, schema, table, index, definition string, b ConcurrentBudget) (DroppedIndex, error)

ExecuteDropIndexConcurrently drops one reviewed index with DROP INDEX CONCURRENTLY, so the drop never takes the ACCESS EXCLUSIVE lock a plain DROP INDEX holds while it waits behind the table's other transactions. A caller has already admitted the index as destructive; definition is the one the plan carried (schemadiff.DroppedObject.Definition).

DROP INDEX CONCURRENTLY cannot run inside a transaction block, so the index is checked and dropped on one pooled session under the CONCURRENTLY wait policy (see ConcurrentBudget). Immediately before the drop the check refuses, dropping nothing, unless schema.index is still a valid plain index of schema.table that has definition and that the server will drop concurrently (ErrDroppedIndexDrift), and is not the replica identity index of a table, whose loss makes UPDATE and DELETE fail while a publication publishes them (ErrReplicaIdentityDrop).

PostgreSQL drops an index only by name, so another session can swap the name in the round trip between the check and the drop. After the drop the checked index's OID is looked up once more. That lookup is detective only: it catches a swap that renamed the checked index aside, reports it as ErrDroppedIndexReplaced, and cannot undo the drop or see a swap that dropped the checked index as well. If the lookup itself fails, the drop returns a *DropOutcomeUnknownError.

statement_timeout is the overall budget, or the caller's cancellation in caller-owned mode, and lock_timeout is disabled for the reasons ConcurrentBudget gives. A drop that does not finish returns a *BudgetError or the caller's cancellation and leaves the index as it was or marks it invalid; an invalid leftover is debris the diff reports as an advisory, never as a drop. It needs one pool connection.

type IndexBuildReport

type IndexBuildReport struct {
	// Schema is the schema the index lives in, resolved from the target
	// table (an index is always created in its table's schema).
	Schema string `json:"schema"`
	// Index is the index name from the statement.
	Index string `json:"index"`
	// IndexOID is the verified index's catalog identity: the durable
	// handle a later reconciliation can use where the name alone could
	// have been reassigned.
	IndexOID uint32 `json:"index_oid"`
	// Duration is the wall-clock time of the build statement itself,
	// excluding session setup and the validity verification. It encodes
	// as integer nanoseconds.
	Duration time.Duration `json:"duration_ns"`
	// ServerVersion is the server_version of the PostgreSQL server that
	// ran the build.
	ServerVersion string `json:"server_version"`
}

IndexBuildReport says what a concurrent build did, machine-readably. It is returned only after the executor re-read the catalog and verified the built index is valid — it means "verified valid", not "the server did not complain" — so it is evidence an orchestrator can store or forward.

func BuildIndexConcurrently

func BuildIndexConcurrently(ctx context.Context, pool *pgxpool.Pool, sql string, b ConcurrentBudget) (IndexBuildReport, error)

BuildIndexConcurrently runs one named CREATE INDEX ... CONCURRENTLY on a schema-qualified table, on its own session, outside any transaction, bounded by b. The pool must come from pkg/dbconn (raw pools may carry a reset baseline the session hygiene here cannot vouch for) and must allow at least two connections: the post-failure verdict's session is acquired up front, alongside the build session, so the verdict can never starve on a busy pool — a pool configured below two is refused at admission (ErrPoolTooSmall), and both acquisitions are bounded by ctx. The build never drops an index: PostgreSQL drops by name, not identity, so a drop here could not prove it is destroying this build's own debris rather than another actor's same-name index registered in the same window. That proof is RebuildAbandonedIndex's job — it holds the table lock every concurrent build needs while it renames the entry by identity and drops it by that unique name. Every invalid index the build meets is surfaced as a typed, fail-closed *InvalidIndexError whose Cleanup says which state it is (see docs/invalid-index-recovery.md):

  • an invalid index with the requested name that another backend is still building refuses to build and says wait (ErrInvalidIndexBuildInFlight, carrying the builder's PID);
  • an abandoned invalid index with the requested name on the target table refuses to build and names the recovery (ErrAbandonedInvalidIndex, Recoverable);
  • an invalid index with the requested name on another table in the schema refuses to build and leaves it to that table's own change (ErrInvalidIndexOnOtherTable);
  • an invalid index with the requested name on the target table whose builder this role cannot observe — another role's progress row is hidden without pg_read_all_stats, and none is recorded with track_activities off — refuses to build without claiming it abandoned (ErrInvalidIndexBuilderUnobservable, Recoverable: the recovery's lock proof does not depend on the view);
  • a failed build that left an invalid entry behind reports it (ErrBuildLeftInvalidIndex, Recoverable) after proving the build's own backend stopped, so the catalog verdict cannot race the dying statement;
  • a failed build that provably left nothing returns its failure alone — a retry can start immediately.

A cancelled build is typed by its cause. A server cancellation at or past the server-owned overall budget is that budget's own statement_timeout and surfaces as a *BudgetError, whatever the caller's context did meanwhile. Below the budget, the caller's own context ending surfaces as ErrCancelledByCaller in either mode, and a cancellation under a live context cannot be the budget's or the caller's and surfaces as ErrCancelledExternally. In caller-owned mode the cancellable context is the only bound and statement_timeout is disabled, so a 57014 under a live context is always ErrCancelledExternally. Caller cancellation is a race: the client returns while the cancel signal travels to the server, so a build cancelled at the finish line may still complete. The guarantee is about the catalog, not the race: after this function returns without an *InvalidIndexError, the index is either valid or absent — success is returned only after re-reading the catalog and verifying pg_index.indisvalid on the built index, a guard against server-version drift in what "success" leaves behind.

Unlike the optimistic attempt, no size-guard proof is required: the size guard exists because a blocking attempt holds ACCESS EXCLUSIVE for its whole budget, while a concurrent build takes only SHARE UPDATE EXCLUSIVE — long builds on large tables are its purpose.

func BuildIndexConcurrentlyWithProgress

func BuildIndexConcurrentlyWithProgress(ctx context.Context, pool *pgxpool.Pool, sql string, b ConcurrentBudget, tracker *progress.Tracker) (rep IndexBuildReport, err error)

BuildIndexConcurrentlyWithProgress runs a concurrent build while updating tracker. The caller may poll tracker concurrently with this blocking call.

type IndexRecoveryReport added in v0.3.0

type IndexRecoveryReport struct {
	// Dropped lists the abandoned invalid indexes removed before the build,
	// in removal order; empty when the table carried none.
	Dropped []DroppedIndex `json:"dropped"`
	// Skipped lists the quarantined entries on the table that DROP INDEX
	// CONCURRENTLY cannot remove — an entry that became a partitioned
	// index's partition or a constraint's index after it was quarantined —
	// which the sweep leaves in place for an operator and steps over, so
	// one such entry never blocks every later recovery on the table. Empty
	// when there were none.
	Skipped []QuarantinedIndex `json:"skipped"`
	// Build is the verified report of the requested index build. It is zero
	// when returned by DropAbandonedIndex, which does not run a build.
	Build IndexBuildReport `json:"build"`
	// Duration is the wall-clock time of the whole recovery call — proof
	// and drops, plus the build when requested — so a caller that sized
	// the budget as a lease can see what the recovery actually spent. It
	// is set on every return, a refusal included, so a refusal that waited
	// out a lock bound reports the wait. It encodes as integer nanoseconds.
	Duration time.Duration `json:"duration_ns"`
}

IndexRecoveryReport says what an abandoned-index recovery did: which abandoned entries it removed, which quarantined entries it left alone, and, for RebuildAbandonedIndex, the verified build.

func DropAbandonedIndex added in v0.3.2

func DropAbandonedIndex(ctx context.Context, pool *pgxpool.Pool, sql string, b ConcurrentBudget) (IndexRecoveryReport, error)

DropAbandonedIndex proves that the invalid index occupying the name in a CREATE INDEX ... CONCURRENTLY statement is abandoned, quarantines it by OID, and drops it concurrently without running the requested build. It has the same admission rules, fail-closed invalid-index verdicts, and proof and drop budgets as RebuildAbandonedIndex. It needs two pool connections: the recovery session and a drop session. Build in the returned report is always zero.

func RebuildAbandonedIndex added in v0.3.0

func RebuildAbandonedIndex(ctx context.Context, pool *pgxpool.Pool, sql string, b ConcurrentBudget) (IndexRecoveryReport, error)

RebuildAbandonedIndex removes the abandoned invalid index occupying the name a CREATE INDEX ... CONCURRENTLY statement asks for, then runs the build. It accepts exactly the statements BuildIndexConcurrently accepts under the same budget, needs a pool one connection larger (its own session stays open across the drops and the build), and is the recovery the build's ErrAbandonedInvalidIndex, ErrBuildLeftInvalidIndex, and ErrInvalidIndexBuilderUnobservable outcomes name. With no invalid index under the name and no quarantined debris on the table it is the build alone.

The removal is safe because it is proven, not because it is named:

  1. Under a bounded SHARE UPDATE EXCLUSIVE lock on the target table — the lock every concurrent index command holds for its whole life, so holding it means no build, drop, or reindex of any index on the table is in flight — the entry is re-verified by OID (still under the requested name, still invalid, still on this table in this schema, still an index the server will drop concurrently, no builder) and renamed to a name derived from that OID. A lock not granted within the bound is reported as a *BudgetError (CauseLock) and nothing is touched.
  2. The rename commits, and every invalid index on the table whose name is its own quarantine name is dropped with DROP INDEX CONCURRENTLY, each verified by OID before and after. The quarantine name can belong to nothing but the entry it was derived from, so the drop by name is a drop by identity; and because the sweep keys on the name pattern, a crash between rename and drop leaves debris a later recovery removes on its own — and a plain BuildIndexConcurrently on the table refuses until it does, so the debris stays loud.
  3. The requested build runs exactly as BuildIndexConcurrently.

The recovery refuses, touching nothing, when the invalid index under the name is visibly another backend's build still in progress (ErrInvalidIndexBuildInFlight), sits on a different table (ErrInvalidIndexOnOtherTable), or is not an index the server will drop concurrently (ErrInvalidIndexNotDroppable: a partitioned table's index, an index partition, a constraint's index — invalid for reasons of their own, never a failed build's debris) — see (*InvalidIndexError).Recoverable — and fails closed with ErrAbandonmentUnproven when the entry changes between two verification points or a drop leaves it in place. A builder this role cannot observe (ErrInvalidIndexBuilderUnobservable at the build) is not a refusal here: the lock in step 1 is the proof, and a hidden build holds the lock like any other, so the recovery reports the lock budget instead of waiting behind it. It never removes a valid index.

Time is bounded by construction. Every lock the recovery waits for on its own behalf — the proof lock and the drops' waits — is bounded by recoveryLockTimeout; the whole sweep of drops shares one Overall budget (each drop gets what the earlier ones left), and the build gets Overall once more, so the recovery takes at most the lock bound plus twice the budget plus the build's own bounded verdict. In caller-owned mode the caller's cancellation bounds the drops and the build alike. The report's Duration says what was actually spent.

type InvalidIndexError

type InvalidIndexError struct {
	// Schema and Index identify the possibly-invalid index.
	Schema string
	Index  string
	// Table is the table the invalid index sits on, when the catalog
	// inspection saw the entry; empty when the state could not be
	// inspected.
	Table string
	// BuilderPID is the backend running a concurrent build or reindex of
	// this exact index (pg_stat_progress_create_index), when the entry is
	// in flight; zero otherwise.
	BuilderPID uint32
	// Build is the build failure that left the index invalid; nil when
	// there is no build failure to carry.
	Build error
	// Cleanup is why the recovery drop was refused, failed, or could not
	// be verified.
	Cleanup error
}

InvalidIndexError reports that an invalid index exists (or may remain) and the executor will not or cannot remove it: the one outcome that needs an operator. Build carries the failure that produced the leftover, nil when there is no build failure to carry (the entry predates this run, or a reported success failed its validity verification); Cleanup carries why automatic recovery was refused, failed, or could not be proven.

func (*InvalidIndexError) Code

func (e *InvalidIndexError) Code() Code

Code returns the invalid-index outcome's stable code, derived from the same state the error's rendering distinguishes: a build that failed on a data fault, then the cleanup state — proven own leftover, another backend's build in flight, abandoned on the target table, on another table, not droppable, builder unobservable, or unproven. The data fault outranks the cleanup state because it names what the operator corrects: no handling of the leftover gets a rerun past the same rows. An invariant breach in either the build or the cleanup outranks both, as it does in OutcomeCode. The cleanup sentinel stays in the chain for errors.Is.

func (*InvalidIndexError) Error

func (e *InvalidIndexError) Error() string

Error implements the error interface. The advice is as state-specific as the type: a removal is named only in the states where the recovery can prove ownership before it drops — the same standard the executor holds itself to. An in-flight build says wait; another table's debris, an index the server will not drop concurrently, and an unproven state get investigation steps, never a statement to copy-paste: the index under that name may be healthy, or may be exactly what it is meant to be. A build that failed on a data fault leads with the fault, since no recovery of the leftover gets past the rows (dataFaultError).

func (*InvalidIndexError) Recoverable added in v0.3.0

func (e *InvalidIndexError) Recoverable() bool

Recoverable reports whether RebuildAbandonedIndex can remove the entry and build the requested index: true for this build's own proven leftover, for an abandoned entry on the target table, and for an entry on the target table whose builder this role cannot observe — the recovery's proof is a table lock, not the progress view, so it decides what the view could not. A visibly in-flight build, another table's debris, an index the server will not drop concurrently, and an unproven state are not this actor's to recover. A build that failed on a data fault is not recoverable either, whatever it left: the rebuild would meet the same rows and fail the same way, so the rows are corrected first and the leftover removed as the error says.

func (*InvalidIndexError) Unwrap

func (e *InvalidIndexError) Unwrap() []error

Unwrap exposes the underlying failures to errors.Is/As.

type MissingPartitionKey added in v0.5.5

type MissingPartitionKey struct {
	// Schema and Table name the partitioned table.
	Schema string
	Table  string
	// Columns are its partition key columns the index's key lacks, in key
	// order.
	Columns []string
	// Expression is true when its partition key includes an expression,
	// which no unique index can contain.
	Expression bool
}

MissingPartitionKey is one partitioned table whose partition key a unique index does not contain.

type PartitionIndexAction added in v0.5.5

type PartitionIndexAction string

PartitionIndexAction says what the build did to give one partition an index attached to the parent's.

const (
	// PartitionIndexBuilt means the build created the partition's index
	// concurrently, then attached it.
	PartitionIndexBuilt PartitionIndexAction = "built"
	// PartitionIndexReused means the partition already had a valid index of
	// the requested definition, under the derived name, that no partitioned
	// index owned: one an earlier run built and did not attach.
	PartitionIndexReused PartitionIndexAction = "reused"
	// PartitionIndexAdopted means the partition already had a valid index of
	// the requested definition under another name, and the build attached it
	// instead of building one. From then on it is a partition of the parent's
	// index, which the server refuses to drop on its own.
	PartitionIndexAdopted PartitionIndexAction = "adopted"
	// PartitionIndexOnly means the partition is itself partitioned, so the
	// build gave it a metadata-only index, filled by its partitions' indexes,
	// and attached that.
	PartitionIndexOnly PartitionIndexAction = "partitioned"
)

type PartitionIndexResult added in v0.5.5

type PartitionIndexResult struct {
	// Schema and Table identify the partition.
	Schema string `json:"schema"`
	Table  string `json:"table"`
	// Index is the name of the partition's index that is now attached.
	Index string `json:"index"`
	// IndexOID is that index's catalog identity.
	IndexOID uint32 `json:"index_oid"`
	// Action says how the partition got its index.
	Action PartitionIndexAction `json:"action"`
	// RecoveredDebris is true when the build first removed the invalid
	// leftover of an earlier failed build of this partition's index, under the
	// proof RebuildAbandonedIndex gives.
	RecoveredDebris bool `json:"recovered_debris,omitempty"`
}

PartitionIndexResult is one partition the build had work to do on. A partition that already had its index attached is counted in PartitionedIndexReport.Partitions and not listed here.

type PartitionedIndexReport added in v0.5.5

type PartitionedIndexReport struct {
	// Schema and Index identify the parent's index.
	Schema string `json:"schema"`
	Index  string `json:"index"`
	// IndexOID is the verified index's catalog identity.
	IndexOID uint32 `json:"index_oid"`
	// ParentCreated is true when this run created the parent's index, and
	// false when it resumed one an earlier run left invalid.
	ParentCreated bool `json:"parent_created"`
	// Partitions is the number of partitions in the tree, at every depth.
	Partitions int `json:"partitions"`
	// Worked lists the partitions this run gave an index, in order.
	Worked []PartitionIndexResult `json:"worked,omitempty"`
	// Passes is how many times the build walked the tree.
	Passes int `json:"passes"`
	// Duration is the wall-clock time of the whole build. It encodes as
	// integer nanoseconds.
	Duration time.Duration `json:"duration_ns"`
	// ServerVersion is the server_version of the server that ran the build.
	ServerVersion string `json:"server_version"`
}

PartitionedIndexReport says what a partitioned index build did. It is returned only after the executor re-read the parent's index and verified it valid, so it means "verified valid, every partition attached".

func BuildPartitionedIndex added in v0.5.5

BuildPartitionedIndex adds the index a CREATE INDEX statement describes to a partitioned table, online, and returns once the parent's index is valid and every partition in the tree has an index attached to it.

The statement is one named, schema-qualified CREATE INDEX on the preflighted partitioned table, with or without CONCURRENTLY and ON ONLY; every form asks for a complete index on the whole tree. The build holds the parent's advisory table lock (LK-1) for its whole run, so a second run on the same parent is refused with a *dbconn.TableLockHeldError; cfg is the connection target that lock's dedicated session dials, the same Config the pool was made from. Under the lock it:

  1. refuses a tree that holds a foreign table (ErrForeignTablePartition), and a unique index that does not contain the partition key of every partitioned table in the tree (ErrUniqueIndexPartitionKey);
  2. creates the parent's index with ON ONLY, or resumes one an earlier run left when it is a partitioned index of the requested definition (ErrPartitionedIndexNameTaken otherwise);
  3. gives each partition an attached index, recursively: a leaf reuses or adopts a matching valid index or builds one concurrently under the derived name, and a sub-partitioned partition gets its own ON ONLY index, filled the same way, before it is attached;
  4. walks the tree again, up to a fixed number of passes, for partitions created or attached meanwhile (ErrPartitionedIndexUnsettled when they keep appearing);
  5. re-reads the parent's index and returns only when it is valid.

A failure at any point leaves a valid prefix, and rerunning the same statement resumes from it. An index adopted from a partition is attached, not copied: it is removed with the parent's index or by detaching its partition. The build never drops an index it did not prove abandoned.

Every partition's build is bounded by b, one budget per partition; every other statement runs under the pool's own bounded lock and statement timeouts. The pool must come from pkg/dbconn and hold at least two connections, the concurrent build's own minimum. Partitions are listed from the catalog at run time, not from a plan, because they can change between planning and running.

func BuildPartitionedIndexAsStep added in v0.5.5

func BuildPartitionedIndexAsStep(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, b ConcurrentBudget, at RunStep) (PartitionedIndexReport, error)

BuildPartitionedIndexAsStep is BuildPartitionedIndex reported to the run step at: the whole build is step at.Step of a run that owns the tracker, so the partitions it works on are each a statement of that one step, named in the step's detail, and the run's step total is untouched. The call never calls Start or Finish; the front door that runs several statements under one tracker keeps one elapsed time and one terminal outcome across them.

func BuildPartitionedIndexWithProgress added in v0.5.5

func BuildPartitionedIndexWithProgress(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, b ConcurrentBudget, tracker *progress.Tracker) (rep PartitionedIndexReport, err error)

BuildPartitionedIndexWithProgress runs a partitioned index build while updating tracker, which the caller may poll concurrently. A step is one partition, the parent's index being step one, and total_steps is the partitions found plus one, growing when the build finds more. It is an upper bound: a partition that already has its index attached takes no step, so a resumed run finishes below it.

type QuarantinedIndex added in v0.3.0

type QuarantinedIndex struct {
	// Schema is the schema the entry lives in.
	Schema string `json:"schema"`
	// Index is the entry's identity-derived quarantine name.
	Index string `json:"index"`
	// IndexOID is the entry's catalog identity.
	IndexOID uint32 `json:"index_oid"`
}

QuarantinedIndex records one quarantined entry the recovery found on the table and deliberately left in place.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts    int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

RetryPolicy bounds retries after lock_timeout expires. Backoff doubles after each failed attempt and is capped at MaxBackoff.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the safe native-DDL retry policy used by callers that do not need to tune lock acquisition.

type RowSecurityOutcomeUnknownError added in v0.4.0

type RowSecurityOutcomeUnknownError struct{ Err error }

RowSecurityOutcomeUnknownError means the commit response was lost or failed. Inspect the catalog before retrying; an error does not prove rollback here.

func (*RowSecurityOutcomeUnknownError) Error added in v0.4.0

Error describes the uncertain commit boundary.

func (*RowSecurityOutcomeUnknownError) Unwrap added in v0.4.0

Unwrap retains the underlying commit error.

type RowSecurityPlan added in v0.4.0

type RowSecurityPlan struct {
	Schema     string   `json:"schema"`
	Table      string   `json:"table"`
	Statements []string `json:"statements"`
	// ExtensionSchemas is set for a table that does not exist yet: the
	// schemas its definition's statements resolve unqualified names
	// against, after the schema and public. The row security statements
	// run under pg_catalog alone.
	ExtensionSchemas []string `json:"extension_schemas,omitempty"`
}

RowSecurityPlan contains generated RLS statements in execution order. A preview of an existing table runs no target DDL. A preview of a table that does not exist yet runs the whole create transaction on the target, readback included, and rolls it back: no catalog change survives, but what a rollback does not undo does, such as a sequence an event trigger on that DDL advances. A plan is not an execution permission.

func PreviewCreateWithRowSecurity added in v0.5.1

func PreviewCreateWithRowSecurity(ctx context.Context, pool *pgxpool.Pool, at preflight.AbsentTarget, cr preflight.CreationRole, desired statement.DesiredWithRowSecurity, b Budget) (RowSecurityPlan, error)

PreviewCreateWithRowSecurity runs everything ExecuteCreateWithRowSecurity runs, including the readback that proves the table and its row security converge, and then rolls back. The statements are the ones execution would run. Nothing is visible to other sessions at any point. The target DDL does run, so what a rollback does not undo survives the preview, such as a sequence an event trigger on that DDL advances.

func PreviewDesiredCreateWithRowSecurity added in v0.5.1

func PreviewDesiredCreateWithRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema, createOwner string, desired statement.DesiredWithRowSecurity, b Budget) (RowSecurityPlan, error)

PreviewDesiredCreateWithRowSecurity mints the same proofs as ExecuteDesiredRowSecurity for an absent table and previews its create, under one deadline. A table at the name returns an error wrapping preflight.ErrRelationExists, and the caller previews the existing table instead.

func PreviewRowSecurity added in v0.4.0

func PreviewRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema string, desired statement.DesiredWithRowSecurity, b Budget) (RowSecurityPlan, error)

PreviewRowSecurity derives the same SQL as execution under a bounded exclusive table lock, then rolls back without changing target policies or settings. While held, ACCESS EXCLUSIVE blocks all reads and writes on the target. LockTimeout bounds acquisition; StatementTimeout bounds the whole attempt.

type RowSecurityReport added in v0.4.0

type RowSecurityReport struct {
	Schema           string   `json:"schema"`
	Table            string   `json:"table"`
	Statements       []string `json:"statements"`
	TableCreated     bool     `json:"table_created,omitempty"`
	ExtensionSchemas []string `json:"extension_schemas,omitempty"`
}

RowSecurityReport contains only committed RLS statements, in execution order. A no-op has an empty Statements slice. Errors return a zero report. TableCreated is true when the run created the table along with its row security, so Statements begins with its CREATE TABLE. ExtensionSchemas is set only then: the schemas the table definition's statements resolved unqualified names against, after the schema and public.

func ExecuteCreateWithRowSecurity added in v0.5.1

ExecuteCreateWithRowSecurity creates the verified-absent table, its indexes, and its complete row security in one transaction. No other session can see the table before the transaction commits, so a table whose policies are still missing is never visible: an API that exposes new tables to clients, or a role with default privileges on the schema, finds either no table or the table with its row security in force.

The proofs follow ExecuteCreate: at proves the name was free and cr that the session can create in its schema, both minted on this pool just before the call. Every table and index statement is qualified into the proof's schema, re-parsed, and admitted by shape and target, and the names it claims are probed free, before the transaction begins. The row security is built in a rolled-back scratch schema first, then rendered from that catalog and run with a pg_catalog-only search_path, as in ExecuteRowSecurity. Before committing, the transaction reads the new table back: it must own every first-choice name it claimed, belong to the creation role, and match the desired table and row security exactly. Any failure before the commit rolls everything back, including a name an occupant took after the probe, which a stepwise create could only report after its table committed. A failed commit is a *RowSecurityOutcomeUnknownError.

b.StatementTimeout bounds each statement and the whole attempt. No retries occur. The caller needs CREATE on the database for the scratch schema.

func ExecuteDesiredRowSecurity added in v0.5.1

func ExecuteDesiredRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema, createOwner string, desired statement.DesiredWithRowSecurity, b Budget) (RowSecurityReport, error)

ExecuteDesiredRowSecurity converges a desired file that declares row security, whether or not its table exists. It mints the absence and creation-access proofs itself, inside the attempt, so b.StatementTimeout bounds the probes as well as the change. An existing table converges as ExecuteRowSecurity converges it. An absent table is created as ExecuteCreateWithRowSecurity creates it, owned by createOwner when that is non-empty. A standalone type at the table's name is a create collision.

func ExecuteReviewedRowSecurity added in v0.4.0

func ExecuteReviewedRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema string, desired statement.DesiredWithRowSecurity, reviewed []string, b Budget) (RowSecurityReport, error)

ExecuteReviewedRowSecurity regenerates SQL under the target lock and refuses any difference from reviewed, including order and duplicates. Empty reviewed authorizes only a no-op. The supplied SQL is compared, never executed directly. This binds execution to SQL, not to a snapshot of the earlier live definition. Budgets, admission, verification and atomicity match ExecuteRowSecurity.

func ExecuteRowSecurity added in v0.4.0

func ExecuteRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema string, desired statement.DesiredWithRowSecurity, b Budget) (RowSecurityReport, error)

ExecuteRowSecurity converges only the complete RLS definition of an existing ordinary table. It locks and inspects the target itself and refuses table deltas. Budget.StatementTimeout also bounds the entire attempt, including connection acquisition, scratch inspection, and lock waits. No retries occur. The caller must have table-owner and scratch-schema creation privileges.

type RunStep added in v0.5.2

type RunStep struct {
	// Tracker is the run's tracker; nil tracks nothing.
	Tracker *progress.Tracker
	// Step is the 1-based step of the run this call is.
	Step int
}

RunStep places one executor call inside a longer run whose tracker the caller owns: the caller has called Start for the whole run and calls Finish when the run ends, and this call is step Step of it. Every step the call executes — each statement of a safer sequence, a concurrent index build included — is reported to Tracker as step Step, with that statement's own operation and SQL, so an observer reads the run's position from the step and what is executing now from the detail. The call never calls Start or Finish: a front door that runs several statements under one tracker keeps one elapsed time and one terminal outcome across them. The zero value tracks nothing.

type SequenceBudget

type SequenceBudget struct {
	// Brief bounds every brief catalog step.
	Brief Budget
	// Concurrent bounds every concurrent index build step.
	Concurrent ConcurrentBudget
	// Validate bounds every VALIDATE CONSTRAINT step.
	Validate ValidateBudget
}

SequenceBudget bounds one sequence run: each admitted step class carries its own budget, because the classes have opposite needs — a brief catalog step must be cancelled fast, a validation scan and a concurrent build must be allowed to run long.

type SequenceReport

type SequenceReport struct {
	// Steps are the per-step reports, in execution order.
	Steps []StepReport `json:"steps"`
}

SequenceReport is the record of a sequence run: one report per committed step, in execution order. On success it covers every step; alongside a *SequenceStepError it covers exactly the committed prefix, so a caller can disclose what already happened.

func ExecuteCreate added in v0.2.0

ExecuteCreate runs the desired schema's statements against the verified-absent target: the CREATE TABLE first, then its indexes in input order, each step a bounded transactional run under the brief budgets, exactly like an optimistic attempt, with its search_path pinned to the proof's schema then public — the same policy the introspection read path sets — so the desired file's unqualified references resolve exactly as the diff resolved them. The pool must come from pkg/dbconn and must be the session the proofs were minted on: cr proves that session's role can create in the proof's schema, and like the absence proof it is time-of-check — a grant revoked after minting fails with the server's own error. Every desired statement is qualified into the proof's schema, re-parsed, and admitted by shape and target, and every index and constraint-index name the file states is probed free in pg_class, before the first step executes. A refusal from either check returns with an empty report and no *SequenceStepError: an occupied name is ErrCreateCollision, an inadmissible shape one of the admission sentinels, and a probe that could not complete (a cancelled context, a lost connection) is that error, wrapped — not a collision. On success every step committed and the report says what each did. On failure the run stops at the failing step and returns a typed *SequenceStepError; the committed prefix remains — a rerun's absence check then refuses with preflight.ErrRelationExists, and the caller re-diffs the live catalog to apply the remainder. retry bounds lock_timeout retries on each step, exactly as in ExecuteNative.

func ExecuteCreateAsSteps added in v0.5.2

ExecuteCreateAsSteps is ExecuteCreate reported to a run whose steps are the desired file's statements: the caller has started tracker for len(ds.Statements()) steps and finishes it, and the create reports its i-th statement as step i. A nil tracker runs exactly as ExecuteCreate.

func ExecuteCreateWithProgress added in v0.2.0

func ExecuteCreateWithProgress(ctx context.Context, pool *pgxpool.Pool, at preflight.AbsentTarget, cr preflight.CreationRole, ds statement.DesiredSchema, b Budget, retry RetryPolicy, tracker *progress.Tracker) (rep SequenceReport, err error)

ExecuteCreateWithProgress runs the create path while updating tracker with the current step. The caller may poll concurrently.

func RunSequence

func RunSequence(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, steps []string, b SequenceBudget, retry RetryPolicy) (SequenceReport, error)

RunSequence runs steps in order against the preflighted table, each step in its own implicit or bounded transaction — the autocommit-each-step contract a planner-produced safer sequence carries. The pool must come from pkg/dbconn and, when the sequence contains a concurrent index build, must allow at least two connections (see BuildIndexConcurrently). The whole sequence is admitted before the first step executes: every step is re-parsed, its shape classified, and its target verified against the preflight proof, so a sequence this executor cannot finish is never started. On success every step committed and the report says what each did. On failure the run stops at the failing step and returns a typed *SequenceStepError; the committed prefix remains, per the planner's documented partial-failure contracts, and the returned report covers exactly that prefix.

Like the concurrent build — and unlike a blind optimistic attempt — no size-guard proof is required beyond the preflight itself: long scans on large tables are the sequence pattern's purpose, and every brief step is still individually bounded by the brief budgets. retry bounds lock_timeout retries on each owner-gated step, exactly as in ExecuteNative.

func RunSequenceAdopting added in v0.4.0

func RunSequenceAdopting(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, steps []string, b SequenceBudget, retry RetryPolicy, adopts schemadiff.IndexAdoption) (SequenceReport, error)

RunSequenceAdopting is RunSequence for a planned ADD CONSTRAINT ... USING INDEX: the step that takes over adopts.Index first checks, under the table's lock and in the same transaction, that the index is still valid and still has adopts.Def, and refuses with ErrAdoptedIndexDrift when it is not. A sequence with no step that takes over that index is refused as an invariant violation before anything runs.

func RunSequenceAsStep added in v0.5.2

RunSequenceAsStep is RunSequence reported to the run step at, taking over adopts, validating validates, and dropping dropped when they are set; at most one of the three may be set. The first two are checked as RunSequenceAdopting and RunSequenceValidating check them; the step that drops dropped first checks, under the table's lock, that the column, constraint, or NOT NULL still has the definition the plan carried, and refuses with ErrDroppedObjectDrift, dropping nothing, when it does not. Each admitted step is reported as at.Step in turn, so a concurrent index build publishes the server's build counters under it. A zero at runs exactly as the untracked entry point for the same arguments.

func RunSequenceDropping added in v0.5.5

func RunSequenceDropping(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, steps []string, b SequenceBudget, retry RetryPolicy, dropped schemadiff.DroppedObject) (SequenceReport, error)

RunSequenceDropping is RunSequence for a planned drop of a column, constraint, or NOT NULL: the step that drops dropped first checks, under the table's lock, that it still has the definition the plan carried, and refuses with ErrDroppedObjectDrift, dropping nothing, when it does not. A sequence with no step that drops it is refused as an invariant violation before anything runs.

func RunSequenceValidating added in v0.4.0

func RunSequenceValidating(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, steps []string, b SequenceBudget, retry RetryPolicy, validates schemadiff.ConstraintValidation) (SequenceReport, error)

RunSequenceValidating is RunSequence for a planned VALIDATE CONSTRAINT: the step that validates validates.Constraint first checks, under the table's lock and in the same transaction, that the constraint still has validates.Def, and refuses with ErrValidatedConstraintDrift when it does not. A sequence with no step that validates that constraint is refused as an invariant violation before anything runs.

func RunSequenceWithProgress

func RunSequenceWithProgress(ctx context.Context, pool *pgxpool.Pool, pt preflight.PreflightedTable, steps []string, b SequenceBudget, retry RetryPolicy, tracker *progress.Tracker) (rep SequenceReport, err error)

RunSequenceWithProgress runs a sequence while updating tracker with the current step and its execution class. The caller may poll concurrently.

type SequenceStepError

type SequenceStepError struct {
	// Step is the failed step's 1-based position, matching the numbering
	// the planner's partial-failure contracts use.
	Step int
	// Total is the number of steps the sequence was admitted with.
	Total int
	// Kind is the execution class the failed step ran under.
	Kind StepKind
	// SQL is the failed step's statement.
	SQL string
	// Err is the step's underlying failure.
	Err error
}

SequenceStepError reports that a step failed and the run stopped there. The steps before it committed and their partial state remains — the planner's sequence constructors document what each failed step leaves behind and how a retry resumes. Err carries the step's own typed failure (*BudgetError, *InvalidIndexError, a server error) for errors.Is/As.

func (*SequenceStepError) Code

func (e *SequenceStepError) Code() Code

Code returns the failed step's own cause code; the step position and the committed prefix ride on the struct's fields.

func (*SequenceStepError) Error

func (e *SequenceStepError) Error() string

Error implements the error interface. It names the failed step and the committed prefix, because "what already happened" is the first triage question a partial sequence raises.

func (*SequenceStepError) Unwrap

func (e *SequenceStepError) Unwrap() error

Unwrap exposes the step's failure to errors.Is/As.

type StepKind

type StepKind string

StepKind is the typed execution class a step was admitted under; automation branches on it, never on the step's SQL text.

const (
	// StepBrief: a bounded transactional run under the brief budgets — a
	// catalog change that must prove itself effectively instant, exactly
	// like an optimistic attempt.
	StepBrief StepKind = "brief"
	// StepConcurrentIndexBuild: a CREATE INDEX CONCURRENTLY delegated to
	// the dedicated concurrent build executor, with its wait policy and
	// invalid-index verdict.
	StepConcurrentIndexBuild StepKind = "concurrent-index-build"
	// StepValidateConstraint: an ALTER TABLE ... VALIDATE CONSTRAINT, alone
	// or beside operations that also take only SHARE UPDATE EXCLUSIVE — a
	// long online scan, bounded by the validate budget rather than the
	// brief one.
	StepValidateConstraint StepKind = "validate-constraint"
	// StepDetachPartition: an ALTER TABLE whose one subcommand is DETACH
	// PARTITION ... CONCURRENTLY, run outside a transaction block under
	// the brief budgets, which finishes a partition an earlier run left
	// detach-pending.
	StepDetachPartition StepKind = "detach-partition-concurrently"
)

The execution classes a step can be admitted under.

func StepKinds added in v0.2.0

func StepKinds() []StepKind

StepKinds returns the closed set of StepKind values. It is part of the documented contract: docs/execution-model.md names every kind.

type StepReport

type StepReport struct {
	// SQL is the step's statement as submitted.
	SQL string `json:"sql"`
	// Kind is the execution class the step ran under.
	Kind StepKind `json:"kind"`
	// Duration is the wall-clock time of the step, session setup and
	// verification included. It encodes as integer nanoseconds.
	Duration time.Duration `json:"duration_ns"`
	// Index carries the concurrent build's verified report; nil for every
	// other step kind.
	Index *IndexBuildReport `json:"index,omitempty"`
	// FinishedPendingDetach is true for a detach step that found its
	// partition left detach-pending by an earlier run and finished it with
	// DETACH PARTITION ... FINALIZE.
	FinishedPendingDetach bool `json:"finished_pending_detach,omitempty"`
}

StepReport says what one committed step did, machine-readably.

type UniqueIndexPartitionKeyError added in v0.5.5

type UniqueIndexPartitionKeyError struct {
	// Schema and Index name the requested index.
	Schema string
	Index  string
	// Missing lists, parents before their partitions, each partitioned table
	// whose partition key the index does not contain.
	Missing []MissingPartitionKey
}

UniqueIndexPartitionKeyError reports a unique index whose plain key columns do not contain the partition key of every partitioned table in the tree. It unwraps to ErrUniqueIndexPartitionKey.

func (*UniqueIndexPartitionKeyError) Error added in v0.5.5

Error implements the error interface.

func (*UniqueIndexPartitionKeyError) Unwrap added in v0.5.5

func (e *UniqueIndexPartitionKeyError) Unwrap() error

Unwrap returns ErrUniqueIndexPartitionKey.

type ValidateBudget

type ValidateBudget struct {
	// LockTimeout bounds how long the step may wait in the lock queue.
	LockTimeout time.Duration
	// Overall bounds the whole validation scan via statement_timeout;
	// expect large tables to need a generous value.
	Overall time.Duration
}

ValidateBudget bounds one VALIDATE CONSTRAINT step. The validation scan is long by design — it is the online half of the NOT VALID pattern — so it gets its own overall bound instead of the brief statement budget, while lock acquisition stays tightly bounded: the SHARE UPDATE EXCLUSIVE it takes conflicts with other DDL, and queueing behind one must not stall the sequence for the whole scan budget.

Jump to

Keyboard shortcuts

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