planner

package
v0.5.8 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 12 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 planner classifies schema-change statements: for each operation it decides whether PostgreSQL can run it online natively (possibly via a safer idiom it suggests), whether it needs the engine's copy-and-swap path, or whether it is refused. The mapping is the "Needs copy-and-swap?" column of docs/postgres-online-ddl-reference.md, applied conservatively: anything the planner cannot prove safe routes to copy-and-swap or refuse. Classification predicts; executors keep their own protections regardless.

In MySQL terms, the planner is PostgreSQL's missing ALGORITHM= / LOCK= declaration: MySQL lets authors assert the cost bracket (INSTANT/INPLACE/COPY) and the lock impact (NONE/SHARED/EXCLUSIVE) and fails closed; PostgreSQL has no such clause, so the planner proves both dimensions before execution and routes to the safest sequence that exists.

The rules assume PostgreSQL 14, the oldest major the test matrix runs; every rule holds unconditionally across the supported range (14–18). Rules that were version-dependent below that floor — fast default (PG 11+), SET NOT NULL proven by a validated CHECK (PG 12+), DETACH PARTITION CONCURRENTLY (PG 14+) — carry no version annotation because the floor makes them unconditional. A rule that varies within the supported range must carry an explicit version fact before it lands.

Index

Constants

View Source
const GeneratedColumnHelp = "drop those generated columns first, then re-plan; " +
	"adding a stored one back afterwards, or changing a stored one's expression instead, rewrites the table"

GeneratedColumnHelp is the operator-facing manual path for a dependent-generated-column decision, phrased to follow a sentence that names the generated columns.

View Source
const MayStallSubscriptionHelp = "add the same rule on the publisher first, so it never sends a row that breaks it"

MayStallSubscriptionHelp is the operator-facing check for an operation that adds a rule a row the publisher sends later can break (Decision.MayStallSubscriptions), phrased to follow a sentence that names the subscriptions.

View Source
const NotNullWithoutDefaultHelp = "give the column a constant DEFAULT, which PostgreSQL stores without rewriting the table, " +
	"or add it without NOT NULL, backfill it, then set NOT NULL"

NotNullWithoutDefaultHelp is the operator-facing manual path for a not-null-without-default decision.

View Source
const PartitionKeyHelp = "create a new partitioned table with the new column definition and move the rows into it"

PartitionKeyHelp is the operator-facing manual path for a partition-key decision, phrased to follow a sentence that names the partitioned tables.

View Source
const RulesPostgresVersions = "14-18"

RulesPostgresVersions is the inclusive PostgreSQL major-version range the classification rules are derived for (see the package comment and docs/postgresql-version-support.md). Offline consumers such as the linter stamp it into their reports so a stored result names the assumptions behind it.

View Source
const TablespaceCreateDeniedHelp = "grant CREATE on the tablespace to the role, or name the database's default tablespace, which needs no grant, then re-plan"

TablespaceCreateDeniedHelp is the operator-facing manual path for a tablespace-create-denied decision.

View Source
const TablespaceNotFoundHelp = "create the tablespace, or name one that exists, then re-plan"

TablespaceNotFoundHelp is the operator-facing manual path for a tablespace-not-found decision.

Variables

This section is empty.

Functions

func ColumnLimitHelp added in v0.5.8

func ColumnLimitHelp(numbers *preflight.ColumnNumbers) string

ColumnLimitHelp is the operator-facing manual path for a column-limit decision: rebuild the tables at the limit, since copying a table gives back the numbers its dropped columns hold, and add fewer columns only when the table has a number left for some. Without the read it names the table alone.

func ColumnLimitSubject added in v0.5.8

func ColumnLimitSubject(numbers *preflight.ColumnNumbers) string

ColumnLimitSubject names what is at the column limit for a column-limit decision: the table itself, its partitions or inheritance children that have used the most numbers, or both. When numbers are left it says how many, so a refusal of the adds past them agrees with the help's offer to add fewer.

func ColumnsPastLimit added in v0.5.8

func ColumnsPastLimit(ops []statement.Op, columns map[string]string, left int) (map[string]bool, int)

ColumnsPastLimit names the columns ops add once no column number is left, given the numbers left before ops run, and returns how many are left after them. columns are the table's live columns: adding one it already has takes no number, unless an earlier operation of ops drops it. A dropped column does not give its number back.

func ConstrainedTypeHelp added in v0.5.8

func ConstrainedTypeHelp(typeName string) string

ConstrainedTypeHelp is the operator-facing manual path for adding a column whose type, typeName, is a domain with constraints: PostgreSQL rewrites the table to check every row against them, whatever default the column is given.

func DependentsPhrase added in v0.5.0

func DependentsPhrase(singular, plural string, names []string) string

DependentsPhrase names dependents after "read by": the singular noun before one name and the plural before several, joined with commas.

func DestructiveOpKinds added in v0.5.0

func DestructiveOpKinds() []statement.OpKind

DestructiveOpKinds returns every operation shape the planner marks destructive, in statement.OpKinds() order. The front door's irreversible-operations registry derives its operation entries from it, so this classification stays the only list of destructive shapes.

func NotNullAlreadyHeld added in v0.5.8

func NotNullAlreadyHeld(column string, facts Facts) bool

NotNullAlreadyHeld reports whether a SET NOT NULL on column, as its statement's only operation, has nothing left to do: the column is already NOT NULL on the table and every table below it (Facts.NotNullColumns), and no helper of an earlier run is on the table (Facts.NotNullHelpers). A run that stopped after its SET NOT NULL and before dropping its helper leaves the column NOT NULL and the helper rejecting writes, so that column still takes the sequence, which drops the helper.

func NotNullFromTypeHelp added in v0.5.8

func NotNullFromTypeHelp(typeName string) string

NotNullFromTypeHelp is the operator-facing manual path for a not-null-without-default decision whose NOT NULL comes from the column's type, typeName, a domain. Neither manual path of NotNullWithoutDefaultHelp exists for it: the column cannot be added without NOT NULL, and PostgreSQL rewrites the table to check every row against a domain with constraints, whatever default the column is given. The NOT NULL may be declared by a domain the named one is defined over rather than by the named one itself.

func NotNullHelperName added in v0.5.7

func NotNullHelperName(table, column string) string

NotNullHelperName is the name of the helper CHECK the online SET NOT NULL sequence adds to table for column, fitted to PostgreSQL's identifier limit.

func NullFillCandidates added in v0.5.0

func NullFillCandidates(ops []statement.Op, columns map[string]string) []string

NullFillCandidates names the columns the operations of one ALTER TABLE add with no DEFAULT of their own, the ones whose existing rows may be left NULL: a front door reads Facts.NullFilledColumns only for these. The statement need not spell NOT NULL, since the column's domain or an inline PRIMARY KEY can make it NOT NULL, so the server's probe decides which candidates PostgreSQL would refuse. columns are the table's live columns. A column the table already has is skipped by ADD COLUMN IF NOT EXISTS, and refused as a duplicate otherwise, so neither fills anything, unless an earlier operation of the same statement drops it, which makes the add a new column again.

