Documentation
¶
Overview ¶
Package schemachange orchestrates copy-and-swap schema changes while enforcing LK-2, LK-4, and ST-5.
Every shadow operation takes the *dbconn.TableLockSession for the table: a dedicated server session, separate from the working pool, that holds the per-table lock (LK-1) for as long as the change runs.
A build that finds a relation under the shadow's name returns ErrShadowExists. The resume order is: InspectShadow first, compare the returned BuiltShadow with the checkpoint the earlier build produced, and continue from that shadow when they agree; DropShadow only when they do not, or when the change is being abandoned. Inspection costs one read transaction; a drop destroys a shadow that may have been resumable and buys a full rebuild and copy.
Runner chains the operations from table lock to old table drop, writing the checkpoint row at every phase transition and dispatching on the row it finds, so a run that stops anywhere resumes from the row. The target's proof chooses the route. A quiesced table's quiescence is enforced, not assumed: the run fences the source with a statement trigger, enabled ALWAYS, that refuses every write until the swap, and the fence stays on a stopped run's source until it is resumed or abandoned with DropWriteFence. The quiesced swap refuses if the fence is no longer there as installed. A table under writes is captured instead: the run creates the slot with the row that owns it, applies the stream to the shadow beside the copy, catches up to a marker past every change committed so far, verifies live, and drains the stream under the swap's lock before it renames; a stopped run's slot stays until it is resumed or abandoned with decode.DropSlot. The one exception to "a shadow is only dropped on abandonment" is a first save whose row does not land: the run drops the shadow it just built, and the slot with it, since a shadow no row records would refuse the next run as ErrShadowExists.
Index ¶
- Constants
- Variables
- func CheckPool(pool *pgxpool.Pool, o copier.Options) error
- func DropOldTable(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, ...) error
- func DropShadow(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, ...) error
- func DropWriteFence(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, ...) error
- func IsDataFault(err error) bool
- func MinPoolConns(o copier.Options) int32
- func NameHash(schema, table string) string
- func OldDependentName(schema, table, dependent string) string
- func OldName(schema, table string) string
- func ShadowName(schema, table string) string
- type AbandonedError
- type BuiltShadow
- func (b BuiltShadow) ConversionFingerprint() string
- func (b BuiltShadow) Conversions() map[string]string
- func (b BuiltShadow) CopyColumns() []string
- func (b BuiltShadow) Fidelity() FidelitySnapshot
- func (b BuiltShadow) IdentityColumns() []IdentityColumn
- func (b BuiltShadow) MarshalJSON() ([]byte, error)
- func (b BuiltShadow) Proof() Proof
- func (b BuiltShadow) Schema() string
- func (b BuiltShadow) ShadowFidelity() FidelitySnapshot
- func (b BuiltShadow) ShadowOID() uint32
- func (b BuiltShadow) ShadowTable() string
- func (b BuiltShadow) SourceFingerprint() string
- func (b BuiltShadow) SourceOID() uint32
- func (b BuiltShadow) SourceTable() string
- func (b BuiltShadow) TargetFingerprint() string
- type CatchupWaitError
- type ColumnGrant
- type ColumnStatisticsTarget
- type CutoverOptions
- type CutoverReady
- type DependentKind
- type DependentPair
- type DependentPairing
- type DerivedKind
- type DrainFunc
- type ExtendedStatisticsTarget
- type FidelitySnapshot
- type Grant
- type IdentityColumn
- type Options
- type OwnedSequence
- type Policy
- type Proof
- type Reconciled
- type Reconciler
- type RefusalCause
- type RefusalError
- type Result
- type Resume
- type ResumeMode
- type RunOptions
- type Runner
- type SequenceOptions
- type SwapProof
- type SwappedTable
- func (s SwappedTable) Attempts() int
- func (s SwappedTable) IdentityColumns() []IdentityColumn
- func (s SwappedTable) Indexes() DependentPairing
- func (s SwappedTable) LiveOID() uint32
- func (s SwappedTable) MarshalJSON() ([]byte, error)
- func (s SwappedTable) OldOID() uint32
- func (s SwappedTable) OldTable() string
- func (s SwappedTable) OwnedSequences() []OwnedSequence
- func (s SwappedTable) Owner() string
- func (s SwappedTable) Proof() SwapProof
- func (s SwappedTable) Schema() string
- func (s SwappedTable) Statistics() DependentPairing
- func (s SwappedTable) Table() string
- type UnvalidatedConstraint
Constants ¶
const WriteFenceSQLState = "55006"
WriteFenceSQLState is the SQLSTATE a write refused by the fence carries: object_in_use, the class of error a writer gets when a relation is busy with something else.
const WriteFenceTrigger = "pgsprite_write_fence"
WriteFenceTrigger is the name of the statement trigger a quiesced run installs on its source so that a write reaching the table while the run is in progress is refused by the server rather than lost. It is also the name of the function the trigger calls, in the engine's own schema; the preflight shape check sets that trigger aside when it counts the table's user triggers.
Variables ¶
var ( // ErrShadowExists reports that the deterministic shadow name is already // taken in the source schema: an earlier run's leftover, which a resume // verifies with InspectShadow or removes with DropShadow rather than // this builder overwriting it. ErrShadowExists = errors.New("shadow table already exists") // ErrInvariantViolation is the sentinel every shadow refusal wraps: a // forged or empty proof, a statement that does not target the proven // table, a lock the operation cannot trust, or a re-verification of the // engine's own work that failed. No operation executes anything after // raising it. The refusal itself is a *RefusalError, whose Cause says // which of those it was. ErrInvariantViolation = errors.New("invariant violation") // ErrInvalidOptions reports a timeout that cannot encode a positive // PostgreSQL setting: PostgreSQL counts timeouts in whole milliseconds, // and a nonzero value below one millisecond would round to zero, which // the server reads as no timeout at all. ErrInvalidOptions = errors.New("invalid shadow build options") )
var ErrConversionNotImmutable = errors.New("USING expression is not immutable")
ErrConversionNotImmutable is wrapped by the CauseStatementConversion refusal of a USING expression the server does not classify as IMMUTABLE: one that reads the clock, the session, or a setting, or calls a function declared STABLE or VOLATILE. The copy evaluates the expression once per row in the chunk copy, again in the verifier's recopy, and again for every image the catch-up flushes, at different times and in different sessions; only an immutable expression is guaranteed to give those evaluations the same answer for the same source value.
var ErrCutoverRolledBack = errors.New("cutover rolled back")
ErrCutoverRolledBack reports a failed swap whose source is known to be live: every attempt rolled back, so the shadow is still in place and the caller may retry Cutover. It wraps the failure itself — a lock exhaustion, a refusal, a drain error, a statement error the server answered, or a lost connection or ended context whose attempt the catalog showed rolled back. A failure that does not carry it says nothing about the source: an option or proof refused before any connection opened, an inspection that itself failed, or an ambiguous outcome. An orchestrator decides whether to retry with errors.Is(err, ErrCutoverRolledBack).
var ErrLockRetriesExhausted = errors.New("cutover lock retries exhausted")
ErrLockRetriesExhausted reports that every bounded attempt to take ACCESS EXCLUSIVE on the source timed out behind other lock holders (LK-2). The swap executed nothing; the error wraps the server's last lock_timeout refusal, so errors.As against *pgconn.PgError still reaches it.
var ErrNotDerivedName = errors.New("name is not derived from any table in the schema")
ErrNotDerivedName reports a name that no table in the schema derives, so it is not a relation this engine created or retained.
var ErrNotSwapped = errors.New("source table is still live, not swapped")
ErrNotSwapped reports that the source still bears its name: no swap committed, so there is no swapped table to inspect and the caller runs Cutover.
var ErrOldTableNotFound = errors.New("old table not found")
ErrOldTableNotFound reports that the shadow bears the source's name and the retained source no longer exists under any name: the drop already committed, so the swap is complete and there is nothing left for DropOldTable to do.
var ErrShadowNotFound = errors.New("shadow table not found")
ErrShadowNotFound reports that no relation wears the shadow's name in the source schema: there is nothing to inspect or drop.
var ErrSourceNotFound = errors.New("source table not found")
ErrSourceNotFound reports that no relation bears the source's name.
Functions ¶
func CheckPool ¶ added in v0.5.3
CheckPool refuses a pool smaller than MinPoolConns(o) with an error wrapping executor.ErrPoolTooSmall, the refusal the native route's admission gives, so a caller classifies both with one errors.Is. Run calls it before it takes the table lock; a front door that refuses earlier calls it too. A nil pool is refused with ErrInvariantViolation, since no run can proceed without one.
func DropOldTable ¶
func DropOldTable(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, swapped SwappedTable, opts Options) error
DropOldTable removes the retained source after a committed swap (D9), in one bounded transaction separate from the swap's, under SET LOCAL ROLE owner and only while the caller holds the table lock. It accepts only the SwappedTable proof Cutover or InspectSwapped minted and drops only the relation whose OID that proof recorded as the source — a different relation under the _old name is refused, not dropped. The drop is without CASCADE: the old table owns its renamed indexes and its old identity sequences, which go with it, and nothing the live table depends on. A caller that wants the old table kept for a rollback window simply does not call this.
func DropShadow ¶
func DropShadow(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, target preflight.CopySwapTarget, opts Options) error
DropShadow removes the shadow an earlier build left behind, in one bounded transaction under SET LOCAL ROLE owner and only while the caller holds the table lock, so a drop can never race a build or a copy on the same table. It drops only a plain table owned by the source's owner under the shadow's name — anything else wearing that name is not this engine's shadow and is refused (ST-5) — and it drops without CASCADE: the shadow's identity defaults depend on the source's sequences, never the other way round, so the shadow owns nothing the source needs and a cascade could only reach objects the engine did not create. A missing shadow is ErrShadowNotFound.
func DropWriteFence ¶
func DropWriteFence(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, target preflight.CopySwapTarget, opts Options) error
DropWriteFence takes the write fence off the source of a run that is being abandoned, so the table takes writes again. A run that completes needs no call: the fence goes to the retained source with the swap and is dropped with it, or taken off it under KeepOld. The drop runs in one bounded transaction and only while the caller holds the table lock, so it cannot race a run on the same table, and it refuses anything under the source's name that is not a plain table owned by the proof's owner (ST-5). A source without the fence is left as it is. The answer does not depend on the pool's session search_path: the drop's transaction searches the catalog alone, so a caller-built pool with another schema ahead of it gets the same verdict.
func IsDataFault ¶
IsDataFault reports whether err is the server rejecting the data under the statement's new shape — a fault a rerun meets again on the same rows, as opposed to a lost connection, a cancelled context, or a lock the run could take next time. It is the predicate Runner.Run abandons a stopped run on, and the one a verdict's remedy reads.
func MinPoolConns ¶ added in v0.5.3
MinPoolConns is the smallest pool Run admits for a copy sized by o: one connection per copy worker, with zero workers meaning copier.DefaultWorkers, and two beside them. Each worker holds a pool connection while it copies a chunk, so a pool of only the workers would leave a live run's catch-up flushes waiting behind the copy while the slot's lag grows. A host that builds its own pool sizes it with this (dbconn.Config.MaxConnsFloor). A worker count no pool size can hold answers math.MaxInt32 rather than wrapping to a number every pool would pass.
func NameHash ¶
NameHash is the sixteen-hex-digit FNV-1a hash of "schema.table" that keys every derived copy-and-swap name. The same source table always derives the same names, so a resumed run finds the shadow it built earlier.
func OldDependentName ¶
OldDependentName is the name an index, extended-statistics object, or identity sequence of the retained source table wears after cutover, which frees its original name for the shadow's corresponding dependent. The dependent is hashed like the table, so every derived name has one fixed width well inside PostgreSQL's identifier limit and no source name, however long, can push a derived name into server-side truncation.
func ShadowName ¶
ShadowName is the shadow table's name for a source table.
Types ¶
type AbandonedError ¶
type AbandonedError struct {
// Schema and Table name the target whose run was abandoned.
Schema, Table string
// Fault is the data fault the run stopped on.
Fault error
}
AbandonedError is the error Runner.Run returns for a run it abandoned on a data fault: the server rejected the rows as the statement would shape them (IsDataFault), so the same run would stop on the same rows however often it was resumed, and the Runner discarded it — the shadow, the hold on the source, the checkpoint row — under its own lock session before returning. Nothing of the run remains; the next Run of the statement starts from the beginning. Fault is the server's error, and Unwrap exposes it so errors.As against *pgconn.PgError still reads the SQLSTATE.
func (*AbandonedError) Error ¶
func (e *AbandonedError) Error() string
func (*AbandonedError) Unwrap ¶
func (e *AbandonedError) Unwrap() error
type BuiltShadow ¶
type BuiltShadow struct {
// contains filtered or unexported fields
}
BuiltShadow is the proof that the shadow table exists in the source schema with the gated schema change applied, introspected, and owner-correct. Its constructor is private: the copier and cutover accept only a value this builder returned.
func BuildShadow ¶
func BuildShadow(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, target preflight.CopySwapTarget, st statement.Statement, opts Options) (BuiltShadow, error)
BuildShadow creates the copy-and-swap shadow for the proven target and applies the gated ALTER TABLE to it, all in one bounded transaction under SET LOCAL ROLE owner: CREATE TABLE … LIKE INCLUDING ALL EXCLUDING IDENTITY, the identity-sequence defaults (D5), the metadata LIKE does not carry (D2), and finally the statement retargeted onto the shadow — after re-proving that the retargeted form differs from the gated one only in its target relation and that the target is the shadow (ST-7). Both models are introspected inside the same transaction, so a failure at any step leaves no shadow behind. An existing relation under the shadow's name is ErrShadowExists.
The caller holds the per-table lock (LK-1): the build runs under the lock session's Bind context, so a lost lock cancels the statement in flight, and the transaction confirms from its own connection that the lock session's backend holds the table before its first write.
func InspectShadow ¶
func InspectShadow(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, target preflight.CopySwapTarget, st statement.Statement, opts Options) (BuiltShadow, error)
InspectShadow re-derives the BuiltShadow proof for a shadow an earlier build left behind, from the catalog and the gated statement st, in one bounded read transaction under SET LOCAL ROLE owner. It is the resume path: the caller compares the returned proof's whole Proof — fingerprints, both fidelity snapshots, and conversions — with its checkpoint before trusting the shadow, since the gated statement is not recoverable from the catalog and a snapshot re-read from the catalog records the table as it is now, not as the build left it. The statement is needed for the same reason: the catalog records a retyped column's new type, not the USING expression that made it, and the copy of that column must carry the expression; the caller proves st is the row's statement before passing it. What the catalog can prove, it proves here: the source still has the proven shape (ST-6), the shadow is a table owned by the source's owner (ST-5), and every source identity column the change kept on the shadow still draws its default from the source sequence there (D5) — a shadow whose default was stripped would silently insert nulls into its key. A missing shadow is ErrShadowNotFound.
func (BuiltShadow) ConversionFingerprint ¶
func (b BuiltShadow) ConversionFingerprint() string
ConversionFingerprint is the digest of the catalog entries the conversion expressions resolve among, read in the build's transaction after the gated statement ran: every function, operator, type, and collation under a name an expression spells, in every schema on the path the copy resolves them in. Every guarded write recomputes it and refuses when it differs, so an object created, replaced, or dropped under one of those names after the build cannot change what a later chunk lands (CO-9). It is empty exactly when Conversions is.
func (BuiltShadow) Conversions ¶
func (b BuiltShadow) Conversions() map[string]string
Conversions maps each copy column the gated statement retyped with a USING clause to that clause's expression, rendered by pkg/statement; the copier selects the column as the expression so every value is converted the way the statement declared. The catalog keeps no record of a USING clause, so the proof carries it from the statement; a column the change retyped and then dropped has no entry, since the copy does not carry it.
func (BuiltShadow) CopyColumns ¶
func (b BuiltShadow) CopyColumns() []string
CopyColumns are the columns the copier moves: every non-generated source column that is still the same column on the shadow after the schema change. Generated columns are excluded because the server computes them on insert; a column the change dropped is excluded because the shadow has nowhere to put it, and so is one the change dropped and added again under the same name, which is a new column holding its own default.
func (BuiltShadow) Fidelity ¶
func (b BuiltShadow) Fidelity() FidelitySnapshot
Fidelity is the source's metadata snapshot at build time, the one the builder replicated onto the shadow; the ST-5 gate re-reads the source and refuses a source that drifted from it.
func (BuiltShadow) IdentityColumns ¶
func (b BuiltShadow) IdentityColumns() []IdentityColumn
IdentityColumns are the source identity columns cutover hands over (D5).
func (BuiltShadow) MarshalJSON ¶
func (b BuiltShadow) MarshalJSON() ([]byte, error)
MarshalJSON encodes the built shadow as its Proof, so a checkpoint can store a BuiltShadow directly. BuiltShadow has no UnmarshalJSON on purpose: decode into a Proof instead.
func (BuiltShadow) Proof ¶
func (b BuiltShadow) Proof() Proof
Proof returns the plain view of the built shadow: each field is what the accessor of the same name returns.
func (BuiltShadow) Schema ¶
func (b BuiltShadow) Schema() string
Schema is the schema holding both the source and the shadow.
func (BuiltShadow) ShadowFidelity ¶
func (b BuiltShadow) ShadowFidelity() FidelitySnapshot
ShadowFidelity is the shadow's metadata snapshot as the gated statement left it. It is kept apart from Fidelity because the statement may change metadata on purpose — a NOT VALID constraint, a storage parameter — so the ST-5 gate compares the shadow against this, not against the source.
func (BuiltShadow) ShadowOID ¶
func (b BuiltShadow) ShadowOID() uint32
ShadowOID is the shadow relation's OID as created by this build.
func (BuiltShadow) ShadowTable ¶
func (b BuiltShadow) ShadowTable() string
ShadowTable is the shadow table name.
func (BuiltShadow) SourceFingerprint ¶
func (b BuiltShadow) SourceFingerprint() string
SourceFingerprint is the digest of the source's introspected model at build time; a resume compares it to refuse a source that changed shape.
func (BuiltShadow) SourceOID ¶
func (b BuiltShadow) SourceOID() uint32
SourceOID is the source relation's OID as resolved inside the build transaction; a later stage compares it rather than re-resolving the name.
func (BuiltShadow) SourceTable ¶
func (b BuiltShadow) SourceTable() string
SourceTable is the source table name.
func (BuiltShadow) TargetFingerprint ¶
func (b BuiltShadow) TargetFingerprint() string
TargetFingerprint is the digest of the shadow's introspected model after the schema change; the checkpoint carries it so a resume can prove the shadow it finds is the one this build produced.
type CatchupWaitError ¶ added in v0.5.1
type CatchupWaitError struct {
// Schema and Table name the target whose catch-up was waited for.
Schema, Table string
// Marker is the WAL position the capture had to confirm past.
Marker decode.LSN
// Status is the catch-up's status when the wait ended.
Status applier.Status
// Err is what ended the wait: the context's error, or whatever an
// injected RunOptions.Sleep returned.
Err error
}
CatchupWaitError is the error a live run returns when the wait for the capture to confirm past a marker, written to the WAL at the start of the wait, ended before it did: the run had not caught up when the caller stopped it. Status is the catch-up's status when the wait ended, so the error says what the wait was for — a change whose transaction the source had not made visible (a commit waiting on a synchronous standby or a flush), one deferred behind an in-flight chunk or a refused batch, one held for a read the flush made, or plainly a stream behind the marker — where the bare context error could not tell a stalled source from a slow copy. Err is what ended the wait, and Unwrap exposes it, so the error still reads as the cancellation it is (errors.Is against context.Canceled or context.DeadlineExceeded). The row keeps the phase it waited in, catching up or, for a row resumed there, verifying, for the next Run to resume.
func (*CatchupWaitError) Error ¶ added in v0.5.1
func (e *CatchupWaitError) Error() string
func (*CatchupWaitError) ShortOfMarker ¶ added in v0.5.1
func (e *CatchupWaitError) ShortOfMarker() uint64
ShortOfMarker is how many WAL bytes the confirmed position trailed the marker when the wait ended. Unlike Status.Lag, which needs a completed cycle to measure the server's write position, it is known from the first moment of the wait, and it is the same quantity on every retry.
func (*CatchupWaitError) Unwrap ¶ added in v0.5.1
func (e *CatchupWaitError) Unwrap() error
type ColumnGrant ¶
type ColumnGrant struct {
// Column is the column carrying the ACL.
Column string `json:"column"`
Grant
}
ColumnGrant is one effective per-column ACL entry; its Privilege is SELECT, INSERT, UPDATE, or REFERENCES.
type ColumnStatisticsTarget ¶
type ColumnStatisticsTarget struct {
// Column is the column name.
Column string `json:"column"`
// Target is the per-column statistics target.
Target int `json:"target"`
}
ColumnStatisticsTarget is one column's explicit ALTER COLUMN … SET STATISTICS target. CREATE TABLE … LIKE INCLUDING ALL leaves every shadow column at the server default, so the builder re-applies each explicit target; a column at the default is not recorded.
type CutoverOptions ¶
type CutoverOptions struct {
Options
// LockAttempts is how many times the swap tries to take ACCESS
// EXCLUSIVE before giving up (LK-2). Zero means the default.
LockAttempts int
// LockBackoff is the wait after the first failed attempt; each later
// wait is one step longer. Zero means the default.
LockBackoff time.Duration
// Sleep waits between attempts, and between polls of the catalog while
// a lost attempt's backend is followed to its exit; nil waits on the
// wall clock. Tests inject one to drive the retry loop without real
// time passing.
Sleep func(ctx context.Context, d time.Duration) error
// contains filtered or unexported fields
}
CutoverOptions bounds the swap transaction and the ACCESS EXCLUSIVE acquisition that opens it. Zero values take the defaults; Options bounds every lock wait and statement inside the transaction as it does for the other shadow operations.
type CutoverReady ¶
type CutoverReady struct {
// contains filtered or unexported fields
}
CutoverReady is the proof that the shadow may be swapped in: the data proof (CO-1) and the ST-5 fidelity checklist both held against the live catalog, and the facts the swap itself needs — which shadow dependent takes which source name (D8) and which sequences change owner (D5) — were read in the same transaction. Its constructor is private: only GateCutover mints one, and the cutover accepts nothing else.
func GateCutover ¶
func GateCutover(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, built BuiltShadow, verified checksum.VerifiedShadow, opts Options) (CutoverReady, error)
GateCutover runs the ST-5 checklist against the live catalog, in one bounded read-only transaction under SET LOCAL ROLE owner, and mints the CutoverReady proof when every item holds. It refuses, fail-closed, when: the verified-shadow proof is missing, names other relations, or stops short of the whole key space; the source or the shadow is no longer the relation the build proved; a shadow index is invalid; either table's introspected model or metadata snapshot drifted from what the build recorded; a shadow identity column no longer draws from the source's sequence; or a name the swap must assign is already taken. It executes nothing and holds no lock beyond the per-table session; the cutover re-runs the same checklist inside its own transaction, under ACCESS EXCLUSIVE, before the first rename.
The caller holds the per-table lock (LK-1): the gate runs under the lock session's Bind context, and its transaction confirms from its own connection that the lock session's backend holds the table.
func (CutoverReady) Built ¶
func (r CutoverReady) Built() BuiltShadow
Built is the shadow proof the gate held against the catalog.
func (CutoverReady) Indexes ¶
func (r CutoverReady) Indexes() DependentPairing
Indexes pairs the source's indexes with the shadow's by definition.
func (CutoverReady) OwnedSequences ¶
func (r CutoverReady) OwnedSequences() []OwnedSequence
OwnedSequences are the sequences the source's columns own, which cutover re-owns to the live table.
func (CutoverReady) Statistics ¶
func (r CutoverReady) Statistics() DependentPairing
Statistics pairs the source's extended-statistics objects with the shadow's by definition.
func (CutoverReady) Verified ¶
func (r CutoverReady) Verified() checksum.VerifiedShadow
Verified is the data-equality proof the gate accepted.
type DependentKind ¶
type DependentKind string
DependentKind says which kind of table dependent a pairing describes.
const ( // DependentIndex is an index, constraint-backed or not. DependentIndex DependentKind = "index" // DependentStatistics is an extended-statistics object. DependentStatistics DependentKind = "statistics" )
type DependentPair ¶
type DependentPair struct {
// Kind is the dependent's kind.
Kind DependentKind `json:"kind"`
// SourceName is the name the source dependent holds, which the shadow
// dependent takes after the swap.
SourceName string `json:"source_name"`
// ShadowName is the name the shadow dependent holds before the swap.
// It is empty in a pairing re-derived after the swap: the shadow
// dependent bears SourceName by then, and the catalog does not keep
// the name it gave up.
ShadowName string `json:"shadow_name"`
}
DependentPair is one source dependent and the shadow dependent that cutover renames to its name (D8). The two are paired by definition, never by name: LIKE derives every shadow dependent's name from the shadow's.
type DependentPairing ¶
type DependentPairing struct {
// Pairs are the dependents cutover renames, in source-name order.
Pairs []DependentPair `json:"pairs"`
// UnpairedSource are the source dependents no shadow dependent matches.
UnpairedSource []string `json:"unpaired_source"`
// UnpairedShadow are the shadow dependents no source dependent matches.
UnpairedShadow []string `json:"unpaired_shadow"`
}
DependentPairing is the outcome of pairing one kind of dependent between the source and its shadow. A dependent without a partner is not a fault: the gated statement may have dropped a source index's column or added an index of its own. Cutover renames only the pairs; an unpaired shadow dependent keeps its shadow-derived name, and an unpaired source dependent ends with the old table.
type DerivedKind ¶
type DerivedKind string
DerivedKind says which derived name a source table produced.
const ( // DerivedShadow is the shadow table built for a source table. DerivedShadow DerivedKind = "shadow" // DerivedOld is the source table retained under its post-cutover name. DerivedOld DerivedKind = "old" )
func SourceOfDerivedName ¶
func SourceOfDerivedName(ctx context.Context, db dbconn.Querier, schema, derived string) (string, DerivedKind, error)
SourceOfDerivedName maps a relation name the engine derived back to the table it was derived from: the hash has no inverse, but a derived relation always lives in its source's schema, so the source is whichever table in that schema derives the name. It returns ErrNotDerivedName when none does. The answer does not depend on db's session search_path: a caller-built pool with another schema ahead of the catalog gets the same source.
type DrainFunc ¶
DrainFunc flushes every captured change through the final WAL position into the shadow, inside the swap transaction and after ACCESS EXCLUSIVE on the source has excluded every writer, so no row can change after the drain and before the rename. The transaction is bounded by the swap's options and runs as the table's owner. A nil DrainFunc drains nothing: a quiesced table, or a caller that has already applied the final position and verified the shadow with a quiesced pass since. A proof a live pass minted (checksum.VerifiedShadow.Live) is refused without a drain, since the stream still carries the changes the proof does not cover.
The drain runs once per attempt. An attempt can still fail after the drain — a lock wait later in the transaction times out, say — and that rolls back everything the drain applied; the next attempt calls the drain again against a shadow holding none of the previous run's work. Derive what to apply from durable state (the captured changes and the position they end at), never from what an earlier call consumed.
type ExtendedStatisticsTarget ¶
type ExtendedStatisticsTarget struct {
// Name is the statistics object's unqualified name.
Name string `json:"name"`
// Target is the object's statistics target.
Target int `json:"target"`
}
ExtendedStatisticsTarget is one extended-statistics object's explicit ALTER STATISTICS … SET STATISTICS target. CREATE TABLE … LIKE INCLUDING ALL copies the object but leaves the copy at the server default, so the builder re-applies each explicit target; an object at the default is not recorded.
type FidelitySnapshot ¶
type FidelitySnapshot struct {
// Owner is the catalog owner of the table.
Owner string `json:"owner"`
// ReplicaIdentity is pg_class.relreplident: 'd' for DEFAULT, 'f' for FULL.
ReplicaIdentity string `json:"replica_identity"`
// RLSEnabled and RLSForced are the row-level-security switches.
RLSEnabled bool `json:"rls_enabled"`
// RLSForced reports FORCE ROW LEVEL SECURITY.
RLSForced bool `json:"rls_forced"`
// Comment is the table comment, empty when none.
Comment string `json:"comment"`
// Tablespace is the table's own tablespace, empty when it lives in the
// database default. LIKE places the shadow in the default tablespace
// whatever the source uses; the builder moves the still-empty shadow.
Tablespace string `json:"tablespace"`
// RelOptions are the table's storage parameters as the server prints
// them, with the TOAST relation's parameters prefixed "toast.".
RelOptions []string `json:"rel_options"`
// Grants are the table's effective privileges, expanded from its ACL
// (or from the owner's default ACL when none is stored): one entry per
// privilege and grantee, grantable when any grantor made it so.
Grants []Grant `json:"grants"`
// ColumnGrants are the effective privileges granted on individual
// columns.
ColumnGrants []ColumnGrant `json:"column_grants"`
// Policies are the table's row-level-security policies.
Policies []Policy `json:"policies"`
// UnvalidatedChecks are the CHECK constraints the user left NOT VALID.
// LIKE copies them as validated; the builder re-adds them NOT VALID so
// the copier accepts every row the source legally holds.
UnvalidatedChecks []UnvalidatedConstraint `json:"unvalidated_checks"`
// ColumnStatisticsTargets are the columns with an explicit SET
// STATISTICS target, which LIKE resets to the default.
ColumnStatisticsTargets []ColumnStatisticsTarget `json:"column_statistics_targets"`
// ExtendedStatisticsTargets are the extended-statistics objects with an
// explicit SET STATISTICS target, which LIKE leaves at the default on
// the copies it makes.
ExtendedStatisticsTargets []ExtendedStatisticsTarget `json:"extended_statistics_targets"`
}
FidelitySnapshot is the table metadata that CREATE TABLE … LIKE INCLUDING ALL does not carry and the shadow builder therefore replicates itself: the ST-5 checklist minus the data-side facts (sequence positions, index validity) that only exist once rows have been copied. The build records one snapshot per table — the source's before the shadow was made, and the shadow's as the gated statement left it, which legitimately differs where the statement changed metadata on purpose. The cutover gate re-reads each table's snapshot and refuses to swap when either drifted from its record; it compares the two tables with each other only on the facts the gated statement cannot change.
type Grant ¶
type Grant struct {
// Privilege is the privilege keyword as aclexplode reports it.
Privilege string `json:"privilege"`
// Grantee is the role name; empty when Public is set.
Grantee string `json:"grantee"`
// Public reports the PUBLIC pseudo-role (grantee OID 0). It is carried
// as a fact of its own because a real role may be named "PUBLIC": the
// server reserves only the folded spelling "public".
Public bool `json:"public"`
// Grantable reports WITH GRANT OPTION.
Grantable bool `json:"grantable"`
}
Grant is one effective ACL entry.
type IdentityColumn ¶
type IdentityColumn struct {
// Column is the column name.
Column string `json:"column"`
// Always reports GENERATED ALWAYS (false is GENERATED BY DEFAULT).
Always bool `json:"always"`
// SequenceSchema and SequenceName locate the source identity sequence.
SequenceSchema string `json:"sequence_schema"`
// SequenceName is the sequence's unqualified name.
SequenceName string `json:"sequence_name"`
// Options are the sequence's declared options.
Options SequenceOptions `json:"options"`
}
IdentityColumn records one source identity column and the sequence behind it. The shadow carries the column as a plain column with DEFAULT nextval(<source sequence>), so source and shadow draw from one sequence during copy and apply; cutover uses these facts to recreate the identity on the live table with the source sequence's options.
type Options ¶
type Options struct {
// LockTimeout bounds every lock wait inside the build transaction.
LockTimeout time.Duration
// StatementTimeout bounds every statement inside the build transaction.
StatementTimeout time.Duration
}
Options bounds the shadow build transaction. Zero values take the dbconn session defaults, so a caller that passes Options{} still gets bounded waits (LK-2); any other value must be at least one millisecond.
type OwnedSequence ¶
type OwnedSequence struct {
// Column is the owning source column.
Column string `json:"column"`
// SequenceSchema is the sequence's schema.
SequenceSchema string `json:"sequence_schema"`
// SequenceName is the sequence's unqualified name.
SequenceName string `json:"sequence_name"`
}
OwnedSequence is one sequence a source column owns through OWNED BY — a serial column's, or one the user attached by hand. LIKE … INCLUDING DEFAULTS makes the shadow column draw from the same sequence, which keeps its name; cutover re-owns it to the live table so it survives the old table's drop (D5). Identity sequences are not among these: they depend on their column internally and are handed off through IdentityColumn.
type Policy ¶
type Policy struct {
// Name is the policy name.
Name string `json:"name"`
// Permissive reports AS PERMISSIVE (false is AS RESTRICTIVE).
Permissive bool `json:"permissive"`
// Command is the pg_policy.polcmd code: '*', 'r', 'a', 'w', or 'd'.
Command string `json:"command"`
// Roles are the real role names the policy applies to.
Roles []string `json:"roles"`
// AppliesToPublic reports TO PUBLIC, which the server stores as the
// single pseudo-role OID 0 in place of any role list.
AppliesToPublic bool `json:"applies_to_public"`
// Using is the decompiled USING expression, empty when none.
Using string `json:"using"`
// WithCheck is the decompiled WITH CHECK expression, empty when none.
WithCheck string `json:"with_check"`
}
Policy is one row-level-security policy.
type Proof ¶
type Proof struct {
// Schema is the schema holding both the source and the shadow.
Schema string `json:"schema"`
// SourceTable is the source table name.
SourceTable string `json:"source_table"`
// ShadowTable is the shadow table name.
ShadowTable string `json:"shadow_table"`
// SourceOID is the source relation's OID as resolved inside the build.
SourceOID uint32 `json:"source_oid"`
// ShadowOID is the shadow relation's OID as created by the build.
ShadowOID uint32 `json:"shadow_oid"`
// SourceFingerprint is the digest of the source's introspected model.
SourceFingerprint string `json:"source_fingerprint"`
// TargetFingerprint is the digest of the shadow's introspected model.
TargetFingerprint string `json:"target_fingerprint"`
// IdentityColumns are the source identity columns cutover hands over.
IdentityColumns []IdentityColumn `json:"identity_columns"`
// Fidelity is the source's metadata snapshot at build time.
Fidelity FidelitySnapshot `json:"fidelity"`
// ShadowFidelity is the shadow's metadata snapshot as the gated
// statement left it.
ShadowFidelity FidelitySnapshot `json:"shadow_fidelity"`
// CopyColumns are the columns the copier moves.
CopyColumns []string `json:"copy_columns"`
// Conversions are the USING expressions the copier converts retyped
// copy columns with, by column; absent when the change retypes none.
Conversions map[string]string `json:"conversions,omitempty"`
// ConversionFingerprint is the digest of the catalog entries the
// conversion expressions resolve among, as the build read them; absent
// exactly when Conversions is.
ConversionFingerprint string `json:"conversion_fingerprint,omitempty"`
}
Proof is the plain view of a BuiltShadow: the same facts as its accessors, as exported fields a checkpoint can encode and decode. A resume decodes the checkpoint it kept into a Proof and compares it with the Proof of what InspectShadow returned; the two are equal exactly when the shadow the inspection found is the one the build produced, since every field is derived from the catalog the same way on both paths. Proof is a view only: nothing turns it back into a BuiltShadow, so the copier and cutover still accept only a value the builder or the inspection returned.
type Reconciled ¶
type Reconciled struct {
// Slot is the new slot with its replication connection still open, as
// CreateSlot returns it; the caller opens its stream at
// Slot.ConsistentPoint() and closes it.
Slot *decode.Slot
// Checkpoint is the row after the reconcile: the phase the watermark
// implies, the new slot's name, and its consistent point as the last
// applied position.
Checkpoint checkpoint.Checkpoint
// Outcome is the recopy pass's report and the chunks it recopied.
Outcome checksum.Outcome
}
Reconciled is what a completed reconcile hands back: the slot change capture resumes from, the checkpoint row as it now stands, and the recopy pass's outcome — the zero Outcome when nothing had landed to recopy.
type Reconciler ¶
type Reconciler struct {
// contains filtered or unexported fields
}
Reconciler is reconcile mode (ST-4): the recovery for a run whose replication slot is gone or lost, keeping the shadow and the copier's watermark and replacing only what the slot carried. One Reconciler serves one built shadow; its verifier is built up front, and the options its clear of the shadow runs under are validated then, so a reconcile never starts with options that cannot run a pass.
func NewReconciler ¶
func NewReconciler(cfg dbconn.Config, lock *dbconn.TableLockSession, store *checkpoint.Store, target preflight.CopySwapTarget, shadow BuiltShadow, opts checksum.Options) (*Reconciler, error)
NewReconciler prepares reconcile mode for target and its built shadow, under the table's lock session, writing the checkpoint row through store. opts bound the recopy pass as they bound any verification pass.
func (*Reconciler) Reconcile ¶
func (r *Reconciler) Reconcile(ctx context.Context, pool *pgxpool.Pool, cp checkpoint.Checkpoint) (Reconciled, error)
Reconcile recovers from slot loss for the run cp records, in an order a crash at any point leaves restartable from the top:
- The source and shadow are confirmed to be the relations the built shadow proved, so a row whose tables have been swapped or replaced under their names is refused before anything is written.
- When anything has landed, the shadow is cleared above the row's watermark, as the copier that resumes from it would clear it first (CO-4): the rows the earlier run's unlanded chunks committed there lie outside the pass that follows, and one still holding a unique value the source has since moved into a chunk the pass recopies would collide with every recopy of it, with no comparison through the watermark able to clear the collision. A complete watermark has nothing above it. The clear runs before any slot command, so a new slot retains WAL only while the pass runs; a crash after it leaves the row in its earlier phase, and clearing again is harmless.
- The row is saved in PhaseReconciling, naming the slot the reconcile will own under the target's derived name, so a resume that finds it reconciles again rather than trusting whatever slot it finds, and the reaper sees the slot as the row's.
- The slot under the derived name is dropped — a slot already gone is success, a half-made one from an earlier attempt goes too.
- A new slot is created under the same name. Every change committed after its consistent point replays when the stream is reopened.
- Then one recopy pass runs through the row's watermark under checksum.DivergenceRecopy: every chunk that differs is recopied from the source, which is where the changes the lost slot never delivered are, and is not read again. The source keeps taking writes throughout; a write that lands in a chunk after its recopy is behind the new slot's consistent point and replays when the stream reopens, so the pass has nothing to prove about it. A unique value the source moves from a chunk the pass read equal into a differing chunk, between the comparison and the recopy, makes the recopy collide with the shadow row still holding it; the pass then compares again and recopies both chunks, a bounded number of times.
- The row is saved out of PhaseReconciling: PhaseCatchingUp when the watermark is complete, PhaseCopying when the copier still has keys to land, with the new slot's consistent point as the last applied position.
The lost slot is read nowhere: whether the catalog shows it gone, lost, or intact under the name, the row said reconcile and that is what runs. A row in a terminal or cutover phase, or one that does not describe this target and shadow, is refused. On an error the slot the attempt created, if any, stays under the row's name, so the reaper leaves it for the next attempt to drop, and the row stays in PhaseReconciling for that attempt. The clear can end an attempt before any slot command, with the copier's own refusals (a lost lock, a replaced relation, conversion drift) or with an untyped lock timeout when a writer still holds the shadow past lock_timeout; either leaves the row and the watermark as they were, and a later attempt clears again. Retry the timeout.
The whole sequence runs under the lock session's context: a lock lost at any point cancels the statement in flight — a drop still waiting out the lost slot's holder included — before the next slot command is issued, and is reported as shadow-lock-lost, so a session that has lost the table never drops, or makes, a slot that a run holding the lock since may own.
type RefusalCause ¶
type RefusalCause string
RefusalCause identifies why a shadow operation refused to proceed. Every cause is a fail-closed refusal under ErrInvariantViolation; the cause is what tells an importer which way to react — re-acquire the lock, clean up a relation the engine does not own, drop and rebuild, or report a bug — without matching on the message text, which carries schema, role, sequence, and backend names an importer must not render verbatim.
const ( // CauseLockUnproven means the operation was handed no table lock // session, or one whose proof is empty or names a different table // (LK-1). It is a caller error, refused before any connection opens. CauseLockUnproven RefusalCause = "shadow-lock-unproven" // CauseLockLost means the table lock session reported that it lost the // lock, either before the operation began or while it ran (LK-1). The // operation's transaction is aborted; the caller re-acquires the lock // and repeats the operation. CauseLockLost RefusalCause = "shadow-lock-lost" // CauseLockHeldElsewhere means pg_locks shows the table lock granted to // a backend other than the lock session's own (LK-1): another engine // instance holds the table, and the session this operation trusts does // not. CauseLockHeldElsewhere RefusalCause = "shadow-lock-held-elsewhere" // CauseLockUnconfirmed means pg_locks shows no session holding the // table lock, although the lock session has not reported loss (LK-1). CauseLockUnconfirmed RefusalCause = "shadow-lock-unconfirmed" // CauseProofEmpty means the copy-and-swap target proof is the zero value // (ST-6): only the shape check mints a populated one. CauseProofEmpty RefusalCause = "shadow-proof-empty" // CauseSourceShape means the source's catalog is outside the shape the // proof admits in a way the shape check does not decide: an identity // column without an internally owned sequence, or a replica identity // other than DEFAULT or FULL (ST-6). CauseSourceShape RefusalCause = "shadow-source-shape" // CauseStatementTarget means the gated statement is not an ALTER TABLE // on the proven table, or its retargeted form does not match it in // every operation and name the shadow (ST-7). CauseStatementTarget RefusalCause = "shadow-statement-target" // CauseStatementConversion means the gated statement retypes a column // with a USING expression the copy cannot carry as written (ST-7): the // deparser cannot prove it rendered the expression faithfully, the // expression reads a column other than the one it retypes, the // statement retypes the same column twice, the expression converts // the primary key, whose values the copy's chunk ranges, watermark, and // resume clear are expressed in, or the server does not classify the // expression as immutable, so its evaluations in the copy, the recopy, // and the catch-up need not agree. The statement's own sentinel, or // ErrConversionNotImmutable, is wrapped for errors.Is. CauseStatementConversion RefusalCause = "shadow-statement-conversion" // CauseShadowOwner means the shadow the build just created is not owned // by the source's owner (ST-5): the role the proof carries is no longer // the owner the catalog reports, so the proof is stale. CauseShadowOwner RefusalCause = "shadow-owner-mismatch" // CauseForeignRelation means the relation wearing the shadow's name is // not a plain table owned by the source's owner (ST-5): it is not a // shadow this engine built, and neither inspection nor drop may treat // it as one. CauseForeignRelation RefusalCause = "shadow-foreign-relation" // CauseGrantsDiffer means the shadow's grants still differ from the // source's after the build synchronised them (ST-5). CauseGrantsDiffer RefusalCause = "shadow-grants-differ" // CauseIdentityHandoff means a source identity column the change kept on // the shadow does not carry DEFAULT nextval(<source sequence>) there // (ST-5): at build, the gated statement altered the column; at // inspection, the shadow was altered since the build. CauseIdentityHandoff RefusalCause = "shadow-identity-handoff" // CauseStatementReadd means the gated statement drops a column and // adds one under the same name that the copy cannot fill (ST-11): the // re-added column is a new column the copy leaves out, and it is the // primary key every chunk is keyed on, a column that refuses NULL with // no default of its own or its domain's for the copied rows to take, or // the replacement of a source identity column whose sequence the // handoff cannot carry to it. CauseStatementReadd RefusalCause = "shadow-statement-readd" // CauseStatementNewColumn means the gated statement leaves the shadow // with a column the copy cannot fill, or without the column the copy // is keyed on (ST-11): a new column — added beside the other changes, // not re-added under a dropped column's name — that refuses NULL with // no default of its own or its domain's for the copied rows to take, or // a primary key dropped outright or replaced under a new name, so that // no chunk range or streamed change can name it on the shadow. CauseStatementNewColumn RefusalCause = "shadow-statement-new-column" // CauseStatementNewSequence means the gated statement gives the shadow // an identity or sequence-owned column the source does not have — an // added identity or serial column, or a kept column made an identity // (ST-6): the swap hands the live table exactly the source's sequences // and identity columns, so a sequence the statement minted would copy // every row and then stop at the swap; the build refuses it before any // shadow exists. CauseStatementNewSequence RefusalCause = "shadow-statement-new-sequence" // CauseCutoverUnverified means the cutover gate was handed no usable // data-equality proof (CO-1): the built-shadow proof or the verified // shadow proof is empty, the two name different relations, or the // verified watermark does not cover the whole key space. CauseCutoverUnverified RefusalCause = "cutover-unverified" // CauseCutoverUndrained means the cutover was handed a verified shadow // proof a live pass minted — the shadow equal to the source as of a // position the stream had reached, with every change since still in // the stream — and no drain to apply those changes under the swap lock // (CO-1). CauseCutoverUndrained RefusalCause = "cutover-undrained" // CauseCutoverUnfenced means the swap of a quiesced proof found the // source without the engine's write fence enabled ALWAYS under the // swap lock (CO-1): the trigger was disabled, dropped, or replaced by // one of another shape since it was installed, so a write may have // reached the source after the pass that proved the shadow equal to // it. CauseCutoverUnfenced RefusalCause = "cutover-unfenced" // CauseDrainDeferred means the shadow refused a batch the swap's drain // had to apply under the swap lock (CO-6): a unique-key move the // changes since the live pass cannot be ordered into the shadow. No // copy is left to change the outcome, so the schema change cannot // converge and the swap is rolled back. CauseDrainDeferred RefusalCause = "cutover-drain-deferred" // CauseRelationReplaced means the source or the shadow under its name // is no longer the relation the build proved (ST-6): the OID moved, so // the proof describes a table that no longer exists. CauseRelationReplaced RefusalCause = "cutover-relation-replaced" // CauseSchemaDrift means the source's or the shadow's introspected model // no longer matches the fingerprint the build recorded (ST-5): a // column, constraint, index, storage parameter, or column-owned // sequence declaration was added, dropped, or changed since. CauseSchemaDrift RefusalCause = "cutover-schema-drift" // CauseFidelityDrift means the source's or the shadow's metadata — owner, // grants, policies, comment, replica identity, statistics targets, // unvalidated checks, or identity columns and their sequences — // no longer matches the snapshot the build recorded (ST-5). CauseFidelityDrift RefusalCause = "cutover-fidelity-drift" // CauseIndexInvalid means a shadow index has pg_index.indisvalid false // (ST-5): swapping it in would put an index the planner never uses // under the user's name. CauseIndexInvalid RefusalCause = "cutover-index-invalid" // CauseNameTaken means a name cutover must assign is already worn // (D8): a derived _old name by a relation or statistics object in the // schema, or a source dependent's name by a shadow constraint that is // not the one being renamed to it. CauseNameTaken RefusalCause = "cutover-name-taken" // CauseSwapMismatch means the catalog, re-read inside the swap // transaction after the renames and handoffs, does not show what the // swap set out to produce — the shadow under the source's name, the // source under its _old name, a paired dependent under its new name, // or the live table's sequences and identities as the source had them // (ST-6). The transaction is rolled back and nothing is swapped. CauseSwapMismatch RefusalCause = "cutover-swap-mismatch" // CauseOutcomeAmbiguous means that after a failed swap attempt the // source's name is borne by neither the source nor the shadow (LK-4): // the catalog cannot say whether the swap committed, so the engine // stops rather than retry or report either outcome. CauseOutcomeAmbiguous RefusalCause = "cutover-outcome-ambiguous" // CauseResumeTerminal means the checkpoint row handed to a resume is in // a terminal phase (ST-4): the run it records is done or failed, so // there is nothing to resume or reconcile. CauseResumeTerminal RefusalCause = "resume-row-terminal" // CauseResumeCutover means the checkpoint row handed to a resume is in // the cutover phase (LK-4): a swap was attempted, and whether it // committed is read from the catalog by InspectSwapped, never assumed. // Neither a clean resume nor a reconcile acts on the row until the // caller has that answer; a swap the catalog shows rolled back is a // run back before its cutover, and the caller writes the row there. CauseResumeCutover RefusalCause = "resume-row-cutover" // CauseRestartSwapCommitted means a Run asked to start over // (RunOptions.Restart) met a cutover row whose swap the catalog shows // committed (LK-4): the shadow already bears the source's name, so // there is nothing to discard and the change is past the point of // starting over. The row is left as found for a Run without the // restart to finish. CauseRestartSwapCommitted RefusalCause = "restart-swap-committed" // CauseResumeRowMismatch means the checkpoint row handed to a resume // does not describe the proven target and built shadow (ST-2): it is // keyed on another table, names another shadow or slot, or carries the // fingerprints of another statement. CauseResumeRowMismatch RefusalCause = "resume-row-mismatch" // CauseResumeRowDecoding means the checkpoint row handed to a resume // was written by the other kind of run (ST-3): the quiesced runner was // handed a row that names a slot or publication, or is in a phase only // a run that decodes WAL enters; or the live runner was handed a row // that names no slot. Continuing a decoding row without its slot would // leave the slot as nobody's and the changes it carried unapplied, and // a quiesced row names no position a stream could start from, so the // row is refused either way. CauseResumeRowDecoding RefusalCause = "resume-row-decoding" // CauseShadowUnrecorded means a relation already bears the target's // derived shadow name while no checkpoint row records a run for the // target (ST-2). The row is the only record of which statement a shadow // embodies; without one the shadow is dropped and the run started over. CauseShadowUnrecorded RefusalCause = "shadow-unrecorded" // CauseResumeShadowGone means the checkpoint row handed to a resume // records a shadow under which no relation stands (ST-2): the row's // swap has not committed — it is in copying, catching_up, reconciling, // verifying, or a cutover whose swap rolled back — so the shadow it // names should be there, and the run can neither continue on it nor // start over on its own while the row stands. Nothing is written: the // row, and the slot a live row names, are left for the operator to // drop and delete, or for a restart (RunOptions.Restart) to discard; // ErrShadowNotFound is wrapped for errors.Is. CauseResumeShadowGone RefusalCause = "resume-shadow-gone" // CauseResumeSlotForeign means the slot wearing the row's derived name // is not this route's (ST-3): it is a physical slot, or a logical slot // of another database. It is neither decoded from nor replaced; an // operator renames or drops it. CauseResumeSlotForeign RefusalCause = "resume-slot-foreign" // CauseResumeSlotHeld means the row's slot is intact but another // backend holds it (ST-4), so no stream can be opened on it now. The // holder is named; a walsender of this engine's earlier process lets go // within wal_sender_timeout of losing its client, and the resume is // inspected again after it. CauseResumeSlotHeld RefusalCause = "resume-slot-held" // CauseCopyShadowMismatch means the shadow the Runner handed its copier // does not describe a copy into the proven target's shadow (ST-6): the // built-shadow proof is empty, names another table or the source // itself, lacks the relation OIDs, or its copy columns do not carry the // primary key. It re-mints the copier's copy-shadow-mismatch. CauseCopyShadowMismatch RefusalCause = "copy-shadow-mismatch" // CauseCopyConversionDrift means the catalog entries the conversion // expressions resolve among changed under the copy (CO-9): a function, // operator, type, or collation under a name an expression spells was // created, replaced, or dropped in a schema on the copy's search_path // after the shadow build. It re-mints the copier's // copy-conversion-drift and the drift the verifier's reads and the // flusher's writes refuse on during verification and catch-up, and a // resume mints it for a row whose proof differs from the one the // inspection re-derives in its conversion fingerprint alone. CauseCopyConversionDrift RefusalCause = "copy-conversion-drift" // CauseCopyFrontierBroken means the copier's own accounting of the key // space broke (CO-4): a chunk was cut or claimed out of order, or the // copy returned without error at a watermark short of the key space. // It re-mints the copier's copy-frontier-broken. CauseCopyFrontierBroken RefusalCause = "copy-frontier-broken" // CauseCopyChunksInFlight means the copier's ledger and its workers // disagreed about what landed (LK-3): a worker landed a chunk the // ledger had not in flight, or the copy stopped without error with // chunks still in flight. It re-mints the copier's // copy-chunks-in-flight. CauseCopyChunksInFlight RefusalCause = "copy-chunks-in-flight" // CauseCopyChunkUnknown means a chunk no chunker cut was fed back to // the copier's chunker as if it had been copied (ST-6). It re-mints the // copier's copy-chunk-unknown. CauseCopyChunkUnknown RefusalCause = "copy-chunk-unknown" )
func RefusalCauseOf ¶
func RefusalCauseOf(err error) RefusalCause
RefusalCauseOf returns the shadow refusal cause carried by err, or the empty cause when err is nil or carries no shadow refusal. Wrappers are read through, so a copier refusal the Runner re-minted answers its shadow cause here and its copier cause to copier.RefusalCauseOf. RefusalCauseOf(err).Class() is therefore the refusal's class, and the empty class for an error that is not a shadow refusal — a server error the importer routes by SQLSTATE, or the bare sentinel.
func RefusalCauses ¶
func RefusalCauses() []RefusalCause
RefusalCauses returns the closed set of shadow refusal causes, so documentation and importers can enumerate them instead of maintaining their own list.
func (RefusalCause) Class ¶
func (c RefusalCause) Class() refusal.Class
Class is the routing class of the cause, from docs/refusal-classes.md: what kind of boundary the importer is looking at. A cause that describes a lock, a proof, a relation, a slot, or a row whose state moved under the operation is environmental — state outside the engine stopped a supportable change. A statement the engine declines to carry as written — a conversion the copy cannot reproduce, a re-added or new column it cannot fill, a new identity or sequence the swap cannot carry — is a capability boundary. Every other cause is an invariant violation: an input the caller handed in that cannot have come from this engine, or a write of the engine's own that the catalog does not show; nothing on the server changes that, so the importer reports it. The class is a triage decision; the cause's row in the document decides what the importer does next — re-acquire, re-run preflight, drop and rebuild, or hand the catalog to an operator — and no class licenses an automatic retry on its own: an ambiguous cutover outcome is environmental and is resolved by inspection, never by running the swap again. An unknown cause has no class.
func (RefusalCause) Invariant ¶
func (c RefusalCause) Invariant() string
Invariant is the identifier, from docs/invariants.md, of the invariant the cause upholds.
type RefusalError ¶
type RefusalError struct {
// Cause is the refusal cause.
Cause RefusalCause
// Detail is the catalog or session fact behind the cause.
Detail string
// contains filtered or unexported fields
}
RefusalError is a shadow operation's fail-closed refusal. It wraps ErrInvariantViolation, so errors.Is against that sentinel keeps working, and any error behind the refusal — the lock session's loss, the statement the cancelled context interrupted — so errors.Is against those works too. Detail names the catalog fact that decided the refusal; identifiers in it appear unquoted, so a renderer embedding it in structured output owns escaping it.
func (*RefusalError) Error ¶
func (e *RefusalError) Error() string
Error implements the error interface.
func (*RefusalError) Unwrap ¶
func (e *RefusalError) Unwrap() []error
Unwrap exposes ErrInvariantViolation and every wrapped error to errors.Is and errors.As.
type Result ¶
type Result struct {
// Checkpoint is the row as the run saved it last, in PhaseDone. It is
// the row as written, not as read back: UpdatedAt, which the store
// stamps from its own clock at the write, is zero here and is read
// with Store.Inspect.
Checkpoint checkpoint.Checkpoint
// Shadow is the proof of the shadow the run built or resumed on.
Shadow Proof
// Swapped is the proof of the committed swap, made by this run's
// cutover or re-derived from the catalog on resume. It is the zero
// SwapProof when the run resumed after the retained source was already
// dropped: the renames the swap performed cannot be read back once
// one side of them is gone, and Shadow still names the live table.
// SwapProven says which of the two Swapped is.
Swapped SwapProof
// SwapProven reports whether Swapped is a proof this run made or
// re-derived. It is false only when the run resumed after the retained
// source was already dropped, so a reader does not compare Swapped
// against the zero value to learn that; the swap itself committed in
// every run that returns. False does not mean the swap is in doubt.
// Run returns the zero Result with an error from a stopped run, so the
// field is read only when Checkpoint stands in PhaseDone.
SwapProven bool
// Verification is the report of the verification pass this run made,
// or the zero Report when the run resumed after the swap had already
// committed and so made none.
Verification checksum.Report
// OldTableDropped reports whether the retained source is gone when the
// run returns: dropped by this run, or found already dropped by the
// run that was resumed. It is false under KeepOld.
OldTableDropped bool
// Reconciled reports whether the run found its slot gone when it
// resumed and replaced it in reconcile mode (ST-4) before its stream
// reopened; Reconciliation is then the recopy pass's outcome, the zero
// Outcome when nothing had landed to recopy.
Reconciled bool
Reconciliation checksum.Outcome
}
Result is what a completed run hands back.
type Resume ¶
type Resume struct {
Mode ResumeMode
// Lost is why the row's slot cannot be decoded from, when that is what
// decided the mode: the slot no longer exists, or the server reports
// it lost, with the server's cause when it gives one. It is nil for a
// clean resume, and for a row already in PhaseReconciling, whose slot
// is not to be trusted whatever the catalog says of it.
Lost *decode.SlotLostError
// Slot is the row's slot as the catalog has it, when Found.
Slot decode.SlotStatus
Found bool
}
Resume is InspectResume's reading of a checkpoint row against the catalog: the mode, and the slot state that decided it. What decided the mode is readable from the fields:
Mode Lost Found Slot the row's slot ResumeClean nil false zero none to read: the target does not decode WAL ResumeClean nil true as read present, served, and held by nobody ResumeReconcile nil either as read the row is already reconciling, whatever the catalog shows ResumeReconcile non-nil false zero the row names no slot, or no slot of the name exists ResumeReconcile non-nil true as read the server reports the slot lost
func InspectResume ¶
func InspectResume(ctx context.Context, pool *pgxpool.Pool, target preflight.CopySwapTarget, cp checkpoint.Checkpoint) (Resume, error)
InspectResume decides how a run resumes from a checkpoint row for target. A target that does not decode WAL has no slot to lose and always resumes clean. Otherwise a row in PhaseReconciling is reconciled again from the top: the phase is written before the lost slot is dropped, so the row says a reconcile started and nothing says it finished, whatever slot the catalog shows under the name. Any other row's slot is read on pool: a slot that no longer exists or that the server reports lost means reconcile, with the server's verdict in Lost; a slot the server still serves and nothing holds means a clean resume. A row that names no slot — saved before its slot was created — is reconciled too, since nothing captured the changes behind what landed.
Refusals come before any slot is touched. A row in a terminal phase has nothing to resume (resume-row-terminal) — a caller that reads cp.Phase.Terminal() first, as the ordinary end of a run, never meets that refusal; a row in the cutover phase is the swap's to answer for — InspectSwapped reads whether it committed — and is resume-row-cutover until the caller has that answer; a row that does not describe target is resume-row-mismatch. A slot of the derived name that is not this route's — physical, or another database's — is resume-slot-foreign in every phase, since neither a clean resume nor a reconcile may decode from or replace it, whatever its WAL status says. A slot of the route's own that another backend holds is resume-slot-held rather than clean, since no stream opens on it until the holder lets go; the caller inspects again once it has.
type ResumeMode ¶
type ResumeMode uint8
ResumeMode is how a run picks up a checkpoint row it did not finish.
const ( // ResumeClean means the row's slot is intact and readable: the run // reopens the stream at the row's last applied position and continues // the phase the row records. ResumeClean ResumeMode = iota + 1 // ResumeReconcile means change capture cannot continue from the row's // slot (ST-4): the run keeps the shadow and the watermark and goes // through Reconciler.Reconcile before any stream is opened. ResumeReconcile )
type RunOptions ¶
type RunOptions struct {
// Shadow bounds the shadow build, inspection, cutover gate, swapped
// table inspection, and old table drop.
Shadow Options
// Copier bounds the copy.
Copier copier.Options
// Checksum bounds the verification pass.
Checksum checksum.Options
// Cutover bounds the swap and its ACCESS EXCLUSIVE acquisition.
Cutover CutoverOptions
// Applier bounds each flush of captured changes into the shadow, and
// the drain the swap runs under its lock.
Applier applier.Options
// Catchup bounds the catch-up cycles that apply the stream to the
// shadow while the copy and the verification pass run. Its Tracker is
// the caller's to set.
Catchup applier.CatchupOptions
// Tracker, when set, is the tracker of a longer run this one is step
// Step of: the caller has called Start and calls Finish, and the Runner
// reports its phases to it as that step. The copy is reported as
// progress.OperationCopy with the copier as the work source, a live
// run's wait for its capture to catch up to the marker as
// progress.OperationCatchUp with the run's catch-up as the work source,
// and the verification pass as progress.OperationChecksum with the
// verifier as the work source; each phase starts the step again with
// its own operation, so the step's elapsed time is the phase's. The
// statement is left empty: no one statement is what a phase runs. It
// replaces Copier.Tracker, Checksum.Tracker and Catchup.Tracker, which
// must be left nil when it is set: a tracker reads one work source at
// a time, and the Runner hands it the one the phase in progress owns.
Tracker *progress.Tracker
// Step is the 1-based step of the caller's run that Tracker reports
// this run as; zero when Tracker is nil.
Step int
// Live bounds how the verification pass settles a chunk the stream was
// still carrying changes for. Its Confirmed source is the run's own
// catch-up and must be left nil. So must Flushes: the run's pass
// recopies nothing (a divergence aborts it), and the flush gate a
// repair needs is the run's own catch-up too. CarryKeys must be left
// zero: the run's swap compares no key the pass leaves it.
Live checksum.LiveOptions
// KeepOld leaves the retained source under its derived _old name after
// the swap (D9), for a rollback window the caller manages; the run
// still reaches PhaseDone, with the write fence taken off the old
// table so it can be renamed back and written. False drops it before
// the row is done. The caller ends the window with InspectSwapped on
// the done row's proof and DropOldTable, under the table's lock.
KeepOld bool
// ReplaceDone lets a Run that meets a row in PhaseDone — the record of
// a run on the table that completed — delete that row inside its own
// lock session and start fresh, so a second change on the table needs
// no step between the two runs in which another engine could take the
// lock. The one thing a done row can still stand for is a KeepOld
// rollback window: a done row whose retained source still bears its
// derived _old name is refused as resume-row-terminal, with the
// remedy in the detail, as every done row is when this is false. A
// failed row and a live row are never replaced.
ReplaceDone bool
// Restart lets a Run that meets a row before its swap committed — the
// record of a run on the table that stopped — discard what that run
// left, inside its own lock session, and start fresh: the shadow is
// dropped, the write fence taken off a quiesced source or the slot
// dropped for a live one, and the row deleted, in that order, so a
// restart that stops partway leaves a row that still records what
// stands. A relation under the shadow's name with no row to record it
// is dropped the same way instead of being refused as
// shadow-unrecorded. The one row a restart will not discard is a
// cutover row whose swap the catalog shows committed: the change is
// past the point of starting over, so the run is refused as
// restart-swap-committed and the row is finished by a Run without
// this set. A done row is governed by ReplaceDone, not by this.
Restart bool
// CheckpointInterval is how often the copy in progress saves its
// landed watermark, so a run that stops mid-copy resumes from the last
// save rather than from the start (TM-3). Zero means the default.
CheckpointInterval time.Duration
// Sleep waits between periodic saves, and in a live run between the
// polls that wait for the catch-up to pass a marker and for a stopped
// stream's backend to leave; nil waits on the wall clock. Tests inject
// one to drive the waits without real time passing.
Sleep func(ctx context.Context, d time.Duration) error
// AfterCheckpoint, when set, is called after every successful save of
// the checkpoint row with the row as saved, and is the run's one
// progress signal: the phase saves call it on the caller's goroutine,
// the periodic watermark saves on the copy's saving goroutine, so it
// must be safe to call from either, and the periodic calls arrive at
// CheckpointInterval, not as the copy lands rows. An error it returns
// stops the run there, with the row as the last save left it, so a
// test can stop a run at any transition and resume it (TM-3 fault
// hook) — except at the done save, which stops nothing: the change is
// complete and recorded, and Run returns its Result beside the error.
AfterCheckpoint func(ctx context.Context, cp checkpoint.Checkpoint) error
}
RunOptions bounds one copy-and-swap run. Zero values take the defaults of each step they configure. Applier, Catchup, and Live bound the steps only a run that decodes WAL has, and are not read by a quiesced run.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner drives one copy-and-swap change end to end: table lock, shadow build, copy, verification pass, cutover gate, swap, and old table drop, with the checkpoint row written at every transition so a run that stops anywhere resumes from the row (TM-3). Which of two runs it drives is read from the target's proof (preflight.CopySwapTarget.DecodesWAL):
- A quiesced run, for a target not proven to decode WAL. No writer touches the source while the run is in progress: the Runner decodes no WAL and applies no captured change, so the copy and the verification pass are the whole proof of data equality (CO-1). The Runner enforces that itself with a write fence on the source — a statement trigger, enabled ALWAYS so that it fires in every session whatever its session_replication_role, that refuses INSERT, UPDATE, DELETE, and TRUNCATE with SQLSTATE WriteFenceSQLState — installed before the copy starts and in place until the swap, across any stop and resume in between. A writer that reaches the table while the fence is in place gets an error. The swap confirms, under its ACCESS EXCLUSIVE lock, that the fence is still there, of the shape the install gave it, and enabled ALWAYS, and refuses as CauseCutoverUnfenced when it was disabled, dropped, or replaced, leaving the next Run to install it again and verify again. The fence is not tamper-proof: a role that owns the table can disable it, write, and put it back between the verification pass and the swap, and that write is not seen.
- A live run, for a target proven to decode WAL. The source keeps taking writes throughout: the run owns a replication slot under the target's derived name, decodes the source's changes from it, and applies them to the shadow beside the copy and the verification pass, then drains the last of them under the swap's lock so the renamed shadow holds every row the source held at the swap (CO-1, ST-4). No fence is installed.
The two runs never resume each other's rows: a row that names a slot is a live run's, one that names none a quiesced run's, and a Runner that finds the other kind refuses it as resume-row-decoding (ST-3).
func NewRunner ¶
func NewRunner(cfg dbconn.Config, store *checkpoint.Store, opts RunOptions) (*Runner, error)
NewRunner prepares runs over the database cfg names, writing the checkpoint row through store. It refuses a nil store and options a run could not honour. cfg opens the dedicated connection the table lock session holds for the run; every other statement runs on the pool handed to Run, which must hold MinPoolConns(opts.Copier) connections, and store writes through its own pool. All three must name one database: each working transaction confirms the table lock from the pool it runs on, and a pool that reaches another database sees no lock and refuses as shadow-lock-unconfirmed before writing anything.
func (*Runner) Run ¶
func (r *Runner) Run(ctx context.Context, pool *pgxpool.Pool, target preflight.CopySwapTarget, st statement.Statement) (result Result, err error)
Run carries target through the gated statement st, or resumes the run its checkpoint row records, and returns once the change is complete and the row is in PhaseDone. A pool smaller than MinPoolConns for the run's copy options is refused first, with an error wrapping executor.ErrPoolTooSmall, before the lock is taken or anything is read or written. It then takes the table's lock for the whole run (LK-1), makes sure the checkpoint table exists, reads the target's row, and dispatches on what it finds:
- No row: the shadow is built from st and the row saved in PhaseCopying, with st's text — for a quiesced run with the write fence put on the source first, for a live run naming the slot the run is about to make. A relation already under the shadow's name is refused as shadow-unrecorded, since no row says what built it (ST-2). A first save whose row does not land drops the shadow, and the fence, again, so the next Run starts fresh rather than meeting that refusal.
- Any other row records a run of the statement it carries, and st must be that statement — the same operations on the same table, compared as parsed — or the row is refused as resume-row-mismatch before anything is touched: a resume completes the change the row records, never the one the caller changed its mind to.
- A row before its cutover: the shadow under the row's name is inspected and its proof must equal the one the row carries, or the row is refused as resume-row-mismatch; the run continues from the row's phase and watermark. A row whose shadow no relation bears is refused as resume-shadow-gone, the counterpart of shadow-unrecorded, and the row — with the slot a live row names — is left for the operator to drop and delete. A live run reads its slot too (InspectResume): a slot that is gone or that the server reports lost is replaced in reconcile mode (ST-4) before any stream opens.
- A row in PhaseCutover: whether the swap committed is read from the catalog (LK-4) — a committed swap continues at the old table drop, a swap that rolled back is verified and gated again and swapped, after a live run has caught up again from the row's position. A rolled-back swap's row is held against its shadow as a row before its cutover is, resume-shadow-gone included.
- A terminal row is refused as resume-row-terminal: the run it records has ended, and a caller that means to run the table again deletes it first with Store.Delete, under the table's lock — or sets RunOptions.ReplaceDone, under which a done row whose retained source is gone is deleted here, inside this run's lock session, and the run starts fresh; a failed row is refused either way.
- A row of the other kind of run — one naming a slot, or in a phase only a live run enters, met by a quiesced Runner; one naming none, met by a live Runner — is refused as resume-row-decoding.
A quiesced run's phases then run in order — the write fence on the source, installed over the one a stopped run left; copy, saving the landed watermark every CheckpointInterval and when the copy ends; one verification pass through the complete watermark under checksum.DivergenceAbort; the cutover gate; the row saved in PhaseCutover; the swap; the old table drop, or under KeepOld the fence taken off the old table; the row saved in PhaseDone.
A live run opens its stream at the row's last applied position and applies the source's changes to the shadow in the background for as long as the shadow is being filled: through the copy, which saves the applied position beside the watermark; through PhaseCatchingUp, which ends once the stream has confirmed past a marker written to the WAL after the copy; and through one live verification pass under checksum.DivergenceAbort, which settles each chunk the stream was still carrying changes for. Capture then stops, the row is saved in PhaseCutover with the position confirmed so far, and the swap applies every change committed since under its own lock, in its own transaction, before it renames — so the renamed shadow holds every row the source held at the swap (CO-1). The slot is dropped once the swap has committed, then the old table is dropped or kept as for a quiesced run and the row saved in PhaseDone.
The row is never written to PhaseFailed: a run that stops leaves the row where its last save put it, with the fence or the slot in place, and the next Run resumes from there. A run that stopped under a verification difference is wedged in PhaseVerifying until the operator finds the cause, drops the shadow with DropShadow, takes the fence off with DropWriteFence or drops the slot with decode.DropSlot, and deletes the row, or runs the statement again with RunOptions.Restart, which does those steps under the run's own lock; no Run without the restart goes back to the copy. A run that stopped on a data fault (IsDataFault) — the server rejecting the rows as the statement would shape them, in the copy, the stream's apply, or the swap's drain — is the one stop the Runner does not leave to resume, since every resume would meet the same rows: it is discarded whole under this run's lock session, as RunOptions.Restart would discard it, and the error returned is an *AbandonedError carrying the fault; the next Run of the statement starts from the beginning. A cutover row is still answered by the catalog first, and one whose swap committed is refused as restart-swap-committed rather than discarded. Every error is returned as the step returned it, with a lost table lock reported as shadow-lock-lost, and with the zero Result — except when the run is complete and its done row saved and only what came after failed: AfterCheckpoint handed the done row, or the release of the lock session. The change is then done and recorded, so the Result is returned as it stands with that error alongside, and Result.Checkpoint.Phase in PhaseDone is how a caller tells that case from a stopped run.
type SequenceOptions ¶
type SequenceOptions struct {
// Start is START WITH, the declared start the sequence keeps for
// ALTER SEQUENCE … RESTART; it is not the counter's position.
Start int64 `json:"start"`
// Increment is INCREMENT BY.
Increment int64 `json:"increment"`
// Min is MINVALUE.
Min int64 `json:"min"`
// Max is MAXVALUE.
Max int64 `json:"max"`
// Cache is CACHE.
Cache int64 `json:"cache"`
// Cycle reports CYCLE.
Cycle bool `json:"cycle"`
}
SequenceOptions are the pg_sequence facts cutover replays into ADD GENERATED … AS IDENTITY, so the recreated sequence declares exactly what the source's did. The counter's current value is deliberately not among them: it is a runtime fact that moves with every insert on the shared sequence, so cutover reads last_value and is_called from the sequence itself at swap time and sets the recreated sequence to that position with setval, after the declaration.
type SwapProof ¶
type SwapProof struct {
// Schema is the schema both tables live in.
Schema string `json:"schema"`
// Table is the name the live table bears: the source's name.
Table string `json:"table"`
// OldTable is the name the retained source bears.
OldTable string `json:"old_table"`
// LiveOID is the live table's OID: the shadow the build created.
LiveOID uint32 `json:"live_oid"`
// OldOID is the retained source's OID.
OldOID uint32 `json:"old_oid"`
// Owner is the role that owns both tables.
Owner string `json:"owner"`
// Indexes are the index renames the swap performed.
Indexes DependentPairing `json:"indexes"`
// Statistics are the extended-statistics renames the swap performed.
Statistics DependentPairing `json:"statistics"`
// OwnedSequences are the sequences the swap re-owned to the live table.
OwnedSequences []OwnedSequence `json:"owned_sequences"`
// IdentityColumns are the identity columns the live table carries.
IdentityColumns []IdentityColumn `json:"identity_columns"`
// Attempts is how many ACCESS EXCLUSIVE acquisitions the swap needed;
// zero in a proof re-derived after the fact.
Attempts int `json:"attempts"`
}
SwapProof is the plain view of a SwappedTable: the same facts as its accessors, as exported fields a checkpoint can encode and decode. A resume decodes the checkpoint it kept into a SwapProof and asks SameSwap whether what InspectSwapped returned describes the same swap; the two are not compared field for field, since a proof re-derived after the fact cannot carry everything the cutover's did. SwapProof is a view only: nothing turns it back into a SwappedTable, so DropOldTable still accepts only a value the cutover or the inspection minted.
func (SwapProof) SameSwap ¶
SameSwap reports whether the two proofs describe the same committed swap: the same two relations by OID under the same names in the same schema, owned by the same role, with the same sequences re-owned to the live table and the same identity columns recreated on it. These are the facts that identify what the swap left, and every one of them is read back from the catalog whichever way the proof was minted. The dependent pairings and Attempts are left out on purpose: the cutover's pairing names the shadow dependents the swap renamed, a pairing re-derived afterwards cannot (the derived names have no inverse), and no later read can know how many lock acquisitions the swap needed. A resume compares its checkpoint with the inspection through this, not through ==.
type SwappedTable ¶
type SwappedTable struct {
// contains filtered or unexported fields
}
SwappedTable is the proof that the swap committed: the shadow now bears the source's name and the source its derived _old name, with the dependents renamed and the sequences handed off as recorded here. Its constructor is private: only Cutover and InspectSwapped mint one, and DropOldTable accepts nothing else.
func Cutover ¶
func Cutover(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, ready CutoverReady, drain DrainFunc, opts CutoverOptions) (SwappedTable, error)
Cutover swaps the verified shadow in for the source, in one transaction under ACCESS EXCLUSIVE on both tables, and returns the SwappedTable proof of what the live catalog now holds. The transaction takes the lock under lock_timeout and, when the wait times out or the server breaks a deadlock, rolls back and tries again after a bounded backoff — the engine never queues behind readers (LK-2). Under the lock it runs the caller's drain, re-runs the ST-5 checklist so the pairing it renames by is as fresh as the lock, renames the source and its dependents to their derived _old names and the shadow and its paired dependents to the names the source held (D8), hands every sequence and identity to the live table (D5), re-reads the catalog to confirm each rename and handoff took, and commits. The old table is left in place for DropOldTable (D9).
A failed attempt is never assumed to have rolled back: an attempt that lost its connection or whose context ended is followed to its backend's exit on the server, and only then is the catalog read from a fresh connection to learn which relation now bears the source name (LK-4). A commit the client never heard of is reported as the success it was; a name neither the source nor the shadow bears is refused rather than guessed at. Every failure that leaves the source live wraps ErrCutoverRolledBack, so a caller can tell "retry later" from "do not assume" without reading the message.
The caller holds the per-table lock (LK-1) and passes the CutoverReady the gate minted; a zero proof is refused before any connection opens.
func InspectSwapped ¶
func InspectSwapped(ctx context.Context, pool *pgxpool.Pool, lock *dbconn.TableLockSession, expected Proof, opts Options) (SwappedTable, error)
InspectSwapped re-derives the SwappedTable proof for a swap an earlier run committed, from the catalog alone, in one bounded read transaction under SET LOCAL ROLE owner. It is the resume path for a run that stopped between Cutover and DropOldTable, and the one home of LK-4's committed branch. The expectation is the BuiltShadow proof the caller checkpointed before the cutover: only the catalog can say what the swap did, but only that proof can say which two relations the swap was about. The live name must be borne by the proof's shadow OID and the derived _old name by the proof's source OID (ST-6); both must still be owned by the role the build recorded; the dependent renames are re-derived from the names the swap gave, each live dependent paired with the old-table dependent under its derived name; and every identity column the proof handed off must be an identity column on the live table drawing from the sequence the handoff recreated under the source sequence's name.
The catalog states the proof does not describe each get their own answer: the source still live is ErrNotSwapped, the retained source gone under every name is ErrOldTableNotFound, the _old name borne by another relation or the retained source renamed away from it is refused as cutover-relation-replaced, a live or old table owned by another role is refused as cutover-swap-mismatch, and the live name borne by neither relation is refused as cutover-outcome-ambiguous (LK-4). A swap whose COMMIT is still deciding holds both relations exclusively and the catalog does not yet show it, so the read is refused as ambiguous until that backend lets go; the same call answers once it has.
func (SwappedTable) Attempts ¶
func (s SwappedTable) Attempts() int
Attempts is how many ACCESS EXCLUSIVE acquisitions the swap needed.
func (SwappedTable) IdentityColumns ¶
func (s SwappedTable) IdentityColumns() []IdentityColumn
IdentityColumns are the identity columns the swap recreated on the live table, each with the options its sequence now declares: the source sequence's, with a bound the source took from its column's old type moved to the new type when the statement widened the column.
func (SwappedTable) Indexes ¶
func (s SwappedTable) Indexes() DependentPairing
Indexes are the index renames the swap performed, paired by definition. In a SwappedTable InspectSwapped re-derived, each pair's ShadowName is empty and an unpaired source index is listed under the derived name it now bears.
func (SwappedTable) LiveOID ¶
func (s SwappedTable) LiveOID() uint32
LiveOID is the live table's OID: the shadow the build created.
func (SwappedTable) MarshalJSON ¶
func (s SwappedTable) MarshalJSON() ([]byte, error)
MarshalJSON encodes the swapped table as its SwapProof, so a checkpoint can store a SwappedTable directly. SwappedTable has no UnmarshalJSON on purpose: decode into a SwapProof instead.
func (SwappedTable) OldOID ¶
func (s SwappedTable) OldOID() uint32
OldOID is the retained source's OID.
func (SwappedTable) OldTable ¶
func (s SwappedTable) OldTable() string
OldTable is the name the retained source bears after the swap.
func (SwappedTable) OwnedSequences ¶
func (s SwappedTable) OwnedSequences() []OwnedSequence
OwnedSequences are the sequences the swap re-owned to the live table.
func (SwappedTable) Owner ¶
func (s SwappedTable) Owner() string
Owner is the role that owns both tables, which the old table's drop runs as. It is the role the build recorded; the swap carries it forward and the inspection confirms both relations are still owned by it before minting, so a proof never names an owner the catalog disagrees with.
func (SwappedTable) Proof ¶
func (s SwappedTable) Proof() SwapProof
Proof returns the plain view of the swapped table: each field is what the accessor of the same name returns.
func (SwappedTable) Schema ¶
func (s SwappedTable) Schema() string
Schema is the schema both tables live in.
func (SwappedTable) Statistics ¶
func (s SwappedTable) Statistics() DependentPairing
Statistics are the extended-statistics renames the swap performed, with the same shape as Indexes when re-derived.
func (SwappedTable) Table ¶
func (s SwappedTable) Table() string
Table is the name the live table bears: the source's name.
type UnvalidatedConstraint ¶
type UnvalidatedConstraint struct {
// Name is the constraint name.
Name string `json:"name"`
// Def is the pg_get_constraintdef text.
Def string `json:"def"`
}
UnvalidatedConstraint is one CHECK constraint whose pg_constraint row has convalidated = false, with its server-decompiled definition (which ends in NOT VALID).
Source Files
¶
- catchup_wait.go
- column_identity.go
- column_statistics.go
- cutover.go
- cutover_backend.go
- cutover_gate.go
- cutover_grants.go
- cutover_handoff.go
- cutover_outcome.go
- cutover_resolve.go
- cutover_swap.go
- data_fault.go
- dependents.go
- dependents_retype.go
- doc.go
- drop.go
- drop_old.go
- extended_statistics.go
- fence.go
- fidelity.go
- fidelity_drift.go
- grants.go
- identity.go
- identity_bounds.go
- inspect.go
- inspect_swapped.go
- lock.go
- names.go
- new_column.go
- new_sequence_column.go
- proof.go
- readded_column.go
- reconcile.go
- refusal.go
- resume.go
- runner.go
- runner_abandon.go
- runner_capture.go
- runner_copy.go
- runner_copy_refusal.go
- runner_dispatch.go
- runner_drain.go
- runner_live.go
- runner_live_dispatch.go
- runner_pool.go
- runner_progress.go
- runner_restart.go
- sequences.go
- shadow.go
- shadow_conversion.go
- swap_proof.go