copier

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package copier fills the shadow table from its source under the table's lock session. A Chunker cuts the primary-key space into row-count chunks that tile the whole int64 range, so every key belongs to exactly one chunk (CO-4) and each copy statement stays bounded (LK-3). A Copier copies those chunks with several workers — one guarded, never-overwriting insert per chunk; a chunk that collides with a shadow row the catch-up has yet to rewrite commits around the rows held off and copies those alone, after bounded waits, once the row is gone — first clearing the shadow above the watermark when it resumes, and reports a Position whose Classify is the applier's rule for a captured key: uncut, in flight, or landed. A column the Shadow proof names in Conversions is copied through that USING expression; the copier does not decide whether the statement behind the proof may run — the router's availability check is that gate, and a caller that drives the copier directly is trusted to have consulted it. Every refusal is a *RefusalError carrying a RefusalCause from the closed set RefusalCauses, fail-closed under ErrInvariantViolation; RefusalCauseOf reads it through wrapping.

Index

Constants

View Source
const (
	// DefaultTargetChunkTime is the copy duration each chunk is sized toward.
	DefaultTargetChunkTime = 500 * time.Millisecond
	// DefaultInitialChunkRows is the first chunk's row count, before any
	// timing feedback has arrived.
	DefaultInitialChunkRows int64 = 1000
	// DefaultMinChunkRows is the floor timing feedback can shrink a chunk to.
	DefaultMinChunkRows int64 = 100
	// DefaultMaxChunkRows is the ceiling timing feedback can grow a chunk to.
	DefaultMaxChunkRows int64 = 100_000
)

Chunk sizing defaults. A chunk is sized in rows, not key width, so a sparse key space still produces chunks of predictable work.

View Source
const (
	// DefaultCollisionAttempts is the number of passes a chunk whose insert
	// collided is given before the copy stops, when Options leaves
	// CollisionAttempts zero.
	DefaultCollisionAttempts = 10
	// DefaultCollisionBackoff is the wait before a collided chunk's first
	// pass over the rows it held off when Options leaves CollisionBackoff
	// zero. Each later wait is one backoff longer, so the default passes
	// together outlast many catch-up cycles, and a cycle's flush is what
	// moves the colliding value out of the held-off rows' way.
	DefaultCollisionBackoff = 250 * time.Millisecond
)
View Source
const DefaultWorkers = 4

DefaultWorkers is the number of chunks copied concurrently when Options leaves Workers zero.

Variables

View Source
var (
	// ErrInvalidChunkerOptions reports options that cannot describe a
	// bounded chunk: a non-positive target time or row count, or a floor
	// above the ceiling.
	ErrInvalidChunkerOptions = errors.New("invalid chunker options")
	// ErrInvariantViolation aliases dbconn's fail-closed error class so one
	// errors.Is check covers a breach raised here or in the connection layer.
	ErrInvariantViolation = dbconn.ErrInvariantViolation
)
View Source
var (
	// ErrInvalidOptions reports copier options that cannot bound the copy: a
	// negative worker count, a timeout below PostgreSQL's one-millisecond
	// resolution, which the server would read as no timeout at all, a
	// collision attempt count below one, or a negative collision backoff.
	ErrInvalidOptions = errors.New("invalid copier options")
	// ErrAlreadyRun reports a second Run on the same Copier; a Copier drives
	// one copy and is then only a record of where it stopped.
	ErrAlreadyRun = errors.New("copier has already run")
)

Functions

func ClearAbove added in v0.5.0

func ClearAbove(ctx context.Context, pool *pgxpool.Pool, target preflight.CopySwapTarget, shadow Shadow, lock *dbconn.TableLockSession, from Watermark, opts Options) error