func ProvenCatalogOnly added in v0.5.6

func ProvenCatalogOnly(decisions []Decision) bool

ProvenCatalogOnly reports whether every decision is an operation PostgreSQL is certain to run on the catalog alone (see Decision.ProvenCatalogOnly), so running them costs the same on a table of any size. An empty plan proves nothing and reports false.

func PublicationHelp added in v0.5.8

func PublicationHelp(kind statement.OpKind) string

PublicationHelp is the operator-facing manual path for a dependent-publication decision on an operation of kind, phrased to follow a sentence that names the publications.

func PublishingHelp added in v0.5.8

func PublishingHelp(kind statement.OpKind) string

PublishingHelp is the operator-facing order of work for a change that sends subscribers a column or a table they do not have yet, for the operation's kind.

func SubscriptionHelp added in v0.5.8

func SubscriptionHelp(kind statement.OpKind) string

SubscriptionHelp is the operator-facing manual path for an operation of kind that stops the replication of the subscriptions writing the table (Decision.StopsSubscriptions), phrased to follow a sentence that names them. The publisher has to stop sending what the table would refuse before the table refuses it, except for an added column, which the publisher cannot send until the subscriber has it.

Types

type ColumnDependents added in v0.5.0

type ColumnDependents struct {
	// Tree covers the table and every table below it, which is what a
	// recursive ALTER COLUMN TYPE changes.
	Tree map[string][]string
	// Drop covers the tables whose copy of the column a recursive DROP
	// COLUMN drops: a child that declares the column itself or also
	// inherits it from a table outside the drop keeps its copy.
	Drop map[string][]string
	// Own covers the table alone, which is all an ALTER TABLE ONLY
	// changes.
	Own map[string][]string
}

ColumnDependents maps a column to the objects that depend on it, read for each set of tables an ALTER COLUMN TYPE or DROP COLUMN reaches (preflight.ReadColumnDependents). A column absent from a map has none, or the facts were not read, as in an offline lint; either way the server's own refusal at execution remains the backstop.

type Decision

