schemadiff

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 16 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 schemadiff builds the canonical table model both front-ends share and diffs two models into an ordered statement list. The model always comes from a real PostgreSQL catalog — the live table is introspected directly, and a desired-state file is executed on a transaction-scoped scratch schema and introspected the same way, then the transaction is rolled back (execute-and-introspect; semantics are never derived from the AST). Canonical text (types, defaults, constraint and index definitions) is whatever the server's own decompilers print, so cosmetic differences (type aliases, default formatting, implicit names) never show up as diffs.

This is a periphery package (see SAFETY.md): its output is a plan request, and the core executors re-verify their own preconditions.

Index

Constants

This section is empty.

Variables

View Source
var ErrDesiredConstraintMerged = errors.New("a desired constraint repeats another one on the same columns, and one CREATE TABLE keeps only one of them; declare it once")

ErrDesiredConstraintMerged is returned when the desired CREATE TABLE names a PRIMARY KEY, UNIQUE, or EXCLUDE constraint that repeats an earlier one exactly, so the server kept only one of them (see confirmIndexConstraintsBuilt). Two such constraints enforce the same rule; the remedy is to declare it once.

View Source
var ErrDesiredInherits = errors.New("a desired CREATE TABLE ... INHERITS cannot be planned: building it would lock the live parent and add an inheritance edge to it")

ErrDesiredInherits is returned for a desired file whose CREATE TABLE INHERITS from a parent. Classic inheritance is not planned, and the scratch build would bind the parent to the live table of that name, lock it, and add an inheritance edge to it until the scratch transaction rolls back, so the file is refused before anything runs.

View Source
var ErrDesiredPartitionOf = errors.New("a desired CREATE TABLE ... PARTITION OF cannot be planned: building it would lock the live partitioned parent")

ErrDesiredPartitionOf is returned for a desired file whose CREATE TABLE is PARTITION OF a parent. The scratch build would attach the scratch table to the live partitioned parent, which takes ACCESS EXCLUSIVE on the parent and blocks its reads and writes until the scratch transaction rolls back, so the file is refused before anything runs.

View Source
var ErrDifferentTables = errors.New("models describe different tables")

ErrDifferentTables is returned when the two models describe different tables — a caller bug, refused rather than diffed.

View Source
var ErrExpressionUnsettled = errors.New("the server prints a desired expression differently each time it parses it")

ErrExpressionUnsettled reports a desired expression whose printed text was still changing after maxSettleRounds replays, so no text on its chain can be trusted to be the last one a live table might hold.

View Source
var ErrMultipleOwnedSequences = errors.New("column default uses more than one sequence the column owns")

ErrMultipleOwnedSequences is returned for a column whose default uses more than one sequence the column owns (Column.MultipleOwnedSequences): the serial shorthand declares one, and exporting the default as written would leave both sequences out of the file.

View Source
var ErrNotTable = errors.New("not an ordinary or partitioned table")

ErrNotTable is returned when the target exists but is not an ordinary or partitioned table (e.g. a view or foreign table).

View Source
var ErrOnlyTableDiffers = errors.New("the row security matches and only the table definition differs")

ErrOnlyTableDiffers marks the error DiffWithRowSecurity returns when the row security matches and only the table definition differs, including when the table change is one the table's own plan refuses; the error then also wraps that refusal. The sentinel itself wraps nothing, but every error returned with it also wraps ErrUnsupportedChange, so a caller that treats every difference as a refusal still refuses. diffplan.PlanWithRowSecurity plans the table definition on its own instead, which leaves the row security unchanged and states the table refusal in its own terms.

View Source
var ErrReferencedTableNotFound = errors.New("foreign key references a table that does not exist in the target schema")

ErrReferencedTableNotFound is returned when a desired file's foreign key references a table that does not exist in the target schema. The scratch build binds each foreign key to an empty copy of the live referenced table, so the referenced table must already exist.

View Source
var ErrReferencedTableNotReadable = errors.New("planning role lacks SELECT on a table a foreign key references")

ErrReferencedTableNotReadable is returned when the planning role lacks SELECT on a table a desired file's foreign key references. The scratch build copies the referenced table's shape with LIKE, which PostgreSQL allows only to a role that can read the source table.

View Source
var ErrTableNotFound = errors.New("table not found")

ErrTableNotFound is returned when the target table does not exist in the requested schema.

View Source
var ErrUnrenderableCollation = errors.New("columns with an explicit collation cannot be rendered as a desired schema")

ErrUnrenderableCollation is returned when a column carries an explicit collation. The declarative model does not manage collations, so a rendered baseline without the COLLATE clause would silently change sort order and index semantics — the renderer refuses instead.

View Source
var ErrUnrenderableDefault = errors.New("sequence-backed default cannot be rendered as a desired schema")

ErrUnrenderableDefault is returned when a column carries a sequence-backed default that is not the canonical serial form. A desired schema file cannot define a standalone sequence, so the only sequence-backed default a rendered file can reproduce is the serial shorthand (an owned sequence named <table>_<column>_seq on a NOT NULL integer column). Anything else — a shared sequence, a renamed or truncated sequence name, a nullable column — must be resolved by hand.

