Documentation
¶
Overview ¶
Package db opens muster's Postgres pool and applies its migrations.
It is deliberately small. muster's domain lives elsewhere; this package owns exactly two things nothing else may own — the connection settings every caller inherits, and the migration runner.
Index ¶
- Constants
- Variables
- func ApplyByHandCommand(version int, name string) string
- func Connect(ctx context.Context, dsn string) (*pgxpool.Pool, error)
- func LikeEscape(q string) string
- func Migrate(ctx context.Context, pool *pgxpool.Pool, logger *log.Logger) error
- func Ping(ctx context.Context, pool interface{ ... }) error
- func RLSOff(ctx context.Context, pool *pgxpool.Pool) error
- func RLSOn(ctx context.Context, pool *pgxpool.Pool) error
- func SetQueryTracer(t pgx.QueryTracer)
- func SetUnscopedHook(f func(caller string)) (restore func())
- type RLSState
Constants ¶
const AppRole = "muster_app"
AppRole is the Postgres role every application connection acts as. Created by migration 0007.
const MigrationLockKey int64 = 0x6d_75_73_74_01
MigrationLockKey is the advisory-lock key Migrate takes.
🔴 ADVISORY LOCKS ARE DATABASE-SCOPED, so this shares no namespace with a key taken against any other database — including the one internal/dbtest takes in the `postgres` maintenance database. Mint every new muster key HERE so a collision is visible in one place rather than discovered as a deadlock.
const StatementTimeout = 10 * time.Second
StatementTimeout is injected into every connection this package opens.
🔴 IT IS SET HERE RATHER THAN LEFT TO THE SERVER'S DEFAULT (which is "no limit"), because a query with no bound is indistinguishable from a hung process at every layer above it. A caller that genuinely needs longer — the migration runner's own CREATE INDEX, say — must say so explicitly on its own connection rather than raise this for everyone.
Variables ¶
var ErrSkippedMigration = errors.New("db: an embedded migration below the applied version was never applied")
ErrSkippedMigration: an embedded migration older than the newest applied one was never applied. Migrate refuses to boot rather than skip it forever.
Functions ¶
func ApplyByHandCommand ¶
ApplyByHandCommand is the operator's remedy for one skipped migration: apply the file AND record it, in ONE transaction, through the deployment's own Postgres pod (the in-cluster form: the file is streamed on stdin, so it is read from the operator's checkout — which must be at the commit the running image was built from, the refusal says so).
🔴 -1 IS THE POINT (round-3 audit on #69). Without it psql runs the file in autocommit: every file begins `SET LOCAL lock_timeout`, which outside a transaction only warns — the 3 s guard is silently gone — and a failure part way through leaves the file half-applied and unrecorded. With -1 the file (-f -, stdin) and the -c INSERT run as one transaction; ON_ERROR_STOP makes the first error abort it. Measured on PostgreSQL 16 (psql 16.15) with this exact stdin form (`docker exec -i … psql … -1 -f - -c … < file`): a re-applied 0009 plus its row committed, rc 0, no SET LOCAL warning; a file failing on its third statement left neither its table nor the schema_migrations row, rc 3. Pinned by TestTheSkippedMigrationRefusalGivesTheSingleTransactionCommand.
func Connect ¶
Connect opens a pool against dsn with muster's connection settings applied, and verifies it can actually reach the server before returning.
func LikeEscape ¶
LikeEscape makes a user string safe as the BODY of a LIKE/ILIKE pattern. Use it with `ESCAPE '\'` on the SQL side:
WHERE col ILIKE '%' || $1 || '%' ESCAPE '\'
🔴 WITHOUT IT A QUERY OF "%" MATCHES EVERY ROW. `%` and `_` are LIKE metacharacters, so a search box that pasted its input straight into a pattern would answer "%" with the whole table and "a_b" with rows containing "axb" — wrong answers that look like working search. The backslash is escaped FIRST, or escaping the other two would double-escape the escape.
🔴 IT LIVES HERE, NOT IN ITS CALLER, BECAUSE A PREDICATE OPEN-CODED PER PACKAGE ENDS UP SUBTLY DIFFERENT AT EACH SITE. Upstream this began as a private `likeEscape` inside the agents package and was promoted when a second searcher needed exactly the same predicate.
Its callers: agents.PGStore.SearchSessions, and the Asks page's search — attention.PGStore.Search and plugins.PGStore.SearchDraftCards. (Notes' directory search, an upstream caller, was NOT carried across: see the carve note in internal/notes/pgstore.go.)
Behaviour is covered directly by TestLikeEscape here, and from each caller's side through real SQL: the agents package's pgstore_search_test.go, attention's search_pg_test.go and plugins' drafts_search_pg_test.go.
func Migrate ¶
Migrate applies every embedded migration whose numeric prefix is greater than the highest already recorded, each inside a transaction, under a session advisory lock so that two processes starting at once cannot both apply them. It REFUSES (ErrSkippedMigration) when an embedded migration below that highest version was never recorded — see checkNoSkippedMigration.
It is idempotent: a second run with no new files is a no-op.
func Ping ¶
Ping checks the pool can hand out a connection AS THE APPLICATION ROLE, which is a stronger readiness answer than a bare ping: it fails if migration 0007's role is missing, which would fail every request. It is the readiness check cmd/muster-server installs.
func RLSOff ¶
RLSOff disables row-level security on every owned table and restores owner_id DEFAULT 1 (rollback/rls_off.sql), so that an image built before accounts PR 3a can run against this schema. It runs as the migrator (the login role), never as AppRole. cmd/muster-migrate --rls-off calls it.
🔴 schema_migrations IS NOT TOUCHED. Version 7 stays recorded, so a newer image booting afterwards does NOT re-enable RLS on its own; RLSOn does that, explicitly.
func RLSOn ¶
RLSOn re-applies migration 0007's body (it is idempotent): RLS enabled and forced on every owned table, the policies, owner_id defaulting to the principal, the role and its grants — and 0008's for mirror_tokens when that table exists. It undoes RLSOff.
func SetQueryTracer ¶
func SetQueryTracer(t pgx.QueryTracer)
SetQueryTracer installs t on every pool Connect opens from now on: muster-server hands it internal/telemetry's (nil while tracing is off). It is a setter rather than an import so the packages that link internal/db into the agent pod's binary do not link the tracing SDK with it.
func SetUnscopedHook ¶
func SetUnscopedHook(f func(caller string)) (restore func())
SetUnscopedHook installs f to be called with the caller's function name every time a connection is acquired under a context with NO principal, and returns a func that restores the previous hook. Tests use it to assert a code path is scoped; production installs none and gets one log line per distinct call site instead.
Types ¶
type RLSState ¶
RLSState is what RLSStatus reads back: per owned table, whether row-level security is enabled and forced, and owner_id's default expression.