postgres

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 28 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 postgres is the PostgreSQL state store: the shared SQL store in internal/store/sqlstore over pgx, with the locking and retry a database with concurrent writers needs.

Index

Constants

View Source
const DefaultLeaseTTL = 15 * time.Second

DefaultLeaseTTL is Options.LeaseTTL when it is zero: ha.lease_ttl's default.

View Source
const ServerLockKey int64 = 0x7371692d73727672

ServerLockKey is the advisory lock a running sqi-server holds on its database (the bytes spell "sqi-srvr"). Advisory locks are per database, so servers on different databases of one cluster do not collide.

Variables

View Source
var ErrSchemaBehindWithOtherServers = errors.New("the database schema is behind this sqi-server")

ErrSchemaBehindWithOtherServers means the database needs migrating, which only a server that has the database to itself may do.

View Source
var ErrServerLockHeld = errors.New("another sqi-server, or a command that needs the database alone " +
	"(migrate up, restore, store copy), is already using this database " +
	"(PostgreSQL advisory lock 0x7371692d73727672 is held); stop it first. " +
	"Servers can share a database only when high availability is enabled on all of them")

ErrServerLockHeld means another sqi-server, or a command that needs the database alone, already holds it. Servers share a database only when every one of them runs with high availability enabled.

View Source
var ErrUnreadableArchive = errors.New("postgres: unreadable archive")

ErrUnreadableArchive means pg_restore could not read the file as an archive, or the archive's goose_db_version data could not be parsed.

Functions

func ArchiveSchemaVersion

func ArchiveSchemaVersion(ctx context.Context, archive string) (int64, error)

ArchiveSchemaVersion reads the sqi schema version recorded in a pg_dump custom-format archive without connecting to any database: pg_restore prints goose_db_version's data as a COPY block. 0 means the archive has no goose_db_version data (not an sqi backup). A file pg_restore cannot read, or whose goose data cannot be parsed, is ErrUnreadableArchive; a missing pg_restore, a canceled ctx, and a pg_restore older than the pg_dump that wrote the archive are other errors, since the archive may be fine.

func BackupDSN

func BackupDSN(ctx context.Context, dsn, out string, log *slog.Logger) error

BackupDSN writes a pg_dump custom-format archive of the database dsn names to out, which must not exist, without opening the store, so it works on a schema this binary is too old for. It runs the pg_dump found on PATH, which must be at least the server's major version. Restore with pg_restore.

The password reaches pg_dump through PGPASSWORD, never its argument list, which any local user can read from the process list: see [pgDumpInvocation].

func CheckRestoreTool

func CheckRestoreTool(ctx context.Context, dsn string) error

CheckRestoreTool finds pg_restore on PATH and refuses one older than the server dsn names, so a restore can report a tool problem before it reads the archive.

func RequireEmptyDatabase

func RequireEmptyDatabase(ctx context.Context, dsn string) error

RequireEmptyDatabase fails unless the database dsn names has no tables in its search path. restore loads an archive only into an empty database: sqi does not drop databases (it may lack the privilege, and it is the operator's decision).

Tables are listed from pg_class, which every role can read in full, not information_schema, which hides tables the role has no privilege on.

func Restore

func Restore(ctx context.Context, dsn, archive string, log *slog.Logger) error

Restore loads a pg_dump custom-format archive into the empty database dsn names, in one transaction (a failed load leaves it empty), with the password passed as for backup. pg_restore must be at least the server's major version.

Ownership and grants are not restored (--no-owner, --no-acl): the archive's roles need not exist in the target cluster, and under --exit-on-error one GRANT to a missing role would fail the whole load.

func SchemaVersion

func SchemaVersion(ctx context.Context, db *sql.DB) (int64, error)

SchemaVersion returns the highest applied goose version, or 0 when the database has never been migrated. It creates nothing.

func SchemaVersionDSN

func SchemaVersionDSN(ctx context.Context, dsn string) (int64, error)

SchemaVersionDSN is SchemaVersion for the database dsn names, on a connection of its own.

Types

type DatabaseLock

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

DatabaseLock is the single-server lock held by a command (restore, store copy, migrate up) rather than by a store: its own one-connection pool.

func LockDatabase

func LockDatabase(ctx context.Context, dsn string, log *slog.Logger) (*DatabaseLock, error)

LockDatabase takes the server lock on the database dsn names, failing with ErrServerLockHeld when a server (or another such command) holds it.

func (*DatabaseLock) Release

func (d *DatabaseLock) Release() error

Release unlocks and closes the lock's connection.

type Options

type Options struct {
	// MaxConns is the write pool's size (store.postgres.max_conns).
	MaxConns int
	// AutoMigrate runs pending migrations before Open returns.
	AutoMigrate bool
	// ServerLock takes the advisory lock on the database for the store's life
	// (see ServerLockKey). The server sets it; the CLIs do not. The lock's
	// connection comes out of the write pool, so a server with MaxConns 16 has
	// 15 for its work, and ServerLock needs MaxConns of at least 2. It is
	// exclusive, except with HA, when servers of one group hold it shared.
	ServerLock bool
	// HA opens a pool of its own for the leader lease and the server
	// membership (see leasePoolMaxConns), outside the write pool, so a lease
	// renewal never waits behind other writes however many hold its
	// connections. Set it for a server that runs in a group; without it the
	// lease methods share the write pool. HA also bounds every session (see
	// LeaseTTL), and with ServerLock makes the lock shared: the first server
	// to start migrates, and one that joins others requires a current schema.
	HA bool
	// LeaseTTL is the leader lease's lifetime, from which an HA session's
	// idle_in_transaction_session_timeout (a third of it) derives, so a
	// frozen leader's open transactions end before a standby takes over.
	// DefaultLeaseTTL when zero. Ignored without HA.
	LeaseTTL time.Duration
	// ForceTxRetry rehearses every transaction once (sqlstore.WithForcedRetry).
	// Tests only.
	ForceTxRetry bool
	// Logger receives retry diagnostics and a lost server lock; slog.Default()
	// when nil.
	Logger *slog.Logger
	// WrapDialect, when set, wraps the dialect every statement goes through.
	// Tests only: the race tests pause a transaction at a chosen statement.
	WrapDialect func(sqlstore.Dialect) sqlstore.Dialect
}

Options configures Open.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the server's defaults: 16 write connections, migrate.

type Store

type Store struct {
	*sqlstore.Store
	// contains filtered or unexported fields
}

Store is the PostgreSQL state store.

func Open

func Open(ctx context.Context, dsn string, opts Options) (*Store, error)

Open connects to the database dsn names, optionally migrates it and takes the server lock, and prepares every statement. Every connection runs READ COMMITTED whatever the server's default: the store's locking argument (docs/architecture.md, "Store invariants") depends on it.

func (*Store) Close

func (s *Store) Close() error

Close releases the server lock, then closes every prepared statement and every pool (sqlstore.Store.Close owns the pools from Open's success on). Safe to call more than once; later calls return nil.

func (*Store) DSNForTest

func (s *Store) DSNForTest() string

DSNForTest returns the DSN the store was opened with. Tests open raw connections to the same database with it.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping checks the read pool, so a burst of writers holding every write connection does not fail readiness.

Jump to

Keyboard shortcuts

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