View Source
var ErrUnrenderableForeignKey = errors.New("tables that own or are referenced by foreign keys cannot be rendered as a desired schema")

ErrUnrenderableForeignKey is returned when the table owns foreign keys or other tables reference it with foreign keys. The single-table model carries no incoming foreign-key topology, so a rendered baseline would look complete while silently dropping the table's relationships. Desired files may declare outgoing foreign keys for planning, but desired-state execution refuses every foreign-key change, so a baseline carrying one could never be applied; the renderer refuses both directions instead.

View Source
var ErrUnrenderableInheritance = errors.New("table inheritance cannot be rendered as a desired schema")

ErrUnrenderableInheritance is returned for either side of a classic PostgreSQL inheritance relationship. The desired model cannot express inheritance edges, so rendering would flatten a child or omit its children.

View Source
var ErrUnrenderableMergedConstraints = errors.New("constraints that repeat each other on the same columns cannot be rendered as a desired schema")

ErrUnrenderableMergedConstraints is returned for a table with two PRIMARY KEY, UNIQUE, or EXCLUDE constraints declared the same way. Built from one CREATE TABLE, the server keeps only one of them, and a desired file has no other way to declare the second (see ErrDesiredConstraintMerged).

View Source
var ErrUnrenderablePartition = errors.New("partitioned tables cannot be rendered as a desired schema")

ErrUnrenderablePartition is returned for a partitioned parent or a partition. The model does not carry partition bounds or the parent/partition topology, so a rendered file would silently lose the PARTITION BY clause or the partition attachment — the renderer refuses instead of emitting a wrong baseline.

View Source
var ErrUnrenderableRowSecurity = errors.New("row security cannot be rendered as a desired schema")

ErrUnrenderableRowSecurity means exporting a table would omit its RLS settings or policies. Desired files cannot represent these objects yet.

View Source
var ErrUnrenderableSequenceOptions = errors.New("sequence options cannot be rendered as a desired schema")

ErrUnrenderableSequenceOptions is returned when a column owns a sequence declared differently from what declaring the column fresh creates and a desired file cannot state the declaration: a serial column, whose shorthand has no options clause, or an identity whose sequence's type differs from the column's. Rendering the column at the defaults would silently move its bounds, step, or type.

View Source
var ErrUnrenderableToastOptions = errors.New("TOAST storage parameters on a table whose remaining columns may not build a TOAST table cannot be rendered as a desired schema")

ErrUnrenderableToastOptions is returned for TOAST storage parameters on a table whose TOAST table a fresh CREATE TABLE might not build (see Model.ToastMayNotRebuild). The server would discard the parameters when it builds the rendered file, so the baseline would plan them again on every diff against the table it came from.

View Source
var ErrUnrenderableUnlogged = errors.New("unlogged tables cannot be rendered as a desired schema")

ErrUnrenderableUnlogged is returned for an unlogged table. The declarative model does not manage persistence, so a rendered plain CREATE TABLE would silently change the table's crash-safety and replication behavior — the renderer refuses instead.

View Source
var ErrUnrenderableVirtual = errors.New("virtual generated columns cannot be rendered as a desired schema")

ErrUnrenderableVirtual is returned when a column is generated VIRTUAL. The desired-file grammar cannot parse VIRTUAL, and rendering the column as STORED or as a plain default would silently change what it is.

View Source
var ErrUnsupportedChange = errors.New("unsupported schema change")

ErrUnsupportedChange is returned when converging live onto desired would need a change the engine does not derive: identity, generation, or collation changes on an existing column, a persistence (unlogged) or storage-parameter difference, or a partitioning difference (partition key or partition attachment) — table identity that no ALTER converges. The caller surfaces it; nothing is guessed.

Functions

func ListManagedTables added in v0.3.2

func ListManagedTables(ctx context.Context, pool *pgxpool.Pool, schema string) ([]string, error)

ListManagedTables returns, sorted by name, the tables of a live PostgreSQL schema that a declarative schema directory is expected to account for: the set pull enumerates before it exports each one. Ordinary tables and partitioned parents are listed, INHERITS children among them; partitions are represented by their parent's PARTITION BY and extension members belong to their extension, so neither is a table an owner declares. Views, materialized views, foreign tables, and sequences are outside the declarative model and are not listed. The listing is the candidate set, not the set of files pull writes: a listed table whose shape Render refuses is still undeclared and still the owner's to resolve, and pull reports the refusal by table.

Every catalog relation, operator, and type in the query is pg_catalog qualified (CO-9), so a search_path that lists a user schema ahead of pg_catalog cannot change the answer: an unqualified relation or operator would join nothing and list no tables, while an unqualified regclass cast would stop matching the extension dependency and list extension members as undeclared. Both are silent wrong answers, and each blocks or waves through a table nobody touched.

func Render added in v0.2.0

func Render(m Model) (string, error)

Render renders the canonical model into a desired-state schema file: one CREATE TABLE, with a WITH clause carrying the table's storage parameters, followed by the model's CREATE INDEX statements. The output is proven admissible by parsing it through statement.ParseDesired before it is returned, so anything a desired file refuses (a schema-qualified name, for example) surfaces here as that gate's typed error. Materializing the output with IntrospectDesired reproduces the model's names and definitions, so diffing it against the table it came from yields no changes — the round-trip contract the integration tests enforce. Validity is not rendered: an index the table carries invalid — an unfinished concurrent build — renders as its definition and materializes valid, so the round-trip diff of such a table is exactly the create-index change that rebuilds it.