type Decision struct {
	// Operation is the operator-facing label (display only).
	Operation string `json:"operation"`
	// Kind is the operation's parsed shape. The router's availability
	// policy branches on it together with Reason: whether a backend
	// carries a rewrite depends on what the operation does to the table,
	// not only on why PostgreSQL would rewrite it. It is not part of the
	// plan-report contract; a consumer branches on Reason.
	Kind statement.OpKind `json:"-"`
	// Destructive marks operations that discard live structure — a dropped
	// column, constraint, index, or NOT NULL. It is derived from the operation shape
	// here, in the one place every front door shares, so a plan reports the
	// same statement as destructive no matter how it was submitted. It is
	// always emitted, never omitted: a safety flag a consumer gates on must
	// be explicit even when false.
	Destructive bool `json:"destructive"`
	// Route is where the operation goes.
	Route Route `json:"route"`
	// Reason is why.
	Reason Reason `json:"reason"`
	// Unverified marks a decision the planner took without the live facts
	// needed to prove a cheaper one — it failed closed to the heavier
	// route. The route is what the engine would do, not a proven property
	// of the change: with facts (a live introspection or a supplied
	// column type) the same operation may classify as native.
	Unverified bool `json:"unverified,omitempty"`
	// ProbeLocked marks a column add whose catalog-only proof needed a
	// lock another session held: the planner routed it as Unverified, and
	// planning again once that lock is released can prove it in place. An
	// add that is Unverified for any other reason, such as a proof that was
	// never run, does not carry it.
	ProbeLocked bool `json:"probe_locked,omitempty"`
	// ProvenCatalogOnly marks an operation PostgreSQL runs on the catalog
	// alone, never rewriting or reading the table's rows and running no
	// code a user defined, so its cost does not grow with the table.
	// Unlike Reason metadata-only, which is the planner's classification,
	// it is set only where that is certain:
	//   - DROP COLUMN, DROP DEFAULT, DROP NOT NULL, DROP CONSTRAINT, and a
	//     rename of an index, which PostgreSQL defines that way;
	//   - ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID, which checks no row;
	//   - an ADD COLUMN the server's probe proved adds in place without a
	//     scan, evaluating nothing a user defined;
	//   - a SET DEFAULT, or an ADD CONSTRAINT ... CHECK ... NOT VALID, whose
	//     expression the server proved refers to nothing a user defined
	//     (Facts.DefaultsRunNoUserCode, Facts.ChecksRunNoUserCode);
	//   - a SET NOT NULL a validated CHECK (column IS NOT NULL) already
	//     proves (Facts.ValidatedNotNull), or on a column already NOT NULL
	//     (NotNullAlreadyHeld);
	//   - a binary-coercible type change on a column no index, foreign key,
	//     CHECK, or generated column reads, all of which PostgreSQL would
	//     rebuild or check again.
	// Absent means not established, not that the operation reads rows. An
	// event trigger is outside the proof: its code runs under the
	// statement's lock whatever the table's size, bounded by the attempt's
	// budget like any other statement. The operation still takes its lock,
	// and runs under the executor's lock_timeout like any other.
	ProvenCatalogOnly bool `json:"proven_catalog_only,omitempty"`
	// CatalogOnlySteps lists the steps of SaferSQL that change only the
	// catalog, by the same rule as ProvenCatalogOnly, for a decision that
	// is not proven as a whole: the NOT VALID step of an added CHECK or
	// foreign key, and every step of the SET NOT NULL sequence but its
	// VALIDATE, since its SET NOT NULL runs once the VALIDATE before it has
	// proven the column holds no NULL. A step absent from the list is not
	// proven. Each entry is spelled exactly as it is in SaferSQL.
	CatalogOnlySteps []string `json:"catalog_only_steps,omitempty"`
	// SaferSQL is the ordered safer native sequence, present only for
	// safer-idiom decisions where the planner could construct it. It is a
	// safer form of the submitted statement, not a semantic equivalent: it
	// converges on the same declared end state with different locking,
	// transactionality, and failure modes. SaferSQLExecution carries the
	// execution contract: the steps run one at a time, in order, each in
	// its own implicit transaction — never inside an enclosing transaction
	// block, which the CONCURRENTLY forms refuse. Each sequence constructor
	// documents what a failed step leaves behind and how a retry resumes
	// (a failed CONCURRENTLY build leaves an invalid index the runner must
	// detect via pg_index.indisvalid and rebuild).
	SaferSQL []string `json:"safer_sql,omitempty"`
	// SaferSQLExecution is the typed execution contract for SaferSQL,
	// present exactly when SaferSQL is. Automation branches on it instead
	// of prose — it is what tells a consumer the sequence must not be
	// wrapped in a transaction block.
	SaferSQLExecution Execution `json:"safer_sql_execution,omitempty"`
	// DependentViews names the views and materialized views that read the
	// column, each schema-qualified with every identifier quoted, present
	// whenever one blocks the change, whatever the decision's reason.
	DependentViews []string `json:"dependent_views,omitempty"`
	// DependentMaterializedViews names the materialized views among
	// DependentViews and DependentViewDropOrder, rendered the same way, so
	// the help can call each by its kind; recreating one runs its query to
	// fill it again. Like DependentFix, it is not part of the plan-report
	// contract.
	DependentMaterializedViews []string `json:"-"`
	// DependentViewDropOrder names every view the manual path drops to
	// change DependentViews: those views and the views that read them,
	// directly or through other views, deepest first, so each comes before
	// every view it reads. PostgreSQL refuses to drop a view another view
	// reads, so they are dropped in this order and recreated in reverse.
	// It is nil when no view reads another, where any order works. Like
	// DependentFix, it is not part of the plan-report contract.
	DependentViewDropOrder []string `json:"-"`
	// DependentPolicies names the row-level security policies that read
	// the column, each rendered "policy" ON "schema"."table" with every
	// identifier quoted, present whenever one blocks the change, whatever
	// the decision's reason.
	DependentPolicies []string `json:"dependent_policies,omitempty"`
	// DependentTriggers names the triggers whose UPDATE OF list or WHEN
	// condition names the column, each rendered "trigger" ON
	// "schema"."table" with every identifier quoted, present whenever one
	// blocks the change, whatever the decision's reason.
	DependentTriggers []string `json:"dependent_triggers,omitempty"`
	// DependentRules names the rewrite rules that read the column,
	// each rendered "rule" ON "schema"."table" with every identifier
	// quoted, present whenever one blocks the change, whatever the
	// decision's reason.
	DependentRules []string `json:"dependent_rules,omitempty"`
	// TriggerReads names the triggers whose PL/pgSQL function reads the
	// column as NEW.column or OLD.column, each rendered "trigger" ON
	// "schema"."table" (function "schema"."function"() line N), present
	// whenever one does. PostgreSQL records no dependency for such a read,
	// so it lets the change run, and the trigger then fails on every row
	// it fires on. It does not change the route: a consumer that runs the
	// change decides whether to require the trigger be changed first.
	TriggerReads []string `json:"trigger_reads,omitempty"`
	// UncheckedTriggers names the triggers on the table whose function may
	// read the column without the read being visible to the planner: a
	// function in a language other than PL/pgSQL, or a PL/pgSQL body that
	// runs dynamic SQL or passes the whole row to an expression. Each is
	// rendered "trigger" ON "schema"."table" (function
	// "schema"."function"() <why>), present whenever one exists. It does
	// not change the route.
	UncheckedTriggers []string `json:"unchecked_triggers,omitempty"`
	// DependentPublications names the publications whose column list or
	// row filter for the table names the column, each rendered
	// "publication" with its identifier quoted, present whenever one
	// blocks the change, whatever the decision's reason.
	DependentPublications []string `json:"dependent_publications,omitempty"`
	// StopsSubscriptions names the logical replication subscriptions that
	// write the table, each rendered "subscription" with its identifier
	// quoted, when the operation leaves the table unable to take a change
	// the publisher still sends: it drops a column or changes its type, or
	// makes a column NOT NULL that the publisher may send NULL or not send
	// at all. The subscription's apply worker then fails on the first such
	// change and retries it in a loop, and the publisher's slot keeps WAL
	// until the subscriber catches up. The field is advisory and leaves the
	// route unchanged: the subscriber cannot see whether the publisher has
	// already made the change, which is what makes it safe.
	StopsSubscriptions []string `json:"stops_subscriptions,omitempty"`
	// MayStallSubscriptions names the logical replication subscriptions
	// that write the table when the operation adds a uniqueness or CHECK
	// rule that a row the publisher sends later can break, which stops
	// the subscription's replication at that row. Advisory, like
	// StopsSubscriptions.
	MayStallSubscriptions []string `json:"may_stall_subscriptions,omitempty"`
	// DependentGeneratedColumns names the generated columns whose
	// expression reads the column, each rendered "schema"."table"."column"
	// with every identifier quoted, present whenever one blocks the change,
	// whatever the decision's reason. A copy that dropping the table's own
	// generated column removes is left out, since PostgreSQL refuses to
	// drop it on its own.
	DependentGeneratedColumns []string `json:"dependent_generated_columns,omitempty"`
	// PartitionKeyTables names the partitioned tables whose partition key
	// includes the column, each schema-qualified with every identifier
	// quoted, present exactly for partition-key decisions.
	PartitionKeyTables []string `json:"partition_key_tables,omitempty"`
	// ColumnLimit is how many column numbers the table had left before the
	// change, and which of it and its partitions or inheritance children
	// have used the most, present exactly for column-limit decisions.
	ColumnLimit *preflight.ColumnNumbers `json:"column_limit,omitempty"`
	// NotNullFromType is the added column's type, as the statement spells
	// it with every identifier quoted, when that type is what makes the column NOT NULL: a domain that
	// declares NOT NULL, on a column that spells neither NOT NULL nor
	// PRIMARY KEY. Present only for not-null-without-default decisions.
	// Adding a nullable column of that type is impossible, so the manual
	// path is the type's base type instead (see NotNullFromTypeHelp).
	NotNullFromType string `json:"not_null_from_type,omitempty"`
	// Column is the column the operation adds, as the statement names it,
	// unquoted. Present only for not-null-without-default decisions, so a
	// consumer can name the column the refusal is about.
	Column string `json:"column,omitempty"`
	// ConstrainedType is the added column's type, as the statement spells
	// it with every identifier quoted, when that type is a domain with constraints, which PostgreSQL
	// checks against every row by rewriting the table whatever default the
	// column is given. Present only for type-rewrite decisions. The manual
	// path is the domain's base type with its constraints on the column
	// instead (see ConstrainedTypeHelp).
	ConstrainedType string `json:"constrained_type,omitempty"`
	// LiveType is the column's type before an ALTER COLUMN TYPE, as
	// format_type renders it, when the live schema has the column. Present
	// only for alter-column-type decisions. statement.StepTypeFit reads it to
	// list the live values the new type cannot hold.
	LiveType string `json:"live_type,omitempty"`
	// ReplicatingPublications names the publications that send the change
	// on to logical replication, each rendered "publication" with its
	// identifier quoted, when the operation adds a column they send or
	// creates a table they publish and a pgoutput slot may be reading them
	// (ReplicationSlots). A native subscriber stops at the first change
	// that carries a column, or names a table, it does not have, and that
	// halts every table in its subscription. The field is advisory and
	// leaves the route unchanged: the publisher cannot see whether each
	// subscriber is ready, and a change-data-capture consumer reading the
	// same plugin may take the change as it comes.
	ReplicatingPublications []string `json:"replicating_publications,omitempty"`
	// ReplicationSlots names the pgoutput slots in the database, each
	// rendered "slot" with its identifier quoted, that may be reading
	// ReplicatingPublications; present exactly when they are.
	ReplicationSlots []string `json:"replication_slots,omitempty"`
	// DependentFix is the manual path for the views, policies, and
	// triggers that block the change, which depends on what the change
	// would do with those dependents out of the way. Like Kind, it is not part
	// of the plan-report contract: it selects the help the engine's own
	// text renders.
	DependentFix DependentFix `json:"-"`
	// ReadsInTimeZone names the session time zone a change between
	// timestamp and timestamptz reads every stored value in, so the
	// engine's text can say which instant each value becomes. Empty for
	// any other operation, or when the zone was not read. Like Kind, it is
	// not part of the plan-report contract.
	ReadsInTimeZone string `json:"-"`
}