ClearAbove removes every shadow row whose key lies above from, as a resumed Run does before it cuts its first chunk, and nothing else. It is for a caller that compares the shadow against the source through from before any copier resumes — reconcile mode (ST-4) — since a shadow row above the watermark is outside such a comparison yet still holds its values: a unique value the source has since moved out of it into a chunk the comparison finds differing would make every recopy of that chunk collide with it, and no comparison through from can clear the collision. With the shadow clear above from, the rows the comparison reads are the only rows the shadow has, and the copier that resumes from the same watermark lands the rest. ClearAbove refuses what NewCopier refuses and bounds each batch as a chunk transaction is bounded. Of opts it honors LockTimeout, StatementTimeout and Chunker (the batch size, read once); the clear runs one batch at a time, times nothing, and reports no progress, so Workers, Clock and Tracker have no effect. It runs under the lock session's Bind context, so a lost lock cancels the batch in flight (LK-1). A complete watermark has nothing above it and clears nothing.

Types

type Chunk

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

Chunk is a closed range of a single-column integer primary key. Its fields are unexported so that lower <= upper holds for every value the chunker can observe; NewChunk is the only way to obtain a non-zero Chunk.

func NewChunk

func NewChunk(lower, upper int64) (Chunk, error)

NewChunk validates and returns the closed range [lower, upper].

func (Chunk) Lower

func (c Chunk) Lower() int64

Lower returns the inclusive lower bound.

func (Chunk) Rows added in v0.4.0

func (c Chunk) Rows() int64

Rows returns the row count a Chunker cut the chunk to: the number of keys it holds, except for the final open-above chunk, which holds fewer. It is zero for a chunk not cut by a Chunker.

func (Chunk) Upper

func (c Chunk) Upper() int64

Upper returns the inclusive upper bound.

type Chunker added in v0.4.0

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

Chunker cuts the proven table's primary-key space into consecutive closed ranges. Every key a row can carry belongs to exactly one chunk: the first chunk is open below (its lower bound is the smallest int64) and the last is open above (its upper bound is the largest), so a row that arrives under a key outside the table's bounds at the time chunking began is still covered by some chunk (CO-4 coverage).

Coverage alone tells the applier which chunk a key belongs to, not whether the copier has read that key yet. The keys the copier will still read are exactly those in chunks Next has not yet returned; a chunk Next has returned may be in flight or landed whatever the watermark says, because concurrent workers land chunks out of order and the watermark advances only over the contiguous landed prefix. Cut reports the frontier between the two, so the applier discards a captured change only for a key beyond it; the low watermark alone is not that signal.

Boundaries are cut by keyset: the upper bound of the next chunk is the key that makes the chunk hold exactly the current row count, read from the live table when Next is called. Sparse or dense key spaces therefore yield chunks of the same row count rather than the same key width.

A Chunker is safe for concurrent use: Next serializes callers so chunks stay consecutive, while Cut, Rows, and Feedback never wait behind the boundary query a Next in progress is running.

func NewChunker added in v0.4.0

func NewChunker(target preflight.CopySwapTarget, from Watermark, opts ChunkerOptions) (*Chunker, error)

NewChunker returns a chunker that resumes after from, or covers the whole key space when from is the zero watermark. It rejects a zero proof.

func (*Chunker) Cut added in v0.4.0

func (c *Chunker) Cut() Watermark

Cut reports the cut frontier: the highest key inside any chunk Next has returned, or that the chunker resumed past. Its zero value means no key has been cut. Every key above the frontier lies in a chunk the copier has not started reading, so a change captured for such a key can be discarded (CO-4); every key at or below it lies in a chunk that is in flight or landed and must be applied or deferred, whatever the watermark says.

func (*Chunker) Feedback added in v0.4.0

func (c *Chunker) Feedback(chunk Chunk, elapsed time.Duration) error

Feedback reports how long chunk took to copy so the next chunk is sized toward the target time — the chunk-time throttle of docs/copy-and-swap-design.md#d12--throttle-by-chunk-time-and-slot-lag. The new size is scaled from the row count chunk was cut to, not from the current size, so reports from workers copying concurrently each propose a size for the work they measured instead of compounding on one another. One step changes the size by at most a factor of two in either direction, within the configured floor and ceiling. A chunk no chunker cut, such as a zero Chunk or one built with NewChunk, is refused.

