package db import ( "fmt" "regexp" "strings" ) // Migration is a change to the schema from schema 30 on, for both // databases. It's written once, in SQLite's SQL; Postgres gets the same // statements with SQLite's types and defaults translated (see PostgresSQL). // A migration that changes data with SQL only SQLite has gives Postgres // its own. // // Never edit or reorder one that has shipped: add a new one instead. type Migration struct { Note string // what it does, for the record (Postgres' schema_migrations) SQLite string Postgres string // empty: PostgresSQL(SQLite) } // both are the migrations after schema 29, on both databases: schema 30 // is both[0]. (migrations, before them, are SQLite's own; Postgres starts // from postgres.sql, which is schema 29 as a whole.) var both = []Migration{ // 30 { Note: "secrets kept in the database, encrypted (server and multi-tenant editions)", SQLite: ` CREATE TABLE secrets ( name TEXT PRIMARY KEY, value TEXT NOT NULL, -- v1:, AES-256-GCM key_id TEXT NOT NULL, -- which key sealed it: a fingerprint, never the key updated_at TEXT NOT NULL ); `, }, // 31 { Note: "copies of the app, and the locks that let only one of them do a job", SQLite: ` CREATE TABLE instances ( id TEXT PRIMARY KEY, -- a copy of the app, while it runs host TEXT NOT NULL DEFAULT '', version TEXT NOT NULL DEFAULT '', started_at TEXT NOT NULL, seen_at TEXT NOT NULL -- its last check-in (every 30 seconds) ); CREATE TABLE locks ( name TEXT PRIMARY KEY, -- the work, e.g. job:seo, outreach:send, audit: holder TEXT NOT NULL DEFAULT '', -- :, or '' when free taken_at TEXT NOT NULL DEFAULT '', expires_at TEXT NOT NULL DEFAULT '' -- renewed while the work runs; free after it ); `, }, // 32 { Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)", SQLite: ` CREATE TABLE users ( id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE COLLATE NOCASE, name TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT 'person', -- person or agent status TEXT NOT NULL DEFAULT 'invited', -- invited, active or disabled password_hash TEXT NOT NULL DEFAULT '', -- Argon2id, in the PHC string format; '' for none title TEXT NOT NULL DEFAULT '', time_zone TEXT NOT NULL DEFAULT '', -- an IANA name, such as Europe/Paris photo TEXT NOT NULL DEFAULT '', -- a name in the file storage emails TEXT NOT NULL DEFAULT '[]', -- the emails they want, as a JSON list created_at TEXT NOT NULL, signed_in_at TEXT NOT NULL DEFAULT '' -- their last sign-in ); CREATE TABLE memberships ( team_id INTEGER NOT NULL DEFAULT 1, -- one team until the multi-tenant edition user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, role TEXT NOT NULL, -- owner, admin or member modules TEXT NOT NULL DEFAULT '{}', -- a member's modules: {"seo":"edit","metrics":"view"} created_at TEXT NOT NULL, PRIMARY KEY (team_id, user_id) ); CREATE TABLE sessions ( id TEXT PRIMARY KEY, -- the SHA-256 of the cookie's random ID, never the ID itself user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at TEXT NOT NULL, seen_at TEXT NOT NULL, expires_at TEXT NOT NULL, ip TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '' ); CREATE INDEX sessions_user ON sessions(user_id); `, }, // 33 { Note: "one-time links: setting up the first owner, password resets, invitations", SQLite: ` CREATE TABLE links ( id TEXT PRIMARY KEY, -- the SHA-256 of the link's random token purpose TEXT NOT NULL, -- setup, reset or invite user_id INTEGER NOT NULL DEFAULT 0, -- whose it is; 0 for setup created_at TEXT NOT NULL, expires_at TEXT NOT NULL ); CREATE INDEX links_user ON links(user_id, purpose); `, }, // 34 { Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries", SQLite: ` ALTER TABLE users ADD COLUMN failed_signins INTEGER NOT NULL DEFAULT 0; -- in a row, since the last sign-in ALTER TABLE users ADD COLUMN locked_at TEXT NOT NULL DEFAULT ''; -- locked after too many; '' when not ALTER TABLE users ADD COLUMN two_factor INTEGER NOT NULL DEFAULT 0; -- an authenticator app is on (its secret is in secrets, totp:) ALTER TABLE users ADD COLUMN totp_step INTEGER NOT NULL DEFAULT 0; -- the last code's time step: each code works once ALTER TABLE users ADD COLUMN recovery_codes TEXT NOT NULL DEFAULT '[]'; -- SHA-256s of the unused recovery codes CREATE TABLE throttle ( key TEXT PRIMARY KEY, -- what's counted, e.g. signin:ip:203.0.113.5 count INTEGER NOT NULL DEFAULT 0, since TEXT NOT NULL -- when the count started ); `, }, // 35 { Note: "posting accounts (several per network, the company's and people's own), who may post to them, and who wrote and posted each draft", SQLite: ` CREATE TABLE posting_accounts ( id INTEGER PRIMARY KEY, network TEXT NOT NULL, -- x, linkedin, linkedin_page, reddit name TEXT NOT NULL DEFAULT '', -- as shown: @acme, u/jo, the page's or the member's name external TEXT NOT NULL DEFAULT '', -- the network's ID for it: a URN, a username owner_id INTEGER NOT NULL DEFAULT 0, -- 0: the company's; else the user whose own account it is created_by INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, expires_at TEXT NOT NULL DEFAULT '' -- when the sign-in runs out (LinkedIn); '' if renewed ); CREATE TABLE posting_grants ( account_id INTEGER NOT NULL REFERENCES posting_accounts(id) ON DELETE CASCADE, user_id INTEGER NOT NULL, PRIMARY KEY (account_id, user_id) ); ALTER TABLE drafts ADD COLUMN account_id INTEGER NOT NULL DEFAULT 0; -- 0: the company's account for the channel ALTER TABLE drafts ADD COLUMN written_by INTEGER NOT NULL DEFAULT 0; ALTER TABLE drafts ADD COLUMN posted_by INTEGER NOT NULL DEFAULT 0; ALTER TABLE drafts ADD COLUMN posted_as TEXT NOT NULL DEFAULT ''; -- the account it went out as, when it did `, }, // 36 { Note: "the audit log: who did what, and who made each outreach email", SQLite: ` CREATE TABLE audit_log ( id INTEGER PRIMARY KEY, at TEXT NOT NULL, user_id INTEGER NOT NULL DEFAULT 0, -- 0: Supermarket itself, or the local edition's owner user_name TEXT NOT NULL DEFAULT '', -- as they were called then kind TEXT NOT NULL DEFAULT 'person', -- person, agent or system action TEXT NOT NULL, -- e.g. signin, signin-failed, invited, published, deleted target TEXT NOT NULL DEFAULT '', -- what it was done to: an address, an account, a page detail TEXT NOT NULL DEFAULT '', ip TEXT NOT NULL DEFAULT '' ); CREATE INDEX audit_log_at ON audit_log(at); CREATE INDEX audit_log_user ON audit_log(user_id, at); ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0; `, }, // 37 { Note: "agents' keys, and a description for each agent", SQLite: ` CREATE TABLE agent_keys ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, hash TEXT NOT NULL UNIQUE, -- the SHA-256 of the key; the key itself is shown once prefix TEXT NOT NULL, -- its first characters, to tell keys apart created_at TEXT NOT NULL, expires_at TEXT NOT NULL DEFAULT '', -- '' for never retires_at TEXT NOT NULL DEFAULT '', -- replaced by a newer key: works until then revoked_at TEXT NOT NULL DEFAULT '', used_at TEXT NOT NULL DEFAULT '', used_from TEXT NOT NULL DEFAULT '' -- the address of its last use ); CREATE INDEX agent_keys_user ON agent_keys(user_id); ALTER TABLE users ADD COLUMN description TEXT NOT NULL DEFAULT ''; `, }, } // Schema is the schema version this build migrates databases to. func Schema() int { return len(migrations) + len(both) } // sqliteStep is the SQL that takes SQLite from schema i to i+1. func sqliteStep(i int) string { if i < len(migrations) { return migrations[i] } return both[i-len(migrations)].SQLite } // postgresStep is the migration that takes Postgres from schema i to i+1 // (i is pgBaseline or later). func postgresStep(i int) (Migration, string) { m := both[i-pgBaseline] if m.Postgres != "" { return m, m.Postgres } return m, PostgresSQL(m.SQLite) } var ( ddlIntegerKey = regexp.MustCompile(`(?i)\bINTEGER\s+PRIMARY\s+KEY\b`) ddlInteger = regexp.MustCompile(`(?i)\bINTEGER\b`) ddlReal = regexp.MustCompile(`(?i)\bREAL\b`) ddlBlob = regexp.MustCompile(`(?i)\bBLOB\b`) ddlNow = regexp.MustCompile(`(?i)strftime\('%Y-%m-%dT%H:%M:%SZ',\s*'now'\)`) // A column whose COLLATE comes after its constraints: Postgres wants it // right after the type. ddlCollateLate = regexp.MustCompile(`(?i)\bTEXT((?:\s+(?:NOT\s+NULL|UNIQUE|PRIMARY\s+KEY|DEFAULT\s+(?:'(?:[^']|'')*'|\([^)]*\)|[^\s,]+)))+)\s+COLLATE\s+NOCASE\b`) ddlCollate = regexp.MustCompile(`(?i)\bCOLLATE\s+NOCASE\b`) ) // PostgresSQL translates SQLite's DDL (CREATE TABLE, CREATE INDEX, ALTER // TABLE … ADD COLUMN) to Postgres': 64-bit integers, identity keys, // doubles, the nocase collation in its place, and timestamps from now(). func PostgresSQL(sqlite string) string { s := ddlIntegerKey.ReplaceAllString(sqlite, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY") s = ddlInteger.ReplaceAllString(s, "BIGINT") s = ddlReal.ReplaceAllString(s, "DOUBLE PRECISION") s = ddlBlob.ReplaceAllString(s, "BYTEA") s = ddlNow.ReplaceAllString(s, `to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`) s = ddlCollateLate.ReplaceAllString(s, "TEXT COLLATE nocase$1") s = ddlCollate.ReplaceAllString(s, "COLLATE nocase") return s } // checkMigrations catches a mistake in the list before it reaches a // database: an empty step. func checkMigrations() error { for i, m := range both { if strings.TrimSpace(m.SQLite) == "" || strings.TrimSpace(m.Note) == "" { return fmt.Errorf("migration %d needs its SQLite SQL and a note", len(migrations)+i+1) } } return nil }