postgres

package
v0.9.2 Latest Latest
Warning

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

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

Index

Constants

View Source
const (
	DefaultQueryTimeout     = 5 * time.Second
	DefaultMigrationTimeout = 60 * time.Second
)
View Source
const (
	LockKeyBootstrap int64 = 76540006
)

Transaction-scoped advisory-lock keys. This is the only advisory lock left in the app after ADR-114 moved singleton-role leadership onto the leader_leases row:

  • LockKeyBootstrap serializes first-boot tenant bootstrap (pg_advisory_xact_lock inside the bootstrap transaction).

Migrations take goose's own session lock (id 4097083626, ADR-125) on a dedicated 1-connection pool; that key is goose's, not listed here.

Retired keys, do not reuse the numbers: the per-role session keys 76540001-76540005 and the topology-probe key 76540008 (an old binary in a mixed fleet still takes them for the duration of its tick), and the hybrid migration loop key 76540007 (v0.8.x migration runs take it).

Variables

View Source
var ErrLivemodeUnset = errors.New("postgres: livemode was never set on ctx (set postgres.WithLivemode at the entry point)")

ErrLivemodeUnset means ctx carries no livemode. Every entry point sets one with WithLivemode, so this is a bug at the entry point. Nothing guesses a mode in its place: the database refuses an insert, and shows no row, when app.livemode is unset (migrations 00213 and 00214).

View Source
var ErrTenantUnset = errors.New("postgres: TxTenant opened with no tenant ID")

ErrTenantUnset means a tenant-scoped transaction was asked for with no tenant ID.

Functions

func EscapeLike

func EscapeLike(s string) string

EscapeLike returns s with all LIKE/ILIKE metacharacters escaped. Use for every operator-typed search term that reaches an ILIKE pattern — without it, a term like "100%" matches everything and "_" matches any single character.

func IsCheckViolation

func IsCheckViolation(err error) bool

IsCheckViolation reports whether err is a Postgres check-constraint violation (SQLSTATE 23514). Used to translate DB-level invariant failures (e.g. the test_clocks livemode CHECK, or subscriptions_test_clock_requires_testmode) into user-facing 400s instead of leaking raw SQL error text.

func IsDeadlock

func IsDeadlock(err error) bool

IsDeadlock reports whether err is Postgres aborting the transaction to break a deadlock (SQLSTATE 40P01). Nothing the transaction wrote is kept, so running it again from the start is safe.

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

func IsTransient

func IsTransient(err error) bool

IsTransient reports whether err means the statement never reached a verdict because the connection or the transaction was taken away: the connection was lost, the server is shutting down, or the server aborted the transaction to resolve a serialization conflict or a deadlock. The row a statement was working on cannot cause any of these, so a caller that counts failures against a row (the billing run, ADR-119) does not count one.

A timeout the server or the caller decided is deliberately NOT transient: not a statement timeout (57014), not a lock timeout (55P03), and not a Go deadline. Such a timeout is the only way a query that is too slow for its own data ever shows up, and it recurs. Resource exhaustion (class 53) is not transient either.

A network timeout with no ctx error behind it IS transient: the kernel gave up on a connection to a dead or partitioned server (ETIMEDOUT), or a dial timed out. That is a lost connection that never got a reset. The driver reports a Go deadline as a wrapped context error, which the first check below has already turned away, so the two cannot be confused by type.

func IsUniqueViolation

func IsUniqueViolation(err error) bool

func Livemode

func Livemode(ctx context.Context) (bool, error)

Livemode reads the livemode flag from ctx, or returns ErrLivemodeUnset.

func NewID

func NewID(prefix string) string

NewID generates a prefixed, time-sortable ID (e.g., hc_cus_cv2q6ktjml6ng3v2q0tg). Uses xid: globally unique, 20-char, URL-safe, naturally ordered by creation time.

func NullableString

func NullableString(v string) any

func NullableStringPtr

func NullableStringPtr(v *string) any

NullableStringPtr converts a *string into a sql-friendly value: nil (becomes SQL NULL) when the pointer is nil or points at an empty string, otherwise the dereferenced value. Saves callers from juggling sql.NullString for optional reference columns.

func NullableTime

func NullableTime(v *time.Time) any

func Rollback

func Rollback(tx *sql.Tx)

func UniqueViolationConstraint

func UniqueViolationConstraint(err error) string

UniqueViolationConstraint returns the constraint name if err is a Postgres unique-violation (SQLSTATE 23505), otherwise "". Use this to disambiguate multiple unique constraints on the same table — e.g. subscriptions has both (tenant_id, code) and a partial-unique (tenant_id, customer_id, plan_id) for live statuses, and the callers need to surface distinct errors.

func WithLivemode

func WithLivemode(ctx context.Context, live bool) context.Context

WithLivemode returns a derived context carrying the mode flag. Every entry point sets it: the auth middleware from the key or session, public links from their token's row, and background workers per row or per mode. BeginTx reads it to set app.livemode, which the RLS policy filters on alongside tenant.

Types

type DB

type DB struct {
	Pool         *sql.DB
	QueryTimeout time.Duration
}

DB wraps *sql.DB with query timeout and RLS-aware transactions.

func NewDB

func NewDB(pool *sql.DB, queryTimeout time.Duration) *DB

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context, mode TxMode, tenantID string) (*sql.Tx, error)

func (*DB) WithTenantTx

func (db *DB) WithTenantTx(ctx context.Context, tenantID string, fn func(tx *sql.Tx) error) error

WithTenantTx runs fn inside one tenant-scoped (TxTenant) transaction: commit when fn returns nil, rollback otherwise. It exists as the seam for cross-store coordinator transactions — a caller that must commit writes in two domain stores atomically (e.g. the billing engine's threshold fire + cycle re-anchor) passes the same *sql.Tx to each store's Tx variant. Unit tests fake the interface this satisfies with a runner that calls fn(nil); the store mocks ignore the tx handle.

type TxMode

type TxMode int

TxMode controls how a transaction sets RLS session variables.

const (
	TxTenant TxMode = iota // Sets app.tenant_id, enforces RLS
	TxBypass               // Sets app.bypass_rls = on, skips RLS
)

Jump to

Keyboard shortcuts

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