func (*Chunker) Next added in v0.4.0

func (c *Chunker) Next(ctx context.Context, db dbconn.RowQuerier) (chunk Chunk, ok bool, err error)

Next cuts the next chunk from the live table with one query on db. The query is bounded only as far as db is: it takes ACCESS SHARE on the source and resolves its key comparison through the session's search_path, so the caller passes a transaction that has set lock_timeout and statement_timeout and pinned search_path to pg_catalog, as Copier and checksum.Verifier do (LK-2, CO-9). ok is false once the key space is covered; the last chunk returned before that has the largest int64 as its upper bound.

func (*Chunker) Rows added in v0.4.0

func (c *Chunker) Rows() int64

Rows returns the row count the next chunk will be cut to.

type ChunkerOptions added in v0.4.0

type ChunkerOptions struct {
	// TargetChunkTime is the copy duration each chunk is sized toward: the
	// chunk-time throttle of
	// docs/copy-and-swap-design.md#d12--throttle-by-chunk-time-and-slot-lag.
	TargetChunkTime time.Duration
	// InitialRows is the first chunk's row count.
	InitialRows int64
	// MinRows is the smallest chunk feedback may produce.
	MinRows int64
	// MaxRows is the largest chunk feedback may produce.
	MaxRows int64
}

ChunkerOptions bounds chunk sizing. Zero values take the defaults above, fitted to whatever the caller did set: a floor, ceiling, or initial size given on its own pulls the other defaults around it, so setting one value never makes the defaults contradict it. Explicitly set values are validated as given.

type Copier added in v0.4.0

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

Copier copies a proven source table into its built shadow, chunk by chunk, with several workers, never overwriting a shadow row (CO-4). It runs only under the table's lock session and reports its progress as a Position the applier can judge captured changes against.

func NewCopier added in v0.4.0

func NewCopier(target preflight.CopySwapTarget, shadow Shadow, lock *dbconn.TableLockSession, from Watermark, opts Options) (*Copier, error)

NewCopier prepares a copy of target into shadow that resumes after from (or covers the whole key space when from is the zero watermark). It refuses a proof, shadow, or lock session that does not describe this table, and options that cannot bound the copy.

func (*Copier) Collisions added in v0.4.0

func (c *Copier) Collisions() int64

Collisions is the number of chunk passes this copier's run has had to repeat: passes the server refused on a unique index or an exclusion constraint, passes it rolled back to break a deadlock, and passes that left rows held off, each followed by another pass or by the copy stopping. It mixes both causes in one count; the error a stopped copy returns names the one that ended it. It counts per pass, so one chunk waiting on a single held-off key adds one for each pass that still finds the key's value taken. It is safe to read from any goroutine while Run is in progress; a copy whose source saw no value move during it reads zero.

func (*Copier) Position added in v0.4.0

func (c *Copier) Position() Position

Position snapshots the copier's progress under one lock acquisition. It is safe to call from any goroutine while Run is in progress.

func (*Copier) Run added in v0.4.0

func (c *Copier) Run(ctx context.Context, pool *pgxpool.Pool) error

Run copies every chunk after the resume watermark and returns once the whole key space has landed, or once the first failure or cancellation has stopped every worker. A resumed copy first clears the shadow above the watermark, so every key above it is genuinely uncut (CO-4). Run returns only after every worker has exited, so the copier holds no chunk transaction when it does (LK-3) and a caller that then checkpoints Position().Watermark records only committed work; a chunk whose transaction did not commit stays in Position().InFlight. Every chunk transaction runs under the lock session's Bind context, so losing the table lock cancels the statements in flight and Run reports the loss. While it runs the copier is the tracker's work source (Options.Tracker), and it has stopped being one by the time Run returns.

A cut or a copy that ends at the chunk's lock_timeout — the source was held by a stronger lock for longer than Options.LockTimeout — returns the server's error wrapped, and dbconn.Retryable identifies it. The copier is single-use, but Position is resumable as it stands: a new Copier from Position().Watermark clears the shadow above the watermark and continues, so a caller can back off and resume behind a busy table.

