tenant

package
v0.6.45 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 19 Imported by: 0

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

View Source
const Column = "org_id"

Column is the tenant column every table carries first.

Variables

View Source
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

func Duplicate(err error) bool

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 Escape

func Escape(s string) string

Escape makes s match only itself inside a Like pattern.

func Provision

func Provision(ctx context.Context, super *sql.DB, login, database string) error

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.

func ReadOnly

func ReadOnly(ctx context.Context) context.Context

ReadOnly marks ctx as content with a replica's view. A read on it goes to the replica when one is configured; writes, and every statement inside a transaction, stay on the primary, so a caller that needs to read its own write simply does not mark the read.

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 And

func And(cs ...Cond) Cond

And holds when every c holds.

func Eq

func Eq(col string, v any) Cond

Eq is col = v. v is a value, or a Ref to another column.

func Exists

func Exists(from string, where Cond) Cond

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 Ge

func Ge(col string, v any) Cond

Ge is col >= v.

func Gt

func Gt(col string, v any) Cond

Gt is col > v.

func In

func In[V any](col string, vs ...V) Cond

In is col IN (vs…); with no values it holds for no row.

func InSelect

func InSelect(col, from, of string, where Cond) Cond

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 Le

func Le(col string, v any) Cond

Le is col <= v.

func Like

func Like(col, pattern string) Cond

Like matches col against pattern without regard to case, on both backends. % and _ are wildcards and \ escapes one; Escape makes text match itself.

func Lt

func Lt(col string, v any) Cond

Lt is col < v.

func Ne

func Ne(col string, v any) Cond

Ne is col <> v.

func Not

func Not(c Cond) Cond

Not holds when c does not.

func NotIn

func NotIn[V any](col string, vs ...V) Cond

NotIn is col NOT IN (vs…); with no values it holds for every row.

func NotNull

func NotNull(col string) Cond

NotNull is col IS NOT NULL.

func Null

func Null(col string) Cond

Null is col IS NULL.

func Or

func Or(cs ...Cond) Cond

Or holds when any c holds.

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

func Open(ctx context.Context, cfg Config) (*DB, error)

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

func (d *DB) Delete(ctx context.Context, table string, where Cond) (int64, error)

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

func (d *DB) Insert(ctx context.Context, table string, row any) error

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

func (d *DB) Platform(ctx context.Context, why string) (*DB, error)

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

func (d *DB) Select[T any](table string, cols ...string) *Query[T]

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

func (d *DB) Tx(ctx context.Context, fn func(*DB) error) error

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

func (d *DB) Update(ctx context.Context, table string, set Row, where Cond) (int64, error)

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

func (d *DB) Upsert(ctx context.Context, table string, row any, key ...string) error

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]) All

func (q *Query[T]) All(ctx context.Context) ([]T, error)

All reads every row.

func (*Query[T]) Count

func (q *Query[T]) Count(ctx context.Context) (int64, error)

Count counts the rows the query reads.

func (*Query[T]) Exists

func (q *Query[T]) Exists(ctx context.Context) (bool, error)

Exists reports whether the query reads any row.

func (*Query[T]) First

func (q *Query[T]) First(ctx context.Context) (T, bool, error)

First reads the first row and whether there was one.

func (*Query[T]) GroupBy

func (q *Query[T]) GroupBy(cols ...string) *Query[T]

GroupBy groups by the given columns.

func (*Query[T]) Join

func (q *Query[T]) Join(table string, on Cond) *Query[T]

Join adds an inner join of table ("table alias") on the condition on.

func (*Query[T]) LeftJoin

func (q *Query[T]) LeftJoin(table string, on Cond) *Query[T]

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.

func (*Query[T]) Limit

func (q *Query[T]) Limit(n int) *Query[T]

Limit reads at most n rows.

func (*Query[T]) Offset

func (q *Query[T]) Offset(n int) *Query[T]

Offset skips the first n rows.

func (*Query[T]) One

func (q *Query[T]) One(ctx context.Context) (T, error)

One reads the first row, or reports sql.ErrNoRows when there is none.

func (*Query[T]) OrderBy

func (q *Query[T]) OrderBy(cols ...string) *Query[T]

OrderBy orders by each "column" or "column DESC" in turn.

func (*Query[T]) Where

func (q *Query[T]) Where(c Cond) *Query[T]

Where adds a condition. Conditions conjoin: a later Where narrows the read and can never widen it. A nil c adds nothing.

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

type Row map[string]any

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.

type Type

type Type int

Type is a column's type. Each is spelled for the backend in hand, and each reads back into the same Go type on both.

const (
	Text  Type = iota + 1 // string
	Int                   // int64
	Real                  // float64
	Bool                  // bool
	Bytes                 // []byte
)

Jump to

Keyboard shortcuts

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