sqlite-schema-contract.mjs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import { DatabaseSync } from "node:sqlite";
  2. const identifier = (name) => `"${name.replaceAll('"', '""')}"`;
  3. // 字符串中的 CHECK/括号不是约束,字面量大小写也不能随 SQL 关键字一起归一化。
  4. function sqlTokens(sql) {
  5. return (
  6. sql.match(
  7. /--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|[a-zA-Z_][a-zA-Z_0-9]*|\d+(?:\.\d+)?|[^\s]/g,
  8. ) ?? []
  9. )
  10. .filter((token) => !token.startsWith("--") && !token.startsWith("/*"))
  11. .map((token) => (/^[a-zA-Z_]/.test(token) ? token.toLowerCase() : token));
  12. }
  13. function checks(db, table) {
  14. const tokens = sqlTokens(
  15. db.prepare("SELECT sql FROM sqlite_schema WHERE type='table' AND name=?").get(table).sql,
  16. );
  17. const result = [];
  18. for (let i = 0; i < tokens.length; i++) {
  19. if (tokens[i] !== "check" || tokens[i + 1] !== "(") continue;
  20. const start = ++i;
  21. let depth = 0;
  22. do {
  23. if (tokens[i] === "(") depth++;
  24. if (tokens[i] === ")") depth--;
  25. i++;
  26. } while (i < tokens.length && depth > 0);
  27. result.push(JSON.stringify(tokens.slice(start, i)));
  28. i--;
  29. }
  30. return result.sort();
  31. }
  32. function automaticUniqueKeys(db, table) {
  33. return db
  34. .prepare(`PRAGMA index_list(${identifier(table)})`)
  35. .all()
  36. .filter((index) => index.origin === "u")
  37. .map((index) =>
  38. JSON.stringify(
  39. db
  40. .prepare(`PRAGMA index_xinfo(${identifier(index.name)})`)
  41. .all()
  42. .filter((column) => column.key)
  43. .map(({ name, desc, coll }) => ({ name, desc, coll })),
  44. ),
  45. )
  46. .sort();
  47. }
  48. export function dumpSqliteSchema(db) {
  49. const objects = db
  50. .prepare(
  51. "SELECT type,name,sql FROM sqlite_schema WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'index' THEN 1 ELSE 2 END,name",
  52. )
  53. .all();
  54. return objects.map((object) => `${object.sql};`).join("\n\n") + "\n";
  55. }
  56. export function assertAdditiveSchema(beforeSql, afterSql) {
  57. const before = new DatabaseSync(":memory:");
  58. const after = new DatabaseSync(":memory:");
  59. try {
  60. before.exec(beforeSql);
  61. after.exec(afterSql);
  62. const oldTables = before
  63. .prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'")
  64. .all();
  65. for (const { name } of oldTables) {
  66. const oldColumns = before.prepare(`PRAGMA table_info(${identifier(name)})`).all();
  67. const newColumns = after.prepare(`PRAGMA table_info(${identifier(name)})`).all();
  68. if (!newColumns.length) throw new Error(`Removed table: ${name}`);
  69. if (JSON.stringify(checks(before, name)) !== JSON.stringify(checks(after, name)))
  70. throw new Error(`Changed CHECK constraints: ${name}`);
  71. if (
  72. JSON.stringify(automaticUniqueKeys(before, name)) !==
  73. JSON.stringify(automaticUniqueKeys(after, name))
  74. )
  75. throw new Error(`Changed UNIQUE constraints: ${name}`);
  76. for (const column of oldColumns) {
  77. const next = newColumns.find((value) => value.name === column.name);
  78. if (!next) throw new Error(`Removed column: ${name}.${column.name}`);
  79. for (const key of ["type", "notnull", "dflt_value", "pk"]) {
  80. if (column[key] !== next[key])
  81. throw new Error(`Changed column contract: ${name}.${column.name}.${key}`);
  82. }
  83. }
  84. for (const column of newColumns) {
  85. if (
  86. !oldColumns.some((value) => value.name === column.name) &&
  87. column.notnull &&
  88. column.dflt_value == null
  89. ) {
  90. throw new Error(`New required column has no default: ${name}.${column.name}`);
  91. }
  92. }
  93. const oldFks = before.prepare(`PRAGMA foreign_key_list(${identifier(name)})`).all();
  94. const newFks = after.prepare(`PRAGMA foreign_key_list(${identifier(name)})`).all();
  95. for (const key of oldFks) {
  96. if (
  97. !newFks.some((value) =>
  98. ["table", "from", "to", "on_update", "on_delete"].every(
  99. (field) => value[field] === key[field],
  100. ),
  101. )
  102. ) {
  103. throw new Error(`Changed foreign key: ${name}.${key.from}`);
  104. }
  105. }
  106. }
  107. for (const index of before
  108. .prepare(
  109. "SELECT name,sql FROM sqlite_schema WHERE type IN ('index','trigger') AND sql IS NOT NULL",
  110. )
  111. .all()) {
  112. const next = after.prepare("SELECT sql FROM sqlite_schema WHERE name=?").get(index.name);
  113. const normalize = (sql) => JSON.stringify(sqlTokens(sql));
  114. if (!next || normalize(next.sql) !== normalize(index.sql))
  115. throw new Error(`Removed or changed index/trigger: ${index.name}`);
  116. }
  117. } finally {
  118. before.close();
  119. after.close();
  120. }
  121. }