streaming-migration-backup.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { promisify } from "node:util";
  8. import { DatabaseSync, type SQLInputValue } from "node:sqlite";
  9. import { afterEach, describe, expect, it } from "vitest";
  10. import { sqliteMigrations } from "@zcode/shared/sqlite-migrations";
  11. const roots: string[] = [];
  12. const databases: DatabaseSync[] = [];
  13. const exec = promisify(execFile);
  14. async function fixture() {
  15. const root = await mkdtemp(join(tmpdir(), "zcode-streaming-backup-"));
  16. roots.push(root);
  17. return root;
  18. }
  19. function database() {
  20. const db = new DatabaseSync(":memory:");
  21. databases.push(db);
  22. return db;
  23. }
  24. async function migrate(db: DatabaseSync, root: string, sql = "UPDATE item SET value='changed'") {
  25. return sqliteMigrations.migrate(
  26. db,
  27. [{ id: "0001_change", appVersion: "test", sql, touchedTables: ["item"] }],
  28. {
  29. database: "cli",
  30. backupDirectories: [root],
  31. fallbackBackupDirectories: async () => [],
  32. },
  33. );
  34. }
  35. afterEach(async () => {
  36. for (const db of databases.splice(0)) db.close();
  37. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  38. });
  39. describe("迁移备份的有界内存与恢复", () => {
  40. it("96 MiB 堆完成超过单字符串上限的表备份、重开和恢复", async () => {
  41. const root = await fixture();
  42. const { stdout } = await exec(
  43. process.execPath,
  44. [
  45. "--max-old-space-size=96",
  46. "--import",
  47. "tsx",
  48. fileURLToPath(new URL("./fixtures/streaming-migration-backup-process.ts", import.meta.url)),
  49. root,
  50. ],
  51. { timeout: 180_000, maxBuffer: 1024 * 1024 },
  52. );
  53. const report = JSON.parse(stdout.trim());
  54. console.info("streaming migration backup:", report);
  55. expect(report.bytes).toBeGreaterThan(report.maxStringLength);
  56. expect(report.rows).toBeGreaterThan(60_000);
  57. expect(report.maxRssKiB).toBeLessThan(384 * 1024);
  58. }, 190_000);
  59. it("新版哈希忽略行顺序,保留重复行,并在写原库前拒绝备份篡改", async () => {
  60. const hashes: string[] = [];
  61. for (const values of [
  62. ["a", "b", "a"],
  63. ["b", "a", "a"],
  64. ["a", "b"],
  65. ]) {
  66. const root = await fixture();
  67. const db = database();
  68. db.exec("CREATE TABLE item(value TEXT)");
  69. for (const value of values) db.prepare("INSERT INTO item VALUES (?)").run(value);
  70. const result = await migrate(db, root);
  71. const metadata = JSON.parse(await readFile(join(result.backupPath!, "backup.json"), "utf8"));
  72. expect(metadata.version).toBe(2);
  73. hashes.push(metadata.tables[0].hash);
  74. await sqliteMigrations.restore(db, result.backupPath!);
  75. expect(
  76. db
  77. .prepare("SELECT value FROM item ORDER BY value")
  78. .all()
  79. .map((r) => r.value),
  80. ).toEqual([...values].sort());
  81. const backup = new DatabaseSync(join(result.backupPath!, "tables.sqlite"));
  82. backup.exec("UPDATE item SET value='tampered' WHERE rowid=1");
  83. backup.close();
  84. await expect(sqliteMigrations.restore(db, result.backupPath!)).rejects.toThrow(
  85. "Backup row count/hash mismatch",
  86. );
  87. expect(
  88. db
  89. .prepare("SELECT value FROM item ORDER BY value")
  90. .all()
  91. .map((r) => r.value),
  92. ).toEqual([...values].sort());
  93. }
  94. expect(hashes[0]).toBe(hashes[1]);
  95. expect(hashes[0]).not.toBe(hashes[2]);
  96. });
  97. it("恢复旧版备份:UTF-16 排序、重复行、精确整数、BLOB、空值与新列默认值", async () => {
  98. const root = await fixture();
  99. const backupPath = join(root, "legacy");
  100. await mkdir(backupPath);
  101. const values: SQLInputValue[][] = [
  102. ["\uE000", null],
  103. ["😀", 9223372036854775807n],
  104. ['a"\\\n', new Uint8Array([0, 255])],
  105. ['a"\\\n', new Uint8Array([0, 255])],
  106. ["real", 1.25],
  107. ];
  108. const encoded = values
  109. .map((row) =>
  110. JSON.stringify(row, (_key, value: unknown) => {
  111. if (typeof value === "bigint") return { integer: value.toString() };
  112. if (value instanceof Uint8Array) return { blob: Buffer.from(value).toString("hex") };
  113. return value;
  114. }),
  115. )
  116. .sort();
  117. const backup = new DatabaseSync(join(backupPath, "tables.sqlite"));
  118. backup.exec("CREATE TABLE item(value, detail)");
  119. for (const row of values) backup.prepare("INSERT INTO item VALUES (?, ?)").run(...row);
  120. backup.close();
  121. await writeFile(
  122. join(backupPath, "backup.json"),
  123. JSON.stringify({
  124. version: 1,
  125. database: "cli",
  126. migrations: ["0001_change"],
  127. tables: [
  128. {
  129. name: "item",
  130. columns: ["value", "detail"],
  131. rows: values.length,
  132. hash: createHash("sha256").update(JSON.stringify(encoded)).digest("hex"),
  133. },
  134. ],
  135. }),
  136. );
  137. const db = database();
  138. db.exec(
  139. "CREATE TABLE item(value, detail, added TEXT DEFAULT 'default'); CREATE TABLE schema_migration(id TEXT); INSERT INTO schema_migration VALUES ('0001_change'),('unknown'); INSERT INTO item(value) VALUES ('changed')",
  140. );
  141. await sqliteMigrations.restore(db, backupPath);
  142. const rows = db.prepare("SELECT value,detail FROM item");
  143. rows.setReadBigInts(true);
  144. expect(rows.all().map((r) => [r.value, r.detail])).toEqual(values);
  145. expect(db.prepare("SELECT DISTINCT added FROM item").all()).toEqual([{ added: "default" }]);
  146. expect(db.prepare("SELECT id FROM schema_migration").all()).toEqual([{ id: "unknown" }]);
  147. });
  148. it("迁移失败保留完整备份,原库回滚且不产生迁移记录", async () => {
  149. const root = await fixture();
  150. const db = database();
  151. db.exec("CREATE TABLE item(value TEXT); INSERT INTO item VALUES ('original')");
  152. await expect(
  153. migrate(db, root, "UPDATE item SET value='changed'; SELECT * FROM missing_table"),
  154. ).rejects.toThrow();
  155. expect(db.prepare("SELECT value FROM item").get()!.value).toBe("original");
  156. expect(db.isTransaction).toBe(false);
  157. expect(
  158. db.prepare("SELECT name FROM sqlite_schema WHERE name='schema_migration'").get(),
  159. ).toBeUndefined();
  160. const directories = await readdir(root);
  161. expect(directories).toHaveLength(1);
  162. const backup = new DatabaseSync(join(root, directories[0]!, "tables.sqlite"));
  163. try {
  164. expect(backup.prepare("SELECT value FROM item").get()!.value).toBe("original");
  165. } finally {
  166. backup.close();
  167. }
  168. });
  169. it("流式恢复保持类型和未备份子表,插入失败时原库完整回滚", async () => {
  170. const root = await fixture();
  171. const db = database();
  172. db.exec(
  173. "PRAGMA foreign_keys=ON; CREATE TABLE item(id INTEGER PRIMARY KEY, value); CREATE TABLE child(parent INTEGER REFERENCES item(id) ON DELETE CASCADE)",
  174. );
  175. const values: SQLInputValue[] = [
  176. null,
  177. 9223372036854775807n,
  178. new Uint8Array([0, 255]),
  179. 1.25,
  180. "正文",
  181. ];
  182. for (const [id, value] of values.entries())
  183. db.prepare("INSERT INTO item VALUES (?, ?)").run(id, value);
  184. db.exec("INSERT INTO child VALUES (0)");
  185. const result = await migrate(db, root);
  186. db.exec(
  187. "CREATE TRIGGER reject_restore BEFORE INSERT ON item WHEN NEW.id=2 BEGIN SELECT RAISE(ABORT, 'restore rejected'); END",
  188. );
  189. await expect(sqliteMigrations.restore(db, result.backupPath!)).rejects.toThrow(
  190. "restore rejected",
  191. );
  192. expect(db.prepare("SELECT count(*) AS n FROM item WHERE value='changed'").get()!.n).toBe(
  193. values.length,
  194. );
  195. expect(db.prepare("SELECT count(*) AS n FROM schema_migration").get()!.n).toBe(1);
  196. expect(db.prepare("PRAGMA foreign_keys").get()!.foreign_keys).toBe(1);
  197. db.exec("DROP TRIGGER reject_restore");
  198. await sqliteMigrations.restore(db, result.backupPath!);
  199. const rows = db.prepare("SELECT value FROM item ORDER BY id");
  200. rows.setReadBigInts(true);
  201. expect(rows.all().map((row) => row.value)).toEqual(values);
  202. expect(db.prepare("SELECT parent FROM child").all()).toEqual([{ parent: 0 }]);
  203. expect(db.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
  204. expect(db.prepare("PRAGMA foreign_keys").get()!.foreign_keys).toBe(1);
  205. });
  206. });