func RenderRowSecurity added in v0.4.0

func RenderRowSecurity(schema string, m Model) ([]string, error)

RenderRowSecurity renders only settings, policies, and policy comments from a catalog model. It does not authorize execution; callers must admit the model and execute with pg_catalog as the search path, as used during introspection.

func RenderWithRowSecurity added in v0.4.0

func RenderWithRowSecurity(m Model) (string, error)

RenderWithRowSecurity exports the complete table-local RLS definition, including explicit DISABLE when RLS is off. The result is admitted only by ParseDesiredWithRowSecurity and cannot be passed to the live create executor.

Types

type AccessImpact added in v0.4.0

type AccessImpact string

AccessImpact is advisory: it never proves effective access or predicate equivalence.

const (
	AccessMayWiden       AccessImpact = "may-widen"
	AccessReviewRequired AccessImpact = "review-required"
	AccessMetadataOnly   AccessImpact = "metadata-only"
)

Known widening patterns are flagged even when other changes could offset them.

type Advisory added in v0.4.0

type Advisory struct {
	// Kind classifies the observation.
	Kind AdvisoryKind `json:"kind"`
	// Index is the live index the observation is about.
	Index string `json:"index"`
}

Advisory is one typed observation the diff made about the live table that produced no change: reported so a consumer sees what the plan declined to do, never acted on by the engine. The table is the report's.

func Advisories added in v0.4.0

func Advisories(live, desired Model) []Advisory

Advisories reports every invalid index on a plain live table, in live index order, classified by whether desired names it. These are the entries Diff observes and declines to drop; Diff's change list alone would discard the observation, so a caller reporting a plan pairs the two over the same models. A partitioned parent's invalid entries are not unfinished builds and produce no advisory.

type AdvisoryKind added in v0.4.0

type AdvisoryKind string

AdvisoryKind classifies an observation the diff made but could not turn into a change, so a consumer can act on it without parsing prose.

const (
	// AdvisoryInvalidIndexRebuild marks an invalid index the desired
	// schema names, with the same or a different definition: the plan
	// carries its create-index, and that create cannot run as-is against
	// the occupied name. Completing the plan goes through the proven
	// removal path (executor.RebuildAbandonedIndex or the invalid-index
	// runbook), which renames and drops the entry only after proving it
	// abandoned.
	AdvisoryInvalidIndexRebuild AdvisoryKind = "invalid-index-rebuild"
	// AdvisoryInvalidIndexUndeclared marks an invalid index the desired
	// schema does not name: the diff plans no drop for it, so no statement
	// touches it and an empty plan is not evidence the table is clean. An
	// abandoned entry clears per the invalid-index runbook; a
	// build still running finishes on its own.
	AdvisoryInvalidIndexUndeclared AdvisoryKind = "invalid-index-undeclared"
)

The advisory kinds a plan can carry. Both describe an invalid index on a plain table — an unfinished concurrent build, abandoned or still running — which the diff never drops (see indexNeedsDrop).

func AdvisoryKinds added in v0.4.0

func AdvisoryKinds() []AdvisoryKind

AdvisoryKinds returns the closed set of AdvisoryKind 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 advisory as unknown and surface it.

func (AdvisoryKind) Description added in v0.4.0

func (k AdvisoryKind) Description() string

Description renders the kind for an operator: what the diff observed and what completes the plan. Display only — consumers branch on the kind.

type Change

type Change struct {
	// SQL is the literal statement, without a trailing semicolon.
	SQL string `json:"sql"`
	// Kind classifies the statement for consumers that gate by class.
	Kind ChangeKind `json:"kind"`
	// Destructive marks statements that discard data, constraints, or
	// indexes (column, constraint, and index drops — dropping a unique
	// index discards the same guarantee as dropping a unique constraint).
	// Destructive changes are gated by the caller, never executed
	// silently.
	Destructive bool `json:"destructive,omitempty"`
	// Adopts is set on an ADD CONSTRAINT ... USING INDEX: the live index
	// the constraint takes over, with the definition the diff matched it
	// against. The statement names only the index, so execution checks
	// the definition again under the table's lock before attaching it.
	// The SQL already identifies the change, so it stays out of the JSON.
	Adopts *IndexAdoption `json:"-"`
	// Validates is set on a VALIDATE CONSTRAINT: the live constraint it
	// validates, with the definition the diff matched it against. The
	// statement names only the constraint, so execution checks the
	// definition again under the table's lock before validating it.
	Validates *ConstraintValidation `json:"-"`
}

Change is one derived statement of the ordered plan.

func Diff

func Diff(schema string, live, desired Model) ([]Change, error)

Diff derives the ordered statement list that converges live onto desired. Order is dependency-correct: drops first (indexes, then constraints, then columns), then column adds and alters, then constraint adds, then index creates — so an added column exists before an index or constraint that references it. Within each bucket the order is deterministic: attribute order for columns, name order for constraints and indexes. schema qualifies the emitted statements' table references. Columns are compared by name only: attribute order carries no semantics in PostgreSQL and is deliberately out of scope for convergence. An invalid index on a plain table never yields a drop (see indexNeedsDrop); Advisories over the same models reports each such entry so the observation is not lost. RowSecurity is observational only: table-only desired files do not claim ownership of access control, so missing policies never produce policy drops.