A chunk whose insert the server refuses on a unique index or an exclusion constraint (SQLSTATE 23505 or 23P01) is given up to Options.CollisionAttempts passes: the value it collided on was moved between keys by a source change the applier has yet to flush. The next pass commits every row of the chunk but those whose values other shadow rows hold, and the chunk's Position entry then names those keys as Pending, so the applier writes the rest of the chunk while later passes, each after a wait, copy only the held-off rows once the flush has rewritten the rows holding their values. A collision no pass outlasts returns the server's error wrapped, the chunk in flight with its pending keys, and Collisions counts every pass that left a row held off. A pass the server rolls back to break a deadlock (SQLSTATE 40P01) — two shadow writers each waiting on a value the other holds — is treated as a collision: it committed nothing, so the chunk takes its next pass.

Cancellation reaches the server as a closed connection, so a statement that was running keeps running until it finishes or hits the transaction's statement_timeout, and only then is its transaction rolled back; the server-side end of a cancelled chunk is bounded by that timeout, not by Run's return. A Run stopped by ctx returns an error that answers errors.Is for ctx.Err() (context.Canceled or context.DeadlineExceeded), and also for the cause when ctx was cancelled with one (context.WithCancelCause).

func (*Copier) Work added in v0.4.0

func (c *Copier) Work(ctx context.Context) (progress.Work, error)

Work reports the copy's counters for the progress tracker: it is the progress.WorkSource the copier registers for the lifetime of Run.

  • rows_copied is the number of rows this run's committed chunks inserted into the shadow, exact and monotone; a resumed run counts only its own rows, never those the earlier run landed below the watermark.
  • rows_total is the catalog's last-known row count of the source at the start of Run (pg_class.reltuples), 0 for a table ANALYZE has never visited. On a resumed run rows_copied / rows_total is this run's share of the source, not the copy's completion.
  • bytes_copied and bytes_total are the shadow's and the source's on-disk table sizes measured at the poll. The two tables differ in shape, so the shadow finishes smaller or larger than the source; the pair is a measured size, not a fraction.

The size read runs in its own transaction under the chunk budgets, so a poll queued behind a lock on either table ends at the lock timeout whatever session defaults the caller's pool carries. Outside Run the copier holds no connection, so the sizes read as 0 while the row counters still report what the ledger knows.

type KeyState added in v0.4.0

type KeyState int

KeyState is where a primary key stands relative to the copy: the CO-4 discard rule the applier judges every captured change by.

const (
	// KeyUncut lies above the cut frontier, in a chunk no worker has started
	// reading. A change captured for it can be discarded: the copier's own
	// read will see the change.
	KeyUncut KeyState = iota
	// KeyInFlight lies in a chunk a worker is reading now, or in a chunk
	// whose transaction did not commit before the run failed, or is one of
	// the keys an in-flight chunk has committed everything but. A change for
	// it must wait for the key to land: applied earlier, a stale copy could
	// resurrect a deleted row or the applier could read a shadow row that is
	// not there yet. A resumed run re-copies such a chunk.
	KeyInFlight
	// KeyLanded lies in a chunk whose transaction committed (or that a
	// resumed run had already copied), or outside the pending keys of an
	// in-flight chunk that has committed everything else. A change for it
	// applies immediately.
	KeyLanded
)

func (KeyState) String added in v0.4.0

func (s KeyState) String() string

String names the state for logs and error messages.

type Options added in v0.4.0

