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 IsCheckViolation(err error) bool
- func IsDeadlock(err error) bool
- func IsForeignKeyViolation(err error) bool
- func IsTransient(err error) bool
- func IsUniqueViolation(err error) bool
- func Livemode(ctx context.Context) (bool, 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-lock keys. This is the only advisory lock left in the app, because singleton-role leadership is a leader_leases row (ADR-114):
- LockKeyBootstrap serializes first-boot tenant bootstrap, with pg_advisory_xact_lock inside the bootstrap transaction.
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 IsCheckViolation ¶
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 ¶
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 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 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 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.