Documentation
¶
Overview ¶
Package preflight verifies preconditions before the engine writes anything (invariant ST-6). In Phase 1 that is the table-size guard in front of the optimistic attempt: a cancelled rewrite attempt is not a free probe — it holds ACCESS EXCLUSIVE and does real rewrite work for the full statement budget — so above a size threshold the attempt is skipped entirely.
This is a safety-critical core package: see SAFETY.md. It returns proof types with package-private constructors; dangerous downstream APIs accept only the proof.
Index ¶
- Constants
- Variables
- func AddColumnFillsNull(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string, ...) (map[string]bool, error)
- func AddColumnRewrites(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string, ...) (map[string]statement.AddColumnProof, error)
- func CheckCopySwapPartitioning(ctx context.Context, pool *pgxpool.Pool, schema, table string) error
- func CheckCopySwapStatisticsAccess(ctx context.Context, pool *pgxpool.Pool, schema, table string, ...) error
- func CheckNamesAbsent(ctx context.Context, pool *pgxpool.Pool, at AbsentTarget, names []string) error
- func CheckPartitionSupport(table PreflightedTable, serverMajor int, execSQL []string) error
- func CheckPlanPrivileges(ctx context.Context, db rowQuerier, schema string) error
- func CheckedColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
- func CopySwapDecodingName(database, schema, table string) string
- func IsNameOccupied(err error) bool
- func KeyedColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
- func LookupEnumSchema(ctx context.Context, pool *pgxpool.Pool, ref statement.TypeName) (string, error)
- func NotNullColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
- func NullFilledColumns(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string, ...) (map[string]bool, error)
- func PartitionedIndexColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
- func PublicationsPublishingNewTableChanges(ctx context.Context, db rowQuerier, schema string) ([]string, error)
- func ReadTableDropDependents(ctx context.Context, pool *pgxpool.Pool, schema, table string) ([]string, error)
- func RecheckCopySwapShape(ctx context.Context, tx pgx.Tx, target CopySwapTarget) error
- func RoutesToOnlineAttach(sql string) (bool, error)
- func RoutesToPartitionedForeignKeyBuild(serverMajor int, sql string) (bool, error)
- func RoutesToPartitionedIndexBuild(execSQL []string) (bool, error)
- func RoutesToPartitionedKeyBuild(sql string) (bool, error)
- func SchemaConstraintNames(ctx context.Context, pool *pgxpool.Pool, schema string) (map[string]bool, error)
- func SessionTimeZone(ctx context.Context, pool *pgxpool.Pool) (string, error)
- func TableHasRows(ctx context.Context, pool *pgxpool.Pool, schema, table string) (bool, error)
- func UTCTimeZone(zone string) bool
- func ValidatedNotNullColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
- type AbsentTarget
- type AbsentType
- type ColumnDependents
- type ColumnNumbers
- type CopySwapEnvironment
- type CopySwapEnvironmentAdvisory
- type CopySwapEnvironmentError
- type CopySwapHeld
- type CopySwapRefusalCause
- type CopySwapSetting
- type CopySwapShape
- func (s CopySwapShape) Database() string
- func (s CopySwapShape) DecodingName() string
- func (s CopySwapShape) LogicalDecoding() bool
- func (s CopySwapShape) OID() uint32
- func (s CopySwapShape) OwnerRole() string
- func (s CopySwapShape) PKColumn() string
- func (s CopySwapShape) PKType() PKType
- func (s CopySwapShape) Schema() string
- func (s CopySwapShape) Table() string
- type CopySwapShapeCause
- type CopySwapTarget
- func (s CopySwapTarget) Database() string
- func (t CopySwapTarget) DecodesWAL() bool
- func (s CopySwapTarget) DecodingName() string
- func (t CopySwapTarget) FinishesCommittedSwap() bool
- func (s CopySwapTarget) OID() uint32
- func (s CopySwapTarget) OwnerRole() string
- func (s CopySwapTarget) PKColumn() string
- func (s CopySwapTarget) PKType() PKType
- func (s CopySwapTarget) Schema() string
- func (s CopySwapTarget) Table() string
- type CreationRole
- type DependentObjects
- type EnumTarget
- type ExpressionProof
- type FullTable
- type GoneTable
- type IndexUsage
- type LockHolder
- type OwnedRelationNames
- type PKType
- type PartitionRefusalCause
- type PartitionUsage
- func (p PartitionUsage) Foreign() bool
- func (p PartitionUsage) IdxScans() int64
- func (p PartitionUsage) LastIdxScan() (at time.Time, ok bool)
- func (p PartitionUsage) LastSeqScan() (at time.Time, ok bool)
- func (p PartitionUsage) Name() string
- func (p PartitionUsage) OID() uint32
- func (p PartitionUsage) Schema() string
- func (p PartitionUsage) SeqScans() int64
- type PreflightedTable
- type PrivilegeError
- type PrivilegedRole
- type Publishing
- type Requirement
- type SizeError
- type Subscriptions
- type TableUsage
- func (u TableUsage) IdxScans() int64
- func (u TableUsage) InRecovery() bool
- func (u TableUsage) Judge(window time.Duration) (UsageVerdict, error)
- func (u TableUsage) LastIdxScan() (at time.Time, ok bool)
- func (u TableUsage) LastSeqScan() (at time.Time, ok bool)
- func (u TableUsage) LockHolders() []LockHolder
- func (u TableUsage) OID() uint32
- func (u TableUsage) Partitioned() bool
- func (u TableUsage) Partitions() []PartitionUsage
- func (u TableUsage) ReadAt() time.Time
- func (u TableUsage) ScanTimesRecorded() bool
- func (u TableUsage) Schema() string
- func (u TableUsage) SeqScans() int64
- func (u TableUsage) ServerVersionNum() int
- func (u TableUsage) StatsReset() (at time.Time, ok bool)
- func (u TableUsage) Table() string
- func (u TableUsage) TrackCounts() bool
- func (u TableUsage) TrackCountsOffBySetting() bool
- func (u TableUsage) TuplesDeleted() int64
- func (u TableUsage) TuplesInserted() int64
- func (u TableUsage) TuplesUpdated() int64
- type TablespaceUse
- type TargetFacts
- type Tier
- type UnsupportedCopySwapShapeError
- type UnsupportedPartitionedParentError
- type UsageOutcome
- type UsageReason
- type UsageVerdict
- func (v UsageVerdict) Detail() string
- func (v UsageVerdict) Outcome() UsageOutcome
- func (v UsageVerdict) Partition() (p PartitionUsage, ok bool)
- func (v UsageVerdict) Reason() UsageReason
- func (v UsageVerdict) Usage() TableUsage
- func (v UsageVerdict) Window() time.Duration
- func (v UsageVerdict) WindowStart() time.Time
- type UsageWindowError
Constants ¶
const DefaultSlotLagCeiling int64 = 1 << 30
DefaultSlotLagCeiling is the slot lag ceiling, in bytes, a catch-up enforces when its caller sets none (decode.DefaultSlotLagCeiling is this value). It lives here so the disk check counts the same default without importing the package that enforces it.
const EngineSchema = "pgsprite"
EngineSchema is the schema the engine owns in every target database: the checkpoint table lives in it, and so does every function the engine installs for a run. A trigger on the target whose function lives in this schema is the engine's own, not a user trigger, and the shape check sets it aside the way it sets aside the engine's own publication.
const MaxColumnNumber = 1600
MaxColumnNumber is the highest column number PostgreSQL gives a table (MaxHeapAttributeNumber). A dropped column keeps its number until the table is rebuilt, so a table can reach it with far fewer live columns.
const MinUsageWindow = 5 * time.Minute
MinUsageWindow is the shortest window Judge accepts. A scan is recorded with the end time of the transaction that ran it, but the backend publishes it to the shared statistics only when it next goes idle, at most once a second, and defers that by up to a minute when the statistics are contended. A window not well clear of that delay would answer about scans the server has not reported yet.
const NoSizeLimit int64 = math.MaxInt64
NoSizeLimit is a size limit no PostgreSQL relation can exceed. Callers pass it when the check should prove only existence and kind — the online sequence path, whose long steps are safe on any size by design (the size guard protects blind attempts, not planner-proven online idioms).
const PartitionedNotValidForeignKeyMajor = 18
PartitionedNotValidForeignKeyMajor is the first PostgreSQL major that accepts ADD FOREIGN KEY ... NOT VALID on a partitioned table. Before it, a foreign key on a partitioned table is added online only by the partitioned foreign key build (pkg/executor); from it, by the ordinary NOT VALID then VALIDATE steps. It is the one cutoff the routing here, the partitioned-parent refusal, and the build's own server check share.
Variables ¶
var ErrAddColumnProbeLocked = errors.New("the probe could not take a lock at once")
ErrAddColumnProbeLocked means an add-column probe needed a lock another session held, on a system catalog or on an object the column's type or default uses, and did not wait for it, so it proved nothing. The probe never opens the live table. AddColumnFillsNull returns it, since a NULL fill has no safe default answer; AddColumnRewrites does not, and reports the column as statement.AddColumnUnproven instead. A later attempt succeeds once the lock is released.
ErrAddColumnProbeUnavailable means the server refused the temporary table the add-column proof adds each column to: the server accepts no writes (a hot standby, or default_transaction_read_only), or the role lacks TEMPORARY on the database. Without the proof the plan cannot say whether adding the column rewrites the table, so it fails rather than guess.
var ErrCopySwapProofMismatch = errors.New("privilege proof was not verified at the copy-and-swap tier")
ErrCopySwapProofMismatch is returned when the privilege proof handed to the shape check was not verified at the copy-and-swap tier.
var ErrCreateOwnerNotFound = errors.New("create owner role not found")
ErrCreateOwnerNotFound is returned when the named create owner is not a role on the server. The name is caller configuration, so the cause is separated from a missing grant: no GRANT provisions a role that does not exist, and nothing has run.
var ErrEnumTypeNotFound = errors.New("the type ADD VALUE names is not an enum type visible on the session search_path")
ErrEnumTypeNotFound means the type an ALTER TYPE ... ADD VALUE names is not an enum type visible on the session search_path. Nothing has executed.
var ErrNoCreationSchema = errors.New("the session's search_path names no creation schema")
ErrNoCreationSchema is returned when an unqualified check cannot resolve the session's creation schema: the search_path names no usable schema, so there is no schema to verify the absence in. Unlike the other refusals this one is not a database fact — the remedy is entirely on the caller's side: qualify the name, or fix the connection's search_path.
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).
var ErrRelationExists = errors.New("a relation already exists at the target name")
ErrRelationExists is returned when the target name is already occupied by a relation of any kind — a table, view, index, or sequence all block a CREATE TABLE at that name the same way.
var ErrSchemaNotFound = errors.New("schema not found")
ErrSchemaNotFound is returned when the schema a create would target does not exist. Creating a table cannot fix a missing schema, so the cause is separated from a free name.
var ErrTableNotFound = errors.New("table not found")
ErrTableNotFound is returned when the target table does not exist (or is not visible with the session's search_path).
var ErrTableRowsLocked = errors.New("the table cannot be read without waiting for another session's lock")
ErrTableRowsLocked means another session holds or awaits a lock that blocks reading schema.table or a table below it, so whether it holds rows is unknown. The plan cannot say whether adding a NOT NULL column without a default would fail, so it fails rather than guess; a later attempt reads the table once the lock is released.
var ErrTypeExists = errors.New("a type already exists at the target name")
ErrTypeExists is returned when the target name is already occupied by a standalone type — an enum, domain, range, or shell type. Every table gets a composite type of the same name, so a CREATE TABLE collides with these exactly as it does with a relation.
Functions ¶
func AddColumnFillsNull ¶ added in v0.5.0
func AddColumnFillsNull(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string, columns []string, newEnumTypes ...statement.DesiredEnumType) (map[string]bool, error)
AddColumnFillsNull reports which of columns the ALTER TABLE sql adds with NULL in an existing row: each is added, as the statement adds it, to a temporary table holding one row, and the server's not_null_violation is the answer. The server decides, not the statement's shape, so a domain DEFAULT that fills the column counts. A probe the server refuses for another reason, such as a domain CHECK the row's value fails, is not a NULL fill and does not count; the add-column proof and the server's own refusal judge that change.
The probes run like AddColumnRewrites': in a transaction that is always rolled back, each in a savepoint, on the statement's search_path, and never waiting for a lock. The live table is never opened. A probe that meets a lock another session holds returns ErrAddColumnProbeLocked. newEnumTypes are the enum types the same change creates before sql runs, created for the probes as AddColumnRewrites creates them.
func AddColumnRewrites ¶ added in v0.4.0
func AddColumnRewrites(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string, newEnumTypes ...statement.DesiredEnumType) (map[string]statement.AddColumnProof, error)
AddColumnRewrites reports, for each column the ALTER TABLE in sql adds to schema.table, what the server proved about adding it: whether it rewrites the table, and if so whether the column's default or its type is the cause. The server answers, not the statement's shape: a constant DEFAULT still rewrites every row when the column's type is a domain with constraints, and a DEFAULT now() does not, because the server stores any non-volatile default in the catalog.
Each column is added on its own (statement.AddColumnProbes) to an empty temporary table with no columns, inside a savepoint of a transaction that is always rolled back, and a rewrite shows as the probe table's storage being replaced (pg_relation_filenode changes). The probe rewrites exactly when schema.table would, since the decision depends on the added column's type and default, never on the table's rows or its other columns: a default cannot name a column, and a generated column, whose expression can, gets no probe. A column that rewrites is probed again with its type alone, as the server resolved it and with no default or identity, which tells a rewriting type from a rewriting default. The live table is never opened by the probe itself, and needs no privilege.
Adding the column still evaluates its default once, and its domain's checks, the way the real ALTER does, and a function either one calls can read any table, the live one included. A column added in place whose type or default resolves to anything a user defined is reported as statement.AddColumnInPlaceRunsUserCode, so that evaluation is never taken as catalog-only. A probe never waits for a lock: one that cannot be granted at once proves nothing, and the column is reported as statement.AddColumnUnproven. Each probe's savepoint is rolled back as soon as it is read, which releases whatever it locked.
An ADD COLUMN IF NOT EXISTS for a column the table already has is skipped by the server, so it gets no proof and the column is absent from the result. A server that refuses the probe table returns ErrAddColumnProbeUnavailable. A probe that fails for any other reason, such as a column type that does not exist, is returned as an error, never read as an answer.
newEnumTypes are the enum types the same change creates before sql runs. Each is created, with its declared labels, in the probe transaction's temporary schema, which the server searches first for a type name, so a column of a type the change also creates resolves as it will once the change has created it. A caller lists only types schema does not hold. When one cannot be created because a lock is not granted at once, every column is reported as statement.AddColumnUnproven.
func CheckCopySwapPartitioning ¶ added in v0.5.6
CheckCopySwapPartitioning returns the refusal CheckCopySwapShape gives schema.table when the table is a partitioned parent, a partition, or part of an inheritance tree: an *UnsupportedCopySwapShapeError carrying CopySwapCausePartitioned, or CopySwapCauseUnlogged or CopySwapCauseForceRLS when the table is also UNLOGGED or forces row security, which the shape check decides first, with every other shape cause the table has listed after it. It returns nil for a table outside such a tree, supported or not, and mints no proof. It is for a caller that previews the route without running it — a dry run, which proves no privilege and reads no environment — so the preview gives every table in a partition or inheritance tree the refusal the route's preflight gives it, read from the same catalog facts and decided by the same rule, and leaves every other table to that preflight, which reads the facts again when the route runs. The pool should come from dbconn.NewPool.
func CheckCopySwapStatisticsAccess ¶ added in v0.5.8
func CheckCopySwapStatisticsAccess(ctx context.Context, pool *pgxpool.Pool, schema, table string, role PrivilegedRole) error
CheckCopySwapStatisticsAccess verifies that the swap can carry every extended-statistics object on schema.table (search_path resolution when schema is empty). The swap runs as the table's owner, the role the engine takes on with SET ROLE, and renames each source object to its derived old name where it lives; for an object outside the table's schema it also moves the shadow's copy, which LIKE created in the table's schema, into the object's schema and renames it there. PostgreSQL lets only the object's owner rename or move it, both need CREATE on the schema the object ends up in, and naming the object in its schema needs USAGE there, unless the role is a superuser. A missing access would otherwise surface as a rolled-back swap after the whole copy.
The owner's USAGE and CREATE are checked on every object's schema, the table's own included: the privilege ladder checks the table's schema for the engine role, which a direct grant satisfies while the owner holds nothing there. Objects are checked in name order and the first miss is refused, so a table with several objects the owner lacks access to is provisioned one refusal at a time. A missing access is a *PrivilegeError whose Hint names the object; nothing is written either way. role is the proof CheckPrivileges minted at TierCopyAndSwap, whose owner is the role the swap runs as.
func CheckNamesAbsent ¶ added in v0.3.0
func CheckNamesAbsent(ctx context.Context, pool *pgxpool.Pool, at AbsentTarget, names []string) error
CheckNamesAbsent verifies that no relation in the proved target's schema occupies any of names. It reads pg_class in one catalog snapshot and reports the first occupied name in lexical order, regardless of input order — the query's ORDER BY decides, so the caller need not sort. It does not probe pg_type: this check protects index, constraint-index, and sequence names; CheckTableAbsent separately protects the CREATE TABLE name and its composite type. The AbsentTarget binds the check to the resolved, existing schema where those names would land.
func CheckPartitionSupport ¶
func CheckPartitionSupport(table PreflightedTable, serverMajor int, execSQL []string) error
CheckPartitionSupport verifies that the execution steps are safe for the target's relation kind. Ordinary tables and leaf partitions pass unchanged. Supported in-place parent ALTER TABLE operations remain available.
func CheckPlanPrivileges ¶ added in v0.5.8
CheckPlanPrivileges proves the connected role can plan a desired-state file for a table in schema: USAGE on schema, and CREATE on the database for the scratch schema every declarative plan builds the desired table in. CREATE SCHEMA needs the database privilege, which a least-privilege application role often lacks, and without USAGE the schema's own types and sequences are invisible to the plan. Without this check either gap fails later with an error that names no grant, so each is returned as a typed *PrivilegeError carrying the exact statement: USAGE at TierConnect first, then CREATE at TierPlan. An empty schema means the session's current_schema(). A schema that does not exist is left to the plan, which reports it.
db may be a pool, a connection or a transaction: the check reads only session facts, so it answers for the session that builds the scratch schema when given that session.
func CheckedColumns ¶ added in v0.5.8
func CheckedColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
CheckedColumns names the columns of schema.table that a CHECK constraint reads, on the table or on any of its partitions or inheritance children. PostgreSQL checks every such constraint against every row again when the column's type changes, even when the change rewrites nothing, so a type change on one of these columns reads the whole table.
func CopySwapDecodingName ¶ added in v0.4.0
CopySwapDecodingName is the name the copy-and-swap route gives both the replication slot and the single-table publication it creates for a table: the engine prefix followed by eight hex digits of an FNV-1a hash of the quoted, dotted database.schema.table. Quoting keeps the three names apart however they are spelled — a dot inside one name cannot make two tables read as one. A replication slot is cluster-wide while a table is per-database, so the database is part of the hash and two databases holding a same-named table derive different slots. The same table always derives the same name, so a resumed run finds the slot it created and the preflight knows which publication is the engine's own.
func IsNameOccupied ¶ added in v0.2.0
IsNameOccupied reports whether err means the target name is already held, by a relation or by a standalone type. Both block a CREATE TABLE the same way, so a caller routing "name taken" versus "name free" matches this predicate rather than the two sentinels separately — the sentinels stay distinct for messages, where the difference tells an operator what the obstacle actually is.
func KeyedColumns ¶ added in v0.5.8
func KeyedColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
KeyedColumns names the columns of schema.table that an index or a foreign key reads, on the table or on any of its partitions or inheritance children, since a type change on the table changes the column there too. A change between timestamp and timestamptz rebuilds every index on the column and rechecks every foreign key the column is part of under its exclusive lock, so a column in this set never relabels.
Three catalog records cover the readers. A plain index depends on each column it reads, as a key, in an expression, or in a predicate. An index that backs a primary key, unique, or exclusion constraint depends on the constraint instead, and the constraint depends on the columns, so the index's own key columns are read from pg_index and the constraint's columns, expressions and predicate from its dependencies. A foreign key on the table depends on each of its referencing columns the same way.
func LookupEnumSchema ¶ added in v0.5.1
func LookupEnumSchema(ctx context.Context, pool *pgxpool.Pool, ref statement.TypeName) (string, error)
LookupEnumSchema returns the schema of the enum type ref names, resolved as CheckEnumTarget resolves it, without checking that the role may alter the type. It is the fact a plan reports, never a proof.
func NotNullColumns ¶ added in v0.5.8
func NotNullColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
NotNullColumns names the columns of schema.table that are already NOT NULL on the table and on every partition and inheritance child below it, so ALTER COLUMN ... SET NOT NULL on one of them changes nothing. From PostgreSQL 18 a column can carry a NOT VALID NOT NULL constraint, which still sets attnotnull, and SET NOT NULL then validates it by reading every row; such a column, or one that allows NULL on one table of the tree, is left out.
func NullFilledColumns ¶ added in v0.5.0
func NullFilledColumns(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string, columns []string) (map[string]bool, error)
NullFilledColumns reports which of columns, each added by the ALTER TABLE sql with no DEFAULT of its own, PostgreSQL would refuse to add to schema.table because the column is NOT NULL, as spelled or through its domain or an inline PRIMARY KEY, and the table holds a row it would leave NULL in. It is empty when none would: when no column is NOT NULL, when every column gets a value from somewhere else, such as its domain's DEFAULT, or when the table holds no row. The columns come from planner.NullFillCandidates.
Each column is first added to a temporary table holding one row (AddColumnFillsNull), which needs no privilege on the table and no lock on it; the table's rows are read (TableHasRows) only when one of the columns would be left NULL there. A probe that meets another session's lock returns ErrAddColumnProbeLocked, and a locked table ErrTableRowsLocked; either way a later attempt can answer once the lock is released.
func PartitionedIndexColumns ¶ added in v0.5.8
func PartitionedIndexColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
PartitionedIndexColumns names the columns of the partitioned table schema.table that a partitioned index reads, as a key or in an expression or predicate, whether the index stands alone or backs a constraint, on the table or on any partitioned table below it, since a type change on the table changes the column there too; it is empty for a table that is not partitioned. A type change on such a column rebuilds every partition's index attached to that partitioned index, under the change's exclusive lock on the whole tree, even when PostgreSQL relabels the column in place. A plain table's index on the column is kept, and so are a leaf partition's own index and an inheritance child's.
func PublicationsPublishingNewTableChanges ¶ added in v0.5.8
func PublicationsPublishingNewTableChanges(ctx context.Context, db rowQuerier, schema string) ([]string, error)
PublicationsPublishingNewTableChanges names the publications that publish the updates or deletes of every permanent table created in schema, from those newTablePublications names. One that publishes only inserts or truncates needs no key to decode them. Name-sorted; empty when none does.
func ReadTableDropDependents ¶ added in v0.5.6
func ReadTableDropDependents(ctx context.Context, pool *pgxpool.Pool, schema, table string) ([]string, error)
ReadTableDropDependents names the objects that make PostgreSQL refuse a DROP TABLE of schema.table without CASCADE, other than the foreign keys of other tables, which the table's model lists as IncomingForeignKeys. They are the objects with a normal dependency on the table, on one of its columns, on a sequence it owns, or on its row type or that type's array type: views and materialized views that read it, rules and policies of other tables that read it, functions whose body or signature names it, columns of other tables typed by its row type, and defaults of other tables that draw from its serial or identity sequence, which the drop takes with it. Each is named by the server's description of it with its schema, a view by the view rather than its rewrite rule, in a stable order. Objects that belong to the table, such as its own constraints, indexes, triggers, rules, and policies, go with the drop and are left out. A table that does not exist has none.
The read is a planning fact: the server's own refusal at execution stays the backstop for a dependent created after it.
func RecheckCopySwapShape ¶ added in v0.4.0
RecheckCopySwapShape verifies inside the build transaction that the proven relation still has the admitted shape and identity.
func RoutesToOnlineAttach ¶ added in v0.5.8
RoutesToOnlineAttach reports whether a statement is the ATTACH PARTITION the online attach carries: an ALTER TABLE whose only subcommand attaches a table FOR VALUES. A front door asks it of the submitted statement, which the planner marks rewrite-required because the submitted form scans the new table under ACCESS EXCLUSIVE, and runs the online attach with the statement itself. An attach of a DEFAULT partition is false: the flow cannot prove a table holds no row of any other partition's bound, so it stays rewrite-required. A statement that does not parse is an error.
func RoutesToPartitionedForeignKeyBuild ¶ added in v0.5.7
RoutesToPartitionedForeignKeyBuild reports whether a statement whose target is a partitioned table, on a server of major version serverMajor, is the one ADD FOREIGN KEY that the partitioned foreign key build carries: an ALTER TABLE whose only subcommand adds a foreign key without NOT VALID, on a server before version 18. A front door asks it of the submitted statement, after it knows the target is partitioned and before the steps the planner made for a plain table (ADD ... NOT VALID, then VALIDATE, which PostgreSQL refuses on a partitioned table before version 18) reach RefusesPartitionedParent, and runs the build with the statement itself. From version 18 those steps run as they are, so it is false there. A statement the build's own admission refuses, such as an unnamed foreign key or one that references an unqualified table, still routes, so it is refused with the build's reason. A submitted NOT VALID foreign key, and a statement with any other subcommand beside the foreign key, are false and meet RefusesPartitionedParent as before. A statement that does not parse is an error, as it is for RefusesPartitionedParent.
func RoutesToPartitionedIndexBuild ¶ added in v0.5.5
RoutesToPartitionedIndexBuild reports whether the steps planned for one statement are the one CREATE INDEX that the partition-aware index build carries when the statement's target is a partitioned table: a CREATE INDEX in any form, with or without CONCURRENTLY or ONLY. A front door asks it after it knows the target is partitioned, and runs the build with the statement itself, not with the steps, which are a plain table's substitute (a concurrent build) and would fail on a partitioned one. Any other step list is false. A step that does not parse is an error, as it is for RefusesPartitionedParent.
func RoutesToPartitionedKeyBuild ¶ added in v0.5.7
RoutesToPartitionedKeyBuild reports whether a statement whose target is a partitioned table is the one ADD PRIMARY KEY or ADD UNIQUE that the partitioned key build carries: an ALTER TABLE whose only subcommand adds a primary key or unique constraint over columns, not USING INDEX. A front door asks it of the submitted statement, after it knows the target is partitioned and before the steps the planner made for a plain table (a concurrent unique build and an ADD CONSTRAINT ... USING INDEX, which PostgreSQL refuses on a partitioned table) reach RefusesPartitionedParent, and runs the build with the statement itself. A statement the build's own admission refuses, such as an unnamed constraint or one with INCLUDE, still routes, so it is refused with the build's reason. ADD CONSTRAINT ... USING INDEX is false and stays the index-adoption refusal, as is a statement with any other subcommand beside the key. A statement that does not parse is an error, as it is for RefusesPartitionedParent.
func SchemaConstraintNames ¶ added in v0.4.0
func SchemaConstraintNames(ctx context.Context, pool *pgxpool.Pool, schema string) (map[string]bool, error)
SchemaConstraintNames reads the name of every constraint in schema, each table's and each domain's: the names PostgreSQL passes over when it names an unnamed constraint added to a table there, since it looks for a name no constraint in the schema holds.
func SessionTimeZone ¶ added in v0.5.8
SessionTimeZone returns the TimeZone setting a session on pool runs with: the zone ALTER COLUMN TYPE reads each value in when it converts a timestamp column to timestamptz, or a timestamptz column to timestamp.
func TableHasRows ¶ added in v0.5.0
TableHasRows reports whether schema.table, or any partition or inheritance child below it, holds a row the session can see. Adding a NOT NULL column with no default fills every existing row with NULL, so PostgreSQL refuses it exactly when this is true. Only the tables with storage of their own are read, each with ONLY: PostgreSQL checks the new column on those alone, so a foreign table's rows neither count nor get fetched from the remote server.
The read runs in a read-only transaction that never waits for a lock: a lock_timeout of one millisecond, as for the add-column proof, keeps it from queueing behind another session's ACCESS EXCLUSIVE lock, and a read the lock blocks returns ErrTableRowsLocked. It stops at the first row it finds, under a statement_timeout of its own. Rows a row-level security policy hides from the session's role do not count, so for such a role the server's own refusal at execution remains the backstop.
func UTCTimeZone ¶ added in v0.5.8
UTCTimeZone reports whether zone is one of the names PostgreSQL resolves to UTC with no offset and no daylight saving time. The set is deliberately narrow: a zone that is not on it is treated as one that moves the stored values. The planner and the executor both decide with it, so a change planned to relabel is never refused at execution for a zone the planner accepted.
func ValidatedNotNullColumns ¶ added in v0.5.8
func ValidatedNotNullColumns(ctx context.Context, pool *pgxpool.Pool, schema, table string) (map[string]bool, error)
ValidatedNotNullColumns names the columns of schema.table that a validated CHECK (column IS NOT NULL) covers on the table and on every partition and inheritance child below it. PostgreSQL 12 and later take such a constraint as proof that no row holds NULL, so ALTER COLUMN ... SET NOT NULL on one of these columns reads no row. A constraint that is NOT VALID, or missing from one table of the tree, proves nothing.
Types ¶
type AbsentTarget ¶ added in v0.2.0
type AbsentTarget struct {
// contains filtered or unexported fields
}
AbsentTarget proves the target name is free: the schema exists and no relation or standalone type occupies schema.table. It can only be constructed by CheckTableAbsent in this package. The schema it carries is always resolved — an unqualified check records the session's creation schema, so the proof names the exact schema a create would land in.
The proof is time-of-check and session-scoped: mint it inside the apply, in the same session that will run the CREATE TABLE, and never serialize it or carry it across a plan/apply boundary — an absence verified at plan time proves nothing about apply time. The create path must also re-verify it at the point of use, the way ST-7 does for PreflightedTable: reject a proof whose Table() is empty (the zero value is forgeable by any package), and require the CREATE TABLE statement's schema and table to equal the proof's before executing.
func CheckTableAbsent ¶ added in v0.2.0
func CheckTableAbsent(ctx context.Context, pool *pgxpool.Pool, schema, table string) (AbsentTarget, error)
CheckTableAbsent verifies that schema.table names no existing relation or standalone type, so a CREATE TABLE at that name has nothing to collide with. When schema is empty the session's creation schema (current_schema()) is resolved first — the schema an unqualified CREATE TABLE would land in — and the proof carries it. The facts come from one catalog snapshot read directly from pg_class and pg_type, which are visible regardless of privileges, so a missing grant can never masquerade as absence; whether the role may create in the schema is a separate privilege check, not this fact check. The proof is time-of-check: nothing locks the name, so a concurrent create can still take it before the CREATE TABLE runs — the create path must still treat a duplicate-name error as a collision; the proof turns the common case into a clean refusal, not a guarantee.
This check is NOT the complement of CheckTable for an unqualified name: CheckTable resolves across the whole search_path (to_regclass), while this check resolves current_schema() only — the one schema an unqualified CREATE TABLE lands in. A table in a later search_path schema makes both checks succeed for the same arguments: CheckTable finds it, and this check correctly reports the creation schema free. A caller deciding between create and alter on that pairing would create a new table that shadows the one the user meant — so such a caller must pass an explicit schema, where the two checks share one namespace and are true inverses.
func (AbsentTarget) Schema ¶ added in v0.2.0
func (a AbsentTarget) Schema() string
Schema returns the resolved schema the absence was verified in. A proof minted by CheckTableAbsent always carries one: an unqualified check resolves the session's creation schema before verifying.
func (AbsentTarget) Table ¶ added in v0.2.0
func (a AbsentTarget) Table() string
Table returns the verified-absent table name.
type AbsentType ¶ added in v0.5.8
type AbsentType struct {
// contains filtered or unexported fields
}
AbsentType proves a type name is free in a schema: the schema exists and no type, standalone or a table's row type, holds schema.name, so a CREATE TYPE at that name has nothing to collide with. It can only be constructed by CheckTypeAbsent in this package.
Like AbsentTarget it is time-of-check and session-scoped: mint it inside the apply, on the session that will run the CREATE TYPE, and never carry it across a plan/apply boundary. The create path re-verifies it at the point of use: a proof whose Name() is empty is the forgeable zero value.
func CheckTypeAbsent ¶ added in v0.5.8
func CheckTypeAbsent(ctx context.Context, pool rowQuerier, schema, name string) (AbsentType, error)
CheckTypeAbsent verifies that no type occupies schema.name. A table's row type counts, since a CREATE TYPE collides with it exactly as with a standalone type: an occupying relation is ErrRelationExists and a standalone type ErrTypeExists. An autogenerated array type does not count, since CREATE TYPE renames it out of the way. A schema that does not exist is ErrSchemaNotFound. The schema must be named: an unqualified type lands in whichever schema the session's search_path puts first, and the proof must name the exact one.
The facts come from one catalog snapshot of pg_type, which is visible regardless of privileges; whether the role may create in the schema is CheckCreatePrivileges's question. Nothing locks the name, so the create path still treats the server's duplicate_object as a collision.
func (AbsentType) Name ¶ added in v0.5.8
func (a AbsentType) Name() string
Name returns the verified-absent type name.
func (AbsentType) Schema ¶ added in v0.5.8
func (a AbsentType) Schema() string
Schema returns the schema the absence was verified in.
type ColumnDependents ¶ added in v0.5.0
type ColumnDependents struct {
// Views are the views and materialized views that read the column,
// each rendered "schema"."view".
Views DependentObjects
// MaterializedViews names the materialized views among Views and
// ViewReaders, rendered the same way, sorted, each once. Recreating
// one runs its query to fill it again, so the manual path names it
// apart from a plain view.
MaterializedViews []string
// ViewReaders maps each view in Views to the views and materialized
// views that read it, directly or through other views, rendered the
// same way, each to its longest chain of views from the view: 1 for a
// view that reads it itself. PostgreSQL refuses to drop a view another
// view reads, so the readers have to go first, and dropping the deeper
// ones before the shallower never drops a view another still reads.
ViewReaders map[string]map[string]int
// Policies are the row-level security policies whose USING or WITH
// CHECK expression reads the column, each rendered
// "policy" ON "schema"."table", the form DROP POLICY takes. A policy
// counts wherever it is defined: one on another table that reads the
// column through a subquery blocks the change too.
Policies DependentObjects
// Triggers are the triggers whose UPDATE OF list or WHEN condition
// names the column, each rendered "trigger" ON "schema"."table", the
// form DROP TRIGGER takes. A trigger whose function reads the column
// records no dependency on it and does not block the change; it is
// named in TriggerReads instead.
Triggers DependentObjects
// Rules are the rewrite rules whose condition or actions read the
// column, each rendered "rule" ON "schema"."table", the form DROP RULE
// takes. A rule counts wherever it is defined: one on another table, or
// one a view carries beside its query, blocks the change too. A view's
// own query is its _RETURN rule, which Views names as the view instead.
Rules DependentObjects
// TriggerReads are 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). 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.
TriggerReads DependentObjects
// UncheckedTriggers are the triggers whose function may read the
// column without the read being visible: 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>), and every
// column of the trigger's table names it.
UncheckedTriggers DependentObjects
// Publications are the publications whose column list or row filter
// for the table names the column, each rendered "publication", the
// form ALTER PUBLICATION takes. A publication that publishes the
// table without a column list or row filter records no dependency on
// the column and does not block the change.
Publications DependentObjects
// GeneratedColumns are the generated columns whose expression reads
// the column, each rendered "schema"."table"."column".
GeneratedColumns DependentObjects
// PartitionKeys are the partitioned tables whose partition key, as a
// column or inside an expression, includes the column, each rendered
// "schema"."table". A key on a partition that is itself partitioned
// counts on the tables a change reaches.
PartitionKeys DependentObjects
// GeneratedColumnCopies maps each generated column of the table to
// its own copies, rendered as GeneratedColumns renders them, so a
// drop of the generated column can be matched against the generated
// columns that read another column.
GeneratedColumnCopies DependentObjects
}
ColumnDependents names, per column, the objects whose definitions read it and that PostgreSQL will not let a type change or a drop of the column outlive: views, row-level security policies, triggers, rules, publications, generated columns, and partition keys.
func ReadColumnDependents ¶ added in v0.5.0
func ReadColumnDependents(ctx context.Context, pool *pgxpool.Pool, schema, table string) (ColumnDependents, error)
ReadColumnDependents reads which views, materialized views, policies, triggers, rules, publications, generated columns, and partition keys read each column of schema.table, and the same-named column of every table below it. A column only a table below has is left out: no change to the table reaches it.
PostgreSQL refuses to change the type of a column any of them reads, even a relabel that rewrites nothing. It refuses to drop one without CASCADE, and refuses to drop a partition key column at all. A recursive type change reaches the column on every table below, so a dependent on any of them blocks it. A recursive drop reaches less: a child loses its copy only when it does not declare the column itself and every parent it inherits the column from loses its copy in the same drop. A child that declared the column, merged it on INHERIT, or also inherits it from a parent outside the drop keeps its copy and its dependents, while one that inherits it along two paths from the dropped table loses it. Partitions never declare a column of their own, so a drop reaches every partition. The dependency is the one pg_depend records to the column: from the view's rewrite rule, the policy, the trigger, the rule, the publication's entry for the table, or the generated column (from its expression on PostgreSQL 15 and later, from the generated column itself before that), and from the column to its own table for a partition key column. A trigger a partition clones from a parent's trigger in the tree is named once, as the parent's: PostgreSQL drops the clones with it and refuses to drop one alone. A view that reads the table without naming the column does not appear. The read is a planning fact: the server's own refusal at execution stays the backstop for a dependent created after it.
type ColumnNumbers ¶ added in v0.5.8
type ColumnNumbers struct {
// Left is MaxColumnNumber less the highest column number the table, or a
// table that inherits from it, has ever used: zero once the fullest of
// them is at the limit.
Left int `json:"numbers_left"`
// Fullest are the tables that have used that highest number, the table
// itself first when it is one of them, then the rest by name. Rebuilding
// them is what gives numbers back.
Fullest []FullTable `json:"full_tables"`
}
ColumnNumbers is how many more columns PostgreSQL lets an ADD COLUMN give a table, and which tables decide it.
func ReadColumnNumbers ¶ added in v0.5.8
func ReadColumnNumbers(ctx context.Context, pool *pgxpool.Pool, schema, table string) (ColumnNumbers, error)
ReadColumnNumbers reads how many more columns PostgreSQL lets an ADD COLUMN give schema.table, and which of it and the tables that inherit from it have used the most numbers.
type CopySwapEnvironment ¶ added in v0.4.0
type CopySwapEnvironment struct {
// LogicalDecoding is whether the run captures changes through a
// replication slot. When true the server must have wal_level =
// logical, a free replication slot, and a free WAL sender for each of
// the route's two replication connections; a quiesced run has no such
// need.
LogicalDecoding bool
// FreeDiskBytes is the free space on the volume the database writes
// to, as the caller measured it — PostgreSQL has no function that
// reports it. A value that is not positive is refused as unmeasured
// rather than treated as unlimited.
FreeDiskBytes int64
// SlotLagCeilingBytes is the WAL, in bytes, a run that decodes WAL lets
// its slot retain before it stops: the ceiling the caller's catch-up
// will enforce. Zero is DefaultSlotLagCeiling, the catch-up's own
// default, and a negative value is refused. A run that decodes WAL needs
// the ceiling free on the volume beside the shadow copy, so it is added
// to the disk requirement; a quiesced run holds no slot, and the value
// is ignored.
SlotLagCeilingBytes int64
// Held is what a stopped run that this run resumes already holds on
// the volume, which the free space the caller measured already
// excludes; the disk check requires only what is left to grow. The
// zero value is a fresh run and discounts nothing.
Held CopySwapHeld
}
CopySwapEnvironment states what the run needs from the cluster and what the caller knows about it that the server cannot report.
type CopySwapEnvironmentAdvisory ¶ added in v0.5.8
type CopySwapEnvironmentAdvisory struct {
// Cause is the environment cause CheckCopySwapEnvironment raises for the
// same fact.
Cause CopySwapRefusalCause
// Setting is the server setting the fact is about, or the zero value
// when none is (a slot collision).
Setting CopySwapSetting
// Detail is the measurement behind the cause, worded as the
// environment refusal words it.
Detail string
// NextStep is the change to the server that clears it. It does not
// say why the full environment check has not run, nor how to run the
// change offline instead, which decodes no WAL; the caller knows the
// shape was refused and which door it is on, and adds both.
NextStep string
}
CopySwapEnvironmentAdvisory is one environment cause a copy-and-swap run would meet, found by PreviewCopySwapEnvironment for a table whose shape the route refuses. It is a preview, not a verdict: it admits nothing and refuses nothing, and the proof-gated CheckCopySwapEnvironment decides the environment once the shape passes.
func PreviewCopySwapEnvironment ¶ added in v0.5.8
func PreviewCopySwapEnvironment(ctx context.Context, pool *pgxpool.Pool, schema, table string, logicalDecoding bool) ([]CopySwapEnvironmentAdvisory, error)
PreviewCopySwapEnvironment reads, without the shape proof, the cluster facts a copy-and-swap run of schema.table needs when it decodes WAL, and returns every one that falls short, in the order CheckCopySwapEnvironment decides them: logical decoding (wal_level), a slot of the target's derived name held by another database or as a physical slot, a free replication slot, and free WAL senders. A run that does not decode WAL (logicalDecoding false, a run that blocks the table's writes) needs none of them, so the preview reads nothing and returns none.
It is for a caller whose run the shape check refused, so one refusal can also name the server settings to change, a restart-only wal_level above all. It mints no proof and is never a gate. It previews only the checks that read settings and the replication views: the disk check is left out, since it reads the table's size, which locks the relation, and a resume's measure of what a stopped run holds, which locks the shadow; and it is decided on the proven relation. The reads take no lock on any relation and write nothing. The slot name is derived from the pool's database and the schema and table as given, as the shape proof derives it. The pool should come from dbconn.NewPool, which bounds every session's timeouts.
type CopySwapEnvironmentError ¶ added in v0.4.0
type CopySwapEnvironmentError struct {
// Cause is the environment fact that triggered the refusal.
Cause CopySwapRefusalCause
// Setting is the server setting the operator must change, or the zero
// value when no setting is involved (the volume is simply too full).
Setting CopySwapSetting
// Detail is the measurement behind the cause.
Detail string
// The disk figures a measured disk-headroom refusal was decided on, and
// zero for every other refusal: the free space the caller passed, the
// space required for the shadow copy (copySwapDiskHeadroomFactor times
// the table, more than the shadow itself takes), and, for a run that
// decodes WAL, the effective slot lag ceiling counted beside it. The
// ceiling is zero only for a quiesced run.
FreeDiskBytes int64
RequiredShadowBytes int64
SlotLagCeilingBytes int64
// The part of each requirement a resumed run already holds, discounted
// from it (CopySwapEnvironment.Held): the shadow built so far, at most
// RequiredShadowBytes, and the WAL the stopped run's slot retains, at
// most SlotLagCeilingBytes and zero for a quiesced run. Both are zero
// for a fresh run. The space the run was refused for is
// RequiredShadowBytes − HeldShadowBytes + SlotLagCeilingBytes −
// HeldWALBytes.
HeldShadowBytes int64
HeldWALBytes int64
}
CopySwapEnvironmentError reports that the cluster or the volume cannot carry a copy-and-swap of the proven target. Setting names the server setting that admits the run once changed; Detail names the measured fact that decided it.
func (*CopySwapEnvironmentError) Error ¶ added in v0.4.0
func (e *CopySwapEnvironmentError) Error() string
Error implements the error interface.
type CopySwapHeld ¶ added in v0.5.5
type CopySwapHeld struct {
// ShadowBytes is the shadow table's total size (heap, indexes, TOAST)
// as the server reports it.
ShadowBytes int64
// RetainedWALBytes is the WAL the stopped run's slot retains, from its
// restart position to the server's write position. It is counted only
// for a run that decodes WAL; a quiesced run holds no slot.
RetainedWALBytes int64
// SwapCommitted reports that the catalog shows the stopped run's swap
// committed: the shadow already bears the table's name, so the run
// being checked only finishes it — drops the slot, drops the retained
// source or (under KeepOld) takes the write fence off it, and records
// the change done. That run builds no shadow and decodes no WAL, so
// the disk check removes the whole requirement: neither the copy's
// headroom nor the slot lag ceiling is asked. Only MeasureResumeHeld
// in package schemachange should set it. The target it admits reports
// FinishesCommittedSwap, and a run on it that would do anything but
// finish that swap is refused before it writes.
SwapCommitted bool
}
CopySwapHeld is the space a stopped copy-and-swap run already occupies on the volume when the run being checked resumes it: the shadow it built so far and the WAL its replication slot retains, or that its swap has already committed. Every field must be read from the server, never from a checkpoint row, and a figure that could not be read is zero, so the check discounts no more than the volume truly holds. A negative figure is refused.
type CopySwapRefusalCause ¶ added in v0.4.0
type CopySwapRefusalCause string
CopySwapRefusalCause identifies which table shape put a target outside the copy-and-swap route's v1 scope. The zero value means the shape is supported.
const ( // is not logical, so no replication slot can decode the table's // changes; on Aurora/RDS the setting behind it is // rds.logical_replication, a static parameter that needs a reboot. CopySwapCauseLogicalDecodingUnavailable CopySwapRefusalCause = "copy-and-swap-logical-decoding-unavailable" // CopySwapCauseSlotCollision means a replication slot already carries // the name derived for this target and belongs to another database or // is a physical slot: slot names are cluster-wide, so the route can // neither share nor drop it. CopySwapCauseSlotCollision CopySwapRefusalCause = "copy-and-swap-slot-collision" // CopySwapCauseSlotHeadroom means the cluster has no free replication // slot, or fewer free WAL senders than copySwapWALSenders. CopySwapCauseSlotHeadroom CopySwapRefusalCause = "copy-and-swap-slot-headroom" // CopySwapCauseDiskHeadroom means the volume's free space is below the // headroom the shadow copy needs, or was not measured at all. CopySwapCauseDiskHeadroom CopySwapRefusalCause = "copy-and-swap-disk-headroom" )
const ( // CopySwapCausePKUnsupported means the table has no primary key, a // multi-column one, one whose type is outside the integer family the // chunker keys on, or a DEFERRABLE one. A deferrable key is checked at // the end of each statement rather than per row, so one statement can // move a row onto a key another row still holds and the decoded stream // no longer has one row per key, which the applier's buffer relies on; // the server also declines to use it as the DEFAULT replica identity, // so every UPDATE on a published table would fail. CopySwapCausePKUnsupported CopySwapRefusalCause = "copy-and-swap-pk-unsupported" // CopySwapCauseReplicaIdentity means the table's replica identity is // NOTHING, so decoded UPDATE and DELETE events would not carry the key // the applier needs. CopySwapCauseReplicaIdentity CopySwapRefusalCause = "copy-and-swap-replica-identity" // CopySwapCauseReplicaIdentityIndex means the table's replica identity // is a named index, so decoded UPDATE and DELETE events carry that // index's columns rather than the primary key the applier keys on. // Other logical decoding consumers of the table may rely on those // columns, so switching the identity is not a step the refusal can // take for granted. CopySwapCauseReplicaIdentityIndex CopySwapRefusalCause = "copy-and-swap-replica-identity-index" // CopySwapCauseForeignKeys means a foreign key references the table or // leaves it; either is bound to the table's OID and would follow the // retained old table through a rename swap. CopySwapCauseForeignKeys CopySwapRefusalCause = "copy-and-swap-foreign-keys" // CopySwapCauseTriggers means the table carries a user trigger or a // rewrite rule, both OID-bound dependents a rename swap strands. CopySwapCauseTriggers CopySwapRefusalCause = "copy-and-swap-triggers" // CopySwapCausePartitioned means the table is a partitioned parent, a // partition, or part of an inheritance tree. CopySwapCausePartitioned CopySwapRefusalCause = "copy-and-swap-partitioned" // CopySwapCauseUnlogged means the table is UNLOGGED, while the shadow // created by LIKE would be permanent. CopySwapCauseUnlogged CopySwapRefusalCause = "copy-and-swap-unlogged" // CopySwapCauseForceRLS means the table has FORCE ROW LEVEL SECURITY: // the copier runs as the owner, whose reads of the source would be // filtered and whose writes into the shadow would be rejected by the // replicated policies, and the shadow must carry those policies before // it holds a row. CopySwapCauseForceRLS CopySwapRefusalCause = "copy-and-swap-force-rls" // CopySwapCauseDependentViews means a view or materialized view // selects from the table; its rewrite rule is bound to the table's OID // and would keep reading the retained old table after the swap. CopySwapCauseDependentViews CopySwapRefusalCause = "copy-and-swap-dependent-views" // CopySwapCausePublicationMember means a publication other than the // engine's own publishes the table. Explicit membership is bound to the // table's OID, so subscribers would keep following the old table; a // FOR ALL TABLES or FOR TABLES IN SCHEMA publication publishes every // new table in its scope, the shadow included, so its subscribers would // receive the copy's writes to a relation they do not have. CopySwapCausePublicationMember CopySwapRefusalCause = "copy-and-swap-publication-member" // CopySwapCauseSubscriptionTarget means a subscription on this database // applies changes into the table; the subscription binds it by OID, so // after the swap the apply worker would find no state for the new // relation and skip its changes without an error. CopySwapCauseSubscriptionTarget CopySwapRefusalCause = "copy-and-swap-subscription-target" // CopySwapCauseDependents means an object the causes above do not name // depends on the table's OID or its row type — a rule on another table // that writes into it, a SQL-standard function body that reads it, a // policy on another table whose expression consults it, a column of its // row type — and the swap carries none of them to the new table. CopySwapCauseDependents CopySwapRefusalCause = "copy-and-swap-dependents" )
func CopySwapRefusalCauseOf ¶ added in v0.4.0
func CopySwapRefusalCauseOf(err error) CopySwapRefusalCause
CopySwapRefusalCauseOf returns the cause carried by a copy-and-swap shape or environment refusal anywhere in err's chain, or the zero cause when err is neither.
func CopySwapRefusalCauses ¶ added in v0.4.0
func CopySwapRefusalCauses() []CopySwapRefusalCause
CopySwapRefusalCauses returns the closed set of copy-and-swap refusal causes — the shape causes above and the environment causes in copy_swap_environment.go — so documentation and consumers can enumerate them instead of maintaining their own list.
func (CopySwapRefusalCause) Class ¶ added in v0.4.0
func (c CopySwapRefusalCause) Class() refusal.Class
Class is the routing class of the cause, from docs/refusal-classes.md: what kind of boundary the consumer is looking at. A replica identity of NOTHING, which the operator can set to DEFAULT, and every cluster and volume cause — a server setting, a foreign slot, exhausted slot or sender headroom, a short or unmeasured volume — are environmental: the same table is admitted once state outside the engine changes, and no engine release is waited on. Every other shape cause is a capability boundary: a wider key family, an index replica identity other decoders may rely on, an OID-bound dependent re-pointed at cutover, a persistence or row-security path the engine has not built. The class is a triage decision; the cause's row in the document decides what the consumer does next. The zero cause, and an unknown one, have no class.
type CopySwapSetting ¶ added in v0.4.0
type CopySwapSetting string
CopySwapSetting is a server setting an environment refusal asks the operator to change. It is the machine-readable half of a refusal's Detail: an adapter can branch on it where prose would not do.
const ( // CopySwapSettingWALLevel is wal_level itself, which a self-managed // server changes directly. It is also what the refusal names on a // managed service other than RDS; where such a service drives // wal_level from a switch of its own, the operator sets that switch. CopySwapSettingWALLevel CopySwapSetting = "wal_level" // CopySwapSettingRDSLogicalReplication is the parameter-group switch // that drives wal_level on Aurora and RDS, where wal_level cannot be // set directly. Both are static and take effect after a restart. CopySwapSettingRDSLogicalReplication CopySwapSetting = "rds.logical_replication" // CopySwapSettingMaxReplicationSlots is the cluster-wide slot limit. CopySwapSettingMaxReplicationSlots CopySwapSetting = "max_replication_slots" // CopySwapSettingMaxWALSenders is the cluster-wide WAL sender limit. CopySwapSettingMaxWALSenders CopySwapSetting = "max_wal_senders" )
type CopySwapShape ¶ added in v0.4.0
type CopySwapShape struct {
// contains filtered or unexported fields
}
CopySwapShape proves that a table has the shape the copy-and-swap route supports and that the connected role holds the copy-and-swap tier against it. It is minted only by CheckCopySwapShape and is the sole admission to CheckCopySwapEnvironment, which mints the CopySwapTarget every writing step requires: the three checks cannot be reordered or skipped by type. The role proof's replication bit lives here, not on the shared facts, so the target answers "may this run decode WAL" through DecodesWAL alone.
func CheckCopySwapShape ¶ added in v0.4.0
func CheckCopySwapShape(ctx context.Context, pool *pgxpool.Pool, schema, table string, role PrivilegedRole) (CopySwapShape, error)
CheckCopySwapShape verifies that schema.table (search_path resolution when schema is empty) has the shape the copy-and-swap route supports in v1: an ordinary table outside any partition or inheritance tree, exactly one non-deferrable smallint, integer, or bigint primary-key column, a replica identity of DEFAULT or FULL, no FORCE ROW LEVEL SECURITY, no foreign keys, triggers, or rules, no dependent views, no publication other than the engine's own publishing it, no subscription applying into it, and no other object depending on its OID or row type. The role proof must have been verified at TierCopyAndSwap; the owner it carries is the role the shadow builder creates shadow objects as. On success it returns the CopySwapShape proof carrying the catalog-resolved database and schema, which only CheckCopySwapEnvironment accepts: the facts the server cannot settle from the table alone — logical decoding, slot and disk headroom — are that check's, and the CopySwapTarget every writing step requires is minted there. CheckCopySwap runs the whole sequence. The catalog reads are pg_catalog-qualified, so the result does not depend on the pool's search_path; the pool should still come from dbconn.NewPool, which bounds every session's timeouts.
func (CopySwapShape) Database ¶ added in v0.4.0
func (s CopySwapShape) Database() string
Database returns the catalog-resolved database the target lives in.
func (CopySwapShape) DecodingName ¶ added in v0.4.0
func (s CopySwapShape) DecodingName() string
DecodingName returns the name of the replication slot and publication the route creates for this target, derived from its database, schema, and table (see CopySwapDecodingName).
func (CopySwapShape) LogicalDecoding ¶ added in v0.4.0
func (s CopySwapShape) LogicalDecoding() bool
LogicalDecoding reports whether the privilege proof this shape was minted from verified replication access, so a run that decodes WAL can be refused as a proof mismatch when it was not.
func (CopySwapShape) OID ¶ added in v0.4.0
func (s CopySwapShape) OID() uint32
OID returns the catalog OID of the target table at the time the shape was proven. A table dropped and recreated under its name is another table with another OID, which is how a consumer that is handed the table by name — the stream's relation messages — tells it from the one proven here.
func (CopySwapShape) OwnerRole ¶ added in v0.4.0
func (s CopySwapShape) OwnerRole() string
OwnerRole returns the catalog-resolved owner of the target table: the role the shadow builder runs SET LOCAL ROLE to so that the shadow table and its dependents are created owner-correct, and whose SET-usable membership the Tier 3 privilege check proved for the connected role.
func (CopySwapShape) PKColumn ¶ added in v0.4.0
func (s CopySwapShape) PKColumn() string
PKColumn returns the primary-key column.
func (CopySwapShape) PKType ¶ added in v0.4.0
func (s CopySwapShape) PKType() PKType
PKType returns the primary-key type.
type CopySwapShapeCause ¶ added in v0.5.8
type CopySwapShapeCause struct {
// Cause is the shape cause.
Cause CopySwapRefusalCause
// Detail is the catalog fact behind the cause.
Detail string
// NextStep is what the operator does about it.
NextStep string
}
CopySwapShapeCause is one shape fact that puts a table outside the copy-and-swap route's v1 scope: the cause, the catalog fact behind it with the objects it names, and the one next step for the operator. A next step never asks the operator to drop or disable a trigger, foreign key, publication, policy, or view for the run, since the application would lose what it does while the copy runs.
type CopySwapTarget ¶ added in v0.3.2
type CopySwapTarget struct {
// contains filtered or unexported fields
}
CopySwapTarget proves ST-6 prerequisites for a copy-and-swap target: the shape a CopySwapShape proves and, on top of it, that the cluster and the volume were verified for the run's mode. It is minted only by CheckCopySwapEnvironment (or CheckCopySwap, which folds the three checks). Its zero value is forgeable; consumers must reject it when Table is empty.
func CheckCopySwap ¶ added in v0.4.0
func CheckCopySwap(ctx context.Context, pool *pgxpool.Pool, schema, table string, env CopySwapEnvironment) (CopySwapTarget, error)
CheckCopySwap runs the copy-and-swap route's admission checks in order — CheckPrivileges at TierCopyAndSwap (with replication access when the run decodes WAL), CheckCopySwapShape, CheckCopySwapStatisticsAccess, CheckCopySwapEnvironment — and returns the CopySwapTarget the last one mints. It is the one call a caller needs before the first write; the checks stay exported for callers that report each refusal class separately, which call them in the same order.
func CheckCopySwapEnvironment ¶ added in v0.4.0
func CheckCopySwapEnvironment(ctx context.Context, pool *pgxpool.Pool, shape CopySwapShape, env CopySwapEnvironment) (CopySwapTarget, error)
CheckCopySwapEnvironment verifies that the table's owner, whom every writing step runs as, holds USAGE and CREATE on the table's schema — a *PrivilegeError naming the owner when it does not — and that the cluster and the volume can carry a copy-and-swap of the proven shape: when the run decodes WAL, logical decoding is enabled, no other database holds the slot name the route derives for the target, and a slot and the WAL senders for the route's two replication connections are free; in every run the caller-measured free disk covers the shadow copy, and in a run that decodes WAL it covers the slot lag ceiling beside it. A run that decodes WAL must present a shape whose privilege proof verified replication access, or it is a proof mismatch, as is a pool on any database other than the one the shape was proven in. On success it mints the CopySwapTarget — the only way one is minted — recording the run mode it was verified for; a refusal of the cluster or the volume is a *CopySwapEnvironmentError. The owner's access is decided first: no setting the operator changes lets the owner build the shadow. The reads are pg_catalog-qualified, so the result does not depend on the pool's search_path; the pool should still come from dbconn.NewPool, which bounds every session's timeouts.
func (CopySwapTarget) Database ¶ added in v0.4.0
func (s CopySwapTarget) Database() string
Database returns the catalog-resolved database the target lives in.
func (CopySwapTarget) DecodesWAL ¶ added in v0.4.0
func (t CopySwapTarget) DecodesWAL() bool
DecodesWAL reports whether the environment was verified for a run that captures changes through a replication slot. A quiesced run's target reports false: no slot was proven available, so none may be created.
func (CopySwapTarget) DecodingName ¶ added in v0.4.0
func (s CopySwapTarget) DecodingName() string
DecodingName returns the name of the replication slot and publication the route creates for this target, derived from its database, schema, and table (see CopySwapDecodingName).
func (CopySwapTarget) FinishesCommittedSwap ¶ added in v0.5.5
func (t CopySwapTarget) FinishesCommittedSwap() bool
FinishesCommittedSwap reports that the disk check admitted the target only to finish a stopped run whose swap committed (CopySwapHeld.SwapCommitted), asking it for no space. A run on such a target may only finish that swap: one that would build a shadow or resume a copy was never measured, so it must check the environment again.
func (CopySwapTarget) OID ¶ added in v0.4.0
func (s CopySwapTarget) OID() uint32
OID returns the catalog OID of the target table at the time the shape was proven. A table dropped and recreated under its name is another table with another OID, which is how a consumer that is handed the table by name — the stream's relation messages — tells it from the one proven here.
func (CopySwapTarget) OwnerRole ¶ added in v0.3.2
func (s CopySwapTarget) OwnerRole() string
OwnerRole returns the catalog-resolved owner of the target table: the role the shadow builder runs SET LOCAL ROLE to so that the shadow table and its dependents are created owner-correct, and whose SET-usable membership the Tier 3 privilege check proved for the connected role.
func (CopySwapTarget) PKColumn ¶ added in v0.3.2
func (s CopySwapTarget) PKColumn() string
PKColumn returns the primary-key column.
func (CopySwapTarget) PKType ¶ added in v0.3.2
func (s CopySwapTarget) PKType() PKType
PKType returns the primary-key type.
type CreationRole ¶ added in v0.2.0
type CreationRole struct {
// contains filtered or unexported fields
}
CreationRole proves the connected role holds every access a greenfield CREATE TABLE in the schema needs: CONNECT on the database, USAGE and CREATE on the schema for the role the table will be owned by, and — when a create owner other than the connected role is named — membership that lets the session SET ROLE to it. It can only be constructed by CheckCreatePrivileges or CheckCreatePrivilegesAs in this package. The schema it carries is always resolved — an unqualified check records the session's creation schema.
Like AbsentTarget, the proof is time-of-check and session-scoped: a grant can be revoked between the check and the CREATE TABLE, in which case the create fails with the server's own insufficient-privilege error rather than a typed refusal.
func CheckCreatePrivileges ¶ added in v0.2.0
func CheckCreatePrivileges(ctx context.Context, pool *pgxpool.Pool, schema string) (CreationRole, error)
CheckCreatePrivileges verifies the connected role can create a table in the schema (the session's creation schema, current_schema(), when schema is empty): CONNECT on the database, USAGE and CREATE on the schema. A missing grant is a *PrivilegeError naming the exact statement that would satisfy it — the grantee is the connected role itself, because a table that does not exist yet has no owning role to inherit from. On success it returns the CreationRole proof.
func CheckCreatePrivilegesAs ¶ added in v0.3.3
func CheckCreatePrivilegesAs(ctx context.Context, pool *pgxpool.Pool, schema, owner string) (CreationRole, error)
CheckCreatePrivilegesAs verifies creation access for owner. When owner is empty, creation remains under the connected role. Otherwise the connected role must be able to SET ROLE to owner, and owner must hold schema access.
SET ROLE consults membership, not inheritance: pg_has_role(..., 'MEMBER') is the predicate on every supported version, and PostgreSQL 16 adds the SET membership option as a second, narrower gate. A non-inheriting member can assume the owner and is admitted; the USAGE mode — whether the owner's privileges are already available without SET ROLE — is not what the mechanism needs, and a refusal keyed on it could not be cleared by the GRANT it prints.
func (CreationRole) Owner ¶ added in v0.3.3
func (c CreationRole) Owner() string
Owner returns the role a created table will be owned by: the named create owner when one was checked, otherwise the connected role.
func (CreationRole) Role ¶ added in v0.2.0
func (c CreationRole) Role() string
Role returns the connected role the checks ran as — the identity whose CONNECT was proved and the grantee of any membership the create needs.
func (CreationRole) Schema ¶ added in v0.2.0
func (c CreationRole) Schema() string
Schema returns the resolved schema the access was verified in.
func (CreationRole) SchemaTableOwners ¶ added in v0.5.8
func (c CreationRole) SchemaTableOwners() []string
SchemaTableOwners returns the roles that own the schema's existing ordinary and partitioned tables, sorted and without duplicates, as of the check. A caller compares it with Owner to tell an operator that a created table will be owned by a role none of its neighbors use, which leaves it outside the grants the application's roles follow.
func (CreationRole) SetsRole ¶ added in v0.3.3
func (c CreationRole) SetsRole() bool
SetsRole reports whether create steps must SET LOCAL ROLE to Owner because it differs from the connected role.
type DependentObjects ¶ added in v0.5.0
type DependentObjects struct {
// Tree covers the table and every table below it, partitions and
// inheritance children alike: what a recursive ALTER COLUMN TYPE
// changes.
Tree map[string][]string
// Drop covers the table and the tables below it whose copy of the
// column a recursive DROP COLUMN drops: what that drop changes.
Drop map[string][]string
// Own covers the table alone: what an ALTER TABLE ONLY changes.
Own map[string][]string
}
DependentObjects names, per column, the dependent objects of one kind each reach of a change meets, every identifier quoted, sorted. A column no such object reads is absent from every map.
type EnumTarget ¶ added in v0.5.1
type EnumTarget struct {
// contains filtered or unexported fields
}
EnumTarget is the proof that the enum type a statement names resolved, on the session search_path, to an enum the connected role may alter. It carries the name it was resolved from and the type's OID, schema, and name. It is time-of-check: another session can rename the type after minting, so the executor confirms by identity, before its commit, that its statement reached the type with this OID (ST-7).
func CheckEnumTarget ¶ added in v0.5.1
func CheckEnumTarget(ctx context.Context, pool *pgxpool.Pool, ref statement.TypeName) (EnumTarget, error)
CheckEnumTarget resolves the type ref names and mints the proof that the connected role may alter it. An unqualified name resolves on the session search_path, exactly as the statement will when it runs on the same pool. A name that is not an enum type is ErrEnumTypeNotFound. ALTER TYPE needs membership in the type's owning role, the same rung a table's in-place ALTER TABLE needs, so a missing membership is the *PrivilegeError that rung reports, with a hint that transfers the type instead; a qualified name in a schema the role lacks USAGE on is the *PrivilegeError that carries the schema grant.
func (EnumTarget) OID ¶ added in v0.5.1
func (e EnumTarget) OID() uint32
OID returns the resolved type's OID; zero for a proof no check minted.
func (EnumTarget) Qualified ¶ added in v0.5.1
func (e EnumTarget) Qualified() string
Qualified returns the type's schema-qualified name for operator-facing text.
func (EnumTarget) Ref ¶ added in v0.5.1
func (e EnumTarget) Ref() statement.TypeName
Ref returns the type name, as the statement spelled it, that the proof was resolved from.
func (EnumTarget) Schema ¶ added in v0.5.1
func (e EnumTarget) Schema() string
Schema returns the schema the type lives in.
type ExpressionProof ¶ added in v0.5.8
type ExpressionProof struct {
// DefaultsRunNoUserCode maps each column a SET DEFAULT sets to whether
// the server proved the new default evaluates nothing a user defined:
// the column's type and everything the default refers to are built in,
// or an enum, and no built-in it calls reads a table. A column absent
// from the map is unproven too.
DefaultsRunNoUserCode map[string]bool
// ChecksRunNoUserCode maps the name of each CHECK the statement adds,
// as the statement spells it (empty for an unnamed one), to whether the
// server proved it refers to nothing a user defined. Where the
// statement adds several under one name, every one must be proven.
ChecksRunNoUserCode map[string]bool
}
ExpressionProof is what the server proved about the expressions an ALTER TABLE stores in the catalog without reading the table's rows: the defaults its SET DEFAULT subcommands set and the CHECK constraints it adds. PostgreSQL parses each such expression under the table's lock and coerces its literals to their types, and for a type a user defined that runs the type's input function, which can read any table. An expression that resolves to nothing a user defined runs only built-in code, once, whatever the table's size.
func ProveExpressions ¶ added in v0.5.8
func ProveExpressions(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string) (ExpressionProof, error)
ProveExpressions has the server prove, for each SET DEFAULT and ADD CONSTRAINT ... CHECK subcommand of the ALTER TABLE in sql against schema.table, whether the expression it stores evaluates anything a user defined.
Each subcommand runs alone (statement.ExpressionProbes) against a temporary table created LIKE schema.table, which copies the table's columns and their types and nothing else, inside a savepoint of a transaction that is always rolled back. The objects the stored expression depends on are then read from pg_depend, with the same rule as the add-column proof (runsUserCodeQuery): anything with an OID past the built-in catalog other than an enum type is user code. A default is judged with its column's type, since coercing to that type is what runs the input function.
Creating the probe table reads the live table's definition under ACCESS SHARE, which conflicts with nothing but an ACCESS EXCLUSIVE lock. The probe never waits for a lock: like the add-column proof it runs under a one-millisecond lock_timeout. A probe the server refuses for any reason (a lock it cannot take at once, a role without TEMPORARY, a read-only server, or an expression the server rejects) proves nothing, and the subcommand stays unproven; the real statement meets the same refusal when it runs. Only a failure of the probe's own transaction is returned as an error.
func (*ExpressionProof) Merge ¶ added in v0.5.8
func (p *ExpressionProof) Merge(other ExpressionProof)
Merge adds other's proofs to p, keeping a CHECK name proven only when both prove it.
type FullTable ¶ added in v0.5.8
type FullTable struct {
// Name is the table, schema-qualified with every identifier quoted.
Name string `json:"name"`
// Root is true for the table the ADD COLUMN names, and false for a
// partition or inheritance child it reaches.
Root bool `json:"altered_table"`
// Partition is true for a partition, which is rebuilt by detaching it
// and attaching a copy, rather than for an inheritance child.
Partition bool `json:"partition"`
}
FullTable is a table that has used the highest column number among a table and the tables that inherit from it.
type GoneTable ¶ added in v0.5.8
type GoneTable struct {
// contains filtered or unexported fields
}
GoneTable proves that no relation bears schema.table, for a discard of what a stopped copy-and-swap run on a table since dropped left behind: with the table gone there is no shape to prove, and the discard works from the table's names and its checkpoint row instead. It records the database the names were checked in, from which the run's slot and publication name derives (CopySwapDecodingName), and whether the connected role's replication access was verified, so a discard that would drop a slot can refuse a proof without it before dropping anything. It is minted only by CheckTableGone.
The proof is time-of-check: nothing stops a table of the name from being created after it is minted, so its consumer reads the name again under the table's lock before it drops anything.
func CheckTableGone ¶ added in v0.5.8
func CheckTableGone(ctx context.Context, pool *pgxpool.Pool, schema, table string, logicalDecoding bool) (GoneTable, error)
CheckTableGone verifies that no relation of any kind bears schema.table in the connected database, and, when logicalDecoding is set, that the connected role has replication access; a role without it is the *PrivilegeError naming the grant that gives it. Both the schema and the table must be named: a dropped table has no search_path resolution. A relation under the name is ErrRelationExists, whatever its kind: a table that exists is discarded under the shape proof instead (CheckCopySwapShape). A missing schema is no refusal, since a table in it is gone too. pg_class is visible regardless of privileges, so a missing grant cannot masquerade as absence.
func (GoneTable) Database ¶ added in v0.5.8
Database returns the catalog-resolved database the absence was checked in.
func (GoneTable) DecodingName ¶ added in v0.5.8
DecodingName returns the name of the replication slot and publication a live run on the table created, derived from the database, schema, and table names alone (see CopySwapDecodingName), so the table need not exist for it.
func (GoneTable) LogicalDecoding ¶ added in v0.5.8
LogicalDecoding reports whether CheckTableGone verified the connected role's replication access, which dropping a slot needs.
type IndexUsage ¶ added in v0.4.0
type IndexUsage struct {
// IdxScans is the cumulative count of scans of the index
// (pg_stat_all_indexes.idx_scan). For a partitioned index it is the sum
// over its leaf indexes, where the server records the scans; the
// partitioned index itself has no statistics.
IdxScans int64
// LastIdxScan is when the server last recorded a scan of the index, or
// of any of a partitioned index's leaf indexes; nil when it recorded
// none since its statistics began, and always on PostgreSQL 14 and 15,
// which do not record scan times.
LastIdxScan *time.Time
// StatsReset is when the database's statistics were last reset; nil
// when the server reports none. An index created later has counted only
// since its creation, which the server does not record.
StatsReset *time.Time
// ReadAt is the server's now() for the read.
ReadAt time.Time
// Unique reports whether the index enforces uniqueness.
Unique bool
// Partitioned reports whether the index is a partitioned index, whose
// scans are counted on its leaf indexes.
Partitioned bool
// Partitions is the number of leaf indexes of a partitioned index, at
// any depth; 0 for an index that is not partitioned.
Partitions int
// TrackCounts is the reading session's track_counts; with it off the
// server counts no scans at all.
TrackCounts bool
// TrackCountsOffBySetting reports that a saved ALTER ROLE or ALTER
// DATABASE setting turns track_counts off for some role or for this
// database, so the scans of those sessions are not counted even when
// the reading session's TrackCounts is on.
TrackCountsOffBySetting bool
}
IndexUsage is the evidence of how an index has been used, read from the cumulative statistics of the one server the pool is connected to. Like TableUsage it describes that server alone: scans served by a streaming replica or an Aurora reader are counted there, not here. It is built only by ReadIndexUsage.
func ReadIndexUsage ¶ added in v0.4.0
ReadIndexUsage reads the usage evidence of the index with the given OID on the server the pool is connected to, in one read-only transaction bounded by its own lock and statement timeouts, with every statistic from one snapshot. Keying on the OID reads the index the caller resolved, not whatever holds its name now. It changes nothing.
type LockHolder ¶ added in v0.4.0
type LockHolder struct {
// PID is the holder's backend process ID, or 0 when the holder is a
// prepared transaction, which keeps its locks with no backend.
PID int32
// ApplicationName is the holder's application_name, empty when it set
// none or for a prepared transaction.
ApplicationName string
// Modes are the lock modes the holder held on the relation, sorted.
Modes []string
// RelationSchema is the schema of the locked relation.
RelationSchema string
// RelationName is the name of the locked relation: the table itself or,
// for a partitioned table, the table or one of its partitions at any
// level.
RelationName string
// RelationOID is the locked relation's OID.
RelationOID uint32
}
LockHolder is one session, other than the reading one, that held a granted lock on the table — or, for a partitioned table, on the table or one of its partitions — when its usage was read. A session holding locks on several of those relations is one LockHolder per relation.
type OwnedRelationNames ¶ added in v0.3.1
OwnedRelationNames contains the relation names a table owns: the indexes backing its own primary-key, unique, and exclusion constraints, and the sequences owned by its columns. Each list is sorted and duplicate-free. A name is present whether the server invented it or the desired file stated it — a named constraint's index and an ALTER SEQUENCE ... OWNED BY sequence are owned just the same.
func LookupOwnedRelationNames ¶ added in v0.3.1
func LookupOwnedRelationNames(ctx context.Context, db rowQuerier, schema, table string) (OwnedRelationNames, error)
LookupOwnedRelationNames reads the relation names owned by an ordinary or partitioned table so a caller can verify them after a create step. Schema must be explicit because the caller must inspect the exact schema covered by its earlier absence proof rather than resolve a possibly different search_path target. The read excludes standalone indexes, whose own create steps report duplicate-name SQLSTATEs; the table itself, whose name is covered by the caller's absence proof; and the indexes a foreign key borrows from its referenced table, which belong to that table. db is a pool or a transaction; a transaction's read sees the table it created before that table commits.
type PKType ¶ added in v0.3.2
type PKType string
PKType identifies a supported single-column integer primary-key type.
type PartitionRefusalCause ¶
type PartitionRefusalCause string
PartitionRefusalCause identifies which unsupported shape triggered a partitioned-parent refusal. The zero value means the steps are supported.
const ( // PartitionCauseConcurrentIndexBuild means a step list attempts a // concurrent index build on the parent, which PostgreSQL has no // statement for. The front doors send a CREATE INDEX on a partitioned // table to the partition-aware build before this check // (RoutesToPartitionedIndexBuild), and an ADD PRIMARY KEY or ADD UNIQUE // to the partitioned key build (RoutesToPartitionedKeyBuild), so only a // step list that bypasses the routing carries one. PartitionCauseConcurrentIndexBuild PartitionRefusalCause = "parent-concurrent-index-build" // PartitionCauseBlockingIndexBuild means a step would build an index on // the parent while holding a lock that blocks writes to the whole tree. // A CREATE INDEX, ADD PRIMARY KEY, or ADD UNIQUE reaches it only when the // operator forced the submitted form, which overrides the routing to the // partition-aware build. PartitionCauseBlockingIndexBuild PartitionRefusalCause = "parent-blocking-index-build" // PartitionCauseIndexAdoption means a step adopts an existing index as a // primary-key or unique constraint on the parent. PartitionCauseIndexAdoption PartitionRefusalCause = "parent-index-adoption" // PartitionCauseNotValidForeignKey means a step adds a NOT VALID // foreign key, which the server version cannot do on a partitioned // table. PartitionCauseNotValidForeignKey PartitionRefusalCause = "parent-not-valid-foreign-key" // PartitionCauseConcurrentIndexDrop means a step drops an index of the // parent concurrently, which PostgreSQL rejects for a partitioned index. PartitionCauseConcurrentIndexDrop PartitionRefusalCause = "parent-concurrent-index-drop" )
func PartitionRefusalCauses ¶ added in v0.3.2
func PartitionRefusalCauses() []PartitionRefusalCause
PartitionRefusalCauses returns the closed set of partitioned-parent refusal causes, so documentation and consumers can enumerate them instead of maintaining their own list.
func RefusesPartitionedParent ¶
func RefusesPartitionedParent(serverMajor int, execSQL []string) (PartitionRefusalCause, error)
RefusesPartitionedParent reports the cause that makes steps unsupported on a partitioned parent, or the zero value when they are supported. It is the shared static policy used by preflight, plan reporting, and executor admission.
func (PartitionRefusalCause) Class ¶ added in v0.4.0
func (c PartitionRefusalCause) Class() refusal.Class
Class is the routing class of the cause, from docs/refusal-classes.md: what kind of boundary the consumer is looking at. The two index-build causes are a capability boundary: the partition-aware build is the supported route for an index on a partitioned parent, and these are the forms of the same request it does not run as written. Index adoption is by design: no supported server adopts an index as a constraint on a partitioned parent, so waiting for an engine release waits for nothing; the same holds for a concurrent drop of a partitioned index. The NOT VALID foreign key is environmental: the same statement runs on a newer server, so the action that unblocks it is a server upgrade. The class is a triage decision; the cause's row in the document decides what the consumer does next. The zero cause, and an unknown one, have no class.
type PartitionUsage ¶ added in v0.4.0
type PartitionUsage struct {
// contains filtered or unexported fields
}
PartitionUsage is the evidence read for one leaf partition of a partitioned table: a partition that holds rows, at any level below the table, the default partition included. A sub-partitioned partition holds no rows and has no PartitionUsage of its own; its leaves do. It is only built by ReadTableUsage.
func (PartitionUsage) Foreign ¶ added in v0.4.0
func (p PartitionUsage) Foreign() bool
Foreign reports whether the partition is a foreign table. Its rows live on another server, and this server keeps no scan statistics for it.
func (PartitionUsage) IdxScans ¶ added in v0.4.0
func (p PartitionUsage) IdxScans() int64
IdxScans returns the cumulative count of index scans on the partition's indexes (0 with no index, and for a foreign table).
func (PartitionUsage) LastIdxScan ¶ added in v0.4.0
func (p PartitionUsage) LastIdxScan() (at time.Time, ok bool)
LastIdxScan returns when the server last recorded an index scan on any of the partition's indexes. ok is false when it recorded none, when the partition has no index, for a foreign table, and always on a server that does not record scan times.
func (PartitionUsage) LastSeqScan ¶ added in v0.4.0
func (p PartitionUsage) LastSeqScan() (at time.Time, ok bool)
LastSeqScan returns when the server last recorded a sequential scan of the partition. ok is false when it recorded none since its statistics began, for a foreign table, and always on a server that does not record scan times.
func (PartitionUsage) Name ¶ added in v0.4.0
func (p PartitionUsage) Name() string
Name returns the partition's name.
func (PartitionUsage) OID ¶ added in v0.4.0
func (p PartitionUsage) OID() uint32
OID returns the partition's relation OID.
func (PartitionUsage) Schema ¶ added in v0.4.0
func (p PartitionUsage) Schema() string
Schema returns the partition's schema.
func (PartitionUsage) SeqScans ¶ added in v0.4.0
func (p PartitionUsage) SeqScans() int64
SeqScans returns the cumulative count of sequential scans of the partition (0 for a foreign table).
type PreflightedTable ¶
type PreflightedTable struct {
// contains filtered or unexported fields
}
PreflightedTable proves the target table exists, is a table, and is under the size threshold for an optimistic attempt. It can only be constructed by CheckTable in this package.
func CheckTable ¶
func CheckTable(ctx context.Context, pool *pgxpool.Pool, schema, table string, limitBytes int64) (PreflightedTable, error)
CheckTable verifies that schema.table (search_path when schema is empty) exists, is an ordinary or partitioned table, and is at most limitBytes on disk. Above the limit it returns a *SizeError; on success it returns the PreflightedTable proof.
The unqualified lookup is search_path-wide (to_regclass), so success does not mean the name is occupied in the session's creation schema: a table in a later search_path schema satisfies this check while CheckTableAbsent — which resolves current_schema() only — still proves the creation schema free for the same name. The two checks are inverses only when the caller passes an explicit schema.
func (PreflightedTable) Partitioned ¶
func (t PreflightedTable) Partitioned() bool
Partitioned reports whether the verified target is a partitioned parent. Leaf partitions have relkind 'r' and therefore report false.
func (PreflightedTable) RelTuples ¶
func (t PreflightedTable) RelTuples() float64
RelTuples returns the planner's row estimate (-1 when the table has never been vacuumed or analyzed). Reporting only — the size guard's authority is bytes on disk.
func (PreflightedTable) Schema ¶
func (t PreflightedTable) Schema() string
Schema returns the schema qualification the check ran with (empty when the lookup used the session search_path).
func (PreflightedTable) Table ¶
func (t PreflightedTable) Table() string
Table returns the verified table name.
func (PreflightedTable) TotalBytes ¶
func (t PreflightedTable) TotalBytes() int64
TotalBytes returns the measured on-disk size across all partitions, including indexes and TOAST.
type PrivilegeError ¶
type PrivilegeError struct {
// Tier is the access level the failed check belongs to.
Tier Tier
// Check is the catalog predicate that returned false. It is display
// prose: identifiers appear unquoted, so a renderer embedding it in
// structured output (a markdown table, a PR comment) owns escaping it.
Check string
// Grant is the exact statement that would satisfy the check. Every
// identifier in it is Sanitize()-quoted, so it is safe to echo
// verbatim as executable SQL.
Grant string
// Hint explains the remediation when the Grant alone would surprise
// the operator — for example when its grantee differs from the role
// the Check names. Empty when the Grant speaks for itself.
Hint string
// Owner names the table's owner when the failed check is about the
// owner's own access rather than the engine role's: copy-and-swap
// builds its shadow as the owner. Empty for a check about the engine
// role.
Owner string
}
PrivilegeError reports a failed access check: the tier that needs it, the catalog check that returned false, and the exact statement that would satisfy it. It is a refusal input, not an operational failure — the same fail-closed posture as every other refusal in the engine. Provisioning rationale lives in docs/engine-role.md.
func (*PrivilegeError) Error ¶
func (e *PrivilegeError) Error() string
Error implements the error interface.
type PrivilegedRole ¶
type PrivilegedRole struct {
// contains filtered or unexported fields
}
PrivilegedRole proves the connected role holds every access the requirement's tier needs against the target table. It can only be constructed by CheckPrivileges in this package. The owning role it carries is the catalog-resolved owner the copy-and-swap path will SET ROLE to for shadow objects. It records whether replication access was among the verified grants, so a later check that needs it can tell a proof that covers it from one that does not. It proves the engine role's access only: the owner's own USAGE and CREATE on the schema, which the copy-and-swap shadow build needs, is proven by CheckCopySwapEnvironment.
func CheckPrivileges ¶
func CheckPrivileges(ctx context.Context, pool *pgxpool.Pool, schema, table string, req Requirement) (PrivilegedRole, error)
CheckPrivileges verifies the connected role holds the access the requirement needs against schema.table (search_path resolution when schema is empty), per the tiered contract in docs/engine-role.md. A missing requirement is a *PrivilegeError naming the exact statement that would satisfy it; on success it returns the PrivilegedRole proof.
It runs before CheckTable in the preflight order: a role that cannot see the target would otherwise report "table not found" and mask the real cause.
func (PrivilegedRole) LogicalDecoding ¶ added in v0.4.0
func (p PrivilegedRole) LogicalDecoding() bool
LogicalDecoding reports whether the requirement the role was verified against included replication access.
func (PrivilegedRole) Owner ¶
func (p PrivilegedRole) Owner() string
Owner returns the target table's owning role from the catalog.
func (PrivilegedRole) Role ¶
func (p PrivilegedRole) Role() string
Role returns the connected role the checks ran as.
func (PrivilegedRole) Tier ¶
func (p PrivilegedRole) Tier() Tier
Tier returns the tier the role was verified at.
type Publishing ¶ added in v0.5.8
type Publishing struct {
Publications []string
Slots []string
// GeneratedPublications names those of Publications that also send a
// stored generated column (publish_generated_columns = stored, from
// PostgreSQL 18), rendered and sorted the same way. No publication
// sends a virtual generated column.
GeneratedPublications []string
}
Publishing names the publications that send a table's changes, or a new table's, to logical replication, and the pgoutput slots in the current database that may be reading them, each rendered "name" with its identifier quoted and name-sorted. A slot does not record which publications its consumer asks for, so every pgoutput slot counts. Both are empty unless both would be named: a publication nothing reads stops nothing, and a slot that reads none of these publications sees none of the table's changes. The engine's own copy-and-swap publications and slots are never named.
func ReadNewTablePublishing ¶ added in v0.5.8
func ReadNewTablePublishing(ctx context.Context, db rowQuerier, schema string) (Publishing, error)
ReadNewTablePublishing reads the publications that send the changes of a permanent table created in schema: those newTablePublications names that publish any change. A desired file cannot declare a partition, so the table is never one.
func ReadTablePublishing ¶ added in v0.5.8
func ReadTablePublishing(ctx context.Context, db rowQuerier, schema, table string) (Publishing, error)
ReadTablePublishing reads the publications that send a column the table gains: every publication that publishes any change of schema.table, or of a permanent table above or below it in a partition or inheritance tree, without a column list. A column list names the columns a publication sends, so a column added later is not among them. PostgreSQL publishes only permanent tables, so a table that is unlogged or temporary, or does not exist, has none.
type Requirement ¶
type Requirement struct {
Tier Tier
// LogicalDecoding requires replication access on top of the tier:
// rds_replication membership where that role exists (Aurora/RDS), the
// REPLICATION role attribute otherwise. Only valid with
// TierCopyAndSwap — no other strategy decodes WAL.
LogicalDecoding bool
}
Requirement states the access a schema change's plan needs: the tier, and whether the strategy decodes WAL (logical-decoding CDC, copy-and-swap only), which additionally requires replication access.
type SizeError ¶
type SizeError struct {
// TotalBytes is the table's measured on-disk size (all partitions,
// including indexes and TOAST).
TotalBytes int64
// LimitBytes is the threshold that was exceeded.
LimitBytes int64
// RelTuples is the planner's row estimate, read in the same lookup as
// TotalBytes (-1 when the table has never been vacuumed or analyzed),
// so a caller that reports the refused table's size can report its rows
// too. Reporting only, as on PreflightedTable.
RelTuples float64
}
SizeError reports that the table exceeds the configured size threshold, so the optimistic attempt must be skipped. It is a refusal input, not an operational failure.
type Subscriptions ¶ added in v0.5.8
type Subscriptions struct {
// Tree names the subscriptions that write the table or any table
// below it, which is what a recursive ALTER TABLE changes.
Tree []string
// Own names the subscriptions that write the table itself, which is
// all an ALTER TABLE ONLY changes. A subscription that writes a
// partitioned ancestor routes each row into the partition it belongs
// in, so it writes the partition itself.
Own []string
// IdentityIndexes and IdentityConstraints name, when a subscription
// writes the table, the index the subscriber's apply worker finds a
// row to update or delete by, and the primary key or unique
// constraint that owns it: the index REPLICA IDENTITY USING INDEX
// selects, or the primary key under REPLICA IDENTITY DEFAULT. Each is
// the bare name, sorted, and nil when there is none.
IdentityIndexes []string
IdentityConstraints []string
}
Subscriptions names the logical replication subscriptions in the current database that write a table, each rendered "subscription" with its identifier quoted and name-sorted. A subscriber applies every change the publisher sends as the publisher shaped it, so a change that leaves the table unable to take one stops the subscription's replication.
func ReadSubscriptions ¶ added in v0.5.8
func ReadSubscriptions(ctx context.Context, pool *pgxpool.Pool, schema, table string) (Subscriptions, error)
ReadSubscriptions reads the subscriptions that write schema.table, a partition or inheritance child below it, or a partitioned table it is a partition of, from pg_subscription_rel, which lists every table a subscription has added, whether or not the subscription is enabled. A table that does not exist has none.
func (Subscriptions) DropsIdentity ¶ added in v0.5.8
DropsIdentity reports whether op drops the index the subscriber's apply worker finds rows by, or the constraint that owns it. Without one, the worker can find a row only when the publisher sends it whole (REPLICA IDENTITY FULL), so the next UPDATE or DELETE it applies otherwise fails.
type TableUsage ¶ added in v0.4.0
type TableUsage struct {
// contains filtered or unexported fields
}
TableUsage is the evidence of how recently a table was used, read from the cumulative statistics of the one server the pool is connected to. It is only built by ReadTableUsage, and it describes that server alone: reads served by any other server (a streaming replica, an Aurora reader) are not in it. Judge turns it into a UsageVerdict for a window.
A partitioned table stores no rows and the server keeps its scan statistics on the leaf partitions, so its evidence is the evidence of every leaf partition, at every level, and the counters and scan times report the leaves taken together.
func ReadTableUsage ¶ added in v0.4.0
func ReadTableUsage(ctx context.Context, pool *pgxpool.Pool, schema, table string) (TableUsage, error)
ReadTableUsage reads how recently schema.table (search_path when schema is empty) was used on the server the pool is connected to, in one read-only transaction bounded by its own lock and statement timeouts, with every statistic from one snapshot. It reads the server's version, whether it is in recovery, the reading session's track_counts and whether a saved setting turns it off for another role or the database, the server's now(), the database's statistics reset time, the scan and write counters (and, on PostgreSQL 16 and later, the last scan times) of the table or, when it is partitioned, of every leaf partition at every level, and the sessions other than its own holding a lock on the table or any of its partitions. It takes no lock on any of them and changes nothing.
Declarative partitions are followed; inheritance children of an ordinary table are not: they are tables of their own, and a read through the parent is recorded on the parent too.
A missing name is ErrTableNotFound, and a relation that is neither an ordinary nor a partitioned table is ErrNotTable.
func (TableUsage) IdxScans ¶ added in v0.4.0
func (u TableUsage) IdxScans() int64
IdxScans returns the cumulative count of index scans on the table's indexes (0 for a table with no index), summed over the leaf partitions of a partitioned table.
func (TableUsage) InRecovery ¶ added in v0.4.0
func (u TableUsage) InRecovery() bool
InRecovery reports whether the server was a standby when read: its statistics then describe what that standby served, not the primary.
func (TableUsage) Judge ¶ added in v0.4.0
func (u TableUsage) Judge(window time.Duration) (UsageVerdict, error)
Judge decides whether the table was used inside the window before the read, on the server it was read from. It fails closed: only evidence that proves the table idle answers UsageIdle; anything it cannot prove is UsageUnknown, and evidence of use is UsageRecent. A window shorter than MinUsageWindow is a *UsageWindowError.
Judge never decides on the write counters: they carry no time, so one read cannot tell a write a second ago from one a year ago. An UPDATE or DELETE finds its rows through a scan, which the scan times record; an INSERT scans nothing and is seen only while its transaction holds its lock. A transaction still open holds its lock on the table until it ends, so a scan whose time is not yet recorded is seen as a lock holder; one that ended within the publishing delay and holds nothing is not seen at all.
A partitioned table is judged across all of its leaf partitions: a lock on the table or any partition, or a scan of any leaf inside the window, is use of the table, and the most recently scanned leaf names it; a leaf whose own evidence could not prove it idle makes the table unknown unless another relation shows use.
The order is: a lock holder, then a scan inside the window, are evidence of use whatever else holds; only then can missing scan times, recovery, untracked counts, a reset inside the window, a partitioned table with no leaf partition, a foreign-table partition, or an unknown counting start make the answer unknown; idle is what is left.
func (TableUsage) LastIdxScan ¶ added in v0.4.0
func (u TableUsage) LastIdxScan() (at time.Time, ok bool)
LastIdxScan returns when the server last recorded an index scan on any of the table's indexes — for a partitioned table, the latest across its leaf partitions' indexes. ok is false when it recorded none since their statistics began, when there is no index, and always on a server that does not record scan times.
func (TableUsage) LastSeqScan ¶ added in v0.4.0
func (u TableUsage) LastSeqScan() (at time.Time, ok bool)
LastSeqScan returns when the server last recorded a sequential scan of the table — for a partitioned table, the latest across its leaf partitions. ok is false when it recorded none since its statistics began, and always on a server that does not record scan times.
func (TableUsage) LockHolders ¶ added in v0.4.0
func (u TableUsage) LockHolders() []LockHolder
LockHolders returns the sessions, other than the reading one, that held a granted lock on the table, or on any of a partitioned table's partitions, when it was read: one entry per session and relation.
func (TableUsage) OID ¶ added in v0.4.0
func (u TableUsage) OID() uint32
OID returns the table's relation OID. The statistics are keyed on it, so a table recreated or swapped under the same name starts a new history.
func (TableUsage) Partitioned ¶ added in v0.4.0
func (u TableUsage) Partitioned() bool
Partitioned reports whether the table is a partitioned table, whose evidence is read from its leaf partitions.
func (TableUsage) Partitions ¶ added in v0.4.0
func (u TableUsage) Partitions() []PartitionUsage
Partitions returns the evidence read for each leaf partition of a partitioned table, at every level, the default partition included, sorted by schema then name. It is empty for an ordinary table and for a partitioned table with no leaf partition.
func (TableUsage) ReadAt ¶ added in v0.4.0
func (u TableUsage) ReadAt() time.Time
ReadAt returns the server's now() for the read's transaction: every window is measured back from this, never from the client's clock.
func (TableUsage) ScanTimesRecorded ¶ added in v0.4.0
func (u TableUsage) ScanTimesRecorded() bool
ScanTimesRecorded reports whether the server records when a table was last scanned: PostgreSQL 16 and later do, 14 and 15 do not.
func (TableUsage) Schema ¶ added in v0.4.0
func (u TableUsage) Schema() string
Schema returns the schema qualification the read ran with (empty when the lookup used the session search_path).
func (TableUsage) SeqScans ¶ added in v0.4.0
func (u TableUsage) SeqScans() int64
SeqScans returns the cumulative count of sequential scans of the table, summed over the leaf partitions of a partitioned table.
func (TableUsage) ServerVersionNum ¶ added in v0.4.0
func (u TableUsage) ServerVersionNum() int
ServerVersionNum returns the server's server_version_num.
func (TableUsage) StatsReset ¶ added in v0.4.0
func (u TableUsage) StatsReset() (at time.Time, ok bool)
StatsReset returns when the current database's statistics were last reset (pg_stat_database.stats_reset). ok is false when the server reports none: no reset since the statistics began, or statistics discarded by crash recovery — either way the time counting began is unknown.
func (TableUsage) Table ¶ added in v0.4.0
func (u TableUsage) Table() string
Table returns the table name the read ran with.
func (TableUsage) TrackCounts ¶ added in v0.4.0
func (u TableUsage) TrackCounts() bool
TrackCounts reports whether track_counts was on for the reading session. It is that session's value only: it reflects the server's configuration and the reading role's settings, not another session's. With it off the server collects no table statistics at all.
func (TableUsage) TrackCountsOffBySetting ¶ added in v0.4.0
func (u TableUsage) TrackCountsOffBySetting() bool
TrackCountsOffBySetting reports whether a saved per-role or per-database setting (ALTER ROLE … SET or ALTER DATABASE … SET, in pg_db_role_setting) turns track_counts off for some role, in this database or in all of them, or for this database. Scans in sessions it applies to are not counted. A session that turns it off with SET or a connection option leaves no trace any reader can see.
func (TableUsage) TuplesDeleted ¶ added in v0.4.0
func (u TableUsage) TuplesDeleted() int64
TuplesDeleted returns the cumulative count of rows deleted, summed over the leaf partitions of a partitioned table. Write counters carry no time, so Judge never decides on them.
func (TableUsage) TuplesInserted ¶ added in v0.4.0
func (u TableUsage) TuplesInserted() int64
TuplesInserted returns the cumulative count of rows inserted, summed over the leaf partitions of a partitioned table. Write counters carry no time, so Judge never decides on them.
func (TableUsage) TuplesUpdated ¶ added in v0.4.0
func (u TableUsage) TuplesUpdated() int64
TuplesUpdated returns the cumulative count of rows updated, summed over the leaf partitions of a partitioned table. Write counters carry no time, so Judge never decides on them.
type TablespaceUse ¶ added in v0.5.8
type TablespaceUse uint8
TablespaceUse is whether the connected role may name a tablespace in a SET TABLESPACE, judged as PostgreSQL judges it before the statement changes anything (ATPrepSetTableSpace in tablecmds.c): the tablespace must exist, and the role must hold CREATE on it unless it is the database's default tablespace, which every role may use without the grant.
const ( // TablespaceUnread means the fact was not read, as in an offline lint; // the server's own check at execution remains the backstop. TablespaceUnread TablespaceUse = iota // TablespaceUsable is a tablespace the role may name: the database's // default, or one it holds CREATE on. TablespaceUsable // TablespaceMissing is a name no tablespace on the server has, which // PostgreSQL refuses with SQLSTATE 42704. TablespaceMissing // TablespaceCreateDenied is a tablespace other than the database's // default that the role holds no CREATE on, which PostgreSQL refuses // with SQLSTATE 42501. TablespaceCreateDenied )
func ReadTablespaceUse ¶ added in v0.5.8
ReadTablespaceUse reads whether the connected role may name the tablespace name in a SET TABLESPACE.
type TargetFacts ¶
type TargetFacts struct {
// contains filtered or unexported fields
}
TargetFacts are the cheap target facts needed by planning and executor admission without measuring the relation or its partition tree.
func LookupTargetFacts ¶
func LookupTargetFacts(ctx context.Context, pool *pgxpool.Pool, schema, table string) (TargetFacts, error)
LookupTargetFacts verifies that the target is an ordinary or partitioned table and returns its relation kind and server major in one catalog query.
func (TargetFacts) Partitioned ¶
func (f TargetFacts) Partitioned() bool
Partitioned reports whether the target is a partitioned parent.
func (TargetFacts) ServerMajor ¶
func (f TargetFacts) ServerMajor() int
ServerMajor returns the PostgreSQL server major version.
type Tier ¶
type Tier int
Tier is the access level a schema change's plan requires from the engine role, per the tiered contract in docs/engine-role.md. Each tier includes everything below it; a change is admitted at the tier its plan requires and nothing higher.
const ( // TierConnect covers connecting and resolving the target: CONNECT on // the database and USAGE on the target schema. The CONNECT rung // documents the contract rather than catching live failures — a role // missing it fails at connection time, before any check runs — while // the USAGE rung is load-bearing: without it a qualified target // masquerades as "table not found". TierConnect Tier = iota // TierAlterInPlace covers owner-gated in-place ALTER TABLE (the // instant and fast native paths), ALTER INDEX ... RENAME TO, // ALTER TYPE ... ADD VALUE, and a reviewed DROP TABLE: inheritable // membership in the role that owns the table, or the type. TierAlterInPlace // TierIndexBuild covers CREATE INDEX [CONCURRENTLY]: CREATE on the // target schema on top of owning-role membership. TierIndexBuild // TierCopyAndSwap covers shadow-object creation: membership usable // with SET ROLE, so shadow objects are born with the correct owner. TierCopyAndSwap // TierCreateTable covers greenfield CREATE TABLE and sits off the // ladder above: a table that does not exist yet has no owner to be a // member of, so the create path proves CONNECT on the database plus // USAGE and CREATE on the schema — deliberately not the ownership // membership the ALTER tiers require. It is checked by // CheckCreatePrivileges, never by CheckPrivileges, whose ladder walks // facts about an existing table. TierCreateTable // TierPlan covers planning a desired-state file: CREATE on the // database, for the scratch schema every declarative plan builds the // desired table in and rolls back. It sits off the ladder like // TierCreateTable, because the plan needs it before it knows what the // change is. It is checked by CheckPlanPrivileges. TierPlan )
The contract's tiers, lowest to highest.
func RequiredTier ¶
RequiredTier derives the engine-role tier a routed change's exec SQL needs: an in-place ALTER TABLE step, an ALTER INDEX ... RENAME TO on the table's index, and a DROP INDEX of that one index, is owner-gated (TierAlterInPlace), and any step that builds a new index — every CREATE INDEX, and the ALTER TABLE shapes that build one as a side effect — additionally needs CREATE on the schema (TierIndexBuild), so the requirement is the most demanding step's tier — the ladder check covers every rung below it. The mapping from step shape to required access lives here, next to Tier and CheckPrivileges, so every consumer of the routed plan derives the same answer. A step shape the engine does not execute fails closed here, before anything runs.
A CREATE TABLE step derives the off-ladder TierCreateTable — the greenfield create plan's shape: one CREATE TABLE plus CREATE INDEX steps on the table it creates, checked by CheckCreatePrivileges, never by CheckPrivileges, whose ladder states facts about an existing table. A set that mixes CREATE TABLE with a change to an existing table fails closed: the off-ladder tier proves creation access only and cannot vouch for the ladder rungs a change to an existing table needs — and no front door produces such a set.
type UnsupportedCopySwapShapeError ¶ added in v0.4.0
type UnsupportedCopySwapShapeError struct {
// Cause is the primary shape that triggered the refusal.
Cause CopySwapRefusalCause
// Detail is the catalog fact behind the primary cause.
Detail string
// Causes is every shape cause the table has, in the order the shape
// check decides them, so Causes[0] is Cause.
Causes []CopySwapShapeCause
// NoPrimaryKey reports that the table was refused with
// CopySwapCausePKUnsupported as its primary cause because it has no
// primary key at all, the one key shape the operator can fix online by
// adding a key. False for a uuid, text, composite, or DEFERRABLE key,
// and for every other primary cause.
NoPrimaryKey bool
}
UnsupportedCopySwapShapeError reports that the target table's shape is outside the copy-and-swap route's v1 scope. Cause and Detail are the primary cause, the first the shape check decides; Causes lists every cause the table has, the primary first, so one refusal names all of them. Identifiers in the details appear unquoted, so a renderer embedding them in structured output owns escaping them.
func (*UnsupportedCopySwapShapeError) Error ¶ added in v0.4.0
func (e *UnsupportedCopySwapShapeError) Error() string
Error implements the error interface: the one cause with its next step, or every cause numbered in decision order.
type UnsupportedPartitionedParentError ¶
type UnsupportedPartitionedParentError struct {
// Cause is the unsupported shape that triggered the refusal.
Cause PartitionRefusalCause
}
UnsupportedPartitionedParentError reports that an execution plan contains a step pg-sprite cannot safely run on a partitioned parent. Its rendered message is a fixed English sentence with no interpolated identifiers or server text, so orchestrator-facing surfaces may render it verbatim. This is a deliberate property to preserve.
func (*UnsupportedPartitionedParentError) Error ¶
func (e *UnsupportedPartitionedParentError) Error() string
Error implements the error interface.
type UsageOutcome ¶ added in v0.4.0
type UsageOutcome string
UsageOutcome is the closed set of answers to "was this table used inside the window, on this server?".
const ( // UsageIdle means the server's statistics prove no scan of the table // inside the window and no session held a lock on it when read. It is // bounded evidence, not permission: it assumes every session that could // have scanned the table counted its scans, which no reader can check // for a session that turned track_counts off with SET or a connection // option. UsageIdle UsageOutcome = "idle" // UsageRecent means the server's statistics show a scan inside the // window, or a session held a lock on the table when read. UsageRecent UsageOutcome = "recent" // UsageUnknown means the evidence can prove neither: the answer is not // idle. UsageUnknown UsageOutcome = "unknown" )
type UsageReason ¶ added in v0.4.0
type UsageReason string
UsageReason is the typed cause behind a UsageOutcome.
const ( // UsageReasonLockHeld means another session held a lock on the table. UsageReasonLockHeld UsageReason = "lock-held" // UsageReasonSeqScanInWindow means the most recent scan inside the window, // of either kind, is a sequential scan. UsageReasonSeqScanInWindow UsageReason = "seq-scan-in-window" // UsageReasonIndexScanInWindow means the most recent scan inside the // window, of either kind, is an index scan. UsageReasonIndexScanInWindow UsageReason = "index-scan-in-window" // UsageReasonScanTimesNotRecorded means the server (PostgreSQL 14 or 15) // does not record when a table was last scanned. UsageReasonScanTimesNotRecorded UsageReason = "scan-times-not-recorded" // UsageReasonInRecovery means the server is a standby, so its statistics // describe that standby, not the primary schema changes run on. UsageReasonInRecovery UsageReason = "in-recovery" // UsageReasonCountsNotTracked means track_counts is off for the reading // session, so the server may be collecting no table statistics. UsageReasonCountsNotTracked UsageReason = "counts-not-tracked" // UsageReasonCountsNotTrackedBySetting means a saved per-role or // per-database setting turns track_counts off for some role or for this // database, so scans in the sessions it applies to are not counted. UsageReasonCountsNotTrackedBySetting UsageReason = "counts-not-tracked-by-setting" // UsageReasonStatsResetInWindow means the database's statistics were reset // inside the window, so a scan before the reset left no trace. UsageReasonStatsResetInWindow UsageReason = "stats-reset-in-window" // UsageReasonNoPartitions means the table is partitioned and has no leaf // partition. The server records scans only on leaf partitions, so a // query against it leaves no trace, and only a lock holder can show use. UsageReasonNoPartitions UsageReason = "no-partitions" // UsageReasonForeignPartition means a leaf partition is a foreign table, // whose scans this server keeps no statistics for. UsageReasonForeignPartition UsageReason = "foreign-partition" // UsageReasonStatsStartUnknown means the table — or, for a partitioned // table, one of its leaf partitions — has no recorded scan and the server // reports no reset time, so when counting began, and so whether "never // scanned" covers the window, is unknown. UsageReasonStatsStartUnknown UsageReason = "stats-start-unknown" // UsageReasonNoScanInWindow means the statistics, counted continuously since // before the window began, record no scan inside it. UsageReasonNoScanInWindow UsageReason = "no-scan-in-window" )
type UsageVerdict ¶ added in v0.4.0
type UsageVerdict struct {
// contains filtered or unexported fields
}
UsageVerdict is TableUsage judged against one window. It carries the evidence it was judged on, so a message can name what decided it.
func (UsageVerdict) Detail ¶ added in v0.4.0
func (v UsageVerdict) Detail() string
Detail renders the outcome, its reason, and the evidence that decided it, for messages. For a partitioned table it names the leaf partition each scan time comes from and the relation that decided the verdict. It is prose: callers branch on Outcome and Reason.
func (UsageVerdict) Outcome ¶ added in v0.4.0
func (v UsageVerdict) Outcome() UsageOutcome
Outcome returns the verdict: idle, recent, or unknown.
func (UsageVerdict) Partition ¶ added in v0.4.0
func (v UsageVerdict) Partition() (p PartitionUsage, ok bool)
Partition returns the leaf partition of a partitioned table that the reason is about: the one scanned most recently for a scan inside the window, the foreign table for foreign-partition, and the first partition with no recorded scan for stats-start-unknown. ok is false for every other reason and for an ordinary table. A lock holder names its own relation (LockHolder.RelationName).
func (UsageVerdict) Reason ¶ added in v0.4.0
func (v UsageVerdict) Reason() UsageReason
Reason returns the typed cause of the outcome.
func (UsageVerdict) Usage ¶ added in v0.4.0
func (v UsageVerdict) Usage() TableUsage
Usage returns the evidence the verdict was judged on.
func (UsageVerdict) Window ¶ added in v0.4.0
func (v UsageVerdict) Window() time.Duration
Window returns the window the usage was judged against.
func (UsageVerdict) WindowStart ¶ added in v0.4.0
func (v UsageVerdict) WindowStart() time.Time
WindowStart returns the instant the window opened: the read's server time minus the window.
type UsageWindowError ¶ added in v0.4.0
type UsageWindowError struct {
// Window is the window asked for.
Window time.Duration
// Min is the shortest window Judge accepts.
Min time.Duration
}
UsageWindowError reports a window shorter than MinUsageWindow.
func (*UsageWindowError) Error ¶ added in v0.4.0
func (e *UsageWindowError) Error() string
Error implements the error interface.
Source Files
¶
- absent.go
- absent_type.go
- add_column_rewrite.go
- catalog_only_facts.go
- column_dependents.go
- column_limit.go
- constraint_names.go
- copy_swap.go
- copy_swap_check.go
- copy_swap_disk.go
- copy_swap_environment.go
- copy_swap_environment_preview.go
- copy_swap_names.go
- copy_swap_owner.go
- copy_swap_shape.go
- copy_swap_shape_causes.go
- copy_swap_statistics_access.go
- create.go
- enum_target.go
- gone.go
- index_usage.go
- owned.go
- partition.go
- plan.go
- preflight.go
- privileges.go
- publication.go
- publishing.go
- subscription.go
- table_drop_dependents.go
- table_rows.go
- table_usage.go
- table_usage_coverage.go
- table_usage_partitions.go
- table_usage_verdict.go
- tablespace.go
- tier.go
- trigger_reads.go
- type_change_facts.go