Decision is the classification of one operation.

func (Decision) ExecutableAsSubmitted

func (d Decision) ExecutableAsSubmitted() bool

ExecutableAsSubmitted reports whether the operation's submitted form is itself safe to run. It is false for the decisions whose submitted form must be replaced by a safer sequence, whether or not one was constructed: a safer-idiom decision, whose submitted form blocks the table, and an app-breaking rename, whose submitted form breaks every running application instance that still uses the old name. Routing fails closed on the combination of a false ExecutableAsSubmitted and an empty SaferSQL.

func (Decision) OtherDependents added in v0.5.0

func (d Decision) OtherDependents() string

OtherDependents phrases the dependents that block the change besides the kind its reason names, such as the triggers on a dependent-policy decision, or returns "" when there are none. PostgreSQL refuses the change until every one of them is out of the way.

func (Decision) ViewsHelp added in v0.5.8

func (d Decision) ViewsHelp() string

ViewsHelp is the manual path for the views that block the change, phrased to follow a sentence that names them: the dependent fix every recreatable dependent shares, or, on a decision that carries none, redefining the views before planning again. PostgreSQL changes a view's columns only by dropping and recreating it, so the help says when that happens, gives the order to drop the views in when one reads another, and names what a dropped view takes with it so the reader recreates it too.

func (Decision) ViewsNoun added in v0.5.8

func (d Decision) ViewsNoun() string

ViewsNoun is the plural noun for the views that block the change, for DependentFix.Help: "views", "materialized views", or "views and materialized views".

func (Decision) ViewsPhrase added in v0.5.8

func (d Decision) ViewsPhrase() string

ViewsPhrase names the views that block the change after "read by", each by its kind: view "a"."v", materialized view "a"."m", or views "a"."v", "a"."w" and materialized view "a"."m". It is "" when no view blocks it.

type DependentFix added in v0.5.0

type DependentFix string

DependentFix is the manual path for a change PostgreSQL refuses while a view, a row-level security policy, or a trigger reads the column: objects that can be dropped and recreated around the change.

const (
	// DependentFixRewriteDependents is for a column drop. The dependents
	// have to stop reading the column before it can go, and the drop then
	// plans on its own.
	DependentFixRewriteDependents DependentFix = "rewrite-dependents"
	// DependentFixRecreateAroundChange is for a type change PostgreSQL runs
	// in place. Dropping the dependents, running the change, and
	// recreating them in one transaction holds the table's exclusive lock
	// only briefly, and no session sees the table without them; a
	// materialized view holds it while its query fills it again.
	DependentFixRecreateAroundChange DependentFix = "recreate-around-change"
	// DependentFixExpandContract is for a type change that rewrites the
	// table. Recreating the dependents around it would hold the exclusive
	// lock for the whole rewrite, and copy-and-swap rebuilds the table's
	// policies before it retypes the column, so it meets the same refusal
	// (it refuses a table with triggers outright). A new column of the
	// target type takes the dependents over instead.
	DependentFixExpandContract DependentFix = "expand-contract"
)

func (DependentFix) Help added in v0.5.0

func (f DependentFix) Help(plural string) string

Help is the operator-facing manual path, phrased to follow a sentence that names the dependents; plural is their noun, such as "policies".

type Execution

type Execution string

Execution is the typed execution contract for a planner-produced SQL sequence; automation branches on it, never on prose. It tells a consumer how the steps must run and that a failed step can leave partial state the runner owns detecting and recovering.

const (
	// ExecutionAutocommit: the steps run one at a time, in order, each in
	// its own implicit transaction — never inside an enclosing transaction
	// block. The CONCURRENTLY forms refuse an enclosing block outright,
	// and a multi-step sequence inside one block holds every earlier
	// step's locks across the steps designed to avoid them. A failed step
	// leaves partial state the runner must detect and recover before
	// retrying (a failed CONCURRENTLY build leaves an invalid index,
	// pg_index.indisvalid = false).
	ExecutionAutocommit Execution = "autocommit-each-step"
	// ExecutionPartitionedIndexBuild: the one step is a CREATE INDEX on a
	// partitioned table, and it runs as the partition-aware index build, not
	// as the statement: the parent's index is created with ONLY, each
	// partition's index is built concurrently and attached, and the parent's
	// index turns valid with the last attach. The partitions are listed when
	// the build runs, not when the plan is made. The statement must not be
	// run as written, which would build every partition's index under a lock
	// that blocks writes to the whole tree. A failed or interrupted run
	// leaves an invalid parent index and the partition indexes built so far;
	// running the same statement again resumes from them.
	ExecutionPartitionedIndexBuild Execution = "partitioned-index-build"
	// ExecutionPartitionedForeignKeyBuild: the one step is an ALTER TABLE
	// ... ADD FOREIGN KEY on a partitioned table, on a server before
	// PostgreSQL 18, and it runs as the partitioned foreign key build, not as
	// the statement: each partition is given the foreign key NOT VALID and
	// then validated while writes continue, and the parent's ADD FOREIGN KEY
	// then adopts every partition's in one brief transaction that validates
	// nothing. The partitions are listed when the build runs, not when the
	// plan is made. The statement must not be run as written, which would
	// validate every partition while it blocks writes to the whole tree. A
	// failed or interrupted run leaves the partition foreign keys finished
	// so far; running the same statement again resumes from them.
	ExecutionPartitionedForeignKeyBuild Execution = "partitioned-foreign-key-build"
	// ExecutionBlockingIndexDrop: the one step is the plain DROP INDEX of a
	// partitioned table's index, which PostgreSQL cannot drop concurrently.
	// It takes ACCESS EXCLUSIVE on the parent, every partition, and every
	// partition's index for as long as it runs, so the statement stays
	// refused and runs only when the operator accepts that lock, in one
	// engine-owned transaction under explicit lock and statement budgets.
	ExecutionBlockingIndexDrop Execution = "blocking-index-drop"
	// ExecutionPartitionedKeyBuild: the one step is an ALTER TABLE ... ADD
	// PRIMARY KEY or ADD UNIQUE on a partitioned table, and it runs as the
	// partitioned key build, not as the statement: each partition's unique
	// index is built concurrently and given the constraint with ADD
	// CONSTRAINT ... USING INDEX, then the parent's ADD CONSTRAINT adopts
	// them in one brief transaction that builds nothing. The partitions are
	// listed when the build runs, not when the plan is made. The statement
	// must not be run as written, which would build every partition's index
	// under ACCESS EXCLUSIVE on the whole tree. A failed or interrupted run
	// leaves the partition constraints finished so far; running the same
	// statement again resumes from them.
	ExecutionPartitionedKeyBuild Execution = "partitioned-key-build"
	// ExecutionOnlineAttach: the one step is an ALTER TABLE ... ATTACH
	// PARTITION ... FOR VALUES, and it runs as the online attach, not as the
	// statement: the new table is given a validated CHECK that implies the
	// bound, the parent's CHECKs and NOT NULLs, its indexes built
	// concurrently, and its foreign keys validated, all while writes go on,
	// and the ATTACH then changes only the catalog. The statement must not be
	// run as written, which would scan the new table and build its indexes
	// under ACCESS EXCLUSIVE. A failed or interrupted run leaves what the
	// earlier steps finished on the new table; running the same statement
	// again resumes from it.
	ExecutionOnlineAttach Execution = "online-attach"
)