func DiffWithRowSecurity added in v0.4.0

func DiffWithRowSecurity(schema string, live, desired Model) ([]Change, error)

DiffWithRowSecurity checks equality of a complete RLS-scoped declaration. Security deltas and mixed table/security changes return ErrUnsupportedChange, and table changes under matching row security return an error that wraps both it and ErrOnlyTableDiffers; this comparison never emits executable SQL. The dedicated atomic executor uses it to verify convergence. Table-only callers retain Diff.

type ChangeKind

type ChangeKind string

ChangeKind classifies a derived statement so a consumer can gate whole classes of change (destructive, rewriting, index-building) without parsing SQL.

const (
	// ChangeCreateTable creates the table (missing-table plans only).
	ChangeCreateTable ChangeKind = "create-table"
	// ChangeDropIndex drops an index.
	ChangeDropIndex ChangeKind = "drop-index"
	// ChangeDropConstraint drops a table constraint other than a foreign
	// key.
	ChangeDropConstraint ChangeKind = "drop-constraint"
	// ChangeDropForeignKey drops a foreign-key constraint. Desired-state
	// execution refuses it: foreign-key changes are planned, not run.
	ChangeDropForeignKey ChangeKind = "drop-foreign-key"
	// ChangeDropColumn drops a column.
	ChangeDropColumn ChangeKind = "drop-column"
	// ChangeAddColumn adds a column.
	ChangeAddColumn ChangeKind = "add-column"
	// ChangeAlterType changes a column's type.
	ChangeAlterType ChangeKind = "alter-type"
	// ChangeSetGeneratedExpression replaces a stored generated column's
	// expression, which recomputes every row under an exclusive lock. The
	// planner has no online path for it, so the statement is always
	// refused: the plan shows the drift and nothing runs it.
	ChangeSetGeneratedExpression ChangeKind = "set-generated-expression"
	// ChangeSetDefault sets or replaces a column default.
	ChangeSetDefault ChangeKind = "set-default"
	// ChangeDropDefault drops a column default.
	ChangeDropDefault ChangeKind = "drop-default"
	// ChangeSetNotNull adds the NOT NULL attribute.
	ChangeSetNotNull ChangeKind = "set-not-null"
	// ChangeDropNotNull removes the NOT NULL attribute.
	ChangeDropNotNull ChangeKind = "drop-not-null"
	// ChangeAddConstraint adds a table constraint other than a foreign key.
	ChangeAddConstraint ChangeKind = "add-constraint"
	// ChangeAddForeignKey adds a foreign-key constraint. Desired-state
	// execution refuses it: foreign-key changes are planned, not run.
	ChangeAddForeignKey ChangeKind = "add-foreign-key"
	// ChangeValidateConstraint validates a live check constraint left NOT
	// VALID, the state an interrupted online add leaves behind.
	ChangeValidateConstraint ChangeKind = "validate-constraint"
	// ChangeValidateForeignKey validates a live foreign key left NOT VALID.
	// Desired-state execution refuses it like every foreign-key change.
	ChangeValidateForeignKey ChangeKind = "validate-foreign-key"
	// ChangeCreateIndex creates an index.
	ChangeCreateIndex ChangeKind = "create-index"
)

The change kinds a plan can contain.

func ChangeKinds

func ChangeKinds() []ChangeKind

ChangeKinds returns the closed set of ChangeKind 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 statement as unknown and refuse it.

func (ChangeKind) IsForeignKey added in v0.4.0

func (k ChangeKind) IsForeignKey() bool

IsForeignKey reports whether the kind adds, drops, or validates a foreign key.

type Column

