testutil

package
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 37 Imported by: 0 modules, 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 testutil is the integration-test harness: a real PostgreSQL in a container plus per-test throwaway schemas. Integration tests are the workhorse of this repo — core logic is validated against a real database, not mocks.

Index

Constants

View Source
const DefaultPGVersion = "16"

DefaultPGVersion is the major used when PG_VERSION is unset. CI overrides it across the full supported matrix (14 → 18).

View Source
const DifferenceLimit = 20

DifferenceLimit bounds how many differing keys one direction reports; a diverged table is diagnosed from its lowest keys, not enumerated.

View Source
const MutationTimeout = 2 * time.Second

MutationTimeout is the client-side deadline of one mutation; a mutation that outlives it fails with context.DeadlineExceeded.

View Source
const RefusalClassesDoc = "docs/refusal-classes.md"

RefusalClassesDoc is the repository path of the routing contract that classifies every typed refusal cause the engine can raise. Each package that declares a cause type keeps its own cause table in this document honest with the readers below.

View Source
const StandbySlotName = "pg_sprite_standby"

StandbySlotName is the physical slot on the primary the standby streams through.

View Source
const UnlimitedDisk int64 = math.MaxInt64

UnlimitedDisk is the free-disk figure a test hands to the copy-and-swap environment check when the volume is not measured: more free space than any fixture table needs, so the proof under test is the shape, the privileges, or the decoding facts rather than disk headroom. It is a test stand-in only; a run against a real volume measures the figure.

Variables

This section is empty.

Functions

func AssertCatalogQualified added in v0.5.4

func AssertCatalogQualified(t catalogT, query string, own ...string)

AssertCatalogQualified fails on any relation, function, type, or collation in query not qualified with pg_catalog, the relations in own and the query's own common table expressions excepted, and on any operator not spelled OPERATOR(pg_catalog.…). It is the SQL half of CO-9 for a read that runs on a caller's pool, whatever its search_path; a lookalike pool proves the behaviour.

The query is parsed with the PostgreSQL grammar and every node of the parse tree is judged, so a name is caught however it is spelled — quoted, spaced from its parenthesis or cast marker, or written as a type's constructor — and inside subqueries as well. An operator is any A_Expr, which covers the keyword forms that resolve one through the path (IN, LIKE, BETWEEN, IS DISTINCT FROM, NULLIF): those parse with an unqualified operator name, and BETWEEN with no operator name at all, so they are reported however they are written. So are the forms whose = the analyzer builds without any operator node — an IN over a subquery, a simple CASE x WHEN, and a JOIN … USING or NATURAL JOIN — and an ORDER BY … USING operator. Names the grammar itself resolves in pg_catalog, such as the keyword types (::integer, ::boolean) and the SQL-standard functions (EXTRACT, SUBSTRING), parse already qualified and pass. A common table expression's name is excused only where that expression is in scope, and the relations a FOR UPDATE OF clause names are aliases, judged where the query reads them. A relation in own is written as the query spells it, quoted as pgx.Identifier.Sanitize quotes it or plain.

func AssertConverged added in v0.3.2

func AssertConverged(t *testing.T, pool *pgxpool.Pool, source, shadow RelationRef, opts ConvergeOptions)

AssertConverged requires that source and shadow contain equal rows.

func BlockedBy added in v0.5.4

func BlockedBy(ctx context.Context, pool *pgxpool.Pool, holder uint32) (bool, error)

BlockedBy reports whether some session is waiting on a lock held by the session with backend process ID holder. A test that holds a lock and starts the code under test waits on this before acting on the wait: it names the holder, so another test's lock wait on a shared server, in any database, never satisfies it, and the holder's own granted locks do not either.

func ExecInSchema added in v0.4.0

func ExecInSchema(t *testing.T, pool *pgxpool.Pool, schema, sql string)

ExecInSchema runs sql with search_path set to schema, so unqualified fixture SQL lands there.

func InstallEventTrigger added in v0.4.0

func InstallEventTrigger(t *testing.T, pool *pgxpool.Pool, event TriggerEvent, schema, name, body string)

InstallEventTrigger creates the plpgsql event-trigger function schema.name() with the given body and an event trigger on event that calls it, and registers their drop for the end of the test. Event triggers are database-global, so every test that installs one goes through this: the drop keeps the function alive until every transaction that may still hold the trigger in its event-trigger cache has ended (see dropEventTrigger), which an inline DROP EVENT TRIGGER followed by the function's drop — or the schema's cascade — does not.