type Options struct {
	// Workers is the number of chunk transactions in flight at once. The
	// pool's connection limit bounds it from above.
	Workers int
	// LockTimeout bounds every lock wait inside a chunk transaction.
	LockTimeout time.Duration
	// StatementTimeout bounds every statement inside a chunk transaction.
	StatementTimeout time.Duration
	// Chunker sizes the chunks.
	Chunker ChunkerOptions
	// CollisionAttempts is the number of passes a chunk whose insert the
	// server refused on a unique index or an exclusion constraint is given
	// before the copy stops with that refusal: the refused insert, then one
	// pass that commits every row of the chunk but those whose values other
	// shadow rows hold, then passes over only the rows held off. Each pass
	// reads the source afresh, so a value a source change moved between
	// keys lands once the applier has flushed the move's other half into
	// the shadow. On a shadow with a DEFERRABLE unique or exclusion
	// constraint, which cannot be copied around, the passes after the first
	// rerun the refused insert over the whole chunk. A pass the server
	// rolls back to break a deadlock with another shadow writer spends one
	// attempt from the same budget, after waiting up to the server's
	// deadlock_timeout to be chosen.
	CollisionAttempts int
	// CollisionBackoff is the wait before a collided chunk's first pass over
	// the rows it held off; each later wait is one backoff longer. The pass
	// that commits the rest of the chunk waits for nothing.
	CollisionBackoff time.Duration
	// Clock times each chunk for the chunker's chunk-time throttling
	// feedback (docs/copy-and-swap-design.md#d12--throttle-by-chunk-time-and-slot-lag).
	Clock progress.Clock
	// Tracker, when set, is told the copy's work for the lifetime of Run: the
	// copier is its progress.WorkSource from before the first chunk until
	// just before Run returns. The caller owns the tracker's steps; the
	// copier only fills the current step's counters.
	Tracker *progress.Tracker
}

Options bounds the copy. Zero values take the defaults: DefaultWorkers workers, the dbconn session timeouts for every chunk transaction, the ChunkerOptions defaults, DefaultCollisionAttempts attempts spaced by DefaultCollisionBackoff, and the wall clock.

func (Options) Validate added in v0.4.0

func (o Options) Validate() error

Validate refuses options that cannot bound a copy, with the defaults applied as NewCopier applies them: the copier's own fields with ErrInvalidOptions and its Chunker's with ErrInvalidChunkerOptions. NewCopier runs the same check when the copy starts; Validate lets a caller that holds the options long before then refuse them up front, before anything is built or fenced (ST-6).

type PendingKeys added in v0.4.1

type PendingKeys struct {
	Chunk Chunk
	// Keys are the ascending source keys whose shadow slot another row held
	// when the chunk was read.
	Keys []int64
}

PendingKeys names the keys an in-flight chunk still has to copy after a collision made the copier commit the rest of the chunk around them.

type Position added in v0.4.0

type Position struct {
	// Watermark is the contiguous prefix of landed chunks — the value that is
	// checkpointed and resumed from. Its zero value means nothing has landed.
	Watermark Watermark
	// Cut is the cut frontier: the highest key of any chunk a worker has
	// claimed, so every key above it is in a chunk the copier has not started
	// reading. Its zero value means nothing has been claimed, and then every
	// key is uncut.
	Cut Watermark
	// InFlight are the claimed, unlanded chunks, in ascending key order. It is
	// empty once Run has returned nil; after a failed Run it lists the chunks
	// that did not land. A chunk in Pending is listed too although it has
	// committed every row but its pending keys, and its other keys read as
	// landed: use Classify, not membership here, to judge a key.
	InFlight []Chunk
	// Pending lists, in the order of InFlight, the in-flight chunks that have
	// committed every row but a few, with the keys still to copy. Such a
	// chunk stays in InFlight until its keys empty, so the watermark cannot
	// pass it, while its keys outside Keys classify as landed.
	Pending []PendingKeys
	// RowsInserted counts rows the copier inserted into the shadow, excluding
	// rows the applier had already written (the insert never overwrites).
	RowsInserted int64
}

Position is one consistent snapshot of the copier's progress: the two frontiers CO-4 distinguishes plus the chunks between them.

func (Position) Classify added in v0.4.0

func (p Position) Classify(key int64) KeyState

Classify reports where key stands in this snapshot. A key above the cut frontier is uncut whatever the watermark says; a key at or below it is in flight when a claimed chunk covers it — unless the chunk has committed around a few pending keys, when only those are — and landed otherwise.

