Files
CollabTable/backend/db.go
T
Gabriel20xx ac08be0248
Lint / Lint (push) Failing after 7s
Tests / Go backend (push) Failing after 6s
Tests / Dashboard checks (push) Failing after 4s
Docker / Docker Build & Push (push) Failing after 10s
Migrate shared UI and backend components
2026-08-04 17:05:37 +02:00

318 lines
9.4 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
sharedpostgres "repos.gfranz.ch/Gabriel20xx/SharedCode/backend/postgres"
)
// 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) {
pool, err := sharedpostgres.Open(ctx, sharedpostgres.DefaultConfig(connectionString))
if err != nil {
return nil, err
}
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 {
return sharedpostgres.WithTx(ctx, d.pool, fn)
}
// 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,
isdeleted INTEGER NOT NULL DEFAULT 0
);
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,
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,
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,
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);
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';
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
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);
CREATE TABLE IF NOT EXISTS api_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
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);
`)
if err != nil {
return fmt.Errorf("initialize schema: %w", err)
}
return nil
}
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 {
fmt.Printf("[db] session prune failed: %v\n", err)
}
}
}
}
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 {
fmt.Printf("[db] notification cleanup failed: %v\n", err)
}
}
}
}
type AuthUser struct {
ID int64
Username string
Email string
PasswordHash string
}
var ErrSingletonUserExists = errors.New("a user already exists")
func (d *DB) countUsers(ctx context.Context) (int, error) {
var count int
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
return 0, fmt.Errorf("count users: %w", err)
}
return count, nil
}
func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, updated_at)
VALUES ($1, $2, $3, now())
RETURNING id, username, email
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email)
if err != nil {
if sharedpostgres.IsUniqueViolation(err) {
return nil, ErrSingletonUserExists
}
return nil, fmt.Errorf("create user: %w", err)
}
user.PasswordHash = passwordHash
return &user, nil
}
func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
SELECT id, username, email, password_hash
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("get user: %w", err)
}
return &user, nil
}
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
SELECT u.id, u.username, u.email, u.password_hash
FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now()
`, tokenHash).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("get session user: %w", err)
}
return &user, nil
}
func (d *DB) createSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
_, err := d.pool.Exec(ctx, `
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
VALUES ($1, $2, $3)
`, userID, tokenHash, expiresAt)
if err != nil {
return fmt.Errorf("create session: %w", err)
}
return nil
}
func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash)
if err != nil {
return fmt.Errorf("delete session: %w", err)
}
return nil
}
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, email, passwordHash string) error {
_, err := d.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
`, username, email, passwordHash, userID)
if err != nil {
return fmt.Errorf("update user credentials: %w", err)
}
return nil
}
func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
if err != nil {
return fmt.Errorf("delete sessions for user: %w", err)
}
return nil
}
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
}