The function runs for every other test's DDL too, as whatever role that DDL runs as, and such a role need not hold USAGE on schema. So the body must not name schema in anything its IF condition evaluates: a '<schema>.t'::regclass cast, to_regclass('<schema>.t') inside a subquery, or a schema-qualified relation in a subquery's FROM is resolved while the condition is planned, even when an earlier condition is false, and raises "permission denied for schema" in the other test. Find the test's objects by name in the catalogs (pg_namespace.nspname, pg_class.relname) instead. Names in the THEN branch are safe: plpgsql analyzes a statement only when it runs. A DDL trigger's body is held to this at install, by a probe DDL run as a role without access to schema.

func LoseConnectionAtCommit added in v0.4.0

func LoseConnectionAtCommit(t *testing.T, pool *pgxpool.Pool, schema, marker string)

LoseConnectionAtCommit makes the next ALTER TABLE whose text contains marker lose its backend while the COMMIT is being processed: the DDL queues a row in a table guarded by a deferred constraint trigger, and that trigger runs inside COMMIT and terminates its own backend. The client's COMMIT then ends without a success reply — the same observable state as a COMMIT the server applied whose reply never arrived. The probe table, its trigger, and the event trigger live in schema and go with it. The event trigger fires for every package's DDL on a shared database, so it also requires the command to touch an object in schema: another schema's ALTER TABLE with the same marker text keeps its connection.

func NewCatalogShadowingPool added in v0.3.2

func NewCatalogShadowingPool(t *testing.T, serverURL, schema string) *pgxpool.Pool

NewCatalogShadowingPool returns a pool whose every session has schema ahead of pg_catalog on search_path, so impostor relations, views, functions, and operators created in schema answer unqualified catalog names. It is a raw pgx pool on purpose: pools from pkg/dbconn remove a shadowed pg_catalog entry on connect, which would make the impostors unreachable, and the tests that use this pool prove that the queries themselves stay pg_catalog-qualified for a pool the library caller built. It carries none of pkg/dbconn's session defaults.

func NewDatabase

func NewDatabase(t *testing.T, serverURL string) string