type RefusalCause added in v0.4.0

type RefusalCause string

RefusalCause identifies why the copier refused to copy, or refused to report a copy as complete. Every cause is a fail-closed refusal under ErrInvariantViolation; the cause is what tells the orchestrator that runs the copy which way to react — re-acquire the lock, drop the shadow and start the change over, or report a bug — without matching on the message text, which carries schema, table, and backend names.

const (
	// CauseProofEmpty means the copy-and-swap target proof is the zero
	// value (ST-6): only the preflight checks mint a populated one.
	CauseProofEmpty RefusalCause = "copy-proof-empty"
	// CauseShadowMismatch means the shadow handed to the copier does not
	// describe a copy into the proven target's shadow (ST-6): it is nil or
	// empty, built for another table, the source itself by name or by
	// relation, without the OIDs the per-chunk relation check compares
	// against, or its copy columns do not carry the primary key.
	CauseShadowMismatch RefusalCause = "copy-shadow-mismatch"
	// CauseLockUnproven means the copier 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 = "copy-lock-unproven"
	// CauseLockLost means the table lock session reported that it lost the
	// lock, before the copy began or while it ran (LK-1). The chunk the
	// loss interrupted stays in flight; the caller re-acquires the lock and
	// resumes from the landed watermark.
	CauseLockLost RefusalCause = "copy-lock-lost"
	// CauseLockHeldElsewhere means pg_locks, read from the connection about
	// to write a chunk, 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 copy trusts does not.
	CauseLockHeldElsewhere RefusalCause = "copy-lock-held-elsewhere"
	// CauseLockUnconfirmed means pg_locks, read from the connection about
	// to write a chunk, shows no session holding the table lock, although
	// the lock session has not reported loss (LK-1).
	CauseLockUnconfirmed RefusalCause = "copy-lock-unconfirmed"
	// CauseRelationReplaced means the source or the shadow is no longer the
	// relation its proof was minted for (ST-6): the name no longer
	// resolves, resolves to another OID, or the key column the proof says
	// is a primary key answered a boundary query with NULL.
	CauseRelationReplaced RefusalCause = "copy-relation-replaced"
	// CauseConversionDrift means the catalog entries the conversion
	// expressions resolve among are no longer the ones the shadow build
	// saw (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, so a chunk written now could evaluate the
	// expressions differently from the gated statement. The chunk is not
	// written; the caller drops the shadow and starts the change over.
	CauseConversionDrift RefusalCause = "copy-conversion-drift"
	// CauseFrontierBroken means the copier's own accounting of the key
	// space broke (CO-4): a chunk was cut with its lower bound above its
	// upper, a claimed chunk does not start at the cut frontier, or the
	// copy stopped without error short of the key space.
	CauseFrontierBroken RefusalCause = "copy-frontier-broken"
	// CauseChunksInFlight means the copy's ledger and its workers disagree
	// 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.
	CauseChunksInFlight RefusalCause = "copy-chunks-in-flight"
	// CauseChunkUnknown means a chunk no chunker cut — a zero Chunk, or one
	// built with NewChunk — was fed back to the chunker as if it had been
	// copied (ST-6).
	CauseChunkUnknown RefusalCause = "copy-chunk-unknown"
)

func RefusalCauseOf added in v0.4.0

func RefusalCauseOf(err error) RefusalCause

RefusalCauseOf returns the copier refusal cause carried by err, or the empty cause when err is nil or carries no copier refusal. Wrappers are read through. RefusalCauseOf(err).Class() is therefore the refusal's class, and the empty class for an error that is not a copier refusal — a server error the importer routes by SQLSTATE, or the bare sentinel.

func RefusalCauses added in v0.4.0

func RefusalCauses() []RefusalCause

RefusalCauses returns the closed set of copier refusal causes, so documentation and the orchestrator can enumerate them instead of maintaining their own list.

