Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(db): versioned PostgreSQL schema-migration runner (#1029)

Adam Eivy29b449fa8497
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3b23164759..c13c75b073 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Versioned PostgreSQL schema-migration runner** — PortOS now has a lightweight, ordered DB-migration runner for schema *deltas* that the boot-time `ensureSchema()` (which only handles additive `CREATE/ADD IF NOT EXISTS` fresh-install DDL) can't express: column renames, type changes, data transforms, and embedding-dimension changes. Ordered migration files live in `server/scripts/db-migrations/` (both `.sql` and `.js` — a `.js` migration exports `async up(client)` and receives the transaction client so it can read + transform rows in the same transaction). On boot, after the base schema is ensured and the database-ready gate passes but before any store warms or the server starts listening, each unapplied migration runs inside a single transaction together with the insert that records it in a new `schema_migrations` tracking table — so a failed migration rolls back atomically (never marked applied) and aborts boot loudly rather than leaving a half-migrated install serving requests. Already-applied migrations are skipped, so the runner is idempotent on every boot. No real migration ships yet (the schema is current) — this is the runner, the tracking table, and the format documentation (`server/scripts/db-migrations/README.md`). The runner is skipped entirely under the `MEMORY_BACKEND=file` dev/test escape hatch, like `ensureSchema()`. (#1029)
- **Songs: sheet-music harmony parts, derived from the melody by AI** — a song can now carry multiple staves beyond its base melody — **Bass, Mid Harmony I/II, High Harmony I/II** — each its own sheet music that stacks with the melody when sung together. In the Sheet music editor there's a new **Sheet music parts** section with a one-click **Derive with AI**: it reads the song's base melody and writes a full layered-folk vocal stack — *chord-tone* voicings (each voice targets a chord tone and moves smoothly, rather than tracking the melody in parallel 3rds/6ths like a "MIDI choir"), with a hymn-like root–fifth bass, sustained inner pads, an upper pad that keeps the dominant-7 leading tone (e.g. the F# on D7 that pulls back to G), a sparse top descant that enters late, sensible per-voice ranges, and staggered entrances. Parts land in the editor for you to review, tweak, and Save — nothing is auto-saved. You can also add a blank part (seeded from the melody) and hand-edit it. In the read/perform view, the Sheet music card gains a part switcher — flip between Melody and each harmony (laid out low→high) and play any one back as a reference tone on its own. Derive is gated on the base melody being saved (it reads the persisted score), so you won't harmonize stale notes. Built on the existing in-house lead-sheet renderer — no third-party engraving or MIDI library. The built-in **"500 Miles"** now ships with the full five-part harmony stack as a worked example.
- **Songs: pitch-detection core (foundation for the upcoming vocal tuner & color-match)** — a new in-house, dependency-free DSP module estimates the fundamental frequency of sung audio (McLeod normalized-square-difference autocorrelation, with a clarity score that rejects silence and noise) and maps frequency↔note using the same diatonic staff math the sheet-music renderer already uses — so a detected pitch lands on exactly the note position the staff would draw. It also ships a live pitch tracker that reads a microphone analyser on an animation-frame loop and smooths the result (median + EMA) to suppress the octave jumps raw vocal detection produces. No new third-party library — like the rest of the song system's notation stack, the detector is hand-rolled in-tree. This is groundwork; the singer-facing tuner, color-match grading, and sing-to-score features build on it.
- **Songs — an a cappella song workbench (Create → Songs)** — write, arrange, and learn songs like "500 Miles" by Peter, Paul and Mary. Each song tracks its key, tempo, and rhythm shape (slow 4/4 ballad, compound 6/8 dirge, free-time lament, and more), lyric sections, and the voice layers you're stacking — with per-layer learning notes. An "Add from ladder" picker seeds layers in the recommended foundation-first order (lead → bass → thirds → fifths → drone → counter-melody). A deep-linkable **Learning Guide** (Create → Songs → Learning Guide, or `/songs/guide`) covers dirge rhythm shapes with tempo bands, the layer-building ladder, a step-by-step practice sequence for learning a new song, and a plain-language musical-notation primer (staves, time signatures, note values, dynamics, reading a lead sheet). A worked "500 Miles" example is seeded on first visit. Reachable from `⌘K` and voice nav.
diff --git a/server/index.js b/server/index.js
index 69d61dc485..393ba0c7ae 100644
--- a/server/index.js
+++ b/server/index.js
@@ -817,6 +817,26 @@ ensureSelf()
return;
}
await ensureSchema();
+ // Versioned DB-migration runner (#1029): apply ordered schema-DELTA
+ // migrations (renames / type changes / data transforms / embedding-dim
+ // changes) that ensureSchema()'s additive IF NOT EXISTS gates can't
+ // express. Runs AFTER ensureSchema() (base schema + schema_migrations
+ // tracking table present) and AFTER the DB-ready gate, but BEFORE any
+ // store warm or httpServer.listen — so a half-applied delta can't race a
+ // request. Skipped under the file backend by the !dbReady early return
+ // above. A FAILED migration is FATAL: each migration runs in a transaction
+ // so a failure rolls back (NOT marked applied), but we must NOT let boot
+ // continue — a partially-migrated install serving requests is worse than a
+ // hard stop. So this gets its own try/catch (not the generic catalog one
+ // below, which only logs and continues) that exits the process loudly.
+ // This is a process boundary, so the explicit try/catch is sanctioned.
+ const { runDbMigrations } = await import('./scripts/run-db-migrations.js');
+ try {
+ await runDbMigrations();
+ } catch (err) {
+ console.error(`❌ DB migration failed at boot — refusing to start: ${err?.stack ?? err.message}`);
+ process.exit(1);
+ }
const { migrateBibleToCatalog } = await import('./scripts/migrateBibleToCatalog.js');
await migrateBibleToCatalog();
// One-time data repair: rewrite legacy machine universe tags
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index c270b63f87..14589342c8 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -297,6 +297,18 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
});
}
+ // Versioned DB-migration tracker (#1029) — non-`catalog_`-prefixed table in
+ // BOTH DDL sources (base schema), so it gets its own column parity assertion.
+ // No secondary index, nothing to compare there.
+ it('schema_migrations has the same columns in both files', () => {
+ const sqlBody = extractCreateTable(INIT_SQL, 'schema_migrations');
+ const jsBody = extractCreateTable(DB_JS, 'schema_migrations');
+ expect(sqlBody, 'init-db.sql missing CREATE TABLE schema_migrations').toBeTruthy();
+ expect(jsBody, 'db.js missing CREATE TABLE schema_migrations').toBeTruthy();
+ expect([...new Set(extractColumnNames(sqlBody))].sort())
+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());
+ });
+
it('search_tsv payload field set matches', () => {
// Both files re-declare the GENERATED ALWAYS expression character-for-
// character today. If one side adds a payload key (e.g. voiceNotes) and
diff --git a/server/lib/db.js b/server/lib/db.js
index 426e6aa217..ba5fe80feb 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -116,6 +116,18 @@ async function ensureSchemaImpl() {
`ALTER TABLE memories ADD COLUMN IF NOT EXISTS origin_instance_id VARCHAR(36)`,
`CREATE INDEX IF NOT EXISTS idx_memories_origin_instance ON memories (origin_instance_id)`,
`CREATE INDEX IF NOT EXISTS idx_memories_sync_sequence ON memories (sync_sequence)`,
+ // Versioned DB-migration tracker (#1029). Records which ordered migration
+ // files in server/scripts/db-migrations/ have been applied on THIS install.
+ // It's part of the base schema (created here AND in init-db.sql, parity-
+ // locked by db.catalogDdlParity.test.js) so the runner — which executes
+ // AFTER ensureSchema() at boot — can always read it. ensureSchema()'s
+ // additive CREATE/ADD IF NOT EXISTS gates handle fresh-install schema; the
+ // runner handles DELTAS that those gates can't express (renames, type
+ // changes, data transforms, embedding-dimension changes).
+ `CREATE TABLE IF NOT EXISTS schema_migrations (
+ id TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
];
for (const sql of upgrades) {
await pool.query(sql);
diff --git a/server/scripts/db-migrations/README.md b/server/scripts/db-migrations/README.md
new file mode 100644
index 0000000000..2b149de6a6
--- /dev/null
+++ b/server/scripts/db-migrations/README.md
@@ -0,0 +1,69 @@
+# DB Migrations (`server/scripts/db-migrations/`)
+
+Ordered, versioned PostgreSQL schema-DELTA migrations (#1029). Run at boot by
+`server/scripts/run-db-migrations.js` after `ensureSchema()` has created the base
+schema.
+
+## When to use this vs. `ensureSchema()`
+
+| Change | Where it goes |
+| --- | --- |
+| New table / new column / new index (additive, fresh-install) | `ensureSchema()` in `server/lib/db.js` **and** `server/scripts/init-db.sql` (parity-locked by `db.catalogDdlParity.test.js`) |
+| Column **rename**, **type change**, data **transform**, **embedding-dimension** change, dropping a column | A migration file here |
+
+`ensureSchema()`'s `CREATE/ADD IF NOT EXISTS` gates can only express additive
+fresh-install schema. Anything that has to *transform* an existing install —
+something that isn't idempotent as a bare `IF NOT EXISTS` statement — belongs
+here so it runs exactly once, in order, and is recorded.
+
+## File format
+
+Files are applied in **lexical filename order**, so prefix with a zero-padded
+sequence: `001-`, `002-`, … Each filename is the migration **id** recorded in
+the `schema_migrations` table — never rename or reuse an id once shipped.
+
+Two formats are supported:
+
+### `.sql`
+
+Raw SQL, run verbatim against the transaction client. Use for pure DDL deltas.
+
+```sql
+-- 001-rename-foo-to-bar.sql
+ALTER TABLE widgets RENAME COLUMN foo TO bar;
+```
+
+### `.js`
+
+ESM module exporting `async function up(client)` (or a default object with an
+`up` method). Receives the pg transaction client so you can query + mutate in
+the same transaction — use this for data transforms, conditional logic, or
+embedding-dimension changes.
+
+```js
+// 002-backfill-bar.js
+export async function up(client) {
+ const { rows } = await client.query('SELECT id, legacy FROM widgets WHERE bar IS NULL');
+ for (const row of rows) {
+ await client.query('UPDATE widgets SET bar = $1 WHERE id = $2', [derive(row.legacy), row.id]);
+ }
+}
+```
+
+## Guarantees
+
+- **Atomic per migration.** Each migration's statements AND its
+ `INSERT INTO schema_migrations` share one transaction. A failure rolls back
+ both — the migration is **not** marked applied, boot aborts loudly, and the
+ next boot retries it. Nothing half-applies.
+- **Run once, in order.** Already-applied ids (tracked in `schema_migrations`)
+ are skipped. Idempotent on re-run.
+- **Naming.** `_`-prefixed files and `*.test.js` files are ignored (shared
+ helpers / co-located tests).
+
+## Conventions
+
+- Migrations are forward-only (no `down()`). PortOS rolls forward.
+- Keep each migration focused on one logical change.
+- Prefer `.sql` for plain DDL; reach for `.js` only when you need to read rows,
+ branch, or transform data.
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 7b3b7ca4c5..b8de39563f 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -59,6 +59,15 @@ CREATE INDEX IF NOT EXISTS idx_memories_tags ON memories USING gin (tags);
-- Sync sequence index for federation
CREATE INDEX IF NOT EXISTS idx_memories_sync_sequence ON memories (sync_sequence);
+-- Versioned DB-migration tracker (#1029). Records which ordered migration files
+-- in server/scripts/db-migrations/ have been applied on THIS install. Part of
+-- the base schema (mirrored in db.js ensureSchema, parity-locked by
+-- db.catalogDdlParity.test.js) so the boot-time runner can always read it.
+CREATE TABLE IF NOT EXISTS schema_migrations (
+ id TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ DEFAULT NOW()
+);
+
-- Memory relationships (bidirectional links)
CREATE TABLE IF NOT EXISTS memory_links (
source_id UUID REFERENCES memories(id) ON DELETE CASCADE,
diff --git a/server/scripts/run-db-migrations.js b/server/scripts/run-db-migrations.js
new file mode 100644
index 0000000000..15cbbf9570
--- /dev/null
+++ b/server/scripts/run-db-migrations.js
@@ -0,0 +1,126 @@
+#!/usr/bin/env node
+/**
+ * Versioned PostgreSQL schema-migration runner (#1029).
+ *
+ * Mirrors the file-migration runner at `scripts/run-migrations.js` (repo root)
+ * but tracks state in a Postgres table instead of a JSON file, since a row is
+ * more robust than a hand-editable applied-list — there's no corrupt-file
+ * recovery branch because the table can't half-write.
+ *
+ * WHAT THIS IS FOR: deltas on EXISTING installs that `ensureSchema()`'s additive
+ * `CREATE/ADD IF NOT EXISTS` gates can't express — column renames, type changes,
+ * data transforms, embedding-dimension changes. The fresh-install schema stays
+ * in `ensureSchema()` + `init-db.sql`; this runner applies the ordered diffs.
+ *
+ * HOW IT WORKS: read applied ids from `schema_migrations`, scan
+ * `db-migrations/` in lexical order, and run each unapplied file inside a single
+ * `withTransaction` — the migration's SQL/`up(client)` AND the
+ * `INSERT INTO schema_migrations` share one transaction, so a failed migration
+ * rolls BOTH back: it is never marked applied and a re-run retries it cleanly.
+ * Idempotent on re-run (already-applied ids are skipped).
+ *
+ * FILE FORMATS (both supported):
+ * - `NNN-name.sql` — raw SQL run verbatim against the transaction client.
+ * - `NNN-name.js` — ESM module exporting `async function up(client)` (or a
+ * default object with an `up` method). Receives the pg transaction client so
+ * data transforms / multi-step changes can query + mutate in the same tx.
+ *
+ * The migration ID recorded in `schema_migrations` is the filename, matching the
+ * file-migration runner's convention.
+ */
+
+import { readdir, readFile } from 'fs/promises';
+import { join, dirname, resolve } from 'path';
+import { fileURLToPath, pathToFileURL } from 'url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const DEFAULT_MIGRATIONS_DIR = join(__dirname, 'db-migrations');
+
+/**
+ * Apply pending DB migrations.
+ *
+ * @param {object} opts
+ * @param {string} [opts.migrationsDir] - directory of ordered migration files.
+ * @param {object} [opts.db] - injectable db module (query + withTransaction),
+ * defaults to the live `server/lib/db.js`. Tests pass a live or stub module.
+ * @returns {Promise<number>} count of migrations applied this run.
+ */
+export async function runDbMigrations({
+ migrationsDir = DEFAULT_MIGRATIONS_DIR,
+ db,
+} = {}) {
+ const { query, withTransaction } = db ?? await import('../lib/db.js');
+
+ // The tracking table is part of the base schema (ensureSchema + init-db.sql),
+ // so it always exists by the time this runs. Read the applied set once.
+ const { rows } = await query('SELECT id FROM schema_migrations');
+ const applied = new Set(rows.map((r) => r.id));
+
+ // Scan for migration files (*.sql / *.js, sorted by filename). Co-located
+ // vitest files (*.test.js) are excluded — they don't export `up()` and would
+ // throw the runner if imported as migrations. `_`-prefixed files are shared
+ // helpers / fixtures consumed by migrations and their tests, never migrations
+ // themselves. A missing directory is treated as "no migrations".
+ const entries = await readdir(migrationsDir).catch((err) => {
+ if (err.code !== 'ENOENT') throw err;
+ return [];
+ });
+ const files = entries
+ .filter((f) => (f.endsWith('.sql') || f.endsWith('.js')) && !f.endsWith('.test.js') && !f.startsWith('_'))
+ .sort();
+
+ let ran = 0;
+ for (const file of files) {
+ if (applied.has(file)) continue;
+
+ console.log(`🔄 Running DB migration: ${file}`);
+ // Each migration + its bookkeeping insert share ONE transaction so a
+ // failure rolls back both: the migration is NOT marked applied, and a
+ // subsequent boot retries it. Nothing half-applies.
+ if (file.endsWith('.sql')) {
+ const sql = await readFile(join(migrationsDir, file), 'utf-8');
+ await withTransaction(async (client) => {
+ await client.query(sql);
+ await client.query('INSERT INTO schema_migrations (id) VALUES ($1)', [file]);
+ });
+ } else {
+ const mod = await import(pathToFileURL(join(migrationsDir, file)).href);
+ const migration = (mod?.default && typeof mod.default.up === 'function') ? mod.default : mod;
+ if (!migration || typeof migration.up !== 'function') {
+ throw new Error(`DB migration "${file}" does not export an up() function`);
+ }
+ await withTransaction(async (client) => {
+ await migration.up(client);
+ await client.query('INSERT INTO schema_migrations (id) VALUES ($1)', [file]);
+ });
+ }
+ ran++;
+ console.log(`✅ DB migration applied: ${file}`);
+ }
+
+ if (ran === 0) {
+ console.log('✅ No pending DB migrations');
+ } else {
+ console.log(`✅ ${ran} DB migration(s) applied`);
+ }
+ return ran;
+}
+
+// Only run as CLI when invoked directly (not when imported as a module).
+// `pathToFileURL()` requires an absolute path, so we `resolve()` argv[1] first
+// (it may be relative when launched as `node server/scripts/run-db-migrations.js`).
+// URL-vs-URL comparison normalizes slashes / drive-letter casing on Windows.
+const invokedAsScript = process.argv[1]
+ && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
+if (invokedAsScript) {
+ const { close } = await import('../lib/db.js');
+ await runDbMigrations()
+ .then(() => close())
+ .catch(async (err) => {
+ console.error(`❌ DB migration failed: ${err?.stack ?? err}`);
+ // Close the pool so the failure path exits the event loop too; ignore a
+ // secondary close error so the original failure is the one we exit on.
+ await close().catch(() => {});
+ process.exit(1);
+ });
+}
diff --git a/server/scripts/run-db-migrations.test.js b/server/scripts/run-db-migrations.test.js
new file mode 100644
index 0000000000..9cd098ff11
--- /dev/null
+++ b/server/scripts/run-db-migrations.test.js
@@ -0,0 +1,163 @@
+/**
+ * Live-DB test for the versioned DB-migration runner (#1029).
+ *
+ * Like the other db.test.js suites, this needs a live PostgreSQL with the base
+ * schema applied. If no DB is reachable it SKIPS cleanly. When a DB IS reachable
+ * it proves the four contract points:
+ * 1. applies an unapplied migration (both .sql and .js variants),
+ * 2. records each applied migration in schema_migrations,
+ * 3. skips already-applied migrations on re-run (idempotent),
+ * 4. a failing migration rolls back AND is NOT recorded (atomicity).
+ *
+ * It writes throwaway fixture files into a temp directory (not the real
+ * db-migrations/ tree) and cleans up its schema_migrations rows + scratch table
+ * afterward so a developer's DB is left untouched.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { mkdtemp, writeFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { checkHealth, ensureSchema, query, withTransaction, close } from '../lib/db.js';
+import { runDbMigrations } from './run-db-migrations.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'schema_migrations') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'schema_migrations table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ run-db-migrations.test.js skipped: ${skipReason}`);
+
+// Test fixtures use a unique id prefix so we can clean ONLY our own rows /
+// scratch tables without touching a developer's real migration history.
+const PREFIX = `ztest${Date.now()}_`;
+const SCRATCH = `${PREFIX}scratch`;
+
+const db = { query, withTransaction };
+
+describe.skipIf(!dbReady)('versioned DB-migration runner', () => {
+ let dir;
+
+ beforeAll(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'db-mig-test-'));
+ });
+
+ beforeEach(async () => {
+ await query(`DELETE FROM schema_migrations WHERE id LIKE '${PREFIX}%'`);
+ await query(`DROP TABLE IF EXISTS ${SCRATCH}`);
+ });
+
+ afterAll(async () => {
+ await query(`DELETE FROM schema_migrations WHERE id LIKE '${PREFIX}%'`).catch(() => {});
+ await query(`DROP TABLE IF EXISTS ${SCRATCH}`).catch(() => {});
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
+ await close();
+ });
+
+ it('applies an unapplied .sql migration and records it', async () => {
+ const file = `${PREFIX}001-create.sql`;
+ const d = await mkdtemp(join(tmpdir(), 'db-mig-sql-'));
+ await writeFile(join(d, file), `CREATE TABLE ${SCRATCH} (id TEXT PRIMARY KEY);`);
+
+ const ran = await runDbMigrations({ migrationsDir: d, db });
+ expect(ran).toBe(1);
+
+ const exists = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1) AS ok`,
+ [SCRATCH],
+ );
+ expect(exists.rows[0].ok).toBe(true);
+
+ const rec = await query(`SELECT id FROM schema_migrations WHERE id = $1`, [file]);
+ expect(rec.rows).toHaveLength(1);
+
+ await rm(d, { recursive: true, force: true });
+ });
+
+ it('applies a .js migration via its up(client) export', async () => {
+ const file = `${PREFIX}001-js.js`;
+ const d = await mkdtemp(join(tmpdir(), 'db-mig-js-'));
+ await writeFile(
+ join(d, file),
+ `export async function up(client) { await client.query('CREATE TABLE ${SCRATCH} (id TEXT PRIMARY KEY)'); }`,
+ );
+
+ const ran = await runDbMigrations({ migrationsDir: d, db });
+ expect(ran).toBe(1);
+
+ const exists = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1) AS ok`,
+ [SCRATCH],
+ );
+ expect(exists.rows[0].ok).toBe(true);
+
+ await rm(d, { recursive: true, force: true });
+ });
+
+ it('skips an already-applied migration on re-run (idempotent)', async () => {
+ const file = `${PREFIX}001-create.sql`;
+ const d = await mkdtemp(join(tmpdir(), 'db-mig-idem-'));
+ await writeFile(join(d, file), `CREATE TABLE ${SCRATCH} (id TEXT PRIMARY KEY);`);
+
+ expect(await runDbMigrations({ migrationsDir: d, db })).toBe(1);
+ // Second run: nothing pending — the CREATE TABLE (no IF NOT EXISTS) would
+ // throw "already exists" if it re-ran, so a clean 0 proves the skip.
+ expect(await runDbMigrations({ migrationsDir: d, db })).toBe(0);
+
+ const rec = await query(`SELECT id FROM schema_migrations WHERE id = $1`, [file]);
+ expect(rec.rows).toHaveLength(1);
+
+ await rm(d, { recursive: true, force: true });
+ });
+
+ it('rolls back a failing migration and does NOT record it', async () => {
+ const file = `${PREFIX}001-bad.sql`;
+ const d = await mkdtemp(join(tmpdir(), 'db-mig-fail-'));
+ // Create a scratch table, then issue invalid SQL in the SAME migration. The
+ // CREATE must roll back with the failure — proving transactional atomicity.
+ await writeFile(
+ join(d, file),
+ `CREATE TABLE ${SCRATCH} (id TEXT PRIMARY KEY);\nINSERT INTO ${SCRATCH} (nonexistent_column) VALUES ('x');`,
+ );
+
+ await expect(runDbMigrations({ migrationsDir: d, db })).rejects.toThrow();
+
+ // The scratch table CREATE rolled back with the bad INSERT.
+ const exists = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1) AS ok`,
+ [SCRATCH],
+ );
+ expect(exists.rows[0].ok).toBe(false);
+
+ // And it was NOT marked applied — a re-run would retry it.
+ const rec = await query(`SELECT id FROM schema_migrations WHERE id = $1`, [file]);
+ expect(rec.rows).toHaveLength(0);
+
+ await rm(d, { recursive: true, force: true });
+ });
+
+ it('returns 0 for a missing migrations directory', async () => {
+ const ran = await runDbMigrations({ migrationsDir: join(dir, 'does-not-exist'), db });
+ expect(ran).toBe(0);
+ });
+
+ it('ignores _-prefixed helpers and *.test.js files', async () => {
+ const d = await mkdtemp(join(tmpdir(), 'db-mig-ignore-'));
+ await writeFile(join(d, `_helper.js`), `export const x = 1;`);
+ await writeFile(join(d, `${PREFIX}thing.test.js`), `export function up() {}`);
+ const ran = await runDbMigrations({ migrationsDir: d, db });
+ expect(ran).toBe(0);
+ await rm(d, { recursive: true, force: true });
+ });
+});