Documentation
¶
Overview ¶
Package tenant is the relational plane for rows many organizations share.
Tenancy is a column. Every table this package addresses carries org_id as its first column, leading its primary key and every index, and the org a statement acts for comes from the request context and from nowhere else: no call here takes an org as an argument for tenant-owned rows. The same code runs on SQLite and on PostgreSQL; which one is configuration.
Two guards, and the second assumes the first has failed.
The builder, on both backends. A statement whose context names no tenant is refused before any SQL exists. Every tenant-owned table a statement names — the one it reads, every one it joins, every one a subquery reads — is constrained to the tenant's rows: in WHERE for the table read, in ON for a join, so an outer join cannot leak the other side. An insert takes org_id from the context and refuses a row that names another org; an update cannot move a row between orgs; an upsert's conflict target leads with org_id, so one org's write can never land on another org's row. There is no raw SQL: identifiers are validated and quoted, values are always bound, and a condition is built only from the constructors in this package, so nothing a caller passes can reach past the tenant constraint.
Row-level security, on PostgreSQL. The migrator enables and forces RLS on every table and installs one policy for the tenant role — org_id must equal the transaction's app.org — and one for the platform role. Every statement runs in a transaction that first sets the role it acts as and app.org, both transaction-local, so a pooled connection carries neither into the next transaction. The login holds no privilege of its own (NOINHERIT); outside that preamble it can read nothing, so a statement that skipped it fails loudly rather than seeing everything.
The platform scope is the one way to work across orgs — SuperAdmin reads, billing rollups, backfills. It is its own entry point, DB.Platform, which names why it is being entered, is audited, runs as its own role, and refuses a context that names a tenant.
On SQLite there is no RLS, so the builder is the enforcement. A store keeps its tables in one file per store, the file it had before: one file here is one schema on PostgreSQL, so a store's tables have the same names on both.
Index ¶
- Constants
- Variables
- func Duplicate(err error) bool
- func Escape(s string) string
- func Provision(ctx context.Context, super *sql.DB, login, database string) error
- func ReadOnly(ctx context.Context) context.Context
- type Cond
- func And(cs ...Cond) Cond
- func Eq(col string, v any) Cond
- func Exists(from string, where Cond) Cond
- func Ge(col string, v any) Cond
- func Gt(col string, v any) Cond
- func In[V any](col string, vs ...V) Cond
- func InSelect(col, from, of string, where Cond) Cond
- func Le(col string, v any) Cond
- func Like(col, pattern string) Cond
- func Lt(col string, v any) Cond
- func Ne(col string, v any) Cond
- func Not(c Cond) Cond
- func NotIn[V any](col string, vs ...V) Cond
- func NotNull(col string) Cond
- func Null(col string) Cond
- func Or(cs ...Cond) Cond
- type Config
- type DB
- func (d *DB) CreateIfAbsent(ctx context.Context, table string, row any, key ...string) (bool, error)
- func (d *DB) Delete(ctx context.Context, table string, where Cond) (int64, error)
- func (d *DB) Insert(ctx context.Context, table string, row any) error
- func (d *DB) Platform(ctx context.Context, why string) (*DB, error)
- func (d *DB) Select[T any](table string, cols ...string) *Query[T]
- func (d *DB) Tx(ctx context.Context, fn func(*DB) error) error
- func (d *DB) Update(ctx context.Context, table string, set Row, where Cond) (int64, error)
- func (d *DB) Upsert(ctx context.Context, table string, row any, key ...string) error
- type Field
- type Query
- func (q *Query[T]) All(ctx context.Context) ([]T, error)
- func (q *Query[T]) Count(ctx context.Context) (int64, error)
- func (q *Query[T]) Exists(ctx context.Context) (bool, error)
- func (q *Query[T]) First(ctx context.Context) (T, bool, error)
- func (q *Query[T]) GroupBy(cols ...string) *Query[T]
- func (q *Query[T]) Join(table string, on Cond) *Query[T]
- func (q *Query[T]) LeftJoin(table string, on Cond) *Query[T]
- func (q *Query[T]) Limit(n int) *Query[T]
- func (q *Query[T]) Offset(n int) *Query[T]
- func (q *Query[T]) One(ctx context.Context) (T, error)
- func (q *Query[T]) OrderBy(cols ...string) *Query[T]
- func (q *Query[T]) Where(c Cond) *Query[T]
- type Ref
- type Row
- type Table
- type Type
Constants ¶
const Column = "org_id"
Column is the tenant column every table carries first.
Variables ¶
var ( // ErrNoTenant is a tenant statement whose context names no org. ErrNoTenant = errors.New("tenant: the context names no org") // ErrTenantContext is the platform scope asked for from a context that // names an org. Cross-org work never starts inside one org's request. ErrTenantContext = errors.New("tenant: the platform scope is not reachable from a context that names an org") // ErrOtherTenant is a statement inside a transaction whose context names a // different org than the one the transaction is for. ErrOtherTenant = errors.New("tenant: the context names a different org than its transaction") // ErrForeignRow is a write naming an org other than the one it acts for. ErrForeignRow = errors.New("tenant: the row names another org") )
Functions ¶
func Duplicate ¶ added in v0.6.38
Duplicate reports whether err is a write refused because a row with the same key — primary or unique — already exists, whichever engine refused it. A store maps it to "already exists" instead of reading an engine's error text.
func Provision ¶
Provision makes, as a superuser on super, the login Open accepts and the database it works in. It is idempotent and sets no password; the caller sets one from its secret store.
The login is NOINHERIT and holds no privilege of its own. It is a member of three roles it acts as, one transaction at a time: <login>_owner, which owns the database and every table (only the migrator acts as it); <login>_tenant, which every tenant statement acts as; and <login>_platform, which the platform scope acts as. None of them is a superuser or has BYPASSRLS, and none is a member of another.
Types ¶
type Cond ¶
type Cond interface {
// contains filtered or unexported methods
}
Cond is a condition on rows. The set is closed — only the constructors in this package make one — because a condition is SQL, and SQL a caller wrote could name another org's rows.
var Always Cond = always{}
Always holds for every row. An update or delete needs a condition, so one meant for every row of the org says so with this.
func Exists ¶
Exists is EXISTS (SELECT 1 FROM from WHERE where), under the same tenant constraint as the statement around it. where may name the outer row with a Ref.
func InSelect ¶
InSelect is col IN (SELECT of FROM from WHERE where). The subquery reads from under the same tenant constraint as the statement around it. where may be nil.
func Like ¶
Like matches col against pattern without regard to case, on both backends. % and _ are wildcards and \ escapes one; Escape makes text match itself.
type Config ¶
type Config struct {
// Driver is the database/sql driver name DB was opened with: "sqlite" or
// "pgx".
Driver string
// DB is the pool every write, and every read not marked [ReadOnly], runs on.
// The caller owns it. On PostgreSQL it is connected as the login [Provision]
// makes.
DB *sql.DB
// Replica, when set, serves reads whose context is marked [ReadOnly]. It is
// connected as the same login as DB.
Replica *sql.DB
// Schema is the PostgreSQL schema this store's tables live in. Required on
// PostgreSQL; SQLite ignores it, because there the file is the namespace.
Schema string
// Tables are the tenant-owned tables this store addresses. A statement
// naming any other table is refused.
Tables []Table
// Tenant answers the org a context acts for — the org the identity layer
// validated, and nothing a caller supplied. It is the only source of a
// tenant this package has.
Tenant func(context.Context) (org string, ok bool)
// Audit records every entry into the platform scope. Unset, the entry is
// logged at warning level.
Audit func(ctx context.Context, why string)
}
Config opens a DB.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a store's tables in one scope: one org's rows — the org each statement's context names — or, from DB.Platform, every org's. Inside DB.Tx it is bound to that transaction, so a helper that takes a *DB works the same inside a transaction and out.
func Open ¶
Open validates cfg, migrates the tables, and returns the store. On PostgreSQL it refuses a login that could see past row-level security: a superuser, a role with BYPASSRLS, a login that inherits privileges, or roles that are not the ones Provision makes.
func (*DB) CreateIfAbsent ¶
func (d *DB) CreateIfAbsent(ctx context.Context, table string, row any, key ...string) (bool, error)
CreateIfAbsent writes row unless a row with the same key already exists, and reports whether it wrote. The existing row is left as it was. key is as for DB.Upsert.
func (*DB) Delete ¶
Delete removes the rows of table where holds, and reports how many. where is required; Always means every row of the org.
func (*DB) Insert ¶
Insert writes row into table. org_id comes from the context; a row that names a different one is refused. On the platform scope the row names its own org_id and must.
func (*DB) Platform ¶
Platform enters the cross-org scope: statements on it read and write every org's rows, and a write names its org_id itself.
It is refused from a context that names an org, so a request can never reach it by accident — a SuperAdmin path detaches from its request's tenant first, which is a line a reviewer can see. why is required and goes to the audit record; every statement re-checks its own context the same way, so a Platform kept past its entry still cannot serve a tenant's request.
func (*DB) Select ¶
Select starts a read of table — "table", "table alias" or "table AS alias" — into T. cols is the projection: columns ("id", "m.role"), aggregates ("COUNT(*)", "SUM(amount)", "MAX(m.at)"), each optionally "AS name"; with none, the columns T's fields map to.
func (*DB) Tx ¶
Tx runs fn in one transaction in d's scope — for the org ctx names, or on the platform — and commits when fn returns nil. fn's *DB is bound to the transaction; on a *DB already in one, fn simply joins it.
On PostgreSQL the transaction is SERIALIZABLE, so a read-modify-write inside fn is exactly as atomic as it was on a single-connection SQLite file; when the server aborts it for a conflict, fn runs again, so fn must touch nothing but the transaction. Inside fn, use fn's *DB: on SQLite, where a store holds one connection, a statement on the outer *DB waits for the connection the transaction holds.
func (*DB) Update ¶
Update sets the columns in set on the rows of table where holds, and reports how many it changed. org_id cannot be set: a row never moves between orgs. where is required; Always means every row of the org.
func (*DB) Upsert ¶
Upsert writes row into table, or updates every other column of the row already holding the same key. key is the columns after org_id of the table's primary key or of one of its unique indexes, so the conflict is always within one org: one org's upsert cannot land on another org's row. A table whose key is org_id alone — one row per org — is upserted naming none.
type Field ¶
type Field struct {
Name string
Type Type
// Null admits NULL. A column is NOT NULL otherwise.
Null bool
// Default is the column's default: a string, an integer, a float or a bool.
Default any
}
Field is one column after org_id.
type Query ¶
type Query[T any] struct { // contains filtered or unexported fields }
Query reads rows into T, a struct whose fields map to columns by their `db` tag (or the snake_case of their name). A Query is a value: every method returns a new one and leaves its receiver as it was.
func (*Query[T]) LeftJoin ¶
LeftJoin adds a left join. The tenant constraint on the joined table goes in its ON, so the join yields the org's own rows or nulls, never another org's.
type Ref ¶
type Ref string
Ref names a column as a value: the other side of a join's ON, or the outer row a subquery is correlated with.
type Row ¶
Row is a row as column → value, for writes that name their columns directly. A struct with `db` tags writes the same way.
type Table ¶
type Table struct {
Name string
Fields []Field
// Key is the primary key after org_id. Empty makes org_id the whole key:
// one row per org.
Key []string
// Unique are unique indexes, each after org_id.
Unique [][]string
// Index are indexes, each after org_id.
Index [][]string
}
Table is a tenant-owned table. Its first column is org_id, which is not declared: it leads the primary key and every index, so every lookup is already within one org and no uniqueness can ever span two.