Help us shape the future of Go! Take the 2026 Go Developer Survey

database

package
v0.0.0-...-b9a5b38 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package database owns every PostgreSQL connection and transaction in OpsGrid. It is the only package allowed to begin a transaction (enforced by lint), which guarantees that tenant-owned tables are only ever touched with a transaction-local tenant context (ADR-004).

Index

Constants

View Source
const (
	SQLStateUniqueViolation      = "23505"
	SQLStateForeignKeyViolation  = "23503"
	SQLStateCheckViolation       = "23514"
	SQLStateExclusionViolation   = "23P01"
	SQLStateNotNullViolation     = "23502"
	SQLStateSerializationFailure = "40001"
	SQLStateDeadlockDetected     = "40P01"
	SQLStateLockNotAvailable     = "55P03"
	SQLStateQueryCanceled        = "57014" // includes statement_timeout
	SQLStateInsufficientPriv     = "42501" // includes RLS WITH CHECK violations
)

SQLSTATE codes OpsGrid reacts to.

Variables

View Source
var ErrMissingTenant = errors.New("database: tenant transaction requires an organization id")

ErrMissingTenant is returned when InTenantTx is called without an organization. It is a programming error and fails closed.

Functions

func ConstraintName

func ConstraintName(err error) string

ConstraintName returns the violated constraint, or "".

func IsExclusionViolation

func IsExclusionViolation(err error, constraint string) bool

IsExclusionViolation reports an exclusion-constraint violation (for example overlapping technician assignments).

func IsForeignKeyViolation

func IsForeignKeyViolation(err error, constraint string) bool

IsForeignKeyViolation reports an FK violation (including composite tenant FKs that reject cross-organization references).

func IsNoRows

func IsNoRows(err error) bool

IsNoRows reports pgx.ErrNoRows.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether a transaction failed in a way that is safe to retry from the beginning.

func IsUniqueViolation

func IsUniqueViolation(err error, constraint string) bool

IsUniqueViolation reports a unique/PK violation, optionally on a specific constraint (empty matches any).

func SQLState

func SQLState(err error) string

SQLState returns the PostgreSQL error code of err, or "".

Types

type DB

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

DB wraps a pgx pool. Callers never receive the pool for tenant work; they use InTenantTx / InUserTx.

func Open

func Open(ctx context.Context, o Options, log *slog.Logger) (*DB, error)

Open creates the pool and verifies connectivity.

func (*DB) CheckMigrations

func (d *DB) CheckMigrations(ctx context.Context) error

CheckMigrations reports an error unless the database schema is exactly at the version embedded in this binary.

func (*DB) Close

func (d *DB) Close()

Close releases all connections.

func (*DB) InSystemTx

func (d *DB) InSystemTx(ctx context.Context, fn TxFunc) error

InSystemTx runs fn without any tenant or user context. Under RLS it can only see non-tenant tables; it exists for identity bootstrap (user upsert at login, session lookup by hash) and maintenance jobs.

func (*DB) InTenantTx

func (d *DB) InTenantTx(ctx context.Context, s Scope, fn TxFunc) error

InTenantTx runs fn in a READ COMMITTED transaction whose tenant context (app.organization_id, app.user_id) is set with set_config(..., true): it is scoped to this transaction and can never leak to the next borrower of the pooled connection.

func (*DB) InUserTx

func (d *DB) InUserTx(ctx context.Context, userID uuid.UUID, fn TxFunc) error

InUserTx runs fn with only app.user_id set. It is for pre-tenant lookups (sessions, the caller's own memberships) whose RLS policies key on the acting user rather than an organization.

func (*DB) MigrationVersion

func (d *DB) MigrationVersion(ctx context.Context) (int64, error)

MigrationVersion returns the highest applied goose migration version.

func (*DB) Ping

func (d *DB) Ping(ctx context.Context) error

Ping checks connectivity (used by readiness).

type Migrator

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

Migrator applies the embedded migrations. It must connect as opsgrid_migrator (the schema owner), never as a runtime role.

func NewMigrator

func NewMigrator(migratorURL string) (*Migrator, error)

NewMigrator opens a dedicated connection for migrations.

func (*Migrator) Close

func (m *Migrator) Close() error

Close closes the migrator's connection.

func (*Migrator) Status

func (m *Migrator) Status(ctx context.Context, log *slog.Logger) error

Status logs each migration's state.

func (*Migrator) Up

func (m *Migrator) Up(ctx context.Context, log *slog.Logger) error

Up applies all pending migrations.

type Options

type Options struct {
	URL               string
	MaxConns          int32
	MinConns          int32
	MaxConnLifetime   time.Duration
	HealthCheckPeriod time.Duration
	// ApplicationName appears in pg_stat_activity.
	ApplicationName string
}

Options configures Open.

type Scope

type Scope struct {
	OrganizationID uuid.UUID
	UserID         uuid.UUID // may be uuid.Nil for system actors (workers)
}

Scope identifies the tenant and actor for a transaction.

type TxFunc

type TxFunc func(ctx context.Context, tx pgx.Tx) error

TxFunc is the body of a transaction. It may be executed more than once if the transaction is retried after a serialization failure or deadlock, so it must not have side effects outside the transaction.

Jump to

Keyboard shortcuts

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