type Column struct {
	// Name is the column name.
	Name string
	// Type is the canonical type text (format_type), e.g. "character
	// varying(50)" — never an alias like varchar(50).
	Type string
	// NotNull reports the NOT NULL attribute.
	NotNull bool
	// Default is the canonical default expression (pg_get_expr), empty when
	// none. For a generated column it is the generation expression.
	Default string
	// SequenceDefault reports that the default expression depends on a
	// sequence (per pg_depend) — a serial column or a hand-written nextval
	// default. In a desired-state model that sequence exists only inside
	// the rolled-back scratch transaction, so no derived plan can
	// reference it.
	SequenceDefault bool
	// SequenceOwned reports that the sequence behind the default is owned
	// by this exact column (a pg_depend OWNED BY edge, deptype 'a') — what
	// the serial shorthand produces. It is false for a hand-written
	// nextval default on a standalone sequence or another table's
	// sequence, however the sequence is named: sharing distinguishes it
	// from ownership, not naming.
	SequenceOwned bool
	// Collation is the column's explicit collation as a schema-qualified,
	// quote_ident-quoted name, empty when the column uses its type's
	// default collation. The declarative model does not manage collations yet, so
	// the model carries it only to refuse: dropping a COLLATE clause from
	// a rendered baseline would silently change sort order and index
	// semantics, and a collation delta cannot be converged without a
	// table rewrite.
	Collation string
	// Identity is the identity kind, IdentityNone for plain columns.
	Identity Identity
	// Generated reports GENERATED ALWAYS AS (...) STORED.
	Generated bool
	// Virtual reports GENERATED ALWAYS AS (...) VIRTUAL, which exists from
	// PostgreSQL 18. The desired-file grammar predates it, so only a live
	// table carries one, and the model records it only to refuse: export
	// cannot write it back and a diff cannot converge it. Omitted from JSON
	// when false, so a model without virtual columns digests the same as it
	// did before the field existed.
	Virtual bool `json:",omitempty"`
	// Sequence is the declaration of the sequence the column owns, an
	// identity's or a serial's, when it differs from what declaring the
	// column fresh would create; nil when it does not, or when the column
	// owns no sequence. Omitted from JSON when nil, so a model whose
	// sequences are all declared at their defaults digests the same as one
	// without the field; a declared sequence changes the digest, which is
	// why the checkpoint format moved with it.
	Sequence *SequenceOptions `json:",omitempty"`
	// DefaultReplays are the texts Default prints as after each further
	// replay through the server, when replaying changes it, and a live
	// text that prints as Default or one of those; see settleDesired.
	// Only a desired model carries them, and they never reach a digest.
	DefaultReplays []string `json:"-"`
	// MultipleOwnedSequences reports that the column's default calls more
	// than one sequence the column owns. The model carries one sequence
	// per column, so Sequence is nil for such a column and the renderer
	// refuses it (ErrMultipleOwnedSequences) rather than export one of
	// them. Not part of the table's shape, so it never reaches a digest.
	MultipleOwnedSequences bool `json:"-"`
}

Column is one column of the canonical model.

func (Column) IsGenerated added in v0.4.0

func (c Column) IsGenerated() bool

IsGenerated reports a generated column of either kind: its Default is the generation expression, never a column default.

type Constraint

type Constraint struct {
	// Name is the constraint name.
	Name string
	// Def is the canonical definition text.
	Def string
	// ForeignKey reports a FOREIGN KEY constraint (contype 'f'). Omitted
	// from JSON when false, so a model without foreign keys digests the
	// same as it did before the field existed.
	ForeignKey bool `json:",omitempty"`
	// Primary reports a PRIMARY KEY constraint (contype 'p').
	Primary bool `json:"-"`
	// IndexDef is the CREATE UNIQUE INDEX statement of the index a primary
	// key or unique constraint owns, unqualified like Index.Def, and empty
	// for every other constraint. Only a desired model carries it: the diff
	// compares a desired key's with a live index of the constraint's name to
	// adopt that index instead of rebuilding it.
	IndexDef string `json:"-"`
	// Deferrable reports a constraint declared DEFERRABLE.
	Deferrable bool `json:"-"`
	// InitiallyDeferred reports a deferrable constraint declared INITIALLY
	// DEFERRED.
	InitiallyDeferred bool `json:"-"`
	// NotValid reports a check or foreign-key constraint the server has not
	// validated (pg_constraint.convalidated is false), which Def ends with
	// " NOT VALID". Only a live table carries one: CREATE TABLE ignores NOT
	// VALID, so a desired constraint is always validated.
	NotValid bool `json:"-"`
	// DefReplays are the texts a check constraint's Def prints as after
	// each further replay through the server, when replaying changes it,
	// and a live text that prints as Def or one of those; see
	// settleDesired. Only a desired model carries them.
	DefReplays []string `json:"-"`
}

Constraint is one table constraint: its name plus the server-decompiled definition (pg_get_constraintdef), e.g. "PRIMARY KEY (id)".

type ConstraintValidation added in v0.4.0

type ConstraintValidation struct {
	Constraint string
	Def        string
}

ConstraintValidation is a NOT VALID constraint a planned VALIDATE CONSTRAINT validates, and the definition, as introspection reads it (pg_get_constraintdef, NOT VALID suffix included), that the constraint must still have when it does.

type Identity

type Identity string

Identity is a column's identity kind, as pg_attribute.attidentity spells it.

const (
	// IdentityNone means the column is not an identity column.
	IdentityNone Identity = ""
	// IdentityAlways is GENERATED ALWAYS AS IDENTITY.
	IdentityAlways Identity = "a"
	// IdentityByDefault is GENERATED BY DEFAULT AS IDENTITY.
	IdentityByDefault Identity = "d"
)

The identity kinds.

type Index

type Index struct {
	// Name is the index name.
	Name string
	// Def is the canonical CREATE INDEX statement.
	Def string
	// Invalid reports pg_index.indisvalid = false: the entry carries the
	// name and the definition but the planner never uses it, so it does not
	// deliver the desired index. On a plain table it is a concurrent build
	// that has not finished — abandoned, or still running. On a partitioned
	// parent it means not every partition has a matching attached index;
	// the server never builds a partitioned index concurrently. A
	// desired-side index, materialized on the scratch schema, is never
	// invalid, so the zero value is the delivered state.
	Invalid bool
	// DefReplays are the texts Def prints as after each further replay
	// through the server, when replaying changes it, and a live text that
	// prints as Def or one of those; see settleDesired. Only a desired
	// model carries them.
	DefReplays []string `json:"-"`
}

