postgres

package
v0.10.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: 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

Overview

Package postgres opens database transactions with the settings that row-level security (RLS) reads. It also holds small helpers for IDs, Postgres errors and nullable values.

Index

Constants

View Source
const (
	// DefaultQueryTimeout is the QueryTimeout that NewDB uses when it is
	// given zero or less.
	DefaultQueryTimeout     = 5 * time.Second
	DefaultMigrationTimeout = 60 * time.Second
)
View Source
const (
	LockKeyBootstrap int64 = 76540006
)

Transaction-scoped advisory locks. Each is taken with pg_advisory_xact_lock and held until its transaction commits or rolls back, so a transaction-mode pooler cannot leak one. Singleton-role leadership is a leader_leases row (ADR-114), not an advisory lock.

Two kinds of key are in use:

  • LockKeyBootstrap, a fixed number, serializes first-boot tenant bootstrap.
  • Per-row keys are text hashed into the 64-bit key space with hashtextextended(key, 0). The payment-method attach lock ("payment_methods:tenant:customer", internal/paymentmethods) and the customer-rules lock ("customer_rules:tenant:customer", LockCustomerRulesTx, below) name their lock in a prefix. The credit ledger ("tenant:customer", internal/credit) and the credit-note invoice lock ("tenant:invoice", internal/creditnote) are bare "tenant:id" pairs. Those two cannot be equal, because customer and invoice ids differ (hc_cus_ and hc_inv_). A new key takes its own prefix, so it cannot equal any of these. Two different keys share a lock only through a hash collision, which adds a wait and nothing else.

Migrations take goose's own session lock (id 4097083626, ADR-125) on a dedicated one-connection pool. That key is goose's, so it is not listed here.

The retired keys are the per-role session keys 76540001-76540005, the topology-probe key 76540008 and the hybrid migration loop key 76540007. Do not reuse their numbers. An old binary in a mixed fleet still takes the session and topology-probe keys for the duration of its tick, and v0.8.x migration runs take 76540007.

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 and ILIKE metacharacters escaped. Use it 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). Callers use it to turn a database invariant failure into a 400 for the user, instead of leaking raw SQL error text. Examples are the test_clocks livemode CHECK and subscriptions_test_clock_requires_testmode.

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

IsForeignKeyViolation reports whether err is a Postgres foreign-key violation (SQLSTATE 23503).

func IsLockTimeout added in v0.10.0

func IsLockTimeout(err error) bool

IsLockTimeout reports whether err is Postgres ending a statement that waited for a lock longer than lock_timeout (SQLSTATE 55P03). Outside a savepoint that aborts the transaction, so nothing it wrote is kept. A FOR UPDATE NOWAIT raises the same code; no application statement uses NOWAIT.

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. That covers a lost connection, a server shutting down, and a transaction the server aborted 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 that the server or the caller decided is not transient, on purpose: a statement timeout (57014), a lock timeout (55P03) or 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: 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

IsUniqueViolation reports whether err is a Postgres unique violation (SQLSTATE 23505).

func Livemode

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

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

func LockCustomerRulesTx added in v0.10.0

func LockCustomerRulesTx(ctx context.Context, tx *sql.Tx, tenantID, customerID string) error

LockCustomerRulesTx takes the customer-rules lock for one customer on tx and holds it until tx ends. Every customer-scoped writer of a rule that spans a customer's subscriptions takes it: one live subscription item per meter, one currency, no new business on an archived customer, and a customer update read and written as one step. Those are subscription creates, item changes, customer updates and billing-profile writes. Each one reads the state its rule checks after it gets the lock, so it sees every earlier holder's commit. A price write is plan-scoped and takes no customer lock, so a price added to a plan the customer already uses is not ordered with these checks (ADR-130 Risks).

A taker takes it before plans, invoices, credit notes, the tenant's number row, the credit ledger lock and the payment-method lock, and holds no subscription row but its own (ADR-130 §8). It conflicts only with itself: a bounce mark, usage ingest and a foreign-key check on the customer row do not wait for it.

func NewID

func NewID(prefix string) string

NewID generates a prefixed, time-sortable ID such as hc_cus_cv2q6ktjml6ng3v2q0tg. It uses xid, which is globally unique, 20 characters long, URL-safe and naturally ordered by creation time.

func NullableString

func NullableString(v string) any

NullableString returns nil, which becomes SQL NULL, when v is empty or only white space, and v otherwise.

func NullableStringPtr

func NullableStringPtr(v *string) any

NullableStringPtr converts a *string into a value for a SQL argument. It is nil, which becomes SQL NULL, when the pointer is nil or points at an empty string, and the dereferenced value otherwise. Callers then need no sql.NullString for optional reference columns.

func NullableTime

func NullableTime(v *time.Time) any

NullableTime returns nil, which becomes SQL NULL, for a nil pointer, and the time otherwise.

func Rollback

func Rollback(tx *sql.Tx)

Rollback rolls tx back and ignores the error. A nil tx does nothing.

func UniqueViolationConstraint

func UniqueViolationConstraint(err error) string

UniqueViolationConstraint returns the constraint name if err is a Postgres unique violation (SQLSTATE 23505), and "" otherwise. Use it to tell apart several unique constraints on one table. For example, subscriptions has both (tenant_id, code) and a partial unique (tenant_id, customer_id, plan_id) for live statuses, and the callers need to return 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 a query timeout and RLS-aware transactions.

func NewDB

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

NewDB returns a DB on pool. A queryTimeout of zero or less means DefaultQueryTimeout.

func (*DB) BeginTx

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

BeginTx opens a transaction and sets the RLS settings for mode, local to the transaction. TxTenant sets app.tenant_id from tenantID and app.livemode from ctx (WithLivemode). A blank tenantID returns ErrTenantUnset, and a ctx with no livemode returns ErrLivemodeUnset, before anything opens. TxBypass turns app.bypass_rls on, so RLS does not apply and the caller must filter by tenant itself.

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. It commits when fn returns nil and rolls back otherwise. It is the seam for coordinator transactions that span stores. A caller that must commit writes in two domain stores atomically passes the same *sql.Tx to each store's Tx variant, as the billing engine's threshold fire and cycle re-anchor do. Unit tests fake the interface this satisfies with a runner that calls fn(nil), and 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