2026-08-03 18:07:40 +02:00
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
2026-08-04 17:05:37 +02:00
2026-11-20 21:42:42 +01:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
2026-08-06 09:44:57 +02:00
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
2026-08-03 18:07:40 +02:00
)
// DB owns the PostgreSQL pool. The schema deliberately uses the same physical
// column names as the existing Node service: PostgreSQL lowercases unquoted
// camelCase identifiers, so createdAt is stored as createdat, etc.
type DB struct {
pool * pgxpool . Pool
}
func connectDB ( ctx context . Context , connectionString string ) ( * DB , error ) {
2026-08-04 17:05:37 +02:00
pool , err := sharedpostgres . Open ( ctx , sharedpostgres . DefaultConfig ( connectionString ))
2026-08-03 18:07:40 +02:00
if err != nil {
2026-08-04 17:05:37 +02:00
return nil , err
2026-08-03 18:07:40 +02:00
}
return & DB { pool : pool }, nil
}
func ( d * DB ) close () {
d . pool . Close ()
}
func ( d * DB ) withTx ( ctx context . Context , fn func ( pgx . Tx ) error ) error {
2026-08-04 17:05:37 +02:00
return sharedpostgres . WithTx ( ctx , d . pool , fn )
2026-08-03 18:07:40 +02:00
}
2026-10-20 15:27:53 +00:00
func lockChangeClock ( ctx context . Context , tx pgx . Tx ) error {
var token int64
return tx . QueryRow ( ctx , `SELECT token FROM collabtable_sync_clock WHERE id = 1 FOR UPDATE` ). Scan ( & token )
}
2026-08-03 18:07:40 +02:00
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
// be used by the Go server without a separate migration step.
func ( d * DB ) initSchema ( ctx context . Context ) error {
_ , err := d . pool . Exec ( ctx , `
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
createdat BIGINT NOT NULL,
updatedat BIGINT NOT NULL,
2026-10-20 15:27:53 +00:00
isdeleted INTEGER NOT NULL DEFAULT 0,
change_token BIGINT NOT NULL DEFAULT 0
2026-08-03 18:07:40 +02:00
);
CREATE TABLE IF NOT EXISTS fields (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
fieldtype TEXT NOT NULL,
fieldoptions TEXT,
alignment TEXT NOT NULL DEFAULT 'start',
listid TEXT NOT NULL,
"order" INTEGER NOT NULL,
createdat BIGINT NOT NULL,
updatedat BIGINT NOT NULL,
isdeleted INTEGER NOT NULL DEFAULT 0,
2026-10-20 15:27:53 +00:00
change_token BIGINT NOT NULL DEFAULT 0,
2026-08-03 18:07:40 +02:00
FOREIGN KEY (listid) REFERENCES lists(id)
);
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
listid TEXT NOT NULL,
createdat BIGINT NOT NULL,
updatedat BIGINT NOT NULL,
isdeleted INTEGER NOT NULL DEFAULT 0,
2026-10-20 15:27:53 +00:00
change_token BIGINT NOT NULL DEFAULT 0,
2026-08-03 18:07:40 +02:00
FOREIGN KEY (listid) REFERENCES lists(id)
);
CREATE TABLE IF NOT EXISTS item_values (
id TEXT PRIMARY KEY,
itemid TEXT NOT NULL,
fieldid TEXT NOT NULL,
value TEXT,
updatedat BIGINT NOT NULL,
2026-10-20 15:27:53 +00:00
change_token BIGINT NOT NULL DEFAULT 0,
2026-08-03 18:07:40 +02:00
FOREIGN KEY (itemid) REFERENCES items(id),
FOREIGN KEY (fieldid) REFERENCES fields(id)
);
CREATE INDEX IF NOT EXISTS idx_fields_listid ON fields(listid);
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
2026-10-19 21:16:08 +00:00
CREATE INDEX IF NOT EXISTS idx_lists_updatedat ON lists(updatedat);
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
2026-10-20 15:27:53 +00:00
CREATE INDEX IF NOT EXISTS idx_lists_page ON lists(updatedat DESC, id ASC) WHERE isdeleted = 0;
CREATE INDEX IF NOT EXISTS idx_fields_page ON fields(listid, "order" ASC, id ASC) WHERE isdeleted = 0;
CREATE INDEX IF NOT EXISTS idx_items_page ON items(listid, updatedat DESC, id ASC) WHERE isdeleted = 0;
CREATE INDEX IF NOT EXISTS idx_item_values_page ON item_values(itemid, updatedat ASC, id ASC);
ALTER TABLE lists ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
ALTER TABLE fields ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
ALTER TABLE items ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
ALTER TABLE item_values ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS collabtable_sync_clock (
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
token BIGINT NOT NULL DEFAULT 0
);
INSERT INTO collabtable_sync_clock (id, token) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
CREATE INDEX IF NOT EXISTS idx_lists_change_token ON lists(change_token);
CREATE INDEX IF NOT EXISTS idx_fields_change_token ON fields(change_token);
CREATE INDEX IF NOT EXISTS idx_items_change_token ON items(change_token);
CREATE INDEX IF NOT EXISTS idx_item_values_change_token ON item_values(change_token);
CREATE OR REPLACE FUNCTION collabtable_assign_change_token()
RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE next_token BIGINT;
BEGIN
UPDATE collabtable_sync_clock SET token = token + 1 WHERE id = 1 RETURNING token INTO next_token;
IF next_token IS NULL THEN
RAISE EXCEPTION 'sync clock row is missing';
END IF;
NEW.change_token := next_token;
RETURN NEW;
END;
$$;
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'lists_change_token' AND tgrelid = 'lists'::regclass AND NOT tgisinternal) THEN
EXECUTE 'CREATE TRIGGER lists_change_token BEFORE INSERT OR UPDATE ON lists FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'fields_change_token' AND tgrelid = 'fields'::regclass AND NOT tgisinternal) THEN
EXECUTE 'CREATE TRIGGER fields_change_token BEFORE INSERT OR UPDATE ON fields FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'items_change_token' AND tgrelid = 'items'::regclass AND NOT tgisinternal) THEN
EXECUTE 'CREATE TRIGGER items_change_token BEFORE INSERT OR UPDATE ON items FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'item_values_change_token' AND tgrelid = 'item_values'::regclass AND NOT tgisinternal) THEN
EXECUTE 'CREATE TRIGGER item_values_change_token BEFORE INSERT OR UPDATE ON item_values FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
END IF;
END;
$$;
2026-08-03 18:07:40 +02:00
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
deviceidorigin TEXT,
eventtype TEXT NOT NULL,
entitytype TEXT NOT NULL,
entityid TEXT,
listid TEXT,
createdat BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_notifications_createdat ON notifications(createdat);
CREATE INDEX IF NOT EXISTS idx_notifications_listid ON notifications(listid);
ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';
2026-09-01 01:34:48 +02:00
-- auth_users/auth_sessions are RETIRED as of the AuthGuard migration:
-- account and session state now lives in AuthGuard's own database,
-- reached over HTTP via authclient (see auth.go). These two tables and
-- their schema are deliberately left in place rather than dropped --
-- dropping tables/data is a separate, more destructive decision outside
-- the scope of that migration -- but no Go code reads or writes them for
-- authentication purposes anymore. pruneExpiredSessions keeps running
-- only as harmless best-effort cleanup of whatever rows a pre-migration
-- deployment already had.
2026-08-03 18:07:40 +02:00
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
2026-08-03 20:31:32 +02:00
email TEXT NOT NULL DEFAULT '',
2026-08-03 18:07:40 +02:00
password_hash TEXT NOT NULL,
2026-08-05 14:58:07 +02:00
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
2026-08-03 18:07:40 +02:00
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
2026-08-03 20:31:32 +02:00
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
2026-08-05 14:58:07 +02:00
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
2026-08-03 20:31:32 +02:00
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
2026-08-05 14:58:07 +02:00
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
DROP INDEX IF EXISTS auth_users_singleton_idx;
2026-08-03 18:07:40 +02:00
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions(expires_at);
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions(user_id);
2026-09-01 01:34:48 +02:00
-- collabtable_setup_state tracks only whether THIS CollabTable instance
-- has completed its one-time "create the first account" setup flow
-- against AuthGuard (see handleSetup in auth.go). It intentionally holds
-- no credentials or account identity of its own -- AuthGuard is the sole
-- source of truth for accounts -- just the boolean that used to be
-- derived from "COUNT(*) FROM auth_users" before the migration.
CREATE TABLE IF NOT EXISTS collabtable_setup_state (
id SMALLINT PRIMARY KEY DEFAULT 1,
claimed BOOLEAN NOT NULL DEFAULT FALSE,
claimed_at TIMESTAMPTZ,
CHECK (id = 1)
);
2026-09-13 21:11:53 +02:00
-- authguard_totp_cache is RETIRED as of the migration onto
-- shared/backend/auth (sharedauth.Service): it used to be a
-- best-effort, locally-cached mirror of "does this AuthGuard account
-- have TOTP enabled", keyed by AuthGuard's own numeric user id, needed
-- because AuthGuard's HTTP API had no endpoint to query current TOTP
-- status, only to enable/verify/disable it. sharedauth.Service's
-- Me/Status/TOTPStatus now read TOTP-enabled status live from
-- AuthGuard's GET /api/me on every request instead, so no Go code
-- reads or writes this table anymore. Left in place rather than
-- dropped, same as auth_users/auth_sessions above.
2026-09-01 01:34:48 +02:00
CREATE TABLE IF NOT EXISTS authguard_totp_cache (
authguard_user_id BIGINT PRIMARY KEY,
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- api_tokens backs the long-lived per-account bearer token CollabTable's
-- own devices use for the sync API (requireAPIToken in auth.go) -- a
-- concern entirely separate from browser-session auth, so it is NOT
-- proxied to AuthGuard. Its user_id used to be a foreign key into this
-- database's own auth_users; now that account identity lives in
-- AuthGuard (or, when AUTHGUARD_URL is unset, every caller shares the
-- fixed placeholder id 0 -- see localProfile/currentUserID in auth.go),
-- user_id is just an opaque identity id with no matching row in the
-- (now dormant) local auth_users table, so the FK constraint a
-- pre-migration deployment already has is dropped below.
2026-08-03 18:07:40 +02:00
CREATE TABLE IF NOT EXISTS api_tokens (
id BIGSERIAL PRIMARY KEY,
2026-09-01 01:34:48 +02:00
user_id BIGINT NOT NULL,
2026-08-03 18:07:40 +02:00
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
2026-09-01 01:34:48 +02:00
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
2026-10-20 15:27:53 +00:00
CREATE TABLE IF NOT EXISTS list_memberships (
listid TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
user_id BIGINT NOT NULL,
is_owner BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (listid, user_id)
);
CREATE INDEX IF NOT EXISTS idx_list_memberships_user ON list_memberships(user_id, listid);
2026-08-03 18:07:40 +02:00
` )
if err != nil {
return fmt . Errorf ( "initialize schema: %w" , err )
}
2026-10-20 15:27:53 +00:00
if err := d . backfillChangeTokens ( ctx ); err != nil {
return fmt . Errorf ( "backfill change tokens: %w" , err )
}
if err := d . backfillListMemberships ( ctx ); err != nil {
return fmt . Errorf ( "backfill list memberships: %w" , err )
}
2026-08-03 18:07:40 +02:00
return nil
}
2026-10-20 15:27:53 +00:00
func ( d * DB ) backfillListMemberships ( ctx context . Context ) error {
return d . withTx ( ctx , func ( tx pgx . Tx ) error {
if err := lockChangeClock ( ctx , tx ); err != nil {
return err
}
if _ , err := tx . Exec ( ctx , `
INSERT INTO list_memberships (listid, user_id, is_owner)
SELECT lists.id, token_users.user_id, FALSE
FROM lists
CROSS JOIN (SELECT DISTINCT user_id FROM api_tokens WHERE user_id <> 0) AS token_users
-- New lists already have their creator's membership, so they are not
-- expanded to every token user on later starts.
WHERE NOT EXISTS (SELECT 1 FROM list_memberships existing WHERE existing.listid = lists.id)
ON CONFLICT (listid, user_id) DO NOTHING
` ); err != nil {
return err
}
return nil
})
}
func ( d * DB ) backfillChangeTokens ( ctx context . Context ) error {
return d . withTx ( ctx , func ( tx pgx . Tx ) error {
if err := lockChangeClock ( ctx , tx ); err != nil {
return err
}
for _ , table := range [] string { "lists" , "fields" , "items" , "item_values" } {
if _ , err := tx . Exec ( ctx , `UPDATE ` + table + ` SET change_token = change_token WHERE change_token = 0` ); err != nil {
return err
}
}
return nil
})
}
2026-08-03 18:07:40 +02:00
func ( d * DB ) pruneExpiredSessions ( ctx context . Context ) {
ticker := time . NewTicker ( time . Hour )
defer ticker . Stop ()
for {
select {
case <- ctx . Done ():
return
case <- ticker . C :
if _ , err := d . pool . Exec ( ctx , `DELETE FROM auth_sessions WHERE expires_at < now()` ); err != nil {
2026-11-20 21:42:42 +01:00
logPrintf ( logshipper . LevelWarn , "[db] session prune failed: %v\n" , err )
2026-08-03 18:07:40 +02:00
}
}
}
}
func ( d * DB ) cleanupNotifications ( ctx context . Context ) {
retention := envInt64 ( "NOTIF_RETENTION_MS" , 7 * 24 * 60 * 60 * 1000 )
if retention < 0 {
retention = 0
}
ticker := time . NewTicker ( time . Hour )
defer ticker . Stop ()
for {
select {
case <- ctx . Done ():
return
case <- ticker . C :
cutoff := time . Now (). UnixMilli () - retention
if _ , err := d . pool . Exec ( ctx , `DELETE FROM notifications WHERE createdat < $1` , cutoff ); err != nil {
2026-11-20 21:42:42 +01:00
logPrintf ( logshipper . LevelWarn , "[db] notification cleanup failed: %v\n" , err )
2026-08-03 18:07:40 +02:00
}
}
}
}
2026-09-01 01:34:48 +02:00
// --- AuthGuard migration: local-only auxiliary state ------------------------
//
// Everything below is new state introduced by the AuthGuard migration. None
// of it is account/credential data -- that all lives in AuthGuard now -- it
// is bookkeeping CollabTable keeps about itself. See auth.go for how each is
// used.
2026-08-03 18:07:40 +02:00
2026-09-01 01:34:48 +02:00
// IsSetupClaimed reports whether this CollabTable instance has already
// completed its one-time setup flow (see TryClaimSetup).
func ( d * DB ) IsSetupClaimed ( ctx context . Context ) ( bool , error ) {
var claimed bool
err := d . pool . QueryRow ( ctx , `SELECT claimed FROM collabtable_setup_state WHERE id = 1` ). Scan ( & claimed )
2026-08-03 18:07:40 +02:00
if errors . Is ( err , pgx . ErrNoRows ) {
2026-09-01 01:34:48 +02:00
return false , nil
2026-08-03 18:07:40 +02:00
}
if err != nil {
2026-09-01 01:34:48 +02:00
return false , fmt . Errorf ( "check setup claim: %w" , err )
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
return claimed , nil
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
// TryClaimSetup atomically flips the local "setup completed" flag from
// unclaimed to claimed and reports whether this call was the one that did so.
// A caller that wins the claim but then fails to actually create the
// AuthGuard account (e.g. a validation error, or AuthGuard being unreachable)
// must call UnclaimSetup to reopen the slot for a later retry.
func ( d * DB ) TryClaimSetup ( ctx context . Context ) ( bool , error ) {
tag , err := d . pool . Exec ( ctx , `
INSERT INTO collabtable_setup_state (id, claimed, claimed_at) VALUES (1, TRUE, now())
ON CONFLICT (id) DO UPDATE SET claimed = TRUE, claimed_at = now()
WHERE collabtable_setup_state.claimed = FALSE
2026-08-05 14:58:07 +02:00
` )
if err != nil {
2026-09-01 01:34:48 +02:00
return false , fmt . Errorf ( "claim setup: %w" , err )
2026-08-05 14:58:07 +02:00
}
2026-09-01 01:34:48 +02:00
return tag . RowsAffected () > 0 , nil
2026-08-05 14:58:07 +02:00
}
2026-09-01 01:34:48 +02:00
// UnclaimSetup reopens the setup flow after a claimed-but-failed setup
// attempt (see TryClaimSetup).
func ( d * DB ) UnclaimSetup ( ctx context . Context ) error {
if _ , err := d . pool . Exec ( ctx , `UPDATE collabtable_setup_state SET claimed = FALSE, claimed_at = NULL WHERE id = 1` ); err != nil {
return fmt . Errorf ( "unclaim setup: %w" , err )
2026-08-05 14:58:07 +02:00
}
return nil
}
2026-09-13 21:11:53 +02:00
// Note: this instance used to also keep a local best-effort cache of each
// AuthGuard account's TOTP-enabled state (GetCachedTOTPEnabled/
// SetCachedTOTPEnabled, backed by the authguard_totp_cache table above) --
// that existed only because the pre-migration code believed AuthGuard could
// not report TOTP status live. It can (GET /api/me), so sharedauth.Service's
// Me/Status/TOTPStatus now read it live from AuthGuard directly and this
// cache's Go code was deleted along with the migration onto that shared
// package. The authguard_totp_cache table itself (and any rows already in
// it) is left in place rather than dropped, same as auth_users/auth_sessions
// above.
2026-08-03 18:07:40 +02:00
func ( d * DB ) hasAPIToken ( ctx context . Context , userID int64 ) ( bool , error ) {
var exists bool
if err := d . pool . QueryRow ( ctx , `
SELECT EXISTS(SELECT 1 FROM api_tokens WHERE user_id = $1)
` , userID ). Scan ( & exists ); err != nil {
return false , fmt . Errorf ( "check API token: %w" , err )
}
return exists , nil
}
func ( d * DB ) regenerateAPIToken ( ctx context . Context , userID int64 , tokenHash string ) error {
return d . withTx ( ctx , func ( tx pgx . Tx ) error {
if _ , err := tx . Exec ( ctx , `DELETE FROM api_tokens WHERE user_id = $1` , userID ); err != nil {
return fmt . Errorf ( "delete old API token: %w" , err )
}
if _ , err := tx . Exec ( ctx , `
INSERT INTO api_tokens (user_id, token_hash)
VALUES ($1, $2)
` , userID , tokenHash ); err != nil {
return fmt . Errorf ( "insert API token: %w" , err )
}
return nil
})
}
func ( d * DB ) getAPITokenUserID ( ctx context . Context , tokenHash string ) ( int64 , error ) {
var userID int64
err := d . pool . QueryRow ( ctx , `
SELECT user_id FROM api_tokens WHERE token_hash = $1
` , tokenHash ). Scan ( & userID )
if errors . Is ( err , pgx . ErrNoRows ) {
return 0 , nil
}
if err != nil {
return 0 , fmt . Errorf ( "get API token owner: %w" , err )
}
return userID , nil
}