Index is one non-constraint index: its name plus the server-decompiled CREATE INDEX statement (pg_get_indexdef), unqualified under the introspection search_path, and whether the entry is usable.

type IndexAdoption added in v0.4.0

type IndexAdoption struct {
	Index string
	Def   string
}

IndexAdoption is an index a new primary key or unique constraint takes over, and the definition, as introspection reads it (pg_get_indexdef with the schema qualification removed), that the index must still have when it does.

type Model

type Model struct {
	// Table is the unqualified table name.
	Table string
	// RowSecurity records settings and policies for inspection and export
	// refusal. Diff leaves access control separately managed; absence in a
	// table-only desired file is not a request to remove live policies.
	RowSecurity RowSecurity
	// PartitionKey is the server-decompiled partition key definition
	// (pg_get_partkeydef), e.g. "RANGE (created_at)" — empty for a
	// non-partitioned table.
	PartitionKey string
	// IsPartition reports that the table is itself a partition of a
	// partitioned parent (pg_class.relispartition).
	IsPartition bool
	// InheritsParents lists the classic-inheritance parents of this table.
	// Declarative partitions use the same pg_inherits catalog but are
	// excluded using pg_class.relispartition.
	InheritsParents []string
	// InheritanceChildren lists the classic-inheritance children of this
	// table. The model carries both directions so rendering either side can
	// fail closed rather than flattening inherited columns or losing edges.
	InheritanceChildren []string
	// Unlogged reports that the table is unlogged
	// (pg_class.relpersistence 'u'). The declarative model does not manage
	// persistence yet — converging it (SET LOGGED / SET UNLOGGED) is a
	// full table rewrite — so the model carries it only to refuse:
	// rendering an unlogged table as a plain CREATE TABLE would silently
	// change its crash-safety and replication behavior, and a persistence
	// mismatch fails the diff closed instead of diffing to silence.
	Unlogged bool
	// Options are the table's storage parameters (pg_class.reloptions),
	// with its TOAST table's parameters prefixed "toast.", each as the
	// server stores it ("fillfactor=70"), sorted so the order a file lists
	// them in carries no meaning. A desired file declares them with
	// CREATE TABLE ... WITH (...), and the renderer writes them back the
	// same way. The diff does not converge them, so a mismatch fails
	// closed instead of diffing to silence: a parameter declared in the
	// file but never applied, or a tuned live parameter the file drops,
	// would otherwise plan as no change. Omitted from JSON when empty, so a
	// model without storage parameters digests the same as it did before
	// the field existed.
	Options []string `json:",omitempty"`
	// ToastMayNotRebuild reports that the table has a dropped column and no
	// remaining column that guarantees a TOAST table, so a fresh CREATE
	// TABLE of its columns might build none. The server builds a TOAST
	// table at CREATE TABLE only when the columns need one and silently
	// discards toast.* parameters otherwise. A dropped column is the one
	// change that can leave a TOAST table the remaining columns do not
	// need: adding or retyping a column builds one when the columns come
	// to need it, and a rewrite builds it afresh. A remaining column of an
	// unbounded variable-length type, stored other than PLAIN, settles it,
	// since the server always builds a TOAST table for one. When Options
	// carries TOAST parameters the renderer refuses such a table rather
	// than write a
	// baseline that would plan the parameters again on every diff. Read
	// only alongside TOAST parameters, and not part of the table's shape,
	// so it never reaches a digest.
	ToastMayNotRebuild bool `json:"-"`
	// ReplicaIdentity is what the replica identity indexes of the table
	// and of every table below it are built on. It is a live fact for the
	// planner, not part of the table's declared shape, so it is left out of
	// the model's JSON and every digest of it.
	ReplicaIdentity ReplicaIdentityKeys `json:"-"`
	// ReferencedBy lists the incoming foreign keys — constraints on other
	// tables that reference this one — as "table.constraint" strings, in
	// that order. Incoming foreign keys are not part of this table's own
	// definition and cannot be expressed in a desired file, so the model
	// carries them only for the renderer to refuse on.
	ReferencedBy []string
	// Columns are the table's columns in attribute order.
	Columns []Column
	// Constraints are the table constraints, name-sorted.
	Constraints []Constraint
	// Indexes are the non-constraint indexes, name-sorted.
	Indexes []Index
}

Model is the canonical, comparison-ready description of one table. It carries no schema qualification: the live and desired sides are introspected under matching search_path settings so their definitions compare textually.

func Introspect

func Introspect(ctx context.Context, db *pgxpool.Pool, schema, table string) (Model, error)

Introspect reads the live table schema.table into the canonical model. It runs inside a read-only transaction whose search_path is set to the target schema (then public), so the server's decompilers print definitions unqualified — directly comparable with a desired-state model introspected the same way.

func IntrospectDesired

func IntrospectDesired(ctx context.Context, db *pgxpool.Pool, schema string, desired statement.DesiredSchema) (Model, error)