NewDatabase creates a unique throwaway database on the server at serverURL, sets it up for cleanup, and returns a URL that connects to it. Throwaway schemas do not isolate pg_stat_activity, so a test that must observe an exact session set (e.g. none) on a shared server gets a database of its own. serverURL must be in URL form (postgres://...), which StartPostgres always returns.

func NewDatabaseFromTemplate added in v0.4.0

func NewDatabaseFromTemplate(t *testing.T, serverURL, templateURL string) string

NewDatabaseFromTemplate is NewDatabase for a database cloned from the one templateURL connects to, for tests whose subject is what a clone shares with its template: the relations keep their OIDs. The server must hold no other session on the template while it is copied, so the caller closes every pool on it first.

func NewDatabaseWithEncoding added in v0.4.0

func NewDatabaseWithEncoding(t *testing.T, serverURL, encoding string) string

NewDatabaseWithEncoding is NewDatabase for a database created with the given server encoding (e.g. "SQL_ASCII") under the C locale, for tests whose subject is how the engine treats the bytes a database stores. template0 is the template, as a server encoding other than the cluster's requires.

func NewLookalikeNameMatchPool added in v0.5.4

func NewLookalikeNameMatchPool(t *testing.T, databaseURL string, owner *pgxpool.Pool) *pgxpool.Pool

NewLookalikeNameMatchPool plants, in a fresh schema of the database at databaseURL, an = on name and name and a LIKE (~~) on name and text that answer true for every pair, and returns a pool whose search_path lists that schema ahead of pg_catalog. On that pool an unqualified comparison of a slot's database or name matches every slot on the cluster, so a read that judges a slot by its database or name through it is proven to spell its operators OPERATOR(pg_catalog.…). It covers name-typed comparisons only: a read comparing text, oid, or another type needs a lookalike of that type, or AssertCatalogQualified for the text. The pool is asserted to reach both lookalikes before it is returned.

func NewLookalikeTextMismatchPool added in v0.5.5

func NewLookalikeTextMismatchPool(t *testing.T, databaseURL string, owner *pgxpool.Pool) *pgxpool.Pool

NewLookalikeTextMismatchPool plants, in a fresh schema of the database at databaseURL, an = and a <> on text and text that answer false for every pair, and returns a pool whose search_path lists that schema ahead of pg_catalog. On that pool an unqualified comparison of two texts never holds, so a read that finds a row by a text column through it is proven to spell its operators OPERATOR(pg_catalog.…). The pool is asserted to reach both lookalikes before it is returned.

func NewLookalikeTextTypePool added in v0.5.5

func NewLookalikeTextTypePool(t *testing.T, databaseURL string, owner *pgxpool.Pool) *pgxpool.Pool

NewLookalikeTextTypePool plants, in a fresh schema of the database at databaseURL, a type named text — a domain over varchar(3) — and returns a pool whose search_path lists that schema ahead of pg_catalog. On that pool an unqualified ::text cast resolves to the lookalike and cuts the value to its first three characters, so a WAL position reads as 0/1 whatever the server's, and a read that renders a value as text through it is proven to spell the cast ::pg_catalog.text. The pool is asserted to reach the lookalike before it is returned.

func NewPublicTable

func NewPublicTable(t *testing.T, pool *pgxpool.Pool, columns string) string

NewPublicTable creates a uniquely named throwaway table in the public schema — for tests that exercise unqualified-statement resolution, where a dedicated schema would defeat the point — and returns its name. The unique name keeps a shared PG_DSN database safe; cleanup drops the table.

func NewRole

func NewRole(t *testing.T, pool *pgxpool.Pool, options string) string

NewRole creates a throwaway cluster-level role with the given options and registers its drop. Roles are cluster-scoped, so names are unique per process the same way throwaway schemas are.

func NewSchema

func NewSchema(t *testing.T, pool *pgxpool.Pool) string

NewSchema creates a unique throwaway schema on pool, sets it up for cleanup, and returns its name. Tests qualify their objects with it so parallel tests on one container never collide.

func PGVersion

func PGVersion() string

PGVersion returns the PostgreSQL major version under test.

func RefusalCauseRow added in v0.4.0

func RefusalCauseRow(cause string) string

RefusalCauseRow is the row keyed on cause in a cause table: the cause, what the refusal says, its class, and why.

func RefusalCauseTable added in v0.4.0

func RefusalCauseTable(t *testing.T, heading string) string

RefusalCauseTable returns the text of the section of RefusalClassesDoc under heading, up to the next heading of any level: one package's cause table, read from the repository checkout the test runs in. Two tables in the document list some of the same cause names under their own meanings, so a guard looks rows up in its own section alone.

func RefusalClassCell added in v0.4.0

func RefusalClassCell(t *testing.T, table, cause string) string

RefusalClassCell returns the `class` cell of the row keyed on cause in a cause table whose columns are the cause, what it says, its class, and why; the test fails when the table has no such row.

func RunDuringDDL added in v0.3.2

func RunDuringDDL(t *testing.T, pool *pgxpool.Pool, event TriggerEvent, tag, schema, table, sql string)

RunDuringDDL installs an event trigger that executes sql from inside the next DDL command with the given tag whose text names schema.table, at the given event. It is the fault-injection seam for the windows a single-statement DDL leaves open — between a probe and the server's choice of names, or between a commit and the read that verifies it — made deterministic. The trigger is server-wide (event triggers are), so the schema qualifier scopes it to the test's own objects; the trigger and its function are dropped when the test ends.

func SkipOnSharedServer added in v0.4.1

func SkipOnSharedServer(t *testing.T, reason string)

SkipOnSharedServer skips a test that needs a PostgreSQL server of its own — one that creates a cluster-level role or a tablespace, or checks which image the harness chose — when PG_DSN points the suite at a shared long-lived server. reason names what the test does to the cluster.

The long-lived-database targets (make test-db and the CI matrix) never run such a test, so make test-own-server runs exactly these tests the container way; the own-server completeness test holds that target's list to the set of callers of this helper.

func StartPostgres

func StartPostgres(t *testing.T) string

StartPostgres returns a PostgreSQL connection URL for the test.

By default it starts a disposable container (terminated when the test ends). When PG_DSN is set, that external server is used instead and no container is started — the compose/ workflow and CI variants that run a long-lived server use this. Set SKIP_INTEGRATION=1 to skip tests that need a database entirely.

func StartPostgresBehindPgBouncer added in v0.3.3

func StartPostgresBehindPgBouncer(t *testing.T, mode PoolMode) (pooledURL string)

StartPostgresBehindPgBouncer starts a PostgreSQL server with a PgBouncer in front of it in the given pool mode and returns the pooled connection URL — the one a hosted platform would hand an operator.

It always starts its own containers: the pooling mode is the fixture, so an external PG_DSN cannot substitute for it.

func StartPostgresBehindPgBouncerWith added in v0.4.0

func StartPostgresBehindPgBouncerWith(t *testing.T, mode PoolMode, settings map[string]string) (pooledURL string)

StartPostgresBehindPgBouncerWith is StartPostgresBehindPgBouncer with PgBouncer settings overridden, keyed by the image's environment names (DEFAULT_POOL_SIZE, QUERY_WAIT_TIMEOUT, …), for a test about how the pooler behaves when it is short of backends.

func StartPostgresWithSettings added in v0.4.0

func StartPostgresWithSettings(t *testing.T, settings ...string) string

StartPostgresWithSettings returns a connection URL for a dedicated PostgreSQL container started with the given postgresql.conf settings (each "name=value"), for tests that control a restart-only setting such as wal_level or max_replication_slots. Unlike StartPostgres it never uses PG_DSN — a shared server cannot change those settings — and so costs a container start of its own. Set SKIP_INTEGRATION=1 to skip.

Types

type CatalogColumn added in v0.4.0

type CatalogColumn struct {
	Name    string
	Type    string
	NotNull bool
	// Default is the default or generation expression, empty when none.
	Default string
	// Identity is pg_attribute.attidentity: empty, 'a' always, 'd' by
	// default.
	Identity string
	// Generated is pg_attribute.attgenerated: empty, 's' stored, 'v'
	// virtual.
	Generated string
	// Collation is the column's collation when it differs from its type's
	// default, empty otherwise.
	Collation string
	// Storage is pg_attribute.attstorage.
	Storage string
	// Compression is pg_attribute.attcompression, empty for the default.
	Compression string
	// StatisticsTarget is the per-column statistics target, -1 for the
	// default.
	StatisticsTarget int
	// Options are the column's attribute options (pg_attribute.attoptions),
	// e.g. "n_distinct=100", in the order the server stores them. The
	// pg_attver option that newer PostgreSQL minor releases stamp on every
	// column is left out: the server sets it, and it differs per table.
	Options []string
	// Sequence is the sequence the column owns — a serial's or an identity
	// column's — and nil when it owns none.
	Sequence *CatalogSequence
}

CatalogColumn is one column's catalog record.

type CatalogConstraint added in v0.4.0

type CatalogConstraint struct {
	Name string
	// Type is pg_constraint.contype.
	Type string
	// Def is pg_get_constraintdef, which spells NOT VALID, NO INHERIT, and
	// deferrability.
	Def       string
	Validated bool
}

CatalogConstraint is one table constraint's catalog record.

type CatalogIndex added in v0.4.0

type CatalogIndex struct {
	Name string
	// Def is pg_get_indexdef with the ON clause's schema stripped: the
	// server always qualifies it, whatever the search_path.
	Def             string
	Valid           bool
	ReplicaIdentity bool
	Clustered       bool
}

CatalogIndex is one index's catalog record.

type CatalogSequence added in v0.4.0

type CatalogSequence struct {
	Type      string
	Start     int64
	Increment int64
	Min       int64
	Max       int64
	Cache     int64
	Cycle     bool
}

CatalogSequence is the parameters of a column-owned sequence. Its name is left out: a serial's sequence is named after the table, and the parameters are what the column's values depend on.

type ConvergeOptions added in v0.3.2

type ConvergeOptions struct {
	// IgnoreColumns are shadow columns left out of the comparison.
	IgnoreColumns []string
	// ExcludeKeys are primary keys left out of both sides, counts
	// included: a caller that knows which rows were written after the
	// instant the two relations should agree about takes them out of the
	// comparison rather than asking the oracle to judge them.
	ExcludeKeys []int64
}

ConvergeOptions controls convergence comparison.

type DirectionDiff added in v0.3.2

type DirectionDiff struct {
	Direction string
	Keys      []int64
}

DirectionDiff reports differing primary keys in one EXCEPT direction.

type Failure added in v0.5.1

type Failure struct {
	At   time.Time
	Code string
	Err  error
}

Failure is one mutation that failed for a reason other than an expected race. Code is the server's SQLSTATE, or empty when the failure was not a server error (the mutation's client-side deadline, say).

