From 6a08cc8d63d5dd41e6b37bd139cbd55a5868dd62 Mon Sep 17 00:00:00 2001 From: Timo Ruohomaki Date: Sun, 8 Nov 2026 21:10:55 +0200 Subject: [PATCH] MOS-12: Add goose migrations and initial PostgreSQL schema internal/store/postgres embeds SQL migrations and applies them with goose (Migrate, MigrateDownTo, Version). Tables and the goose version table live in the openmos schema; a Postgres session lock keeps concurrent deploys from migrating at once, and the schema is only created if missing, so openmos_migrate needs no CREATE on the database. 00001_init.sql creates running_orders, stories, items and mos_objects: composite keys, deferrable per-parent position constraints, sample-based durations with an exact numeric time base, timestamptz, cascade deletes and MOS limits as CHECK constraints. No GRANTs (default privileges). Tests cover up/down/up, keys, deferred swaps, cascades and limits against OPENMOS_TEST_DATABASE_URL (skipped locally without it, required in CI). CI gains a postgres:17 service container. goose v3.29 requires Go 1.26, so go.mod moves from 1.25 (now out of support) to 1.26. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 18 ++ doc/developer-reference.md | 24 +++ src/go.mod | 15 +- src/go.sum | 61 +++++-- src/internal/store/postgres/migrate.go | 119 +++++++++++++ src/internal/store/postgres/migrate_test.go | 79 +++++++++ .../store/postgres/migrations/00001_init.sql | 101 +++++++++++ src/internal/store/postgres/schema_test.go | 166 ++++++++++++++++++ src/internal/store/postgres/testdb_test.go | 72 ++++++++ 9 files changed, 640 insertions(+), 15 deletions(-) create mode 100644 src/internal/store/postgres/migrate.go create mode 100644 src/internal/store/postgres/migrate_test.go create mode 100644 src/internal/store/postgres/migrations/00001_init.sql create mode 100644 src/internal/store/postgres/schema_test.go create mode 100644 src/internal/store/postgres/testdb_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2730632..c8f7312 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,24 @@ jobs: go: name: Build, vet, test, staticcheck runs-on: ubuntu-latest + # Throwaway PostgreSQL for the store tests; they skip without + # OPENMOS_TEST_DATABASE_URL locally, but must run here. + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: openmos + POSTGRES_PASSWORD: openmos + POSTGRES_DB: openmos_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U openmos -d openmos_test" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + OPENMOS_TEST_DATABASE_URL: postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable steps: - uses: actions/checkout@v5 diff --git a/doc/developer-reference.md b/doc/developer-reference.md index a647822..6bb136b 100644 --- a/doc/developer-reference.md +++ b/doc/developer-reference.md @@ -54,6 +54,7 @@ OpenMOS follows a **Clean Layered Architecture** with clear separation of concer | **Server** | `internal/server/` | TCP connections, client management, heartbeat monitoring | | **Service** | `internal/service/` | Business logic, MOS operations, event publishing | | **Repository** | `internal/repository/` | Data access abstraction, CRUD operations | +| **Store** | `internal/store/postgres/` | PostgreSQL schema migrations (pool and repositories to follow) | | **Model** | `internal/model/` | Domain entities and value objects | | **XML** | `internal/xml/` | Message parsing and serialization | | **Events** | `internal/events/` | Pub-sub event bus for real-time notifications | @@ -85,6 +86,10 @@ OpenMOS/ │ │ │ ├── memory/ # In-memory reference implementation │ │ │ └── repotest/ # Contract suite for every implementation │ │ │ +│ │ ├── store/postgres/ +│ │ │ ├── migrate.go # Goose migrations (embedded SQL) +│ │ │ └── migrations/ # Schema migrations (00001_init.sql, ...) +│ │ │ │ │ ├── server/ │ │ │ ├── server.go # TCPServer main logic │ │ │ ├── client.go # ClientConnection management @@ -313,6 +318,25 @@ sentry: call `repotest.Run` from its tests (see `repository/memory`) - Use interfaces to enable mocking - Test XML parsing with example messages from `/res/` +- PostgreSQL tests (`internal/store/postgres`) need a throwaway database in + `OPENMOS_TEST_DATABASE_URL`; without it they skip locally (CI provides one). + They drop and recreate the `openmos` schema, so never point it at real data: + + ```bash + docker run -d --name openmos-pg -p 127.0.0.1:5432:5432 \ + -e POSTGRES_USER=openmos -e POSTGRES_PASSWORD=openmos -e POSTGRES_DB=openmos_test postgres:17 + export OPENMOS_TEST_DATABASE_URL='postgres://openmos:openmos@localhost:5432/openmos_test?sslmode=disable' + go test ./internal/store/... + ``` + +### Schema migrations +- Migrations are SQL files in `internal/store/postgres/migrations`, embedded + in the binary and applied with goose (`postgres.Migrate`). Tables and the + goose version table live in the `openmos` schema. +- Never edit a migration that has been applied anywhere; add a new one. +- Migrations run as the schema owner (`openmos_migrate` on Aiven) over a + direct connection, not a PgBouncer pool. Do not add GRANTs: the runtime + role `openmos_app` gets privileges through `ALTER DEFAULT PRIVILEGES`. ### Contributing 1. Create a feature branch from main diff --git a/src/go.mod b/src/go.mod index f4b70da..e1117c5 100644 --- a/src/go.mod +++ b/src/go.mod @@ -1,13 +1,22 @@ module airshift/openmos -go 1.25.0 +go 1.26.0 require ( github.com/getsentry/sentry-go v0.50.0 + github.com/jackc/pgx/v5 v5.12.0 + github.com/pressly/goose/v3 v3.29.0 go.yaml.in/yaml/v3 v3.0.6 ) require ( - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.41.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/mfridman/interpolate v0.0.2 // indirect + github.com/sethvargo/go-retry v0.5.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect ) diff --git a/src/go.sum b/src/go.sum index 2d10a21..84dd030 100644 --- a/src/go.sum +++ b/src/go.sum @@ -1,26 +1,63 @@ -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g= github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.12.0 h1:hWwax8YiGT0YiN50U1oIDn5kgR7KC2tG3rmavwpPkxY= +github.com/jackc/pgx/v5 v5.12.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= +github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose/v3 v3.29.0 h1:dtEnBCT7CqkHIUCdgrXsrmeisaN8gFkRU4Y5OEwif4o= +github.com/pressly/goose/v3 v3.29.0/go.mod h1:plA4aP4+u+Q3FMTgbFbhF8TuAWpAdfWpoFGkJsIFWh0= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= +github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= -golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/libc v1.78.0 h1:Lpm+e9K6ruVYEGwWfuBO1xXtYEaXDouFOG1SuWjFDP4= +modernc.org/libc v1.78.0/go.mod h1:wvxR55nOF2/66NkJoNV7/coXBTCvT3HR22rcqW6lOuA= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw= +modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0= diff --git a/src/internal/store/postgres/migrate.go b/src/internal/store/postgres/migrate.go new file mode 100644 index 0000000..1825ca8 --- /dev/null +++ b/src/internal/store/postgres/migrate.go @@ -0,0 +1,119 @@ +// Package postgres is the PostgreSQL store: schema migrations now, and the +// connection pool and repositories as they are added (MOS-13, MOS-14). +package postgres + +import ( + "context" + "database/sql" + "embed" + "fmt" + "io/fs" + + "github.com/pressly/goose/v3" + "github.com/pressly/goose/v3/lock" + + // Registers the "pgx" database/sql driver that goose runs on. + _ "github.com/jackc/pgx/v5/stdlib" +) + +// Schema is the PostgreSQL schema that holds all OpenMOS tables, including +// the goose version table. +const Schema = "openmos" + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +// Open opens a database/sql handle on the pgx driver for running +// migrations. Use a direct connection, not a PgBouncer transaction pool: +// goose holds a session-level advisory lock while it migrates. +func Open(databaseURL string) (*sql.DB, error) { + db, err := sql.Open("pgx", databaseURL) + if err != nil { + return nil, fmt.Errorf("open database: %w", err) + } + return db, nil +} + +// Migrate applies all pending migrations and returns the versions applied. +// It runs as the schema owner (openmos_migrate on Aiven). If the schema does +// not exist yet, as in a fresh local database, it is created first. +func Migrate(ctx context.Context, db *sql.DB) ([]int64, error) { + if err := ensureSchema(ctx, db); err != nil { + return nil, err + } + p, err := newProvider(db) + if err != nil { + return nil, err + } + results, err := p.Up(ctx) + if err != nil { + return nil, fmt.Errorf("migrate up: %w", err) + } + applied := make([]int64, len(results)) + for i, r := range results { + applied[i] = r.Source.Version + } + return applied, nil +} + +// MigrateDownTo rolls back migrations until version is the latest applied; +// version 0 rolls back everything. It is for tests and manual rollback. +func MigrateDownTo(ctx context.Context, db *sql.DB, version int64) error { + p, err := newProvider(db) + if err != nil { + return err + } + if _, err := p.DownTo(ctx, version); err != nil { + return fmt.Errorf("migrate down to %d: %w", version, err) + } + return nil +} + +// Version returns the latest applied migration version, 0 if none. +func Version(ctx context.Context, db *sql.DB) (int64, error) { + p, err := newProvider(db) + if err != nil { + return 0, err + } + return p.GetDBVersion(ctx) +} + +func newProvider(db *sql.DB) (*goose.Provider, error) { + fsys, err := fs.Sub(migrationFiles, "migrations") + if err != nil { + return nil, err + } + // The advisory lock keeps two deploys from migrating at the same time. + locker, err := lock.NewPostgresSessionLocker() + if err != nil { + return nil, err + } + p, err := goose.NewProvider(goose.DialectPostgres, db, fsys, + goose.WithTableName(Schema+".goose_db_version"), + goose.WithSessionLocker(locker), + goose.WithDisableGlobalRegistry(true), + ) + if err != nil { + return nil, fmt.Errorf("create migration provider: %w", err) + } + return p, nil +} + +// ensureSchema creates the schema if it is missing. On Aiven it already +// exists, owned by openmos_migrate, so no CREATE privilege on the database +// is needed there. +func ensureSchema(ctx context.Context, db *sql.DB) error { + var exists bool + err := db.QueryRowContext(ctx, + "SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = $1)", Schema).Scan(&exists) + if err != nil { + return fmt.Errorf("check schema %s: %w", Schema, err) + } + if exists { + return nil + } + if _, err := db.ExecContext(ctx, "CREATE SCHEMA "+Schema); err != nil { + return fmt.Errorf("create schema %s: %w", Schema, err) + } + return nil +} diff --git a/src/internal/store/postgres/migrate_test.go b/src/internal/store/postgres/migrate_test.go new file mode 100644 index 0000000..432fb71 --- /dev/null +++ b/src/internal/store/postgres/migrate_test.go @@ -0,0 +1,79 @@ +package postgres + +import ( + "slices" + "testing" +) + +// tables are the OpenMOS tables, sorted, without goose's version table. +var tables = []string{"items", "mos_objects", "running_orders", "stories"} + +func TestMigrateUpDownUp(t *testing.T) { + db := testDB(t) + ctx := t.Context() + + listTables := func() []string { + t.Helper() + rows, err := db.QueryContext(ctx, `SELECT tablename FROM pg_tables + WHERE schemaname = $1 AND tablename <> 'goose_db_version' ORDER BY tablename`, Schema) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var names []string + for rows.Next() { + var n string + if err := rows.Scan(&n); err != nil { + t.Fatal(err) + } + names = append(names, n) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + return names + } + + // Up on an empty database creates the schema and every table + applied, err := Migrate(ctx, db) + if err != nil { + t.Fatalf("Migrate: %v", err) + } + if !slices.Equal(applied, []int64{1}) { + t.Errorf("applied = %v, want [1]", applied) + } + if got := listTables(); !slices.Equal(got, tables) { + t.Errorf("tables after up = %v, want %v", got, tables) + } + + // Up again is a no-op + applied, err = Migrate(ctx, db) + if err != nil { + t.Fatalf("second Migrate: %v", err) + } + if len(applied) != 0 { + t.Errorf("second Migrate applied %v, want nothing", applied) + } + + // Down removes every table + if err := MigrateDownTo(ctx, db, 0); err != nil { + t.Fatalf("MigrateDownTo(0): %v", err) + } + if got := listTables(); len(got) != 0 { + t.Errorf("tables after down = %v, want none", got) + } + if v, err := Version(ctx, db); err != nil || v != 0 { + t.Errorf("Version after down = %d, %v; want 0", v, err) + } + + // And up works again after a full rollback + if _, err := Migrate(ctx, db); err != nil { + t.Fatalf("Migrate after down: %v", err) + } + if got := listTables(); !slices.Equal(got, tables) { + t.Errorf("tables after re-up = %v, want %v", got, tables) + } + if v, err := Version(ctx, db); err != nil || v != 1 { + t.Errorf("Version = %d, %v; want 1", v, err) + } +} diff --git a/src/internal/store/postgres/migrations/00001_init.sql b/src/internal/store/postgres/migrations/00001_init.sql new file mode 100644 index 0000000..994ecc4 --- /dev/null +++ b/src/internal/store/postgres/migrations/00001_init.sql @@ -0,0 +1,101 @@ +-- Initial OpenMOS schema. See doc/database-migration.md. +-- +-- * Keys are composite: MOS IDs are unique only within their parent +-- (storyID within its running order, itemID within its story, objID within +-- its MOS device). MOS limits IDs to 128 characters. +-- * Stories and items have an explicit position, unique per parent. The +-- constraints are deferrable, so moves and swaps can renumber inside one +-- transaction (SET CONSTRAINTS ... DEFERRED). +-- * Timing follows the protocol: item and object durations are counts of +-- samples (0..0xFFFFFFFF) with a time base in samples per second (objTB, +-- e.g. 50 for PAL or 59.94 for NTSC). roEdDur is hh:mm:ss, so an interval. +-- * Times are timestamptz (UTC). created_at/updated_at are set by the +-- repositories; the defaults only cover direct inserts. +-- * metadata holds simple key/value metadata. How mosExternalMetadata blocks +-- are stored is still open and will come in a later migration. +-- * No GRANTs here: openmos_app gets table privileges through ALTER DEFAULT +-- PRIVILEGES for openmos_migrate (backend01 runbook, MOS-31). + +-- +goose Up +CREATE TABLE openmos.running_orders ( + ro_id text PRIMARY KEY CHECK (ro_id <> '' AND char_length(ro_id) <= 128), + mos_id text NOT NULL DEFAULT '', + slug text NOT NULL DEFAULT '', + channel text NOT NULL DEFAULT '', + ed_start timestamptz, + ed_dur interval CHECK (ed_dur >= interval '0'), + air_trigger text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'PENDING', + metadata jsonb NOT NULL DEFAULT '{}', + version integer NOT NULL DEFAULT 1 CHECK (version >= 1), + created_by text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE openmos.stories ( + ro_id text NOT NULL REFERENCES openmos.running_orders (ro_id) ON DELETE CASCADE, + story_id text NOT NULL CHECK (story_id <> '' AND char_length(story_id) <= 128), + position integer NOT NULL CHECK (position >= 0), + slug text NOT NULL DEFAULT '', + number text NOT NULL DEFAULT '', + presenter text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'PENDING', + metadata jsonb NOT NULL DEFAULT '{}', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (ro_id, story_id), + CONSTRAINT stories_position_key UNIQUE (ro_id, position) DEFERRABLE INITIALLY IMMEDIATE +); + +CREATE TABLE openmos.items ( + ro_id text NOT NULL, + story_id text NOT NULL, + item_id text NOT NULL CHECK (item_id <> '' AND char_length(item_id) <= 128), + position integer NOT NULL CHECK (position >= 0), + slug text NOT NULL DEFAULT '', + obj_id text NOT NULL DEFAULT '', + mos_id text NOT NULL DEFAULT '', + channel text NOT NULL DEFAULT '', + ed_start bigint CHECK (ed_start BETWEEN 0 AND 4294967295), + ed_dur bigint CHECK (ed_dur BETWEEN 0 AND 4294967295), + user_timing_dur bigint CHECK (user_timing_dur BETWEEN 0 AND 4294967295), + time_base numeric CHECK (time_base > 0), + air_trigger text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'PENDING', + metadata jsonb NOT NULL DEFAULT '{}', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (ro_id, story_id, item_id), + FOREIGN KEY (ro_id, story_id) REFERENCES openmos.stories (ro_id, story_id) ON DELETE CASCADE, + CONSTRAINT items_position_key UNIQUE (ro_id, story_id, position) DEFERRABLE INITIALLY IMMEDIATE +); + +-- Objects are independent of running orders: items refer to them by +-- (mos_id, obj_id) without a foreign key, because an item may point at an +-- object this server has not seen. +CREATE TABLE openmos.mos_objects ( + mos_id text NOT NULL CHECK (mos_id <> '' AND char_length(mos_id) <= 128), + obj_id text NOT NULL CHECK (obj_id <> '' AND char_length(obj_id) <= 128), + slug text NOT NULL DEFAULT '', + obj_type text CHECK (obj_type IN ('STILL', 'AUDIO', 'VIDEO')), + time_base numeric CHECK (time_base > 0), + duration bigint CHECK (duration BETWEEN 0 AND 4294967295), + air text CHECK (air IN ('READY', 'NOT READY')), + status text NOT NULL DEFAULT 'PENDING', + abstract text NOT NULL DEFAULT '', + obj_group text NOT NULL DEFAULT '', + revision integer CHECK (revision BETWEEN 0 AND 999), + created_by text NOT NULL DEFAULT '', + changed_by text NOT NULL DEFAULT '', + metadata jsonb NOT NULL DEFAULT '{}', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (mos_id, obj_id) +); + +-- +goose Down +DROP TABLE openmos.mos_objects; +DROP TABLE openmos.items; +DROP TABLE openmos.stories; +DROP TABLE openmos.running_orders; diff --git a/src/internal/store/postgres/schema_test.go b/src/internal/store/postgres/schema_test.go new file mode 100644 index 0000000..40458a5 --- /dev/null +++ b/src/internal/store/postgres/schema_test.go @@ -0,0 +1,166 @@ +package postgres + +import ( + "database/sql" + "errors" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" +) + +// PostgreSQL error codes the schema is expected to raise. +const ( + uniqueViolation = "23505" + foreignKeyViolation = "23503" + checkViolation = "23514" +) + +// wantPgError fails the test unless stmt fails with the given SQLSTATE code. +func wantPgError(t *testing.T, db *sql.DB, code, stmt string) { + t.Helper() + _, err := db.ExecContext(t.Context(), stmt) + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != code { + t.Errorf("%s:\n err = %v, want SQLSTATE %s", stmt, err, code) + } +} + +// seed creates ro-1 with stories s1 (items i1, i2) and s2 (item i3). +func seed(t *testing.T, db *sql.DB) { + t.Helper() + exec(t, db, + `INSERT INTO openmos.running_orders (ro_id) VALUES ('ro-1')`, + `INSERT INTO openmos.stories (ro_id, story_id, position) VALUES ('ro-1', 's1', 0), ('ro-1', 's2', 1)`, + `INSERT INTO openmos.items (ro_id, story_id, item_id, position) + VALUES ('ro-1', 's1', 'i1', 0), ('ro-1', 's1', 'i2', 1), ('ro-1', 's2', 'i3', 0)`, + ) +} + +func TestCompositeKeys(t *testing.T) { + db := migrated(t) + seed(t, db) + + // The same story and item IDs may appear under another parent + exec(t, db, + `INSERT INTO openmos.running_orders (ro_id) VALUES ('ro-2')`, + `INSERT INTO openmos.stories (ro_id, story_id, position) VALUES ('ro-2', 's1', 0)`, + `INSERT INTO openmos.items (ro_id, story_id, item_id, position) VALUES ('ro-2', 's1', 'i1', 0)`, + `INSERT INTO openmos.mos_objects (mos_id, obj_id) VALUES ('a.mos', 'o1'), ('b.mos', 'o1')`, + ) + // but not twice under the same one + wantPgError(t, db, uniqueViolation, `INSERT INTO openmos.stories (ro_id, story_id, position) VALUES ('ro-1', 's1', 5)`) + wantPgError(t, db, uniqueViolation, `INSERT INTO openmos.items (ro_id, story_id, item_id, position) VALUES ('ro-1', 's1', 'i1', 5)`) + wantPgError(t, db, uniqueViolation, `INSERT INTO openmos.mos_objects (mos_id, obj_id) VALUES ('a.mos', 'o1')`) + + // and a child needs its parent + wantPgError(t, db, foreignKeyViolation, `INSERT INTO openmos.stories (ro_id, story_id, position) VALUES ('missing', 's1', 0)`) + wantPgError(t, db, foreignKeyViolation, `INSERT INTO openmos.items (ro_id, story_id, item_id, position) VALUES ('ro-1', 'missing', 'i1', 0)`) +} + +func TestPositions(t *testing.T) { + db := migrated(t) + seed(t, db) + + wantPgError(t, db, uniqueViolation, `INSERT INTO openmos.stories (ro_id, story_id, position) VALUES ('ro-1', 's3', 1)`) + wantPgError(t, db, uniqueViolation, `INSERT INTO openmos.items (ro_id, story_id, item_id, position) VALUES ('ro-1', 's1', 'i9', 0)`) + + // Swapping two stories one row at a time fails while the constraint is + // checked per statement + tx, err := db.BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + _, err = tx.ExecContext(t.Context(), `UPDATE openmos.stories SET position = 1 WHERE ro_id = 'ro-1' AND story_id = 's1'`) + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != uniqueViolation { + t.Errorf("immediate swap step: err = %v, want SQLSTATE %s", err, uniqueViolation) + } + tx.Rollback() + + // but succeeds once deferred to commit + tx, err = db.BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + for _, s := range []string{ + `SET CONSTRAINTS openmos.stories_position_key DEFERRED`, + `UPDATE openmos.stories SET position = 1 WHERE ro_id = 'ro-1' AND story_id = 's1'`, + `UPDATE openmos.stories SET position = 0 WHERE ro_id = 'ro-1' AND story_id = 's2'`, + } { + if _, err := tx.ExecContext(t.Context(), s); err != nil { + tx.Rollback() + t.Fatalf("%s: %v", s, err) + } + } + if err := tx.Commit(); err != nil { + t.Fatalf("commit deferred swap: %v", err) + } + var first string + if err := db.QueryRowContext(t.Context(), + `SELECT story_id FROM openmos.stories WHERE ro_id = 'ro-1' ORDER BY position LIMIT 1`).Scan(&first); err != nil { + t.Fatal(err) + } + if first != "s2" { + t.Errorf("first story after swap = %s, want s2", first) + } +} + +func TestCascadeDeletes(t *testing.T) { + db := migrated(t) + seed(t, db) + + exec(t, db, `DELETE FROM openmos.stories WHERE ro_id = 'ro-1' AND story_id = 's1'`) + if n := count(t, db, `SELECT count(*) FROM openmos.items WHERE story_id = 's1'`); n != 0 { + t.Errorf("%d items left after deleting their story", n) + } + if n := count(t, db, `SELECT count(*) FROM openmos.items`); n != 1 { + t.Errorf("%d items left, want 1 (i3)", n) + } + + exec(t, db, `DELETE FROM openmos.running_orders WHERE ro_id = 'ro-1'`) + if n := count(t, db, `SELECT count(*) FROM openmos.stories`) + count(t, db, `SELECT count(*) FROM openmos.items`); n != 0 { + t.Errorf("%d stories and items left after deleting their running order", n) + } +} + +func TestMOSLimits(t *testing.T) { + db := migrated(t) + seed(t, db) + long := strings.Repeat("x", 129) + + for _, stmt := range []string{ + `INSERT INTO openmos.running_orders (ro_id) VALUES ('')`, + `INSERT INTO openmos.running_orders (ro_id) VALUES ('` + long + `')`, + `INSERT INTO openmos.running_orders (ro_id, ed_dur) VALUES ('ro-neg', interval '-1 second')`, + `INSERT INTO openmos.stories (ro_id, story_id, position) VALUES ('ro-1', 's9', -1)`, + `UPDATE openmos.items SET ed_dur = -1 WHERE item_id = 'i1'`, + `UPDATE openmos.items SET ed_dur = 4294967296 WHERE item_id = 'i1'`, + `UPDATE openmos.items SET time_base = 0 WHERE item_id = 'i1'`, + `INSERT INTO openmos.mos_objects (mos_id, obj_id, obj_type) VALUES ('a.mos', 'o1', 'FILM')`, + `INSERT INTO openmos.mos_objects (mos_id, obj_id, air) VALUES ('a.mos', 'o1', 'MAYBE')`, + `INSERT INTO openmos.mos_objects (mos_id, obj_id, revision) VALUES ('a.mos', 'o1', 1000)`, + } { + wantPgError(t, db, checkViolation, stmt) + } + + // Values at the limits are accepted, and an NTSC time base is exact + exec(t, db, + `INSERT INTO openmos.running_orders (ro_id) VALUES ('`+strings.Repeat("x", 128)+`')`, + `UPDATE openmos.items SET ed_dur = 4294967295, time_base = 59.94 WHERE item_id = 'i1'`, + ) + var tb string + if err := db.QueryRowContext(t.Context(), + `SELECT time_base::text FROM openmos.items WHERE item_id = 'i1'`).Scan(&tb); err != nil { + t.Fatal(err) + } + if tb != "59.94" { + t.Errorf("time_base = %s, want 59.94", tb) + } + + // A float column would print 59.94 too, so check the type is exact + if n := count(t, db, `SELECT count(*) FROM information_schema.columns + WHERE table_schema = 'openmos' AND column_name = 'time_base' AND data_type = 'numeric'`); n != 2 { + t.Errorf("%d numeric time_base columns, want 2 (items, mos_objects)", n) + } +} diff --git a/src/internal/store/postgres/testdb_test.go b/src/internal/store/postgres/testdb_test.go new file mode 100644 index 0000000..84543d5 --- /dev/null +++ b/src/internal/store/postgres/testdb_test.go @@ -0,0 +1,72 @@ +package postgres + +import ( + "context" + "database/sql" + "os" + "testing" +) + +// testDBEnv names a throwaway database for tests. The tests drop and +// recreate the openmos schema in it, so never point it at real data. +const testDBEnv = "OPENMOS_TEST_DATABASE_URL" + +// testDB returns a connection to an empty test database, or skips the test +// if testDBEnv is not set. The openmos schema is dropped before and after. +func testDB(t *testing.T) *sql.DB { + t.Helper() + url := os.Getenv(testDBEnv) + if url == "" { + // CI provides a database, so a missing URL there is a broken setup, + // not a reason to skip. + if os.Getenv("CI") != "" { + t.Fatalf("%s must be set in CI", testDBEnv) + } + t.Skipf("%s not set; skipping PostgreSQL test", testDBEnv) + } + db, err := Open(url) + if err != nil { + t.Fatal(err) + } + dropSchema := func() { + if _, err := db.ExecContext(context.Background(), "DROP SCHEMA IF EXISTS "+Schema+" CASCADE"); err != nil { + t.Fatalf("drop schema: %v", err) + } + } + dropSchema() + t.Cleanup(func() { + dropSchema() + db.Close() + }) + return db +} + +// migrated returns a test database with all migrations applied. +func migrated(t *testing.T) *sql.DB { + t.Helper() + db := testDB(t) + if _, err := Migrate(t.Context(), db); err != nil { + t.Fatalf("Migrate: %v", err) + } + return db +} + +// exec runs statements that must succeed. +func exec(t *testing.T, db *sql.DB, stmts ...string) { + t.Helper() + for _, s := range stmts { + if _, err := db.ExecContext(t.Context(), s); err != nil { + t.Fatalf("%s: %v", s, err) + } + } +} + +// count returns the result of a COUNT(*) query. +func count(t *testing.T, db *sql.DB, query string) int { + t.Helper() + var n int + if err := db.QueryRowContext(t.Context(), query).Scan(&n); err != nil { + t.Fatalf("%s: %v", query, err) + } + return n +}