The execution contracts a sequence can carry.

func Executions

func Executions() []Execution

Executions returns the closed set of Execution values. It is part of the plan-report contract (docs/plan-report.md): the set changes only with a format_version bump, and a consumer that meets an unrecognized value must treat the sequence as unknown and refuse to run it.

type Facts

type Facts struct {
	// ColumnTypes maps a column name to its live type as rendered by
	// PostgreSQL's format_type (e.g. "character varying(50)").
	ColumnTypes map[string]string
	// ColumnCollations maps each live column whose collation is not its
	// type's default to that collation, as schemadiff renders it. A column
	// absent from the map has the default collation. Retyping a column
	// without a COLLATE clause resets it to the new type's default, so a
	// column present here loses its collation and every index on it is
	// rebuilt: never a relabel, unless the clause names this collation.
	ColumnCollations map[string]string
	// ReplicaIdentity is what the replica identity indexes of the table and
	// the tables below it key on; the zero value when none has one to
	// protect.
	ReplicaIdentity schemadiff.ReplicaIdentityKeys
	// AddColumnProofs maps a column the change adds to what the server
	// proved about adding it (preflight.AddColumnRewrites). A column absent
	// from the map is unproven and classifies by the statement's shape
	// alone, which assumes the worst of any default it cannot read as a
	// constant; the proof leaves out only an ADD COLUMN IF NOT EXISTS for a
	// column the table already has, which the server skips.
	AddColumnProofs map[string]statement.AddColumnProof
	// DependentViews maps a column to the views and materialized views that
	// read it, on the table or on any table below it, which is what a
	// recursive ALTER COLUMN TYPE changes
	// (preflight.ReadColumnDependents). A column absent from the map has
	// none, or the facts were not read, as in an offline lint; either way
	// the server's own refusal at execution remains the backstop.
	DependentViews map[string][]string
	// DropDependentViews is DependentViews for the tables whose copy of
	// the column a recursive DROP COLUMN drops: a child that declares the
	// column itself or also inherits it from a table outside the drop
	// keeps its copy.
	DropDependentViews map[string][]string
	// OwnDependentViews is DependentViews for the table alone, which is
	// all an ALTER TABLE ONLY changes.
	OwnDependentViews map[string][]string
	// MaterializedViews names the materialized views among the dependent
	// views and their readers, rendered as they are
	// (preflight.ColumnDependents).
	MaterializedViews []string
	// ViewReaders maps each dependent view to the views that read it,
	// directly or through other views, each to its longest chain of views
	// from the dependent view (preflight.ColumnDependents).
	ViewReaders map[string]map[string]int
	// DependentPolicies maps a column to the row-level security policies
	// that read it, wherever they are defined, on the table or on any
	// table below it (preflight.ReadColumnDependents), each rendered
	// "policy" ON "schema"."table". A column absent from the map has none,
	// or the facts were not read; either way the server's own refusal at
	// execution remains the backstop.
	DependentPolicies map[string][]string
	// DropDependentPolicies is DependentPolicies for the tables whose copy
	// of the column a recursive DROP COLUMN drops.
	DropDependentPolicies map[string][]string
	// OwnDependentPolicies is DependentPolicies for the table alone.
	OwnDependentPolicies map[string][]string
	// DependentTriggers maps a column to the triggers whose UPDATE OF list
	// or WHEN condition names it (preflight.ReadColumnDependents), each
	// rendered "trigger" ON "schema"."table". A trigger whose function
	// reads the column is not one: the server records no dependency for
	// it and lets the change run.
	DependentTriggers ColumnDependents
	// DependentRules maps a column to the rewrite rules that read it
	// (preflight.ReadColumnDependents), each rendered "rule" ON
	// "schema"."table".
	DependentRules ColumnDependents
	// TriggerReads maps a column to the triggers whose PL/pgSQL function
	// reads it as NEW.column or OLD.column (preflight.ColumnDependents).
	TriggerReads ColumnDependents
	// UncheckedTriggers maps a column to the triggers whose function the
	// planner cannot check for reads of it (preflight.ColumnDependents).
	UncheckedTriggers ColumnDependents
	// DependentPublications maps a column to the publications whose column
	// list or row filter for the table names it
	// (preflight.ReadColumnDependents), each rendered "publication".
	DependentPublications ColumnDependents
	// Subscriptions names the logical replication subscriptions that write
	// the table or a table below it (preflight.ReadSubscriptions). The zero
	// value names none, as when the fact was not read in an offline lint.
	Subscriptions preflight.Subscriptions
	// GeneratedColumnCopies maps each generated column to its own copies,
	// named as DependentGeneratedColumns names them, so a statement that
	// drops a generated column stops it blocking a change to the columns
	// it reads (preflight.ReadColumnDependents).
	GeneratedColumnCopies ColumnDependents
	// DependentGeneratedColumns maps a column to the generated columns
	// whose expression reads it, each rendered "schema"."table"."column".
	DependentGeneratedColumns ColumnDependents
	// PartitionKeys maps a column to the partitioned tables whose
	// partition key includes it, each schema-qualified.
	PartitionKeys ColumnDependents
	// NullFilledColumns are the columns the statement adds NOT NULL, as
	// spelled or through the column's domain or an inline PRIMARY KEY,
	// that PostgreSQL would refuse to add because the table, or a
	// partition or inheritance child below it with storage of its own,
	// holds a row the column would be NULL in
	// (preflight.NullFilledColumns). It is read only for the columns
	// NullFillCandidates names. A column absent from the map gets a value
	// in every row, the table holds none, or the fact was not read, as in
	// an offline lint; without it the server's own refusal at execution
	// remains the backstop.
	NullFilledColumns map[string]bool
	// ColumnLimitReached are the columns the statement adds once the table,
	// or a table that inherits from it, has no column number left
	// (ColumnsPastLimit over preflight.ColumnNumbersLeft).
	ColumnLimitReached map[string]bool
	// ColumnNumbers is the read ColumnLimitReached was judged from, which
	// names the tables at the limit for the refusal's help.
	ColumnNumbers preflight.ColumnNumbers
	// ConstraintNames are the names of the constraints already in the
	// table's schema, which the server passes over when it names an
	// unnamed CHECK or FOREIGN KEY. Without them the safer sequence states
	// the server's first choice, and if the table already uses that name
	// its NOT VALID step fails before anything is added.
	ConstraintNames map[string]bool
	// RenamedIndexConstraint is the name of the primary-key, unique, or
	// exclusion constraint the index an ALTER INDEX ... RENAME TO renames
	// backs, which the rename renames with it; empty when the index backs
	// none, or when the fact was not read, as in an offline lint.
	RenamedIndexConstraint string
	// NotNullHelpers are the columns whose SET NOT NULL helper is already on
	// the live table: a CHECK (column IS NOT NULL) under the name
	// NotNullHelperName gives it, left by an earlier run of the online
	// sequence that stopped before its last step dropped it. The sequence
	// resumes at the helper's validation instead of adding it again. A
	// column absent from the map has no such helper, or the fact was not
	// read, as in an offline lint.
	NotNullHelpers map[string]bool
	// Storage reports whether the table has storage of its own: a heap for
	// an ordinary table or a partition, none for a partitioned parent.
	// StorageUnread when the fact was not read, as in an offline lint.
	Storage TableStorage
	// Tablespaces maps the tablespace a SET TABLESPACE on a partitioned
	// parent names to whether the connected role may name it
	// (preflight.ReadTablespaceUse). A name absent from the map was not
	// read, as in an offline lint or a host that builds Facts itself, or for
	// a table with storage, whose move routes to copy-and-swap; on a
	// partitioned parent an unread name keeps the metadata-only route marked
	// unverified, and the server's own check at execution remains the
	// backstop.
	Tablespaces map[string]preflight.TablespaceUse
	// SessionTimeZone is the TimeZone setting the engine's sessions run
	// with (preflight.SessionTimeZone): the zone a change between
	// timestamp and timestamptz reads every stored value in. Empty when
	// the fact was not read, as in an offline lint.
	SessionTimeZone string
	// KeyedColumns are the columns an index or a foreign key reads, on
	// the table or on a table below it (preflight.KeyedColumns). Nil when
	// the fact was not read, as in an offline lint; a column absent from a
	// non-nil map has no index and no foreign key.
	KeyedColumns map[string]bool
	// CheckedColumns are the columns a CHECK constraint reads, on the table
	// or on a table below it (preflight.CheckedColumns). Nil when the fact
	// was not read; a column absent from a non-nil map has no CHECK.
	CheckedColumns map[string]bool
	// PartitionedIndexColumns are the columns of a partitioned parent that
	// one of its partitioned indexes reads (preflight.PartitionedIndexColumns):
	// a type change on one rebuilds every partition's attached index under
	// the change's exclusive lock, even a change PostgreSQL relabels. Nil when
	// the fact was not read; a column absent from a non-nil map has no
	// partitioned index.
	PartitionedIndexColumns map[string]bool
	// DefaultsRunNoUserCode names the columns whose SET DEFAULT in the
	// statement the server proved refers to nothing a user defined
	// (preflight.ProveExpressions). A column absent from the map is
	// unproven.
	DefaultsRunNoUserCode map[string]bool
	// ChecksRunNoUserCode maps the name of each CHECK the statement adds,
	// as the statement spells it, to whether the server proved it refers to
	// nothing a user defined (preflight.ProveExpressions). A name absent
	// from the map is unproven.
	ChecksRunNoUserCode map[string]bool
	// ValidatedNotNull names the columns a validated CHECK (column IS NOT
	// NULL) covers on the table and every table below it
	// (preflight.ValidatedNotNullColumns), so SET NOT NULL reads no row.
	// A column absent from the map is unproven.
	ValidatedNotNull map[string]bool
	// NotNullColumns names the columns already NOT NULL, by a valid NOT
	// NULL, on the table and every table below it
	// (preflight.NotNullColumns), so SET NOT NULL changes nothing. A
	// column absent from the map allows NULL somewhere in the tree, or the
	// fact was not read, as in an offline lint. Set it only together with
	// NotNullHelpers, read from the same table: a column NOT NULL whose
	// helper CHECK an earlier run left still takes the sequence, which drops
	// the helper, and without NotNullHelpers it is taken for a no-op and the
	// helper stays (NotNullAlreadyHeld).
	NotNullColumns map[string]bool
	// Publishing names the publications that send the table's changes,
	// or a new table's, and the pgoutput slots that may read them
	// (preflight.ReadTablePublishing, preflight.ReadNewTablePublishing).
	// The zero value names none, as when the fact was not read in an
	// offline lint.
	Publishing preflight.Publishing
}