type HookedClock added in v0.5.3

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

HookedClock is a clock whose first reading runs a hook. The copier and the verifier read their clock once per chunk, after the chunk is claimed and before its transaction begins, so a hook there lands after the run's setup has committed and meets the first chunk as a concurrent writer.

func NewHookedClock added in v0.5.3

func NewHookedClock(hook func()) *HookedClock

NewHookedClock returns a clock that runs hook on its first reading.

func (*HookedClock) Now added in v0.5.3

func (c *HookedClock) Now() time.Time

Now runs the hook on the first call, then reads the wall clock. Later calls, including ones concurrent with the hook, wait for it to finish.

type LoadGenerator added in v0.3.2

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

LoadGenerator owns running workload workers.

func StartLoad added in v0.3.2

func StartLoad(t *testing.T, pool *pgxpool.Pool, table WorkloadTable, spec LoadSpec) *LoadGenerator

StartLoad starts bounded, cancellable workload workers. An invalid spec fails the test immediately rather than starting a generator that writes nothing.

func (*LoadGenerator) Progress added in v0.5.1

func (g *LoadGenerator) Progress() Progress

Progress returns the counts accumulated so far and leaves the workers running, under one acquisition of the lock the workers record under.

func (*LoadGenerator) Snapshot added in v0.4.0

