Files
Levyraati26_go/migrate.go
T
Esa Kataja 1fe5211ae6 Replace Postgres with SQLite
Ten members and a handful of songs a week never needed a database server,
and the server was the last thing making this a two-container deployment.
modernc.org/sqlite is pure Go, so CGO_ENABLED=0 survives and the dependency
count is unchanged: pgx out, sqlite in.

The port stayed small because the driver matches $1-style placeholders
against argument ordinals exactly as pgx does, so no query needed rewriting
for parameters. What did change:

- timestamptz becomes timestamp holding UTC 'YYYY-MM-DD HH:MM:SS'. The
  declared type is what makes the driver return time.Time, and the
  fixed-width UTC string is what makes ordering and comparison against
  datetime('now') mean what they say.
- interval has no equivalent: sessions.idle_ttl is seconds, and the review
  edit window travels as a SQLite date modifier string.
- No stddev_pop, so the divisive and unified boards spell the population
  formula out, guarded with max(0.0, ...) because cancellation returns a
  tiny negative when every score is identical.
- foreign_keys is off by default, so the cascades only exist because the
  pragma is set on every connection.

Drops the postgres service, its healthcheck, the depends_on gate, the
startup retry loop and POSTGRES_PASSWORD. ./storage is now the whole
backup. Tests get a fresh database file per test and run everywhere
instead of skipping without TEST_DATABASE_URL.
2026-08-02 20:47:41 +03:00

119 lines
3.2 KiB
Go

package main
import (
"context"
"database/sql"
"embed"
"fmt"
"log/slog"
"sort"
)
//go:embed migrations/*.sql
var migrationFS embed.FS
// migrate applies every migrations/*.sql not yet recorded, in filename order, each in its own
// transaction. Applied names are the record — a file that changes after it ran is not re-applied.
func migrate(ctx context.Context, db *sql.DB) error {
_, err := db.ExecContext(ctx, `create table if not exists schema_migrations (
name text primary key,
applied_at timestamp not null default (datetime('now'))
)`)
if err != nil {
return fmt.Errorf("create schema_migrations: %w", err)
}
applied := map[string]bool{}
rows, err := db.QueryContext(ctx, `select name from schema_migrations`)
if err != nil {
return fmt.Errorf("read schema_migrations: %w", err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return err
}
applied[name] = true
}
if err := rows.Err(); err != nil {
return err
}
rows.Close()
entries, err := migrationFS.ReadDir("migrations")
if err != nil {
return err
}
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
sort.Strings(names)
for _, name := range names {
if applied[name] {
continue
}
sql, err := migrationFS.ReadFile("migrations/" + name)
if err != nil {
return err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, string(sql)); err != nil {
tx.Rollback()
return fmt.Errorf("migration %s: %w", name, err)
}
if _, err := tx.ExecContext(ctx, `insert into schema_migrations (name) values ($1)`, name); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("migration %s: %w", name, err)
}
slog.Info("migration applied", "ctx", "startup", "name", name)
}
return nil
}
// sweep runs the startup cleanup from docs/spec.md §4.6. An in-process conversion goroutine dies
// with the process, so without this those rows say "converting" forever.
func sweep(ctx context.Context, db *sql.DB) error {
res, err := db.ExecContext(ctx, `update submissions
set status = 'failed', status_msg = 'interrupted by restart'
where status in ('queued', 'downloading', 'converting')`)
if err != nil {
return err
}
if n := affected(res); n > 0 {
slog.Warn("submissions interrupted by restart", "ctx", "startup", "count", n)
}
// ponytail: temp files of swept submissions are unlinked with the row in step 3, once the
// pipeline exists and there is something to unlink.
if _, err := db.ExecContext(ctx,
`delete from submissions where created_at < datetime('now', '-7 days')`); err != nil {
return err
}
if _, err := db.ExecContext(ctx,
`delete from sessions where expires_at < datetime('now')`); err != nil {
return err
}
var failed int
err = db.QueryRowContext(ctx,
`select count(*) from submissions where status = 'failed'`).Scan(&failed)
if err != nil {
return err
}
if failed > 0 {
// A failed submission is invisible to everyone but its submitter, so a broken pipeline
// has no other way of announcing itself.
slog.Warn("failed submissions present", "ctx", "startup", "count", failed)
}
return nil
}