scribase-cli/tests/migrate.test.ts
caelum0x 09b8e0392a feat(SCR-ACT): npx scribase migrate rollback [n] (0.3.8)
Reverts the n most recently applied migrations (default 1) by running
their stored `-- down` SQL. There is no server route that deletes a
ledger row over the network (orion.schema_migrations is append-only
from the CLI), so this writes the down SQL to disk as a brand new
migration file and sends it through the exact same POST .../migrations
route — and the exact same destructive-push production-approval gate —
any other migration already goes through, instead of a special,
less-audited path. Refuses clearly when a target has no down SQL or
when asked to roll back more than are applied. --dry-run previews
without writing or applying anything.

Verified end to end against a real mail.tm-signed-up project: create
table -> migrate -> rollback -> table confirmed gone
(gtm/tools/scribase-cli-migrate-rollback-walk.py).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:03:40 +03:00

412 lines
21 KiB
TypeScript

/**
* Tests for `npx scribase migrate`: scaffolding a new file, reading and
* splitting local `.sql` files, which project/token it uses, the plan/lint
* request, dry-run, a BLOCK finding stopping apply, and errors (no network,
* in-memory files).
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { InitError } from '../src/cli/init.js';
import { formatMigrate, MIGRATIONS_DIR, parseMigrateArgs, runMigrate } from '../src/cli/migrate.js';
import type { MigrateIo } from '../src/cli/migrate.js';
const ROOT = '/work/app';
const STATE = JSON.stringify({
organization_id: 'tmp-1',
project_id: 'shop',
environment_id: 'production',
api_url: 'https://api.example.test',
});
interface Seen {
url: string;
auth: string | null;
body: Record<string, unknown>;
}
interface Written {
path: string;
contents: string;
}
type Answer = { status: number; body: unknown };
function io(
files: Record<string, string>,
migrationFiles: string[],
answer: Answer | Answer[] | null,
env: Record<string, string> = {},
stored: { token?: string } = {},
now: Date = new Date('2026-10-29T12:34:56Z'),
) {
const seen: Seen[] = [];
const written: Written[] = [];
const queue = answer === null ? [] : Array.isArray(answer) ? [...answer] : null;
const value: MigrateIo = {
cwd: ROOT,
env,
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
seen.push({
url: String(url),
auth: new Headers(init?.headers).get('authorization'),
body: init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {},
});
// A single `answer` object answers every call the same way (every existing test does
// exactly one network call); a queue answers each call in order — `rollback` makes a
// GET (the applied ledger) followed by a POST (the push), in that order.
const next = queue ? queue.shift() : answer;
if (!next) throw new Error('unexpected network call');
return new Response(JSON.stringify(next.body), { status: next.status });
}) as typeof fetch,
readFile: (path) => files[path] ?? null,
writeFile: (path, contents) => {
written.push({ path, contents });
files[path] = contents;
},
listMigrationFiles: () => migrationFiles,
credentials: () => ({ apiUrl: 'https://api.example.test', ...stored }),
now: () => now,
};
return { io: value, seen, written };
}
const COMMITTED = {
plan: { steps: [{ version: 20261029123456, name: 'add_notes', direction: 'up', checksum: 'abc' }] },
lintFindings: [],
applied: [20261029123456],
};
describe('scribase migrate arguments', () => {
it('parses `new <name>`, the default run, --dry-run and --json', () => {
assert.deepEqual(parseMigrateArgs(['new', 'add notes']), { action: 'new', name: 'add notes', dryRun: false, json: false });
assert.deepEqual(parseMigrateArgs([]), { action: 'run', dryRun: false, json: false });
assert.deepEqual(parseMigrateArgs(['up', '--dry-run', '--json']), { action: 'run', dryRun: true, json: true });
});
it('rejects `new` with no name, an unknown argument and an unknown flag', () => {
assert.throws(() => parseMigrateArgs(['new']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument' && /name/.test(error.message));
assert.throws(() => parseMigrateArgs(['down']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument');
assert.throws(() => parseMigrateArgs(['--force']), (error: unknown) => error instanceof InitError && /--force/.test(error.message));
});
it('parses `rollback` with a default count of 1, an explicit count, and --dry-run/--json', () => {
assert.deepEqual(parseMigrateArgs(['rollback']), { action: 'rollback', count: 1, dryRun: false, json: false });
assert.deepEqual(parseMigrateArgs(['rollback', '2']), { action: 'rollback', count: 2, dryRun: false, json: false });
assert.deepEqual(parseMigrateArgs(['rollback', '3', '--dry-run', '--json']), { action: 'rollback', count: 3, dryRun: true, json: true });
});
it('rejects a non-numeric, zero, or extra `rollback` argument', () => {
for (const bad of ['0', '-1', 'two', '1.5']) {
assert.throws(
() => parseMigrateArgs(['rollback', bad]),
(error: unknown) => error instanceof InitError && error.code === 'invalid_argument' && /rollback count/.test(error.message),
bad,
);
}
assert.throws(() => parseMigrateArgs(['rollback', '1', 'extra']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument');
});
});
describe('scribase migrate new', () => {
it('scaffolds a timestamped file with a slugified name and both markers', async () => {
const { io: value, written } = io({}, [], null);
const result = await runMigrate({ action: 'new', name: 'Add Notes!', dryRun: false, json: false }, value);
assert.equal(result.action, 'new');
if (result.action !== 'new') throw new Error('unreachable');
assert.equal(result.version, '20261029123456');
assert.equal(result.name, 'add_notes');
assert.equal(result.path, `${ROOT}/${MIGRATIONS_DIR}/20261029123456_add_notes.sql`);
assert.equal(written.length, 1);
assert.match(written[0]?.contents ?? '', /^-- Add Notes!/);
assert.match(written[0]?.contents ?? '', /missing_rls/);
assert.match(written[0]?.contents ?? '', /\n-- down\n/);
assert.match(written[0]?.contents ?? '', /create table public\.add_notes/);
// Unedited, it is a real no-op: every SQL line is commented out.
for (const line of (written[0]?.contents ?? '').split('\n')) {
if (line.trim().length > 0) assert.match(line, /^--/, `expected a comment line, got: ${line}`);
}
});
it('never produces an empty slug, even from punctuation-only input', async () => {
const { io: value } = io({}, [], null);
const result = await runMigrate({ action: 'new', name: '!!!', dryRun: false, json: false }, value);
if (result.action !== 'new') throw new Error('unreachable');
assert.equal(result.name, 'migration');
});
});
describe('scribase migrate (run)', () => {
it('reports no files without making a network call when the folder has none', async () => {
const { io: value, seen } = io({}, [], null);
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.files, 0);
assert.equal(seen.length, 0);
assert.match(formatMigrate(result), /No migration files/);
});
it('reads local files in version order, splits up/down on the marker, and sends them with apply:true', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/.env.local`]: 'SCRIBASE_ACCESS_TOKEN=scb_agt_tmp\n',
[`${ROOT}/${MIGRATIONS_DIR}/2_second.sql`]: 'create table second (id int);\n-- down\ndrop table second;\n',
[`${ROOT}/${MIGRATIONS_DIR}/1_first.sql`]: 'create table first (id int);',
};
const { io: value, seen } = io(files, ['2_second.sql', '1_first.sql', 'README.md'], { status: 200, body: COMMITTED });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.files, 2);
assert.equal(seen[0]?.url, 'https://api.example.test/v1/organizations/tmp-1/projects/shop/environments/production/migrations');
assert.equal(seen[0]?.auth, 'Bearer scb_agt_tmp');
const sent = seen[0]?.body.migrations as { version: string; up: string; down?: string }[];
assert.deepEqual(sent.map((m) => m.version), ['1', '2'], 'oldest version first, regardless of filesystem order');
assert.equal(sent[0]?.up, 'create table first (id int);');
assert.equal(sent[0]?.down, undefined, 'no marker, no down key');
assert.equal(sent[1]?.up, 'create table second (id int);');
assert.equal(sent[1]?.down, 'drop table second;');
assert.equal(seen[0]?.body.apply, true);
assert.equal(result.blocked, false);
const text = formatMigrate(result);
assert.match(text, /1 migration\(s\) ran/);
assert.doesNotMatch(text, /scb_agt_tmp/, 'the token is never printed');
});
it('sends apply:false with --dry-run and never reports anything applied', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
const { io: value, seen } = io(files, ['1_x.sql'], { status: 200, body: { plan: COMMITTED.plan, lintFindings: [], applied: [] } }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: true, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(seen[0]?.body.apply, false);
assert.equal(result.blocked, false, '--dry-run is never "blocked", it never tried to apply');
assert.match(formatMigrate(result), /Dry run: nothing applied/);
});
it('marks the run blocked when a BLOCK finding stops every pending migration, and exits non-zero', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'create table t (id int);' };
const blocked = {
plan: { steps: [{ version: 1, name: 'x', direction: 'up', checksum: 'c' }] },
lintFindings: [{ rule: 'missing_rls', severity: 'BLOCK', subject: 'public.t', line: 1, message: 'has neither RLS enabled nor any policy' }],
applied: [],
};
const { io: value } = io(files, ['1_x.sql'], { status: 200, body: blocked }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.blocked, true);
const text = formatMigrate(result);
assert.match(text, /\[BLOCK\] missing_rls/);
assert.match(text, /Nothing applied/);
});
it('skips the network call and says up to date when every local file is already applied', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
const upToDate = { plan: { steps: [] }, lintFindings: [], applied: [] };
const { io: value } = io(files, ['1_x.sql'], { status: 200, body: upToDate }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
assert.match(formatMigrate(result), /Up to date/);
});
it('says what to do when the folder is not initialized, has no token, or the token is refused', async () => {
await assert.rejects(
runMigrate({ action: 'run', dryRun: false, json: false }, io({ [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' }, ['1_x.sql'], { status: 200, body: {} }).io),
(error: unknown) => error instanceof InitError && error.code === 'not_initialized' && /scribase init/.test(error.next ?? ''),
);
await assert.rejects(
runMigrate(
{ action: 'run', dryRun: false, json: false },
io({ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' }, ['1_x.sql'], { status: 200, body: {} }).io,
),
(error: unknown) => error instanceof InitError && error.code === 'not_signed_in',
);
const refused = io(
{ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' },
['1_x.sql'],
{ status: 401, body: { code: 'unauthorized', detail: 'token expired' } },
{ SCRIBASE_ACCESS_TOKEN: 'old' },
);
await assert.rejects(
runMigrate({ action: 'run', dryRun: false, json: false }, refused.io),
(error: unknown) => error instanceof InitError && error.code === 'unauthorized' && /HTTP 401/.test(error.message) && /init/.test(error.next ?? ''),
);
});
it('ignores files that do not match <version>_<name>.sql', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
const { io: value, seen } = io(files, ['1_x.sql', 'README.md', 'notes.sql', '.gitignore'], { status: 200, body: COMMITTED }, { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
if (result.action !== 'run') throw new Error('unreachable');
assert.equal(result.files, 1);
assert.equal((seen[0]?.body.migrations as unknown[]).length, 1);
});
});
describe('scribase migrate rollback', () => {
const ONE_APPLIED = { status: 200, body: { migrations: [{ version: 1, name: 'add_notes', sha256: 'abc', applied_at: 1 }] } };
const TWO_APPLIED = {
status: 200,
body: {
migrations: [
{ version: 1, name: 'add_notes', sha256: 'abc', applied_at: 1 },
{ version: 2, name: 'add_tags', sha256: 'def', applied_at: 2 },
],
},
};
function rollbackResponse(version: number, name: string): Answer {
return { status: 200, body: { plan: { steps: [{ version, name, direction: 'up', checksum: 'x' }] }, lintFindings: [], applied: [version] } };
}
it('fetches the ledger (GET), then writes and sends the target migration\'s down SQL as a new forward migration (apply:true)', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/${MIGRATIONS_DIR}/1_add_notes.sql`]: 'create table add_notes (id int);\n-- down\ndrop table add_notes;\n',
};
const { io: value, seen, written } = io(
files,
['1_add_notes.sql'],
[ONE_APPLIED, rollbackResponse(20261029123456, 'rollback_add_notes')],
{ SCRIBASE_ACCESS_TOKEN: 't' },
);
const result = await runMigrate({ action: 'rollback', count: 1, dryRun: false, json: false }, value);
if (result.action !== 'rollback') throw new Error('unreachable');
assert.equal(seen.length, 2);
assert.equal(seen[0]?.url, 'https://api.example.test/v1/organizations/tmp-1/projects/shop/environments/production/migrations');
assert.equal(seen[1]?.url, seen[0]?.url);
assert.equal(seen[1]?.auth, 'Bearer t');
assert.equal(written.length, 1, 'the rollback file is written to disk, same as every other migration file');
assert.equal(written[0]?.path, `${ROOT}/${MIGRATIONS_DIR}/20261029123456_rollback_add_notes.sql`);
assert.match(written[0]?.contents ?? '', /drop table add_notes;/);
const sent = seen[1]?.body.migrations as { version: string; name: string; up: string }[];
assert.equal(sent.length, 2, 'the original file plus the new rollback file, same shape as a normal push');
assert.equal(sent[0]?.version, '1');
assert.equal(sent[1]?.version, '20261029123456');
assert.equal(sent[1]?.name, 'rollback_add_notes');
assert.match(sent[1]?.up ?? '', /drop table add_notes;/);
assert.equal(seen[1]?.body.apply, true);
assert.deepEqual(result.targets, [{ version: 1, name: 'add_notes' }]);
assert.equal(result.blocked, false);
assert.match(formatMigrate(result), /Rolled back 1 migration\(s\): 1_add_notes\./);
});
it('rolls back the last 2 applied migrations in reverse order (most recent first)', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/${MIGRATIONS_DIR}/1_add_notes.sql`]: 'create table add_notes (id int);\n-- down\ndrop table add_notes;\n',
[`${ROOT}/${MIGRATIONS_DIR}/2_add_tags.sql`]: 'create table add_tags (id int);\n-- down\ndrop table add_tags;\n',
};
const { io: value, seen, written } = io(
files,
['1_add_notes.sql', '2_add_tags.sql'],
[TWO_APPLIED, { status: 200, body: { plan: { steps: [] }, lintFindings: [], applied: [20261029123456, 20261029123457] } }],
{ SCRIBASE_ACCESS_TOKEN: 't' },
);
const result = await runMigrate({ action: 'rollback', count: 2, dryRun: false, json: false }, value);
if (result.action !== 'rollback') throw new Error('unreachable');
assert.deepEqual(result.targets, [
{ version: 2, name: 'add_tags' },
{ version: 1, name: 'add_notes' },
]);
assert.equal(written.length, 2);
// version 2 (the most recently applied) is reverted first: its rollback file sorts first.
assert.equal(written[0]?.path, `${ROOT}/${MIGRATIONS_DIR}/20261029123456_rollback_add_tags.sql`);
assert.equal(written[1]?.path, `${ROOT}/${MIGRATIONS_DIR}/20261029123457_rollback_add_notes.sql`);
const sent = seen[1]?.body.migrations as { version: string; name: string }[];
assert.deepEqual(
sent.map((migration) => migration.name),
['add_notes', 'add_tags', 'rollback_add_tags', 'rollback_add_notes'],
);
});
it('sends apply:false and writes nothing with --dry-run, but still previews a real plan', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/${MIGRATIONS_DIR}/1_add_notes.sql`]: 'create table add_notes (id int);\n-- down\ndrop table add_notes;\n',
};
const { io: value, seen, written } = io(
files,
['1_add_notes.sql'],
[ONE_APPLIED, { status: 200, body: { plan: { steps: [{ version: 20261029123456, name: 'rollback_add_notes', direction: 'up', checksum: 'x' }] }, lintFindings: [], applied: [] } }],
{ SCRIBASE_ACCESS_TOKEN: 't' },
);
const result = await runMigrate({ action: 'rollback', count: 1, dryRun: true, json: false }, value);
if (result.action !== 'rollback') throw new Error('unreachable');
assert.equal(written.length, 0, 'a dry run never writes the rollback file to disk');
assert.equal(seen[1]?.body.apply, false);
const sent = seen[1]?.body.migrations as { name: string }[];
assert.ok(sent.some((migration) => migration.name === 'rollback_add_notes'), 'the synthetic entry is still sent in-memory for a real preview');
assert.match(formatMigrate(result), /Would roll back 1 migration\(s\)/);
});
it('refuses clearly when the target migration has no down SQL, before writing or sending anything', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/${MIGRATIONS_DIR}/1_add_notes.sql`]: 'create table add_notes (id int);',
};
const { io: value, seen, written } = io(files, ['1_add_notes.sql'], [ONE_APPLIED], { SCRIBASE_ACCESS_TOKEN: 't' });
await assert.rejects(
runMigrate({ action: 'rollback', count: 1, dryRun: false, json: false }, value),
(error: unknown) => error instanceof InitError && error.code === 'irreversible_migration' && /no down SQL/.test(error.message),
);
assert.equal(seen.length, 1, 'only the ledger GET happened; the push never fires');
assert.equal(written.length, 0);
});
it('refuses clearly when no local file exists for the applied version', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE };
const { io: value } = io(files, [], [ONE_APPLIED], { SCRIBASE_ACCESS_TOKEN: 't' });
await assert.rejects(
runMigrate({ action: 'rollback', count: 1, dryRun: false, json: false }, value),
(error: unknown) => error instanceof InitError && error.code === 'rollback_missing_file' && /version 1/.test(error.message),
);
});
it('refuses when asked to roll back more than are applied, and when nothing is applied yet', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE };
const tooMany = io(files, [], [ONE_APPLIED], { SCRIBASE_ACCESS_TOKEN: 't' });
await assert.rejects(
runMigrate({ action: 'rollback', count: 2, dryRun: false, json: false }, tooMany.io),
(error: unknown) => error instanceof InitError && error.code === 'invalid_argument' && /only 1 migration/.test(error.message),
);
const none = io(files, [], [{ status: 200, body: { migrations: [] } }], { SCRIBASE_ACCESS_TOKEN: 't' });
await assert.rejects(
runMigrate({ action: 'rollback', count: 1, dryRun: false, json: false }, none.io),
(error: unknown) => error instanceof InitError && error.code === 'nothing_applied',
);
});
it('marks the rollback blocked when a BLOCK finding stops it, same as a normal push', async () => {
const files = {
[`${ROOT}/.scribase/project.json`]: STATE,
[`${ROOT}/${MIGRATIONS_DIR}/1_add_notes.sql`]: 'create table add_notes (id int);\n-- down\ncreate table leftover (id int);\n',
};
const blocked = {
status: 200,
body: {
plan: { steps: [{ version: 20261029123456, name: 'rollback_add_notes', direction: 'up', checksum: 'x' }] },
lintFindings: [{ rule: 'missing_rls', severity: 'BLOCK', subject: 'public.leftover', line: 1, message: 'has neither RLS enabled nor any policy' }],
applied: [],
},
};
const { io: value } = io(files, ['1_add_notes.sql'], [ONE_APPLIED, blocked], { SCRIBASE_ACCESS_TOKEN: 't' });
const result = await runMigrate({ action: 'rollback', count: 1, dryRun: false, json: false }, value);
if (result.action !== 'rollback') throw new Error('unreachable');
assert.equal(result.blocked, true);
assert.match(formatMigrate(result), /Rollback blocked, nothing reverted/);
});
it('requires a token for the ledger GET, same as a normal push', async () => {
const files = { [`${ROOT}/.scribase/project.json`]: STATE };
const { io: value } = io(files, [], [ONE_APPLIED]);
await assert.rejects(
runMigrate({ action: 'rollback', count: 1, dryRun: false, json: false }, value),
(error: unknown) => error instanceof InitError && error.code === 'not_signed_in',
);
});
});