func (g *LoadGenerator) Snapshot() Summary

Snapshot returns the summary accumulated so far and leaves the workers running, so a test can mark how much the load had committed when it observed some point in the run under test.

func (*LoadGenerator) Stop added in v0.3.2

func (g *LoadGenerator) Stop() (Summary, error)

Stop promptly cancels workers and waits a bounded time for completion. It always returns the summary accumulated so far; when workers do not stop in time the error joins the deadline with any worker error already recorded, so a wedged worker's cause is not lost behind the timeout.

type LoadSpec added in v0.3.2

type LoadSpec struct {
	Seed                 int64
	Workers              int
	RatePerSecond        int
	Mix                  Mix
	HotRowFraction       float64
	ToastRewriteFraction float64
	// RecordFailures keeps the workers running through a mutation that
	// fails for a reason other than an expected race: the failure is
	// recorded in Summary.Failures and the worker takes its next tick. A
	// generator that does not record failures stops every worker on the
	// first one and reports it from Stop. A workload that writes across
	// a swap records failures, because what the swap does to an
	// application's statements is part of what it measures.
	RecordFailures bool
}

LoadSpec configures a deterministic concurrent workload.

RatePerSecond is the mutation rate of each worker, so the aggregate rate is Workers × RatePerSecond. HotRowFraction is the share of updates aimed at the ten lowest ids (contention on a hot set); ToastRewriteFraction is the share of updates that rewrite the out-of-line blob column — the rest leave it unchanged, so their change records omit it.

type Mix added in v0.3.2

type Mix struct {
	Insert     int
	Update     int
	Delete     int
	UniqueMove int
	KeyMove    int
}

Mix gives relative weights to workload mutations. KeyMove is an update of a row's primary key to a fresh identity value, the change that arrives as an image under a new key with a delete under the old one.

type PoolMode added in v0.3.3

type PoolMode string

PoolMode is a connection pooler's pooling granularity, which is what decides whether a client connection keeps one server session.

const (
	// TransactionPooling returns the backend to the pooler's own pool at
	// the end of every transaction, so a client connection has no stable
	// server session. It is the default on hosted PostgreSQL platforms.
	TransactionPooling PoolMode = "transaction"
	// SessionPooling gives a client connection its own backend for the
	// connection's lifetime, which is all a session-scoped lock needs.
	SessionPooling PoolMode = "session"
	// StatementPooling returns the backend to the pooler's own pool after
	// every statement and refuses a transaction that spans more than one,
	// so a client connection keeps neither a session nor a transaction.
	StatementPooling PoolMode = "statement"
)

type PrimaryStandby added in v0.5.4

type PrimaryStandby struct {
	PrimaryURL string
	StandbyURL string
}