IntrospectDesired materializes a desired-state schema on a scratch schema and introspects it into the canonical model: execute-and-introspect, the decided way the engine understands DDL semantics. The scratch schema is created inside a single transaction that is always rolled back — nothing the desired file defines ever persists, no CREATEDB privilege is needed, and server-version and extension parity with the live table hold by construction because it runs on the same database.

schema is the target schema the desired table lives in. A table the desired foreign keys reference is read from it: the scratch schema holds an empty copy of each one, so no foreign key ever binds to a live table, and planning takes only the ACCESS SHARE lock a plain SELECT takes on it (see createReferencedStandIns).

The file's unqualified names also resolve against the desired schema's extension schemas, which the model still prints qualified.

func IntrospectDesiredWithRowSecurity added in v0.4.0

func IntrospectDesiredWithRowSecurity(ctx context.Context, db *pgxpool.Pool, schema string, desired statement.DesiredWithRowSecurity) (Model, error)

IntrospectDesiredWithRowSecurity materializes an explicitly RLS-scoped file in a rolled-back scratch transaction. Roles and qualified helpers must exist; this never provisions authentication or changes the live table. schema is the target schema the table lives in: the table's own definition resolves that schema's types and functions by the bare names live introspection prints, as IntrospectDesired does, and the extension schemas the declaration names as well. Policy expressions still resolve nothing but the scratch schema, so their helpers must be qualified.

func IntrospectDesiredWithRowSecurityTx added in v0.4.0

func IntrospectDesiredWithRowSecurityTx(ctx context.Context, tx pgx.Tx, schema string, desired statement.DesiredWithRowSecurity) (Model, error)

IntrospectDesiredWithRowSecurityTx materializes the declaration in a nested transaction (savepoint) and always rolls it back. The parent's locks survive. schema is resolved as in IntrospectDesiredWithRowSecurity.

func IntrospectTx added in v0.4.0

func IntrospectTx(ctx context.Context, tx pgx.Tx, schema, table string) (Model, error)

IntrospectTx introspects schema.table inside the caller's open transaction, so a caller that builds a relation and reads its model in one transaction sees its own uncommitted DDL and leaves nothing behind if the read fails. It sets the transaction-local search_path the same way Introspect does, so decompiled definitions print unqualified. A successful read leaves the transaction on a pg_catalog-only search_path, which the row-security read sets last; a caller that needs another path afterwards sets it again.

type Policy added in v0.4.0

type Policy struct {
	Name       string
	Command    PolicyCommand
	Permissive bool
	// Roles contains name-sorted roles; "public" represents PostgreSQL's
	// special PUBLIC audience (OID zero), not a provisioned application role.
	Roles []string
	// Using and WithCheck preserve NULL separately from an explicit expression.
	// In particular, an omitted WITH CHECK can inherit USING semantics.
	Using     *string
	WithCheck *string
	Comment   *string
}

Policy is a pg_policy catalog entry. Expressions come from pg_get_expr with only pg_catalog on search_path, retaining schema qualification for external functions and relations. This is an inventory, not a proof that two expressions grant equivalent access or that their dependencies have unchanged definitions.

type PolicyCommand added in v0.4.0

type PolicyCommand string

PolicyCommand identifies the operations a policy applies to.

const (
	PolicyAll    PolicyCommand = "*"
	PolicySelect PolicyCommand = "r"
	PolicyInsert PolicyCommand = "a"
	PolicyUpdate PolicyCommand = "w"
	PolicyDelete PolicyCommand = "d"
)

PostgreSQL's pg_policy.polcmd values, including ALL (not a wildcard role).

type PolicySnapshot added in v0.4.0

type PolicySnapshot struct {
	Name       string        `json:"name"`
	Command    PolicyCommand `json:"command"`
	Permissive bool          `json:"permissive"`
	Roles      []string      `json:"roles"`
	Using      *string       `json:"using"`
	WithCheck  *string       `json:"with_check"`
	Comment    *string       `json:"comment"`
}

PolicySnapshot is the captured definition in the review JSON contract. Null expressions distinguish omitted clauses from explicit predicates.

type ReplicaIdentityKeys added in v0.4.0

type ReplicaIdentityKeys struct {
	// Indexes are the indexes on this table whose drop removes a replica
	// identity index: the table's own, or a partitioned index that a
	// partition's identity index is attached under. Name-sorted.
	Indexes []string
	// Constraints are the primary key or unique constraints on this table
	// that own one of Indexes. Name-sorted.
	Constraints []string
	// Columns are the columns every replica identity index in the tree
	// covers, INCLUDE columns too. Dropping one drops each index built on
	// it, those of the tables below included. Name-sorted.
	Columns []string
	// OwnColumns are the columns this table's own replica identity index
	// covers, INCLUDE columns too: what a DROP COLUMN under ALTER TABLE
	// ONLY can take, since it leaves the column in the tables below.
	// Name-sorted.
	OwnColumns []string
}

ReplicaIdentityKeys is what the replica identity indexes of a table are built on, across the table and every table below it, partitions and inheritance children alike: the index REPLICA IDENTITY USING INDEX selects, or the primary key under REPLICA IDENTITY DEFAULT on a table a publication publishes updates or deletes for. Logical decoding keys UPDATE and DELETE on that index, and PostgreSQL keeps the setting when the index is dropped, so the table is left with no usable identity and every UPDATE and DELETE on it fails while a publication publishes them. The zero value means no table in the tree has an identity index to protect.

