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
- Variables
- func EscapeLike(s string) string
- func IsDeadlock(err error) bool
- func IsForeignKeyViolation(err error) bool
- func IsLockTimeout(err error) bool
- func IsTransient(err error) bool
- func IsUniqueViolation(err error) bool
- func Livemode(ctx context.Context) (bool, error)
- func LockCustomerRulesTx(ctx context.Context, tx *sql.Tx, tenantID, customerID string) error
- func NewID(prefix string) string
- func NullableString(v string) any
- func NullableStringPtr(v *string) any
- func NullableTime(v *time.Time) any
- func Rollback(tx *sql.Tx)
- func UniqueViolationConstraint(err error) string
- func WithLivemode(ctx context.Context, live bool) context.Context
- type DB
- type TxMode
Constants ¶
const ( // DefaultQueryTimeout is the QueryTimeout that NewDB uses when it is // given zero or less. DefaultQueryTimeout = 5 * time.Second DefaultMigrationTimeout = 60 * time.Second )
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 ¶
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).
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 ¶
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 IsDeadlock ¶
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 ¶
IsForeignKeyViolation reports whether err is a Postgres foreign-key violation (SQLSTATE 23503).
func IsLockTimeout ¶ added in v0.10.0
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 ¶
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 ¶
IsUniqueViolation reports whether err is a Postgres unique violation (SQLSTATE 23505).
func LockCustomerRulesTx ¶ added in v0.10.0
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 active subscription per plan, one active subscription 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, plan 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 ¶
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 ¶
NullableString returns nil, which becomes SQL NULL, when v is empty or only white space, and v otherwise.
func NullableStringPtr ¶
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 ¶
NullableTime returns nil, which becomes SQL NULL, for a nil pointer, and the time otherwise.
func UniqueViolationConstraint ¶
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 ¶
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 ¶
DB wraps *sql.DB with a query timeout and RLS-aware transactions.
func (*DB) BeginTx ¶
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 ¶
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 period close does. Unit tests fake the interface this satisfies with a runner that calls fn(nil), and the store mocks ignore the tx handle.