PrimaryStandby is a primary and a hot standby streaming from it, each in a container of its own.

func StartPrimaryWithStandby added in v0.5.4

func StartPrimaryWithStandby(t *testing.T, settings ...string) PrimaryStandby

StartPrimaryWithStandby starts a primary, then a hot standby cloned from it by pg_basebackup and streaming its WAL, and returns a connection URL for each. settings (each "name=value") go on both servers' command lines, so a setting the standby checks against its own configuration, such as wal_level for logical decoding, holds on both. The standby streams through the physical slot StandbySlotName on the primary. It returns once the standby reports it is in recovery and has replayed the primary's write position as it stood once the standby was up, so a caller reads a standby that is in recovery and current.

It always starts its own containers: a replication pair is the fixture, so an external PG_DSN cannot substitute for it. Set SKIP_INTEGRATION=1 to skip.

type Progress added in v0.5.1

type Progress struct {
	Inserts     int
	Updates     int
	Deletes     int
	UniqueMoves int
	KeyMoves    int
	// Touched is how long Summary.Touches was: the first Touched entries of
	// the final list are the rows written by mutations that committed
	// before this progress was read.
	Touched int
}

Progress is how much a load has committed so far, without the key and failure histories a Summary carries, so a poll that needs only the counts costs the same however long the load has run.

func (Progress) Committed added in v0.5.1

func (p Progress) Committed() int

Committed returns how many mutations of every kind committed.

type RelationRef added in v0.3.2

type RelationRef struct {
	Schema string
	Table  string
}

RelationRef identifies a relation.

type Report added in v0.3.2

type Report struct {
	SourceCount int64
	ShadowCount int64
	Differences []DirectionDiff
}

Report contains row counts and bounded symmetric differences, all read from one REPEATABLE READ snapshot so the numbers describe one instant.

func Diff added in v0.3.2

func Diff(ctx context.Context, pool *pgxpool.Pool, source, shadow RelationRef, opts ConvergeOptions) (Report, error)

Diff compares source against the shadow's visible column contract.

Every catalog read, both counts, and both difference queries run in one read-only REPEATABLE READ transaction, so a Report is a single snapshot: a count difference and a row difference can never disagree about the instant they describe.

func (Report) Converged added in v0.3.2

func (r Report) Converged() bool

Converged reports whether the relations hold equal rows. The counts are diagnostic only: the primary key is always projected and both counts come from the same snapshot as the differences, so any count skew necessarily surfaces as a differing key.

type ShadowPin added in v0.5.3

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

ShadowPin is a row inserted into a shadow table by a transaction left open, standing in for an applier write that is under way while the copy runs: the copier's insert of the chunk holding the key waits on it, so that chunk stays in flight until the pin is committed or released.

The pin is placed at its clock's first reading, which the copier takes after the resume clear and the first claim, before the first chunk's transaction: the pin is a concurrent writer the copy meets, not a straggler the clear's fence waits for. A test that ends before the copier reads the clock has no pin: the cleanup disarms the clock instead of waiting on a reading that will not come.

func PinShadowKey added in v0.5.3

func PinShadowKey(t *testing.T, pool *pgxpool.Pool, shadow pgx.Identifier, key, qty int64) *ShadowPin

PinShadowKey arranges for key to be pinned with image qty in shadow, a table with columns id and qty, at the first reading of the pin's Clock. Callers Wait before relying on the pin and end it with Release or Commit; a pin still open at cleanup is rolled back, and a pin that could not be placed fails the test.

Cleanups run last-registered first, so a test registers the cleanup that waits for its run to return after calling PinShadowKey: the run has then stopped reading the clock before the pin's cleanup ends the pin.

func (*ShadowPin) Clock added in v0.5.3

func (p *ShadowPin) Clock() *HookedClock

Clock places the pin on its first reading; the copier under test takes it as its Options.Clock.

func (*ShadowPin) Commit added in v0.5.3

func (p *ShadowPin) Commit(t *testing.T)

Commit waits for the pin and publishes the pinned row, once.

func (*ShadowPin) Release added in v0.5.3

func (p *ShadowPin) Release(t *testing.T)

Release waits for the pin and rolls it back, once.

func (*ShadowPin) Wait added in v0.5.3

func (p *ShadowPin) Wait(t *testing.T)