func ReadReplicaIdentity added in v0.4.0

func ReadReplicaIdentity(ctx context.Context, tx pgx.Tx, oid uint32) (ReplicaIdentityKeys, error)

ReadReplicaIdentity reads, inside tx, what the replica identity indexes of the table with the given oid and of every table below it are built on. Introspection reads it into Model.ReplicaIdentity, and the executor reads it again under the table's lock, so the answer a drop is checked against cannot change before the drop runs. The tree follows pg_inherits, so it holds partitions and classic inheritance children alike: a DROP COLUMN here recurses into both. An identity index is one pg_index marks indisreplident on a table whose relreplident is 'i', or the primary key of a table whose relreplident is 'd' (DEFAULT) while a publication publishes its updates or deletes. A publication publishes a permanent table when it publishes all tables, lists the table, or lists its schema, and the server applies a partition's ancestors' publications to it as well. The catalogs are read directly rather than through pg_publication_tables, which looks each publication up again by name and fails if one is dropped while the query runs. A partitioned table holds no rows, so only its partitions' primary keys count, each traced up to the parent's as any other identity index is. A DEFAULT table no publication publishes keeps no identity worth protecting, so its primary key stays free to drop. Each is traced up its attachment chain to the index on this table that a DROP INDEX or DROP CONSTRAINT here would cascade from; an identity index on a child that is attached under nothing on this table contributes only its columns, which a DROP COLUMN here still cascades to. Every column the index covers counts, INCLUDE columns too, since dropping any of them drops the index. Only a primary key or unique constraint owns its index; a foreign key that references one does not. The partition functions list nothing for an index outside a partition tree, so each identity index is counted on its own as well.

func (ReplicaIdentityKeys) DroppedBy added in v0.4.0

func (k ReplicaIdentityKeys) DroppedBy(op statement.Op) bool

DroppedBy reports whether op drops a replica identity index of the table or of a table below it: an index it is, or is attached under, the constraint that owns one, or a column one is built on, which takes the index with it. A column dropped under ONLY stays in the tables below, so only the table's own identity index counts for it. The planner refuses such an operation, and the executor asks again under the table's lock before a native drop runs.

type RowSecurity added in v0.4.0

type RowSecurity struct {
	Enabled  bool
	Forced   bool
	Policies []Policy
}

RowSecurity is observed table-local access control, not a desired-state ownership declaration. Diff refuses a desired model carrying it. Enabled and Forced are independent: PostgreSQL retains FORCE and policies while RLS is disabled.

type RowSecurityReview added in v0.4.0

type RowSecurityReview struct {
	Version                 int              `json:"version"`
	Changes                 []SecurityChange `json:"changes"`
	TableChanged            bool             `json:"table_changed"`
	TableComparisonComplete bool             `json:"table_comparison_complete"`
	TableComparisonError    string           `json:"table_comparison_error,omitempty"`
}

RowSecurityReview is diagnostic only. It has no SQL or approval fingerprint. Version 1 compares captured catalog definitions, not grants or helper bodies.

func ReviewRowSecurity added in v0.4.0

func ReviewRowSecurity(schema string, live, desired Model) (RowSecurityReview, error)

ReviewRowSecurity describes RLS changes and reports whether ordinary table changes accompany them. An unsupported table comparison remains explicit.

type SecurityChange added in v0.4.0

type SecurityChange struct {
	Kind          SecurityChangeKind `json:"kind"`
	Policy        string             `json:"policy,omitempty"`
	BeforeSetting *bool              `json:"before_setting,omitempty"`
	AfterSetting  *bool              `json:"after_setting,omitempty"`
	BeforePolicy  *PolicySnapshot    `json:"before_policy"`
	AfterPolicy   *PolicySnapshot    `json:"after_policy"`
	Impact        AccessImpact       `json:"access_impact"`
}

SecurityChange carries either before/after settings or complete policy snapshots. Missing policy sides are null for additions/removals; absent clauses stay null.

type SecurityChangeKind added in v0.4.0

type SecurityChangeKind string

SecurityChangeKind names a review-only RLS delta, never executable SQL.

const (
	SecurityEnabled       SecurityChangeKind = "enabled"
	SecurityForced        SecurityChangeKind = "forced"
	SecurityPolicyAdded   SecurityChangeKind = "policy-added"
	SecurityPolicyRemoved SecurityChangeKind = "policy-removed"
	SecurityPolicyChanged SecurityChangeKind = "policy-changed"
)

Security change kinds are part of the versioned RLS review contract.

type SequenceOptions added in v0.4.0

type SequenceOptions struct {
	// Type is the sequence's data type (format_type), e.g. "bigint".
	Type string
	// Start is START WITH.
	Start int64
	// Increment is INCREMENT BY.
	Increment int64
	// Min is MINVALUE.
	Min int64
	// Max is MAXVALUE.
	Max int64
	// Cache is CACHE.
	Cache int64
	// Cycle reports CYCLE.
	Cycle bool
}

SequenceOptions are the declared parameters of a column-owned sequence (pg_sequence). The counter's position is not among them: it is data, not schema.

Jump to

Keyboard shortcuts

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