import { beforeEach, describe, expect, it, vi } from 'vitest'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; /** * DATA-6(2026-10-19 T4):migrate.ts 不再把 "already exists" 当成功。 * 只允许**显式 SQLSTATE 白名单**(42710/42P07/42701/42723);任何错误(含白名单) * 都不得写 schema_migrations;未知 code + "already exists" 文本必须失败。 */ const H = vi.hoisted(() => ({ fail: null as null | { code?: string; message: string }, inserted: [] as string[], clientSql: [] as string[], })); vi.mock('../src/db', () => ({ pool: { query: async (sql: string, params?: unknown[]) => { const text = String(sql); if (/SELECT 1 FROM schema_migrations/i.test(text)) return { rows: [], rowCount: 0 }; if (/INSERT INTO schema_migrations/i.test(text)) { H.inserted.push(String(params?.[0] ?? '')); return { rows: [], rowCount: 1 }; } return { rows: [], rowCount: 0 }; }, connect: async () => ({ query: async (sql: string, params?: unknown[]) => { const text = String(sql); H.clientSql.push(text); if (/^(BEGIN|COMMIT|ROLLBACK)\b/i.test(text.trim())) return { rows: [], rowCount: 0 }; if (/INSERT INTO schema_migrations/i.test(text)) { H.inserted.push(String(params?.[0] ?? '')); return { rows: [], rowCount: 1 }; } if (H.fail) { throw Object.assign(new Error(H.fail.message), { code: H.fail.code }); } return { rows: [], rowCount: 0 }; }, release: () => undefined, }), }, query: async () => ({ rows: [], rowCount: 0 }), getRawPoolQuery: () => async () => ({ rows: [], rowCount: 0 }), })); import { applySqlFile } from '../src/migrate'; function tempMigration(content = 'SELECT 1;'): string { const dir = mkdtempSync(join(tmpdir(), 't4-migrate-')); const file = join(dir, '20260101_test_migration.sql'); writeFileSync(file, content); return file; } beforeEach(() => { H.fail = null; H.inserted = []; H.clientSql = []; }); describe('DATA-6:migrate 错误码白名单', () => { for (const code of ['42710', '42P07', '42701', '42723']) { it(`SQLSTATE ${code} + already exists ⇒ 不抛,但**不写** schema_migrations`, async () => { H.fail = { code, message: 'relation "x" already exists' }; await expect(applySqlFile(tempMigration())).resolves.toBeUndefined(); expect(H.inserted).toEqual([]); }); } for (const code of ['23505', '23503', '42P01']) { it(`SQLSTATE ${code} ⇒ 抛错且不登记(即使文本含 already exists)`, async () => { H.fail = { code, message: 'already exists but fatal' }; await expect(applySqlFile(tempMigration())).rejects.toThrow(/already exists but fatal/); expect(H.inserted).toEqual([]); }); } it('纯文本 already exists 但无 code ⇒ 必须抛(不再按文本放行)', async () => { H.fail = { message: 'relation "x" already exists' }; await expect(applySqlFile(tempMigration())).rejects.toThrow(/already exists/); expect(H.inserted).toEqual([]); }); it('成功路径 ⇒ 正常写 schema_migrations(仅成功才登记)', async () => { H.fail = null; await applySqlFile(tempMigration()); expect(H.inserted, '成功必须登记').toHaveLength(1); expect(H.inserted[0]).toContain('20260101_test_migration.sql'); }); });