Wait blocks until the pin is in place and fails the test if placing it did not succeed.

type Summary added in v0.3.2

type Summary struct {
	Inserts     int
	Updates     int
	Deletes     int
	UniqueMoves int
	KeyMoves    int
	Races       int
	InsertedIDs []int64
	DeletedIDs  []int64
	Touches     []Touch
	Ambiguous   []int64
	MaxLatency  time.Duration
	Failures    []Failure
}

Summary reports committed operations, inserted and deleted IDs, and the number of mutations that aborted on an expected race (a unique-key collision, a serialization failure, a deadlock, or a vanished row) and were dropped rather than retried. A run whose Races dwarf its committed counts wrote far less than its spec suggests.

Touches lists, in commit order, the primary key of every row a committed mutation wrote — the inserted, updated, or deleted row, both rows of a unique-key swap, and both the old and the new key of a key move — each with the WAL position the mutation read while it wrote. A test that marks the length of the list at some instant knows that every key before the mark committed before it, and can leave the rows written after it out of a comparison.

Ambiguous lists the keys of every mutation whose client-side deadline expired after it had sent its write: the server may have committed the write all the same, before or after the deadline fired, so the row's state is unknown and a comparison leaves the key out rather than judge it. Each mutation names its keys before it writes, so a write whose outcome the client never heard still names the rows it may have changed.

MaxLatency is the longest a committed mutation took from its first statement to its commit returning. Failures holds every mutation that failed for a reason other than an expected race, when the spec records them.

func (Summary) Committed added in v0.4.0

func (s Summary) Committed() int

Committed returns how many mutations of every kind committed.

func (Summary) TouchedIDs added in v0.5.1

func (s Summary) TouchedIDs() []int64

TouchedIDs returns the keys of Touches in the same order.

type TLSPostgres

type TLSPostgres struct {
	// URL is the connection URL without an sslmode parameter, so the
	// caller's TLS configuration decides the handshake.
	URL string
	// CACertPath is the PEM CA certificate that signed the server
	// certificate — the trust anchor for verify-full connections.
	CACertPath string
	// UntrustedCACertPath is a valid CA certificate that did NOT sign the
	// server certificate, for negative verification tests.
	UntrustedCACertPath string
}

TLSPostgres describes a TLS-capable PostgreSQL started by StartPostgresTLS or StartPostgresTLSOrPlaintext.

func StartPostgresTLS

func StartPostgresTLS(t *testing.T) TLSPostgres

StartPostgresTLS starts a disposable PostgreSQL container that accepts only TLS connections, using a CA generated for this test. Unlike StartPostgres it never uses PG_DSN — the whole point is controlling the server's TLS posture. Set SKIP_INTEGRATION=1 to skip.

func StartPostgresTLSOrPlaintext added in v0.4.0

func StartPostgresTLSOrPlaintext(t *testing.T) TLSPostgres

StartPostgresTLSOrPlaintext is StartPostgresTLS for a server that also accepts plaintext TCP connections, so a client that falls back from a failed TLS handshake would succeed rather than be refused.

type TableCatalog added in v0.4.0

type TableCatalog struct {
	// Persistence is pg_class.relpersistence: 'p' permanent, 'u' unlogged.
	Persistence string
	// AccessMethod is the table access method (pg_class.relam), "heap"
	// for an ordinary table and empty when it has none.
	AccessMethod string
	// Tablespace is the table's tablespace, empty for the database
	// default.
	Tablespace string
	// ReplicaIdentity is pg_class.relreplident: 'd' default, 'n' nothing,
	// 'f' full, 'i' index.
	ReplicaIdentity string
	// Options are the storage parameters (pg_class.reloptions), e.g.
	// "fillfactor=70", in the order the server stores them.
	Options []string
	// ToastOptions are the storage parameters of the table's TOAST table,
	// set with the "toast." prefix, in the order the server stores them.
	ToastOptions []string
	// PartitionKey is pg_get_partkeydef, empty for a plain table.
	PartitionKey string
	// RowSecurity and ForceRowSecurity are the ENABLE / FORCE ROW LEVEL
	// SECURITY settings.
	RowSecurity      bool
	ForceRowSecurity bool
	// Columns are the live columns in attribute order.
	Columns []CatalogColumn
	// Constraints are the table constraints, name-sorted.
	Constraints []CatalogConstraint
	// Indexes are every index on the table, constraint-backed ones
	// included, name-sorted.
	Indexes []CatalogIndex
}