func (RefusalCause) Class added in v0.4.0

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 lock the session lost or that the server shows held elsewhere or by nobody, a relation that is no longer the one proved, and a catalog the conversion expressions no longer resolve in as the build did, are environmental — state outside the copier moved under it. Every other cause is an invariant violation: a proof, shadow, or chunk the caller handed in that cannot have come from this engine, or a ledger that disagrees with its workers; 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, and no class licenses an automatic retry on its own. An unknown cause has no class.

func (RefusalCause) Invariant added in v0.4.0

func (c RefusalCause) Invariant() string

Invariant is the identifier, from docs/invariants.md, of the invariant the cause upholds.

type RefusalError added in v0.4.0

type RefusalError struct {
	// Cause is the refusal cause.
	Cause RefusalCause
	// Detail is the ledger, session, or catalog fact behind the cause.
	Detail string
	// contains filtered or unexported fields
}

RefusalError is the copier'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 server's word that the table is not held, the statement that found a relation gone — so errors.Is and errors.As against those work too. Detail names the fact that decided the refusal; identifiers in it appear unquoted, so a renderer embedding it in structured output owns escaping it.

func (*RefusalError) Error added in v0.4.0

func (e *RefusalError) Error() string

Error implements the error interface.

func (*RefusalError) Unwrap added in v0.4.0

func (e *RefusalError) Unwrap() []error

Unwrap exposes ErrInvariantViolation and every wrapped error to errors.Is and errors.As.

type Shadow added in v0.4.0

type Shadow interface {
	// Schema is the schema holding both the source and the shadow.
	Schema() string
	// SourceTable is the table being copied from.
	SourceTable() string
	// ShadowTable is the table being copied into.
	ShadowTable() string
	// SourceOID is pg_class.oid of the source when the shadow was built.
	SourceOID() uint32
	// ShadowOID is pg_class.oid of the shadow when it was built.
	ShadowOID() uint32
	// CopyColumns are the columns present in both tables, in source order.
	CopyColumns() []string
	// Conversions are the USING expressions the gated statement retyped
	// copy columns with, keyed by column, each the SQL text the copy
	// selects in the column's place; a column absent from the map is
	// copied bare. The map is empty when the statement carried no USING.
	Conversions() map[string]string
	// ConversionFingerprint is the digest of the catalog entries the
	// conversion expressions resolve among, read when the shadow was built
	// or inspected. Every guarded write recomputes it and refuses when it
	// differs (CO-9). It is empty exactly when Conversions is.
	ConversionFingerprint() string
}

Shadow is the proof the copier writes into: the shadow table the shadow builder created for a proven source, with the relation OIDs the builder observed and the columns the two tables share. The copier names the shape rather than the builder's type because pkg/schemachange, which owns the builder and the orchestrator that runs the copy, imports every producer and no producer imports it; only the builder and the shadow inspection mint a value whose OIDs are set. What the shape cannot promise, checkShadow verifies before a connection is opened.

type Watermark

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

Watermark is a frontier in the primary-key space: every key at or below its value is on one side of the copy. The copier reports two — the copied-through watermark (every key at or below it has landed) and the cut frontier (every key at or below it is in a chunk a worker has started reading). The zero value means the frontier has not been reached, so there is no key on that side; a valid watermark is obtainable only from NewWatermark, so a value can never be paired with the wrong validity flag.

func NewWatermark

func NewWatermark(value int64) Watermark

NewWatermark returns a valid watermark at value.

func (Watermark) Complete added in v0.4.0

func (w Watermark) Complete() bool

Complete reports whether the frontier is past every key an int64 can hold: the chunker's final open-above chunk has landed, so no key remains on the other side of the watermark.

func (Watermark) Valid

func (w Watermark) Valid() bool

Valid reports whether the frontier has been reached. Value is meaningful only when Valid is true.

func (Watermark) Value

func (w Watermark) Value() int64

Value returns the frontier's primary key. It is zero for an invalid watermark; callers check Valid first.

Jump to

Keyboard shortcuts

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