Facts are properties of the live table that sharpen classification, and they are trusted as stated: the CLI fills them by introspecting the target database, and a library caller may supply facts it already holds — but they must describe the database the change will run on, because a wrong fact can upgrade a rewrite to native. Missing facts never let an unsafe change succeed: the zero value is valid, routes every type change to copy-and-swap, and only defers some refusals, such as a column a view or a policy reads, to the server's own refusal at execution.

func FactsAfter added in v0.5.0

func FactsAfter(sql string, facts Facts) (Facts, error)

FactsAfter returns facts as they stand once sql has run: the generated columns it drops no longer block a later statement's change to the columns they read.

func FactsFrom

func FactsFrom(live schemadiff.Model) Facts

FactsFrom extracts the facts a live introspection model provides: the canonical type of every live column, the collation of every column that has one of its own, and what the table's replica identity keys on. Every front door — the declarative diff and the imperative dry-run — extracts facts through this one function so equivalent changes classify identically.

type Plan

type Plan struct {
	// Statement is the submitted SQL.
	Statement string `json:"statement"`
	// Route is the aggregate route.
	Route Route `json:"route"`
	// Decisions are the per-operation classifications, in statement order.
	Decisions []Decision `json:"decisions"`
}

Plan is the classification of one statement: one decision per operation and the aggregate route (the worst of its decisions — one rewrite makes the whole statement a copy, one refusal refuses it).