TableCatalog is a table's definition as the server's catalogs record it, read with direct catalog queries and never through pkg/schemadiff. It is the reference side of the round-trip oracle: two tables whose catalogs match are the same table, whatever the diff model records about them. A property the model does not carry still differs here, so a plan that converges the model but not the table fails the comparison instead of re-planning to silence.

Definitions are decompiled under a search_path of the table's own schema, so a table in one schema compares equal to the same table in another. Policies, triggers, grants, comments, and ownership are not part of it.

func ReadTableCatalog added in v0.4.0

func ReadTableCatalog(ctx context.Context, pool *pgxpool.Pool, schema, table string) (TableCatalog, error)

ReadTableCatalog reads the catalog record of schema.table in one read-only snapshot.

type Touch added in v0.5.4

type Touch struct {
	ID       int64
	Position uint64
}

Touch is one row a committed mutation wrote: its primary key, and the server's WAL insert position the mutation read inside its own write statement (or, for a multi-statement mutation, inside its transaction after its last write). The mutation held its lock on the table when it read the position, so a session holding ACCESS EXCLUSIVE on the table for a stretch of WAL either saw this write commit before it was granted the lock — the position is below anything it reads under the lock — or let the write run only after it committed, when the position is above its commit.

type TriggerEvent added in v0.4.0

type TriggerEvent string

TriggerEvent is the event an event trigger fires on: a point in a DDL command, or a session's login.

const (
	// DDLCommandStart fires before the command runs: the objects it will
	// create do not exist yet, so a name can still be taken from under it.
	DDLCommandStart TriggerEvent = "ddl_command_start"
	// DDLCommandEnd fires after the command has run but inside its
	// transaction: the objects it created exist and can be altered before
	// the caller sees the commit.
	DDLCommandEnd TriggerEvent = "ddl_command_end"
	// Login fires once a session has authenticated and its startup
	// parameters have been applied, so what it does to the session
	// outranks them. Login triggers exist from PostgreSQL 17.
	Login TriggerEvent = "login"
)

type WorkloadShape added in v0.4.0

type WorkloadShape struct {
	// IDType is the declared type of the identity primary key; empty is
	// bigint. A test that retypes the key itself starts from integer.
	IDType string
}

WorkloadShape is the part of the workload table's shape a test may vary. The zero value is the default shape.

type WorkloadTable added in v0.3.2

type WorkloadTable struct {
	Schema string
	Table  string
	// contains filtered or unexported fields
}

WorkloadTable is the table copy convergence tests run on: one shape, with the few variations WorkloadShape allows.

func NewWorkloadTable added in v0.3.2

func NewWorkloadTable(t *testing.T, pool *pgxpool.Pool) WorkloadTable

NewWorkloadTable creates an empty workload relation in a unique schema.

The shape exercises every convergence race the copy path must survive: an identity primary key, a unique secondary key whose values tests swap between rows, a numeric column for widening changes, and a text column that is always stored out of line so an update leaving it unchanged produces a change record with that column omitted. Compression is turned off for that column: pglz would otherwise keep a repetitive value inline and the omission would never occur.

func NewWorkloadTableOf added in v0.4.0

func NewWorkloadTableOf(t *testing.T, pool *pgxpool.Pool, shape WorkloadShape) WorkloadTable

NewWorkloadTableOf is NewWorkloadTable with shape's variations applied. Every generator and oracle works over the varied table too: the key is still a single identity column, so the load's key moves still draw from its sequence.

func (WorkloadTable) Qualified added in v0.3.2

func (w WorkloadTable) Qualified() string

Qualified returns the safely quoted relation name.

func (WorkloadTable) SeedRows added in v0.3.2

func (w WorkloadTable) SeedRows(ctx context.Context, n int) error

SeedRows inserts n deterministic rows.

func (WorkloadTable) ToastBytes added in v0.3.2

func (w WorkloadTable) ToastBytes(ctx context.Context) (int64, error)

ToastBytes returns the on-disk size of the table's TOAST relation, so a test can prove that the blob column really is stored out of line.

Directories

Path Synopsis
Package modeltest compares schemadiff models in tests.
Package modeltest compares schemadiff models in tests.

Jump to

Keyboard shortcuts

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