// Migration runner — tests the REAL migrate() version-stepping logic against a // minimal fake db (emulating the better-sqlite3 pragma getter/setter + transaction // API), so it runs with zero dependencies. Guards that migrations apply in order, // advance user_version correctly, and no-op when the DB is already current. const { test } = require('node:test'); const assert = require('node:assert'); const Database = require('better-sqlite3'); const { migrate, LATEST_VERSION } = require('../packages/memory-service/src/db/migrations'); // Emulates just the slice of the better-sqlite3 API that migrate() uses. function fakeDb(startVersion = 0) { let version = startVersion; return { ran: [], setCalls: [], pragma(str, opts) { const set = str.match(/^user_version\s*=\s*(\d+)$/); if (set) { version = Number(set[1]); this.setCalls.push(version); return; } if (str === 'user_version') return opts && opts.simple ? version : [{ user_version: version }]; throw new Error('unexpected pragma: ' + str); }, transaction(fn) { return (...args) => fn(...args); }, // execute immediately get version() { return version; }, }; } test('a fresh DB (user_version 0) is stamped to LATEST_VERSION', () => { const db = fakeDb(0); const result = migrate(db); assert.strictEqual(result, LATEST_VERSION); assert.strictEqual(db.version, LATEST_VERSION); }); test('an already-current DB is a no-op (no version writes)', () => { const db = fakeDb(LATEST_VERSION); const result = migrate(db); assert.strictEqual(result, LATEST_VERSION); assert.deepStrictEqual(db.setCalls, [], 'should not touch user_version when current'); }); test('injected migrations run in order, each bumping the version by one', () => { const db = fakeDb(0); const order = []; const migs = [ () => order.push('v1'), () => order.push('v2'), () => order.push('v3'), ]; const result = migrate(db, migs); assert.strictEqual(result, 3); assert.deepStrictEqual(order, ['v1', 'v2', 'v3'], 'migrations apply in sequence'); assert.deepStrictEqual(db.setCalls, [1, 2, 3], 'user_version advances one step at a time'); }); test('only migrations newer than the current version run', () => { const db = fakeDb(1); // already at v1 const order = []; const migs = [ () => order.push('v1'), // should be skipped () => order.push('v2'), () => order.push('v3'), ]; migrate(db, migs); assert.deepStrictEqual(order, ['v2', 'v3'], 'v1 is not re-run'); assert.deepStrictEqual(db.setCalls, [2, 3]); }); test('LATEST_VERSION reflects the appended v1 → v2 migration', () => { // Guards that adding the access-tracking migration bumped the target version. // The real SQL is verified out-of-band (scratch run against a DB copy); here we // only lock the runner-visible contract: the array length drives LATEST_VERSION. assert.strictEqual(LATEST_VERSION, 2); });