session-migration-boundaries.test.ts 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { createHash } from "node:crypto";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { describe, expect, it } from "vitest";
  7. import { sqliteMigrations } from "@zcode/shared/sqlite-migrations";
  8. import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
  9. function hashes(db: DatabaseSync) {
  10. return new Map(
  11. db
  12. .prepare(
  13. "SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name<>'schema_migration'",
  14. )
  15. .all()
  16. .map(({ name }) => {
  17. const table = String(name).replaceAll('"', '""');
  18. const rows = db
  19. .prepare(`SELECT * FROM "${table}"`)
  20. .all()
  21. .map((row) => JSON.stringify(row))
  22. .sort();
  23. return [String(name), createHash("sha256").update(JSON.stringify(rows)).digest("hex")];
  24. }),
  25. );
  26. }
  27. function seedBase(db: DatabaseSync) {
  28. db.exec(`INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated)
  29. VALUES('session','project','slug','/repo','Title','0.2.0',1,2);
  30. INSERT INTO message VALUES('message','session',1,2,'{"role":"user","time":{"created":1}}');
  31. INSERT INTO part VALUES('part','message','session',1,2,'{"type":"text","text":"keep"}');
  32. INSERT INTO permission VALUES('project',1,2,'[{"permission":"read","pattern":"*","action":"allow"}]');
  33. INSERT INTO todo VALUES('session','keep','pending','normal',0,1,2);
  34. INSERT INTO input_history VALUES('input','project','session','keep','prompt',1);
  35. INSERT INTO session_entry VALUES('entry','session','checkpoint',1,2,'{}');`);
  36. }
  37. describe("each CLI migration writes only its declared tables", () => {
  38. it.each(SQLITE_MIGRATIONS.map((migration, index) => ({ migration, index })))(
  39. "$migration.id",
  40. async ({ migration, index }) => {
  41. const directory = await mkdtemp(join(tmpdir(), "migration-boundary-"));
  42. const db = new DatabaseSync(":memory:");
  43. try {
  44. db.exec(
  45. "PRAGMA foreign_keys=ON; CREATE TABLE untouched(id TEXT PRIMARY KEY,value TEXT); INSERT INTO untouched VALUES('sentinel','keep')",
  46. );
  47. // 前序迁移必须经 runner 回放:0022 的 SQL JOIN schema_migration 读取 0020 的记账时间,
  48. // 裸 exec 不建 journal 会在 0023 之后的每条迁移上报 no such table。
  49. const options = {
  50. database: "cli",
  51. backupDirectories: [directory],
  52. appliedAtColumn: "time_applied",
  53. } as const;
  54. if (index > 0) {
  55. await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS.slice(0, 1), options);
  56. seedBase(db);
  57. if (index > 1)
  58. await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS.slice(1, index), options);
  59. }
  60. const before = hashes(db);
  61. await sqliteMigrations.migrate(db, [migration], options);
  62. const after = hashes(db);
  63. const changed = [...new Set([...before.keys(), ...after.keys()])].filter(
  64. (table) => before.get(table) !== after.get(table),
  65. );
  66. expect(changed.filter((table) => !migration.touchedTables.includes(table))).toEqual([]);
  67. expect(db.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
  68. } finally {
  69. db.close();
  70. await rm(directory, { recursive: true, force: true });
  71. }
  72. },
  73. );
  74. });