func Classify

func Classify(sql string, facts Facts) (Plan, error)

Classify parses one statement and routes each of its operations. A parse failure is an error; an unrecognized operation is not — it comes back as a refuse decision so the caller can render the whole plan.

type Reason

type Reason string

Reason is the typed cause of a routing decision; automation branches on it, never on prose.

const (
	// ReasonMetadataOnly: a brief ACCESS EXCLUSIVE catalog change, no scan
	// and no rewrite.
	ReasonMetadataOnly Reason = "metadata-only"
	// ReasonOnlineIdiom: already the safe native form (CONCURRENTLY,
	// NOT VALID, VALIDATE, USING INDEX).
	ReasonOnlineIdiom Reason = "online-idiom"
	// ReasonFastDefault: ADD COLUMN with a default the catalog stores, so
	// no row is rewritten (PG 11+): a constant, or any default the server
	// proved does not rewrite (a non-volatile expression such as now()).
	ReasonFastDefault Reason = "fast-default"
	// ReasonBinaryCoercible: a type change PostgreSQL relabels without a
	// rewrite (widen varchar, varchar to text, widen numeric precision).
	ReasonBinaryCoercible Reason = "binary-coercible"
	// ReasonSaferIdiom: native, but the submitted form blocks; SaferSQL
	// carries the online rewrite when one can be constructed.
	ReasonSaferIdiom Reason = "safer-idiom"
	// ReasonAppBreakingRename: PostgreSQL executes the rename as a brief
	// metadata-only catalog flip, but it cannot land atomically across
	// running application instances — code still referencing the old
	// column, table, or constraint name starts erroring the instant it
	// commits. For a column the safe sequence is expand/contract: add the
	// new column, dual-write and backfill, switch reads, then drop the old
	// column as its own reviewed change. For a table, coordinate the
	// rename with the application deploy that adopts the new name. For an
	// index that backs a constraint, the rename renames the constraint,
	// so coordinate it with the deploy that adopts the new constraint
	// name. No sequence can be constructed from the statement, so the
	// rename is rewrite-required.
	ReasonAppBreakingRename Reason = "app-breaking-rename"
	// ReasonVolatileDefault: ADD COLUMN whose default PostgreSQL computes
	// for every row, rewriting the table — proven by the server, or assumed
	// (Unverified) when the default is not a constant and nothing proved
	// it.
	ReasonVolatileDefault Reason = "volatile-default"
	// ReasonGeneratedStored: adding a stored generated column computes
	// every row — a full rewrite.
	ReasonGeneratedStored Reason = "generated-stored"
	// ReasonTypeRewrite: a type PostgreSQL must check or convert row by
	// row — a type conversion it cannot relabel (rewrite plus reindex), a
	// type change that moves the column's collation or retypes a column a
	// partitioned parent's index reads (reindex alone), or an added column
	// of a domain type with constraints.
	ReasonTypeRewrite Reason = "type-rewrite"
	// ReasonRelocation: SET TABLESPACE moves the heap — a rewrite-scale
	// copy.
	ReasonRelocation Reason = "relocation"
	// ReasonPartitionParentLock: creating a partition takes a brief ACCESS
	// EXCLUSIVE on the partitioned parent — no scan, but it queues behind
	// and then blocks every query on the parent while held.
	ReasonPartitionParentLock Reason = "partition-parent-lock"
	// ReasonReplicaIdentity: the operation drops what the table's replica
	// identity index keys on — the index itself, the constraint that owns
	// it, or one of its columns. The index is the one REPLICA IDENTITY
	// USING INDEX selects, or the primary key under REPLICA IDENTITY
	// DEFAULT while a publication publishes the table's updates or
	// deletes. The setting outlives the index, so the table is left with
	// no usable identity, and every UPDATE and DELETE on it fails while a
	// publication publishes them. Move the identity first (ALTER TABLE ...
	// REPLICA IDENTITY), then re-plan.
	ReasonReplicaIdentity Reason = "replica-identity"
	// ReasonDependentView: the operation changes the type of, or drops, a
	// column that a view or materialized view reads. PostgreSQL refuses
	// both while the view exists, even a type change that rewrites
	// nothing, so the statement could only fail. The decision names the
	// views; change or drop them first, then re-plan.
	ReasonDependentView Reason = "dependent-view"
	// ReasonDependentPolicy: the operation changes the type of, or drops,
	// a column that a row-level security policy reads, in its USING or
	// WITH CHECK expression, on this table or on another table that reads
	// the column through a subquery. PostgreSQL refuses both while the
	// policy exists, even a type change that rewrites nothing, so the
	// statement could only fail. The decision names the policies; drop
	// them first and recreate them after the change, then re-plan.
	ReasonDependentPolicy Reason = "dependent-policy"
	// ReasonDependentTrigger: the operation changes the type of, or drops,
	// a column that a trigger's UPDATE OF list or WHEN condition names.
	// PostgreSQL refuses both while the trigger exists, even a type change
	// that rewrites nothing, so the statement could only fail. The
	// decision names the triggers; a trigger whose function reads the
	// column does not count, since the server records no dependency for
	// it.
	ReasonDependentTrigger Reason = "dependent-trigger"
	// ReasonDependentRule: the operation changes the type of, or drops, a
	// column that a rewrite rule reads in its condition or
	// actions. PostgreSQL refuses both while the rule exists, even a type
	// change that rewrites nothing, so the statement could only fail. The
	// decision names the rules; drop them first and recreate them after
	// the change, then re-plan.
	ReasonDependentRule Reason = "dependent-rule"
	// ReasonDependentPublication: the operation changes the type of, or
	// drops, a column that a publication's column list or row filter for
	// the table names. PostgreSQL refuses both while the publication
	// names it, so the statement could only fail, and a desired-state run
	// would stop part-way with the steps before it committed. The decision
	// names the publications; a publication that publishes the table
	// without a column list or row filter does not count.
	ReasonDependentPublication Reason = "dependent-publication"
	// ReasonDependentGeneratedColumn: the operation changes the type of,
	// or drops, a column that a generated column's expression reads.
	// PostgreSQL refuses both while the generated column exists, so the
	// statement could only fail, except that PostgreSQL 14 drops the
	// generated column along with a dropped column, so there the refusal
	// is what keeps it. The decision names the generated columns.
	ReasonDependentGeneratedColumn Reason = "dependent-generated-column"
	// ReasonPartitionKey: the operation changes the type of, or drops, a
	// column in the partition key of the table or of a partitioned table
	// below it that the change reaches. PostgreSQL never changes or drops
	// a partition key column, so the statement could only fail; the only
	// path is a new partitioned table with the new key, the rows moved
	// into it. The decision names the partitioned tables.
	ReasonPartitionKey Reason = "partition-key"
	// ReasonNotNullWithoutDefault: the operation adds a NOT NULL column
	// with no default to a table that holds rows. Every existing row would
	// hold NULL in the new column, so PostgreSQL refuses the statement
	// (SQLSTATE 23502) after taking the table's exclusive lock; it could
	// only fail. A default, identity, or generated column fills the rows,
	// and an empty table has none to fill, so neither is refused.
	ReasonNotNullWithoutDefault Reason = "not-null-without-default"
	// ReasonColumnLimit: the operation adds a column to a table that has
	// used every column number PostgreSQL gives a table, or that a table
	// inheriting from it has. A dropped column keeps its number until the
	// table is rebuilt, so PostgreSQL refuses the statement (SQLSTATE
	// 54011) however few live columns the table has; it could only fail.
	ReasonColumnLimit Reason = "column-limit"
	// ReasonTablespaceNotFound: SET TABLESPACE on a partitioned parent
	// names a tablespace the server does not have. PostgreSQL refuses the
	// statement (SQLSTATE 42704), so it could only fail. Create the
	// tablespace, or name one that exists, then re-plan.
	ReasonTablespaceNotFound Reason = "tablespace-not-found"
	// ReasonTablespaceCreateDenied: SET TABLESPACE on a partitioned parent
	// names a tablespace, other than the database's default, that the
	// connected role holds no CREATE privilege on. PostgreSQL refuses the
	// statement (SQLSTATE 42501), so it could only fail. Grant CREATE on
	// the tablespace to the role, then re-plan.
	ReasonTablespaceCreateDenied Reason = "tablespace-create-denied"
	// ReasonCascadingDrop: a drop with CASCADE, which also drops whatever
	// depends on what it drops: a view or policy that reads a dropped
	// column, or another table's foreign key on a dropped key. Those
	// objects are not in the statement, so neither the plan nor the
	// table's lock covers them. Drop each dependent object as its own
	// change, then resubmit without CASCADE, which PostgreSQL refuses
	// while anything still depends on the target.
	ReasonCascadingDrop Reason = "cascading-drop"
	// ReasonUnsupportedOperation: the planner does not recognize the
	// operation or knows no safe path for it.
	ReasonUnsupportedOperation Reason = "unsupported-operation"
)

