Phase 13, part 1: a Postgres schema per team

On the multi-tenant edition each team's data is in its own schema; the
tables every team shares (people, sessions, memberships, keys, locks, and
a new teams table) stay in the main one. A team's connection pool searches
its own schema first, so the app's SQL runs unchanged and can't reach
another team's tables. Each request is served by a copy of the Server for
the viewer's team, with that team's database, secrets and caches; agents
work on their own team's. The local and server editions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:08:47 -07:00
co-authored by Claude Opus 5.5
parent ff5eaa9784
commit 0e695ac810
24 changed files with 1037 additions and 289 deletions
+135
View File
@@ -0,0 +1,135 @@
package db
import (
"database/sql"
"errors"
"fmt"
"net/url"
"strconv"
"sync"
"time"
)
// Teams keeps each team's data in a Postgres schema of its own (the
// multi-tenant edition). The main schema has what every team shares (see
// PlatformTables); a team's schema has the rest, made by the same
// migrations. A team's DB is a connection pool whose search_path is its
// schema, then the main one: the app's SQL runs unchanged, finds the
// team's tables, and the shared ones behind them, and can't reach another
// team's tables without naming them.
type Teams struct {
platform *DB
base string // the main database's address
main string // the main schema
prefix string // teams' schemas are <prefix><id>
mu sync.Mutex
open map[int64]*DB
}
// Teams opens the teams of a Postgres database.
func (d *DB) Teams() (*Teams, error) {
if d.Dialect != Postgres || d.url == "" {
return nil, errors.New("teams need Postgres")
}
var main string
if err := d.SQL.QueryRow(`SELECT current_schema()`).Scan(&main); err != nil {
return nil, err
}
prefix := "team_"
if main != "public" {
prefix = main + "_team_" // tests: each in its own schema, its teams named after it
}
return &Teams{platform: d, base: d.url, main: main, prefix: prefix, open: map[int64]*DB{}}, nil
}
// Schema is a team's schema's name.
func (t *Teams) Schema(id int64) string { return t.prefix + strconv.FormatInt(id, 10) }
// connect opens a pool with a search_path.
func (t *Teams) connect(path string) (*sql.DB, error) {
u, err := url.Parse(t.base)
if err != nil {
return nil, err
}
q := u.Query()
q.Set("search_path", path)
u.RawQuery = q.Encode()
return sql.Open("pgx", u.String())
}
// Create makes a team's schema, with its tables at the current schema
// version. Making one that exists only migrates it.
func (t *Teams) Create(id int64) error {
if id <= 0 {
return errors.New("no team")
}
schema := t.Schema(id)
if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema); err != nil {
return err
}
// Only the team's schema on the path while its tables are made, so
// nothing is mistaken for the main schema's.
sqldb, err := t.connect(schema)
if err != nil {
return err
}
defer sqldb.Close()
d := &DB{SQL: sqldb, Dialect: Postgres}
return d.migrateSchema(true)
}
// Open is a team's database: one pool per team, kept while the app runs.
// It migrates the team's schema to this version the first time.
func (t *Teams) Open(id int64) (*DB, error) {
t.mu.Lock()
defer t.mu.Unlock()
if d, ok := t.open[id]; ok {
return d, nil
}
var exists bool
if err := t.platform.SQL.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, t.Schema(id)+".schema_version").Scan(&exists); err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("team %d has no data yet", id)
}
sqldb, err := t.connect(t.Schema(id) + "," + t.main)
if err != nil {
return nil, err
}
// Small: many teams share the server's connections. An idle team holds
// none for long.
sqldb.SetMaxOpenConns(4)
sqldb.SetMaxIdleConns(1)
sqldb.SetConnMaxIdleTime(time.Minute)
d := &DB{SQL: sqldb, Dialect: Postgres, Team: id}
if err := d.migrateSchema(true); err != nil {
sqldb.Close()
return nil, fmt.Errorf("team %d: %w", id, err)
}
t.open[id] = d
return d, nil
}
// Drop deletes a team's schema and everything in it.
func (t *Teams) Drop(id int64) error {
t.mu.Lock()
if d, ok := t.open[id]; ok {
d.SQL.Close()
delete(t.open, id)
}
t.mu.Unlock()
_, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`)
return err
}
// Close closes every team's pool.
func (t *Teams) Close() {
t.mu.Lock()
defer t.mu.Unlock()
for id, d := range t.open {
d.SQL.Close()
delete(t.open, id)
}
}