package db import ( "context" "database/sql" "errors" "fmt" "net/url" "strconv" "strings" "sync" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/stdlib" ) // 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 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) } // Role is the Postgres role a team's connections use: it owns the team's // schema, and may use the shared tables, nothing else. The second guard: // even SQL that named another team's schema would be refused. func (t *Teams) Role(id int64) string { return t.Schema(id) } // connect opens a pool with a search_path, as a team's role. func (t *Teams) connect(path, role 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() cfg, err := pgx.ParseConfig(u.String()) if err != nil { return nil, err } return stdlib.OpenDB(*cfg, stdlib.OptionAfterConnect(func(ctx context.Context, c *pgx.Conn) error { _, err := c.Exec(ctx, `SET ROLE `+role) return err })), nil } // grant lets a team's role use the shared tables (and their identity // sequences) in the main schema: again each time the team opens, so // shared tables added later are covered. func (t *Teams) grant(role string) error { var tables []string rows, err := t.platform.SQL.Query(`SELECT tablename FROM pg_tables WHERE schemaname = $1`, t.main) if err != nil { return err } shared := map[string]bool{} for _, n := range PlatformTables { shared[n] = true } for rows.Next() { var n string if err := rows.Scan(&n); err != nil { rows.Close() return err } if shared[n] { tables = append(tables, t.main+"."+n) } } rows.Close() stmts := []string{`GRANT USAGE ON SCHEMA ` + t.main + ` TO ` + role} if len(tables) > 0 { stmts = append(stmts, `GRANT SELECT, INSERT, UPDATE, DELETE ON `+strings.Join(tables, ", ")+` TO `+role, `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA `+t.main+` TO `+role) } for _, q := range stmts { if _, err := t.platform.SQL.Exec(q); err != nil { return fmt.Errorf("granting %s the shared tables: %w", role, err) } } return nil } // 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, role := t.Schema(id), t.Role(id) var exists bool if err := t.platform.SQL.QueryRow(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil { return err } if !exists { if _, err := t.platform.SQL.Exec(`CREATE ROLE ` + role + ` NOLOGIN`); err != nil { return fmt.Errorf("making the team's database role (the database user needs CREATEROLE): %w", err) } } // The app's own user takes the team's role on each of its connections. if _, err := t.platform.SQL.Exec(`GRANT ` + role + ` TO CURRENT_USER`); err != nil { return err } if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema + ` AUTHORIZATION ` + role); err != nil { return err } if err := t.grant(role); 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; as its role, which owns them. sqldb, err := t.connect(schema, role) 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) } if err := t.grant(t.Role(id)); err != nil { return nil, err } sqldb, err := t.connect(t.Schema(id)+","+t.main, t.Role(id)) 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() if _, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`); err != nil { return err } return dropRole(t.platform.SQL, t.Role(id)) } // dropRole removes a team's role, and what it was granted. func dropRole(d *sql.DB, role string) error { var exists bool if err := d.QueryRow(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil || !exists { return err } if _, err := d.Exec(`DROP OWNED BY ` + role); err != nil { return err } _, err := d.Exec(`DROP ROLE ` + role) 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) } } // Size is how many bytes a team's schema takes: its tables, their indexes // and what's stored beside them. func (t *Teams) Size(id int64) (int64, error) { var n sql.NullInt64 err := t.platform.SQL.QueryRow(`SELECT sum(pg_total_relation_size(c.oid)) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relkind IN ('r', 'm')`, t.Schema(id)).Scan(&n) return n.Int64, err }