The reasons a decision can carry.

func Reasons

func Reasons() []Reason

Reasons returns the closed set of Reason values. It is part of the plan-report contract (docs/plan-report.md): the set changes only with a format_version bump, and a consumer that meets an unrecognized value must treat the decision as unknown and refuse it.

type Route

type Route string

Route is where an operation is sent.

const (
	// RouteNative: PostgreSQL runs it online natively — directly or via
	// the safer idiom in Decision.SaferSQL.
	RouteNative Route = "native"
	// RouteCopyAndSwap: needs a table rewrite; only the engine's shadow
	// copy + cutover can do it online.
	RouteCopyAndSwap Route = "copy-and-swap"
	// RouteRefuse: no known safe path; not executed.
	RouteRefuse Route = "refuse"
)

The three routes.

func Routes

func Routes() []Route

Routes returns the closed set of Route values, in severity order. It is part of the plan-report contract (docs/plan-report.md): the set changes only with a format_version bump, and a consumer that meets an unrecognized value must treat the statement as unknown and refuse it.

type ScriptClassifier added in v0.4.0

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

ScriptClassifier classifies the statements of one script in order, with zero live facts except the constraint names the script's own earlier statements leave behind. Running the script, the server numbers an unnamed CHECK or FOREIGN KEY past a name an earlier statement claimed, so a later safer sequence must state the numbered name too, or it would collide with the constraint the script just added. Names are tracked per schema as the statement writes it, an unqualified table under its own key. The zero value is ready to use.

func (*ScriptClassifier) Classify added in v0.4.0

func (c *ScriptClassifier) Classify(sql string) (Plan, error)

Classify parses and routes sql, the script's next statement, as Classify does, then records the constraint names it leaves: each constraint an ALTER TABLE adds, by its stated name or the name its NOT VALID sequence states, less each it drops. Any other constraint added unnamed is not recorded, since the planner states no name for it.

type TableStorage added in v0.5.6

type TableStorage uint8

TableStorage is what a live read says about a table's own storage.

const (
	// StorageUnread means the fact was not read, as in an offline lint.
	StorageUnread TableStorage = iota
	// StorageHeap is an ordinary table or a partition, whose rows live in
	// a heap of its own.
	StorageHeap
	// StoragePartitionedParent is a partitioned parent, which has no
	// storage of its own; its rows live in its partitions.
	StoragePartitionedParent
)

type ViewLoss added in v0.5.8

type ViewLoss string

ViewLoss names something PostgreSQL discards with a dropped view and does not bring back with CREATE VIEW. A path that drops and recreates a view restores every one of them: a view recreated without its options can stop applying row security to its callers, and an updatable view without its INSTEAD OF triggers refuses writes. A consumer that names the path in its own words maps each token; Phrase is how pg-sprite's own text names it.

const (
	// ViewLossGrants is the privileges granted on the view.
	ViewLossGrants ViewLoss = "grants"
	// ViewLossComment is the COMMENT ON the view.
	ViewLossComment ViewLoss = "comment"
	// ViewLossOwner is the view's owner, which a recreated view takes from
	// the role that creates it.
	ViewLossOwner ViewLoss = "owner"
	// ViewLossOptions is the view's reloptions, such as security_barrier
	// and security_invoker.
	ViewLossOptions ViewLoss = "options"
	// ViewLossRules is the rules defined on the view.
	ViewLossRules ViewLoss = "rules"
	// ViewLossInsteadOfTriggers is the INSTEAD OF triggers that make the
	// view writable.
	ViewLossInsteadOfTriggers ViewLoss = "instead-of-triggers"
	// ViewLossColumnDefaults is the defaults set on the view's columns.
	ViewLossColumnDefaults ViewLoss = "column-defaults"
	// ViewLossIndexes is a materialized view's indexes.
	ViewLossIndexes ViewLoss = "indexes"
)

func MaterializedViewLosses added in v0.5.8

func MaterializedViewLosses() []ViewLoss

MaterializedViewLosses lists what a dropped materialized view loses beyond what ViewLosses lists for a view. Each call returns a fresh slice.

func ViewLosses added in v0.5.8

func ViewLosses() []ViewLoss

ViewLosses lists what a dropped view loses, in the order pg-sprite's text names them. Each call returns a fresh slice.

func (ViewLoss) Phrase added in v0.5.8

func (l ViewLoss) Phrase() string

Phrase is how pg-sprite's own text names the loss.

Jump to

Keyboard shortcuts

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