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 AddColumnRewrites(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string) (map[string]statement.AddColumnProof, error)
- func CheckNamesAbsent(ctx context.Context, pool *pgxpool.Pool, at AbsentTarget, names []string) error
- func CheckPartitionSupport(table PreflightedTable, serverMajor int, execSQL []string) error
- func CopySwapDecodingName(database, schema, table string) string
- func IsNameOccupied(err error) bool
- func RecheckCopySwapShape(ctx context.Context, tx pgx.Tx, target CopySwapTarget) error
- func SchemaConstraintNames(ctx context.Context, pool *pgxpool.Pool, schema string) (map[string]bool, error)
- type AbsentTarget
- type CopySwapEnvironment
- type CopySwapEnvironmentError
- 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 CopySwapTarget
- func (s CopySwapTarget) Database() string
- func (t CopySwapTarget) DecodesWAL() bool
- func (s CopySwapTarget) DecodingName() string
- 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 DependentViews
- 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 Requirement
- type SizeError
- 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 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 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 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).
Variables ¶
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 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 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 AddColumnRewrites ¶ added in v0.4.0
func AddColumnRewrites(ctx context.Context, pool *pgxpool.Pool, schema, table, sql string) (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 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.
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 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 RecheckCopySwapShape ¶ added in v0.4.0
RecheckCopySwapShape verifies inside the build transaction that the proven relation still has the admitted shape and identity.
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.
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 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
}
CopySwapEnvironment states what the run needs from the cluster and what the caller knows about it that the server cannot report.
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
}
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 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 // neither DEFAULT nor FULL, so decoded UPDATE and DELETE events would // not carry the key the applier needs. CopySwapCauseReplicaIdentity CopySwapRefusalCause = "copy-and-swap-replica-identity" // 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 the operator can set, 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 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 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 three admission checks in order — CheckPrivileges at TierCopyAndSwap (with replication access when the run decodes WAL), CheckCopySwapShape, CheckCopySwapEnvironment — and returns the CopySwapTarget the last one mints. It is the one call a caller needs before the first write; the three checks stay exported for callers that report each refusal class separately.
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 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. 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 is a *CopySwapEnvironmentError. 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) 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) 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 DependentViews ¶ added in v0.4.0
type DependentViews 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
}
DependentViews names, per column, the views and materialized views that read it, each schema-qualified with every identifier quoted, sorted. A column no view reads is absent from every map.
func ColumnDependentViews ¶ added in v0.4.0
func ColumnDependentViews(ctx context.Context, pool *pgxpool.Pool, schema, table string) (DependentViews, error)
ColumnDependentViews reads which views and materialized views read each column of schema.table, and of 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 a view reads, even a relabel that rewrites nothing, and refuses to drop one without CASCADE. A recursive type change reaches the column on every table below, so a view 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 views, 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 from the view's rewrite rule to the column, so 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 view created after it.
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, pool *pgxpool.Pool, 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.
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 attempts a concurrent // index build on the parent. PartitionCauseConcurrentIndexBuild PartitionRefusalCause = "parent-concurrent-index-build" // PartitionCauseBlockingIndexBuild means a step would build an index on // the parent while holding ACCESS EXCLUSIVE. 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" )
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 concurrent index flow is a planned engine capability, and refusing the blocking substitute is the policy half of the same gap. 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 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
}
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.
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 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
}
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 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 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): inheritable membership in the // owning role. 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 )
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, and an ALTER INDEX ... RENAME TO on the table's 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 ALTER TABLE fails closed: the off-ladder tier proves creation access only and cannot vouch for the ladder rungs an alter on 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 shape that triggered the refusal.
Cause CopySwapRefusalCause
// Detail is the catalog fact behind the cause.
Detail string
}
UnsupportedCopySwapShapeError reports that the target table's shape is outside the copy-and-swap route's v1 scope. Detail names the catalog fact that decided it; identifiers in it appear unquoted, so a renderer embedding it in structured output owns escaping it.
func (*UnsupportedCopySwapShapeError) Error ¶ added in v0.4.0
func (e *UnsupportedCopySwapShapeError) Error() string
Error implements the error interface.
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
- add_column_rewrite.go
- constraint_names.go
- copy_swap.go
- copy_swap_check.go
- copy_swap_environment.go
- copy_swap_names.go
- copy_swap_shape.go
- create.go
- dependent_views.go
- index_usage.go
- owned.go
- partition.go
- preflight.go
- privileges.go
- table_usage.go
- table_usage_coverage.go
- table_usage_partitions.go
- table_usage_verdict.go
- tier.go