db

package
v0.284.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 15 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 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

View Source
const (
	DefaultMaxConns        = 8
	DefaultMaxConnIdleTime = 5 * time.Minute
)

DefaultMaxConns and DefaultMaxConnIdleTime are the pool's size and idle timeout when the DSN does not set pool_max_conns / pool_max_conn_idle_time.

🔴 pgx's OWN DEFAULT IS max(4, runtime.NumCPU()) — the NODE's CPU count, not anything about the database — so the same image opens 4 connections on a laptop and 24 on a 24-CPU node, and holds them for pgx's 30-minute idle timeout. Measured: a 1Gi Postgres container was OOM-killed by ~24 idle backends at ~40 MB each, worst during a rollout, when two pods each hold a pool. muster's load is a handful of short queries, so 8 is ample.

The DSN is the knob: pool_max_conns=N and pool_max_conn_idle_time=<duration> in DATABASE_URL always win over these (docs/configuration.md).

View Source
const AppRole = "muster_app"

AppRole is the Postgres role every application connection acts as. Created by migration 0007.

View Source
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.

View Source
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

View Source
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

func ApplyByHandCommand(version int, name string) string

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

func Connect(ctx context.Context, dsn string) (*pgxpool.Pool, error)

Connect opens a pool against dsn with muster's connection settings applied, and verifies it can actually reach the server before returning.

func LikeEscape

func LikeEscape(q string) string

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

func Migrate(ctx context.Context, pool *pgxpool.Pool, logger *log.Logger) error

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

func Ping(ctx context.Context, pool interface {
	Ping(context.Context) error
}) error

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

func RLSOff(ctx context.Context, pool *pgxpool.Pool) error

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

func RLSOn(ctx context.Context, pool *pgxpool.Pool) error

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

type RLSState struct {
	Table        string
	Enabled      bool
	Forced       bool
	OwnerDefault string
}

RLSState is what RLSStatus reads back: per owned table, whether row-level security is enabled and forced, and owner_id's default expression.

func RLSStatus

func RLSStatus(ctx context.Context, pool *pgxpool.Pool) ([]RLSState, error)

RLSStatus reads pg_class and information_schema for every table that has an owner_id column — the verification after RLSOff / RLSOn, so a run that did nothing (an image whose muster-migrate predates the flag ignores it and exits 0) cannot pass for one that worked.

Jump to

Keyboard shortcuts

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