durable-db 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/bin.js CHANGED
@@ -5,7 +5,7 @@ import "../snapshot-DMW6j2Ix.js";
5
5
  import "../generator-KHBZaOI1.js";
6
6
  import "../parser-CL3Nlmsy.js";
7
7
  import "../push-DiHH52-G.js";
8
- import { n as registerDbCommands } from "../cli-BCgiaUy_.js";
8
+ import { n as registerDbCommands } from "../cli-m2H7mQpa.js";
9
9
  import { Command } from "commander";
10
10
 
11
11
  //#region src/cli/bin.ts
package/dist/cli/index.js CHANGED
@@ -4,6 +4,6 @@ import "../snapshot-DMW6j2Ix.js";
4
4
  import "../generator-KHBZaOI1.js";
5
5
  import "../parser-CL3Nlmsy.js";
6
6
  import { a as loadSchema, i as discoverDatabases, n as pushOne, o as reportCliError, r as diffSchema, t as push } from "../push-DiHH52-G.js";
7
- import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-BCgiaUy_.js";
7
+ import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-m2H7mQpa.js";
8
8
 
9
9
  export { createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
@@ -334,17 +334,106 @@ async function resetAndPush(ctx = {}, options = {}) {
334
334
  init_state();
335
335
  init_debug();
336
336
  /**
337
- * Extract and normalize schema from a SQLite database.
338
- * Returns a sorted list of CREATE statements from sqlite_master.
337
+ * Extract and normalize non-table schema objects (indexes, views, triggers)
338
+ * from a SQLite database. Returns a sorted list of CREATE statements from
339
+ * sqlite_master.
340
+ *
341
+ * Tables are deliberately excluded: SQLite stores a table's CREATE statement
342
+ * as the original text and rewrites it on `ALTER TABLE ... ADD COLUMN` (the
343
+ * new column is spliced in before the closing paren), so the stored text of a
344
+ * migrated table never string-matches a from-scratch CREATE even when the
345
+ * schemas are identical. Tables are compared structurally instead — see
346
+ * {@link extractTableStructures}.
339
347
  */
340
- function extractSchema(db) {
348
+ function extractNonTableSchema(db) {
341
349
  return db.prepare(`SELECT type, name, tbl_name, sql FROM sqlite_master
342
- WHERE type IN ('table', 'index', 'view', 'trigger')
350
+ WHERE type IN ('index', 'view', 'trigger')
343
351
  AND name NOT LIKE 'sqlite_%'
344
352
  AND name NOT LIKE '\\_\\_%' ESCAPE '\\'
345
353
  ORDER BY type, name`).all().filter((r) => r.sql != null).map((r) => normalizeSql(r.sql));
346
354
  }
347
355
  /**
356
+ * Extract the structural shape of every user table via PRAGMA introspection.
357
+ *
358
+ * This is the drift comparison for tables: it reflects what SQLite actually
359
+ * enforces rather than the stored CREATE text, so it is immune to how the
360
+ * table came to be (fresh CREATE vs. CREATE + ALTERs) and to column order,
361
+ * which is irrelevant for the named-column access the framework generates.
362
+ *
363
+ * Not covered (not exposed by PRAGMAs): CHECK constraints, column collations,
364
+ * and WITHOUT ROWID / STRICT table options.
365
+ */
366
+ function extractTableStructures(db) {
367
+ const tables = db.prepare(`SELECT name FROM sqlite_master
368
+ WHERE type = 'table'
369
+ AND name NOT LIKE 'sqlite_%'
370
+ AND name NOT LIKE '\\_\\_%' ESCAPE '\\'
371
+ ORDER BY name`).all();
372
+ const structures = /* @__PURE__ */ new Map();
373
+ for (const { name } of tables) {
374
+ const columns = /* @__PURE__ */ new Map();
375
+ const columnRows = db.prepare(`SELECT cid, name, type, "notnull", dflt_value, pk FROM pragma_table_info(?)`).all(name);
376
+ for (const col of columnRows) {
377
+ const parts = [col.type.replace(/\s+/g, " ").trim().toLowerCase() || "(dynamic)"];
378
+ if (col.notnull) parts.push("NOT NULL");
379
+ if (col.dflt_value != null) parts.push(`DEFAULT ${col.dflt_value}`);
380
+ if (col.pk) parts.push(`PK ${col.pk}`);
381
+ columns.set(col.name, parts.join(" "));
382
+ }
383
+ const uniques = [];
384
+ const indexRows = db.prepare(`SELECT seq, name, "unique", origin, partial FROM pragma_index_list(?)`).all(name);
385
+ for (const idx of indexRows) {
386
+ if (idx.origin !== "u") continue;
387
+ const cols = db.prepare(`SELECT name FROM pragma_index_info(?) ORDER BY seqno`).all(idx.name).map((c) => c.name ?? "(expr)");
388
+ uniques.push(`(${cols.join(", ")})`);
389
+ }
390
+ uniques.sort();
391
+ const fkRows = db.prepare(`SELECT id, seq, "table", "from", "to", on_update, on_delete FROM pragma_foreign_key_list(?)
392
+ ORDER BY id, seq`).all(name);
393
+ const fkGroups = /* @__PURE__ */ new Map();
394
+ for (const row of fkRows) {
395
+ const group = fkGroups.get(row.id) ?? [];
396
+ group.push(row);
397
+ fkGroups.set(row.id, group);
398
+ }
399
+ const foreignKeys = [...fkGroups.values()].map((group) => {
400
+ const from = group.map((r) => r.from).join(", ");
401
+ const to = group.map((r) => r.to ?? "(implicit pk)").join(", ");
402
+ const { table, on_update, on_delete } = group[0];
403
+ return `(${from}) → ${table}(${to}) ON UPDATE ${on_update} ON DELETE ${on_delete}`;
404
+ }).sort();
405
+ structures.set(name, {
406
+ columns,
407
+ uniques,
408
+ foreignKeys
409
+ });
410
+ }
411
+ return structures;
412
+ }
413
+ /**
414
+ * Diff table structures. Returns a list of human-readable differences.
415
+ */
416
+ function diffTableStructures(fromMigrations, fromSchema) {
417
+ const diffs = [];
418
+ for (const [name, migrated] of fromMigrations) {
419
+ const fresh = fromSchema.get(name);
420
+ if (!fresh) {
421
+ diffs.push(`Table only in migrations: ${name}`);
422
+ continue;
423
+ }
424
+ for (const [col, descriptor] of migrated.columns) {
425
+ const other = fresh.columns.get(col);
426
+ if (other === void 0) diffs.push(`Column ${name}.${col} only in migrations: ${descriptor}`);
427
+ else if (other !== descriptor) diffs.push(`Column ${name}.${col} differs — migrations: ${descriptor}; schema: ${other}`);
428
+ }
429
+ for (const [col, descriptor] of fresh.columns) if (!migrated.columns.has(col)) diffs.push(`Column ${name}.${col} only in schema: ${descriptor}`);
430
+ if (migrated.uniques.join(" | ") !== fresh.uniques.join(" | ")) diffs.push(`Unique constraints on ${name} differ — migrations: [${migrated.uniques.join(" | ") || "none"}]; schema: [${fresh.uniques.join(" | ") || "none"}]`);
431
+ if (migrated.foreignKeys.join(" | ") !== fresh.foreignKeys.join(" | ")) diffs.push(`Foreign keys on ${name} differ — migrations: [${migrated.foreignKeys.join(" | ") || "none"}]; schema: [${fresh.foreignKeys.join(" | ") || "none"}]`);
432
+ }
433
+ for (const name of fromSchema.keys()) if (!fromMigrations.has(name)) diffs.push(`Table only in schema: ${name}`);
434
+ return diffs;
435
+ }
436
+ /**
348
437
  * Normalize SQL for comparison — collapse whitespace, remove trailing semicolons.
349
438
  */
350
439
  function normalizeSql(sql) {
@@ -452,7 +541,7 @@ async function validateDatabase(db, opts) {
452
541
  const schemaDb = new Database(":memory:");
453
542
  try {
454
543
  for (const stmt of createStatements) schemaDb.exec(stmt.endsWith(";") ? stmt : `${stmt};`);
455
- const diffs = diffSchemas(extractSchema(migrationsDb), extractSchema(schemaDb));
544
+ const diffs = [...diffTableStructures(extractTableStructures(migrationsDb), extractTableStructures(schemaDb)), ...diffSchemas(extractNonTableSchema(migrationsDb), extractNonTableSchema(schemaDb))];
456
545
  if (diffs.length > 0) {
457
546
  result.schemaMatches = false;
458
547
  result.schemaDiffs = diffs;
package/dist/db/index.js CHANGED
@@ -274,7 +274,7 @@ var SqliteDurableObject = class extends DurableObject {
274
274
  for (const { name, chunkIndex, statements } of pending) {
275
275
  let currentIndex = -1;
276
276
  let currentStatement = null;
277
- try {
277
+ const applyChunk = () => {
278
278
  for (let i = 0; i < statements.length; i++) {
279
279
  const statement = statements[i];
280
280
  if (!statement.trim()) continue;
@@ -285,6 +285,11 @@ var SqliteDurableObject = class extends DurableObject {
285
285
  currentIndex = -1;
286
286
  currentStatement = null;
287
287
  this.sql.exec("INSERT INTO __migrations (name, chunk_index, applied_at) VALUES (?, ?, ?)", name, chunkIndex, (/* @__PURE__ */ new Date()).toISOString());
288
+ };
289
+ try {
290
+ const storage = this.ctx.storage;
291
+ if (typeof storage.transactionSync === "function") storage.transactionSync(applyChunk);
292
+ else applyChunk();
288
293
  debugMigrations("Migration chunk applied: %s[%d]", name, chunkIndex);
289
294
  } catch (error) {
290
295
  const location = currentStatement !== null ? ` stmt ${currentIndex}: ${formatStatementForLog(currentStatement)}` : " (while recording chunk as applied)";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"