import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { DB, migrate } from '../server/db.ts'; import { MIGRATIONS } from '../server/migrations.ts'; describe('safe migration paths', () => { it('backs up before a schema change and rolls back a failed migration', () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studydesk-migration-test-')); const db = new DB(path.join(dir, 'test.db')); try { migrate(db, dir); db.run("INSERT INTO settings VALUES ('fixture', 'preserved')"); MIGRATIONS.push({ id: 999999, name: 'test_failure', sql: 'CREATE TABLE should_rollback (id INTEGER); INVALID SQL;' }); try { expect(() => migrate(db, dir)).toThrow(); expect(db.get("SELECT name FROM sqlite_master WHERE name = 'should_rollback'")).toBeUndefined(); expect(db.get<{ value: string }>("SELECT value FROM settings WHERE key = 'fixture'")?.value).toBe('preserved'); expect(fs.readdirSync(dir).some((n) => n.startsWith('pre-migration-'))).toBe(true); } finally { MIGRATIONS.pop(); } } finally { db.close(); fs.rmSync(dir, { recursive: true, force: true }); } }); });