durable-db 0.11.0 → 0.13.0

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.
@@ -1,7 +1,8 @@
1
1
  import { i as init_debug, o as __exportAll, t as debugCli } from "./debug-Cz8KzMft.js";
2
- import { _ as saveDevState, a as generateEpoch, d as init_state, f as loadDevMigrations, g as saveDevMigration, h as runningDevServer, i as forgetDatabaseDevState, l as getDevPaths, n as clearDatabaseDevState, o as getDatabaseEpoch, p as loadDevState, r as clearDevMigrations } from "./state-DGYycIoJ.js";
3
- import { _ as renamesFromStatements, f as describeAmbiguity, g as parseRenameSpec, h as formatRename, i as generateSnapshotFromSchema, l as analyzeMigrationRisks, m as findAmbiguities, o as hashSnapshot, p as exampleRenames, r as generateMigrationStatements, s as snapshotsEqual, u as SchemaRenameRequiredError, v as unusedRenames } from "./snapshot-D_z95s6E.js";
4
- import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, saveSnapshot } from "./migrations/generator.js";
2
+ import { _ as saveDevMigration, a as forgetDatabaseDevState, f as init_state, g as runningDevServer, i as clearDevMigrations, m as loadDevState, o as generateEpoch, p as loadDevMigrations, r as clearDatabaseDevState, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "./state-UT6GH0JD.js";
3
+ import { t as guardReferencingRows } from "./referencingRows-B6rU7TDW.js";
4
+ import { _ as parseRenameSpec, d as applyRenames, f as describeAmbiguity, g as obviousRenames, h as formatRename, i as generateSnapshotFromSchema, l as analyzeMigrationRisks, m as findAmbiguities, o as hashSnapshot, p as exampleRenames, r as generateMigrationStatements, s as snapshotsEqual, u as SchemaRenameRequiredError, v as renamesFromStatements, y as unusedRenames } from "./snapshot-CY4FLqAo.js";
5
+ import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, parseSqlMigration, saveSnapshot } from "./migrations/generator.js";
5
6
  import { c as readFile, l as resolveImportPath, n as declaresSchema, r as parseDatabaseFile, s as discoverDatabaseFiles, u as loadViteAliases } from "./parser-mUnAtllk.js";
6
7
  import * as fs from "node:fs";
7
8
  import * as path$1 from "node:path";
@@ -285,6 +286,360 @@ async function pushOne(ctx = {}, dbName) {
285
286
  return writeDevMigration(projectRoot, db, diff);
286
287
  }
287
288
  //#endregion
289
+ //#region src/migrations/withRows.ts
290
+ const quote = (name) => `"${name.replace(/"/g, "\"\"")}"`;
291
+ /** SQL through the database as a Durable Object's `sql.exec` runs it. */
292
+ function objectSql(db) {
293
+ return { exec(query, ...bindings) {
294
+ if (/^\s*PRAGMA\s+foreign_keys\s*=/i.test(query)) return { toArray: () => [] };
295
+ if (/^\s*(SELECT|WITH|EXPLAIN)\b/i.test(query) || /^\s*PRAGMA\b[^=]*$/i.test(query)) {
296
+ const rows = db.prepare(query).all(...bindings);
297
+ return { toArray: () => rows };
298
+ }
299
+ if (bindings.length > 0) db.prepare(query).run(...bindings);
300
+ else db.exec(query);
301
+ return { toArray: () => [] };
302
+ } };
303
+ }
304
+ const all = (db, query, ...params) => db.prepare(query).all(...params);
305
+ /** The app's tables: not SQLite's own, not durable-db's journals, not a rebuild's leftovers. */
306
+ function userTables(db) {
307
+ return all(db, "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map((row) => String(row.name)).filter((name) => !name.startsWith("sqlite_") && !name.startsWith("__"));
308
+ }
309
+ function shapeOf(db, table) {
310
+ const columns = all(db, `PRAGMA table_xinfo(${quote(table)})`).filter((row) => Number(row.hidden ?? 0) === 0).map((row) => ({
311
+ name: String(row.name),
312
+ type: String(row.type ?? "").toUpperCase(),
313
+ notNull: Number(row.notnull) === 1,
314
+ pk: Number(row.pk)
315
+ }));
316
+ const references = /* @__PURE__ */ new Map();
317
+ for (const row of all(db, `PRAGMA foreign_key_list(${quote(table)})`)) {
318
+ const id = Number(row.id);
319
+ let reference = references.get(id);
320
+ if (!reference) references.set(id, reference = {
321
+ parent: String(row.table),
322
+ columns: []
323
+ });
324
+ reference.columns.push({
325
+ from: String(row.from),
326
+ to: row.to === null || row.to === void 0 ? null : String(row.to)
327
+ });
328
+ }
329
+ const unique = new Set(columns.filter((column) => column.pk > 0).map((column) => column.name));
330
+ for (const index of all(db, `PRAGMA index_list(${quote(table)})`)) {
331
+ if (Number(index.unique) !== 1) continue;
332
+ for (const part of all(db, `PRAGMA index_info(${quote(String(index.name))})`)) if (part.name !== null && part.name !== void 0) unique.add(String(part.name));
333
+ }
334
+ return {
335
+ name: table,
336
+ columns,
337
+ references: [...references.values()],
338
+ unique
339
+ };
340
+ }
341
+ /** The primary key of a table's parent row, as the foreign key names it or as the table declares it. */
342
+ function parentColumn(db, parent, to) {
343
+ if (to !== null) return to;
344
+ const key = all(db, `PRAGMA table_xinfo(${quote(parent)})`).filter((row) => Number(row.pk) > 0);
345
+ return key.length === 1 ? String(key[0].name) : null;
346
+ }
347
+ /** A made-up value of a column's declared type. `n` is unique to the value; `same` says two rows may share it. */
348
+ function made(column, n, same) {
349
+ const type = column.type;
350
+ if (type.includes("INT")) return same ? 1 : 1e3 + n;
351
+ if (type.includes("REAL") || type.includes("FLOA") || type.includes("DOUB")) return same ? 1.5 : n + .5;
352
+ if (type.includes("BLOB")) return Buffer.from(same ? [0] : [n & 255, n >> 8 & 255]);
353
+ if (type.includes("CHAR") || type.includes("CLOB") || type.includes("TEXT") || type === "") return same ? column.name : `${column.name}-${n}`;
354
+ return same ? 1 : 1e3 + n;
355
+ }
356
+ /**
357
+ * Three rows for every table, on top of what it has: one with every column
358
+ * filled, one with every nullable column NULL, one that repeats the first
359
+ * wherever nothing says a value is unique. References point at rows that
360
+ * exist — the schema demands it —; everything else is what the schema allows.
361
+ */
362
+ function seed(db, state) {
363
+ const unseeded = /* @__PURE__ */ new Map();
364
+ const tables = userTables(db).map((table) => shapeOf(db, table));
365
+ const done = /* @__PURE__ */ new Set();
366
+ for (let pass = 0; pass <= tables.length && done.size < tables.length; pass++) for (const table of tables) {
367
+ if (done.has(table.name)) continue;
368
+ if (table.references.some((reference) => reference.parent !== table.name && !done.has(reference.parent) && tables.some((other) => other.name === reference.parent)) && pass < tables.length) continue;
369
+ done.add(table.name);
370
+ let inserted = 0;
371
+ let reason = "";
372
+ for (const kind of [
373
+ 0,
374
+ 1,
375
+ 2
376
+ ]) {
377
+ const values = /* @__PURE__ */ new Map();
378
+ let possible = true;
379
+ for (const reference of table.references) {
380
+ const optional = reference.columns.every(({ from }) => !table.columns.find((column) => column.name === from)?.notNull);
381
+ if (kind === 1 && optional) {
382
+ for (const { from } of reference.columns) values.set(from, null);
383
+ continue;
384
+ }
385
+ const targets = reference.columns.map(({ to }) => parentColumn(db, reference.parent, to));
386
+ const parents = targets.every((target) => target !== null) ? all(db, `SELECT ${targets.map((target) => quote(target)).join(", ")} FROM ${quote(reference.parent)} LIMIT 3`) : [];
387
+ const parent = parents[kind % Math.max(parents.length, 1)];
388
+ if (!parent) {
389
+ if (!optional) {
390
+ possible = false;
391
+ reason = `it references ${reference.parent}, which has no row to reference`;
392
+ } else for (const { from } of reference.columns) values.set(from, null);
393
+ continue;
394
+ }
395
+ reference.columns.forEach(({ from }, at) => values.set(from, parent[targets[at]]));
396
+ }
397
+ if (!possible) continue;
398
+ for (const column of table.columns) {
399
+ if (values.has(column.name)) continue;
400
+ if (column.pk > 0 && column.type.includes("INT") && table.columns.filter((other) => other.pk > 0).length === 1) continue;
401
+ const n = ++state.n;
402
+ if (kind === 1 && !column.notNull && column.pk === 0) values.set(column.name, null);
403
+ else values.set(column.name, made(column, n, !table.unique.has(column.name) && kind !== 1));
404
+ }
405
+ const names = [...values.keys()];
406
+ try {
407
+ const sql = names.length > 0 ? `INSERT INTO ${quote(table.name)} (${names.map(quote).join(", ")}) VALUES (${names.map(() => "?").join(", ")})` : `INSERT INTO ${quote(table.name)} DEFAULT VALUES`;
408
+ db.prepare(sql).run(...names.map((name) => values.get(name)));
409
+ inserted++;
410
+ } catch (error) {
411
+ reason = error instanceof Error ? error.message : String(error);
412
+ }
413
+ }
414
+ if (inserted === 0) unseeded.set(table.name, reason || "no row could be made");
415
+ }
416
+ return [...unseeded].map(([table, reason]) => ({
417
+ table,
418
+ reason
419
+ }));
420
+ }
421
+ const keyOf = (row, key) => JSON.stringify(key.map((column) => Buffer.isBuffer(row[column]) ? row[column].toString("hex") : row[column]));
422
+ function snapshot(db) {
423
+ const tables = /* @__PURE__ */ new Map();
424
+ for (const table of userTables(db)) {
425
+ const shape = shapeOf(db, table);
426
+ const key = shape.columns.filter((column) => column.pk > 0).sort((a, b) => a.pk - b.pk).map((column) => column.name);
427
+ const rows = all(db, `SELECT * FROM ${quote(table)}`);
428
+ tables.set(table, {
429
+ columns: shape.columns.map((column) => column.name),
430
+ key,
431
+ rows: new Map(key.length > 0 ? rows.map((row) => [keyOf(row, key), row]) : []),
432
+ count: rows.length
433
+ });
434
+ }
435
+ return tables;
436
+ }
437
+ const lower = (name) => name.toLowerCase();
438
+ /** Whether the migration itself writes to a table's rows: then what happens to them is what its author wrote. */
439
+ function writes(statements, verb, table) {
440
+ const pattern = new RegExp(`^\\s*${verb}\\s+[\`"\\[]?${table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\`"\\]]?(\\s|$)`, "i");
441
+ return statements.some((statement) => pattern.test(statement));
442
+ }
443
+ /** What the rows that were there before a migration have lost by it. */
444
+ function compare(migration, statements, before, after) {
445
+ const findings = [];
446
+ const renames = renamesFromStatements(statements);
447
+ for (const [table, was] of before) {
448
+ const renamed = renames.find((rename) => rename.kind === "table" && lower(rename.from) === lower(table));
449
+ const name = renamed ? renamed.to : table;
450
+ const now = after.get(name) ?? [...after].find(([other]) => lower(other) === lower(name))?.[1];
451
+ if (!now) continue;
452
+ const told = was.key.length > 0 && now.rows.size > 0 && was.key.every((column) => now.columns.includes(column));
453
+ const lost = told ? [...was.rows.keys()].filter((key) => !now.rows.has(key)).length : Math.max(0, was.count - now.count);
454
+ if (lost > 0 && !writes(statements, "DELETE FROM", table) && !writes(statements, "DELETE FROM", name)) {
455
+ findings.push({
456
+ migration,
457
+ kind: "loses-rows",
458
+ table: name,
459
+ message: `${lost} of the ${was.count} rows of ${name} are gone after it, and no statement of it deletes them: a rebuild, or a constraint, took them along`,
460
+ fingerprint: `loses-rows:${name}`
461
+ });
462
+ continue;
463
+ }
464
+ if (!told || writes(statements, "UPDATE", table) || writes(statements, "UPDATE", name)) continue;
465
+ for (const column of was.columns) {
466
+ const moved = renames.find((rename) => rename.kind === "column" && lower(rename.table) === lower(table) && lower(rename.from) === lower(column));
467
+ const columnNow = moved ? moved.to : column;
468
+ if (!now.columns.includes(columnNow)) continue;
469
+ let emptied = 0;
470
+ for (const [key, row] of was.rows) {
471
+ const kept = now.rows.get(key);
472
+ if (kept && row[column] !== null && row[column] !== void 0 && (kept[columnNow] === null || kept[columnNow] === void 0)) emptied++;
473
+ }
474
+ if (emptied > 0) findings.push({
475
+ migration,
476
+ kind: "loses-values",
477
+ table: name,
478
+ column: columnNow,
479
+ message: `${name}.${columnNow} is empty after it in ${emptied} row(s) that held a value before: the rebuild did not copy the column`,
480
+ fingerprint: `loses-values:${name}.${columnNow}`
481
+ });
482
+ }
483
+ }
484
+ return findings;
485
+ }
486
+ /** What to do about a failure, by what SQLite said. */
487
+ function remedy(error) {
488
+ if (/NOT NULL constraint failed/i.test(error)) return "a row holds NULL there — give those rows a value in this migration, before the statement: UPDATE … SET … WHERE … IS NULL";
489
+ if (/FOREIGN KEY constraint failed|foreign key mismatch|references a row that is not there/i.test(error)) return "a row references a row that is not there — remove or repair those rows in this migration, before the statement: DELETE FROM … WHERE … NOT IN (SELECT …)";
490
+ if (/UNIQUE constraint failed/i.test(error)) return "two rows hold the same value there — make them distinct, or remove one, in this migration before the statement";
491
+ if (/CHECK constraint failed/i.test(error)) return "a row does not meet the check — repair those rows in this migration, before the statement";
492
+ return "it passes on an empty database and fails on one with rows";
493
+ }
494
+ function transact(db, work) {
495
+ db.exec("BEGIN");
496
+ try {
497
+ work();
498
+ db.exec("COMMIT");
499
+ } catch (error) {
500
+ try {
501
+ db.exec("ROLLBACK");
502
+ } catch {}
503
+ throw error;
504
+ }
505
+ }
506
+ /** A chunk as the object applies it: its statements in order, the rows that reference a rebuilt table kept through its DROP. */
507
+ function applyChunk(sql, statements, at) {
508
+ const toRun = statements.map((statement, index) => ({
509
+ statement,
510
+ index
511
+ })).filter(({ statement }) => statement.trim());
512
+ const guard = guardReferencingRows(sql, toRun.map(({ statement }) => statement));
513
+ toRun.forEach(({ statement, index }, place) => {
514
+ const execute = () => {
515
+ at.index = index;
516
+ at.statement = statement;
517
+ sql.exec(statement);
518
+ };
519
+ if (!guard) return execute();
520
+ at.index = index;
521
+ at.statement = statement;
522
+ guard.run(place, execute);
523
+ });
524
+ guard?.finish();
525
+ }
526
+ /** Empties every table: what is left is the schema, for a migration that failed on rows to run on. */
527
+ function wipe(db) {
528
+ db.exec("PRAGMA foreign_keys = OFF");
529
+ for (const table of userTables(db)) db.exec(`DELETE FROM ${quote(table)}`);
530
+ db.exec("PRAGMA foreign_keys = ON");
531
+ }
532
+ const short = (statement) => {
533
+ const line = statement.replace(/\s+/g, " ").trim();
534
+ return line.length > 120 ? `${line.slice(0, 117)}…` : line;
535
+ };
536
+ /**
537
+ * Replays `migrations`, in order, on a database with rows: before each one,
538
+ * every table gets rows its schema allows; then the migration runs as a
539
+ * Durable Object would run it. What fails, and what takes rows or values
540
+ * along without saying so, is a finding. A migration that fails is run again
541
+ * on the emptied database, so the ones after it are still checked.
542
+ */
543
+ function replayWithRows(Database, migrations) {
544
+ const db = new Database(":memory:");
545
+ const replay = {
546
+ findings: [],
547
+ unseeded: []
548
+ };
549
+ const unseeded = /* @__PURE__ */ new Map();
550
+ try {
551
+ db.exec("PRAGMA foreign_keys = ON");
552
+ const sql = objectSql(db);
553
+ const state = { n: 0 };
554
+ for (const [name, chunks] of migrations) {
555
+ for (const { table, reason } of seed(db, state)) unseeded.set(table, reason);
556
+ const before = snapshot(db);
557
+ const statements = chunks.flat();
558
+ let failed = false;
559
+ for (let chunk = 0; chunk < chunks.length; chunk++) {
560
+ const at = {
561
+ index: -1,
562
+ statement: ""
563
+ };
564
+ try {
565
+ transact(db, () => applyChunk(sql, chunks[chunk], at));
566
+ } catch (error) {
567
+ const said = error instanceof Error ? error.message : String(error);
568
+ if (!failed) {
569
+ failed = true;
570
+ replay.findings.push({
571
+ migration: name,
572
+ kind: "fails",
573
+ chunk,
574
+ statement: at.statement,
575
+ error: said,
576
+ message: `fails on a database that has rows — ${said} (chunk ${chunk}, statement ${at.index}: ${short(at.statement)}): ${remedy(said)}`,
577
+ fingerprint: `fails:${chunk}:${at.index}:${said.replace(/\s+/g, " ").slice(0, 120)}`
578
+ });
579
+ }
580
+ wipe(db);
581
+ try {
582
+ transact(db, () => applyChunk(sql, chunks[chunk], at));
583
+ } catch (again) {
584
+ replay.stopped = {
585
+ migration: name,
586
+ error: again instanceof Error ? again.message : String(again)
587
+ };
588
+ replay.unseeded = [...unseeded].map(([table, reason]) => ({
589
+ table,
590
+ reason
591
+ }));
592
+ return replay;
593
+ }
594
+ }
595
+ }
596
+ if (!failed) replay.findings.push(...compare(name, statements, before, snapshot(db)));
597
+ }
598
+ } finally {
599
+ db.close();
600
+ }
601
+ replay.unseeded = [...unseeded].map(([table, reason]) => ({
602
+ table,
603
+ reason
604
+ }));
605
+ return replay;
606
+ }
607
+ const ACCEPTED_FILE = "_accepted.json";
608
+ /** The findings nobody has accepted, and the ones somebody has. */
609
+ function sift(findings, accepted) {
610
+ const open = [];
611
+ const let_through = [];
612
+ for (const finding of findings) (accepted[finding.migration]?.includes(finding.fingerprint) ? let_through : open).push(finding);
613
+ return {
614
+ open,
615
+ accepted: let_through
616
+ };
617
+ }
618
+ /** `accepted` with these findings added. */
619
+ function accept(accepted, findings) {
620
+ const next = { ...accepted };
621
+ for (const finding of findings) {
622
+ const list = new Set(next[finding.migration] ?? []);
623
+ list.add(finding.fingerprint);
624
+ next[finding.migration] = [...list].sort();
625
+ }
626
+ return Object.fromEntries(Object.entries(next).sort(([a], [b]) => a.localeCompare(b)));
627
+ }
628
+ /** The acceptances of a database's migrations; none where the file is not there (or cannot be read as one). */
629
+ function readAccepted(migrationsDir) {
630
+ try {
631
+ const parsed = JSON.parse(fs.readFileSync(path$1.join(migrationsDir, ACCEPTED_FILE), "utf-8"));
632
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
633
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((item) => typeof item === "string")));
634
+ } catch {
635
+ return {};
636
+ }
637
+ }
638
+ function writeAccepted(migrationsDir, accepted) {
639
+ fs.mkdirSync(migrationsDir, { recursive: true });
640
+ fs.writeFileSync(path$1.join(migrationsDir, ACCEPTED_FILE), `${JSON.stringify(accepted, null, 2)}\n`);
641
+ }
642
+ //#endregion
288
643
  //#region src/cli/generate.ts
289
644
  init_state();
290
645
  init_debug();
@@ -304,6 +659,60 @@ var UnsafeMigrationError = class extends Error {
304
659
  }
305
660
  };
306
661
  /**
662
+ * `db generate` refuses a migration that is not safe on a database that has
663
+ * rows: one the replay on rows (migrations/withRows.ts) sees fail, or take
664
+ * rows or values along. Nothing is written — unless `force`, for a migration
665
+ * that is going to be repaired by hand before it ships.
666
+ */
667
+ var MigrationFailsOnRowsError = class extends Error {
668
+ findings;
669
+ constructor(findings) {
670
+ super("Refusing to write a migration that is not safe on a database that has rows:\n" + findings.map((finding) => ` ${finding.database}: it ${finding.message}`).join("\n") + "\nEvery tenant's database migrates on its own, after the deploy: a migration has to pass on any rows the schema before it allows.\nChange the schema, or write it and repair the rows in it: generate --force, edit the migration, then db validate.");
671
+ this.findings = findings;
672
+ this.name = "MigrationFailsOnRowsError";
673
+ }
674
+ };
675
+ /** The migration `db generate` is about to write, among the ones a replay runs. */
676
+ const NEW_MIGRATION = "(this migration)";
677
+ /** A migration's statements as its file holds them. */
678
+ const sqlOf = (statements) => statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
679
+ /**
680
+ * What each pending migration does to a database that has rows: the
681
+ * production migrations replayed, then the new one, each on rows the schema
682
+ * before it allows. Without libsql there is nothing to replay on: said, and
683
+ * the migration is written unchecked.
684
+ */
685
+ async function checkOnRows(diffs) {
686
+ const checked = /* @__PURE__ */ new Map();
687
+ const pending = diffs.filter(({ diff }) => diff?.hasChanges);
688
+ if (pending.length === 0) return checked;
689
+ let Database;
690
+ try {
691
+ const mod = await import("libsql");
692
+ Database = mod.default ?? mod;
693
+ } catch {
694
+ for (const { db } of pending) checked.set(db.name, {
695
+ findings: [],
696
+ note: "libsql is not installed: the migration was not replayed on a database that has rows (pnpm add -D libsql)"
697
+ });
698
+ return checked;
699
+ }
700
+ for (const { db, diff } of pending) {
701
+ const before = loadMigrationFiles(db.migrationsDir);
702
+ const migrations = [...before.keys()].sort().map((name) => [name, before.get(name)]);
703
+ try {
704
+ const replay = replayWithRows(Database, [...migrations, [NEW_MIGRATION, parseSqlMigration(sqlOf(diff.statements))]]);
705
+ checked.set(db.name, { findings: replay.findings.filter((finding) => finding.migration === NEW_MIGRATION) });
706
+ } catch (error) {
707
+ checked.set(db.name, {
708
+ findings: [],
709
+ note: `the migration was not replayed on a database that has rows: ${error instanceof Error ? error.message : String(error)}`
710
+ });
711
+ }
712
+ }
713
+ return checked;
714
+ }
715
+ /**
307
716
  * Generate production migrations from schema changes
308
717
  *
309
718
  * This command:
@@ -336,8 +745,17 @@ async function generate(ctx = {}, options = {}) {
336
745
  database: db.name
337
746
  })));
338
747
  if (blocking.length > 0 && !force) throw new UnsafeMigrationError(blocking);
748
+ const onRows = await checkOnRows(diffs);
749
+ const unsafe = diffs.flatMap(({ db }) => (onRows.get(db.name)?.findings ?? []).map((finding) => ({
750
+ ...finding,
751
+ database: db.name
752
+ })));
753
+ if (unsafe.length > 0 && !force) throw new MigrationFailsOnRowsError(unsafe);
339
754
  for (const { db, diff } of diffs) {
340
755
  const result = writeMigration(db, diff, customName);
756
+ const checked = onRows.get(db.name);
757
+ for (const finding of checked?.findings ?? []) result.warnings.push(`it ${finding.message} — db validate refuses it until the migration repairs the rows, or it is accepted there (db validate --accept)`);
758
+ if (checked?.note) result.warnings.push(checked.note);
341
759
  results.push(result);
342
760
  if (result.hasChanges) {
343
761
  clearDatabaseDevState(projectRoot, db.name);
@@ -366,7 +784,7 @@ function writeMigration(db, diff, customName) {
366
784
  const migrationName = generateMigrationName(customName ?? "migration");
367
785
  fs.mkdirSync(db.migrationsDir, { recursive: true });
368
786
  const migrationPath = path$1.join(db.migrationsDir, `${migrationName}.sql`);
369
- const sqlContent = diff.statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
787
+ const sqlContent = sqlOf(diff.statements);
370
788
  fs.writeFileSync(migrationPath, sqlContent);
371
789
  const newSnapshot = {
372
790
  ...diff.currentSnapshot,
@@ -795,15 +1213,20 @@ function diffSchemas(fromMigrations, fromSchema) {
795
1213
  return diffs;
796
1214
  }
797
1215
  /**
798
- * Warnings for the schema change `db generate` has not written yet. Renames
799
- * are unknown until it runs, so a new name next to a vanished one is reported
800
- * both as a possible rename and with the risks of create + drop.
1216
+ * Warnings for the schema change `db generate` has not written yet. A rename
1217
+ * that is one — a name changed, nothing else — is what generate will write,
1218
+ * and no risk. What is left unanswered is unknown until it runs, so a new name
1219
+ * next to a vanished one is reported both as a possible rename and with the
1220
+ * risks of create + drop.
801
1221
  */
802
1222
  async function pendingChangeWarnings(migrationsDir, schema) {
803
- const prod = loadSnapshot(migrationsDir);
1223
+ const production = loadSnapshot(migrationsDir);
804
1224
  const current = await generateSnapshotFromSchema(schema);
805
- if (snapshotsEqual(prod, current)) return [];
1225
+ if (snapshotsEqual(production, current)) return [];
1226
+ const obvious = obviousRenames(production, current);
1227
+ const prod = obvious.length > 0 ? applyRenames(production, current, obvious).snapshot : production;
806
1228
  const warnings = analyzeMigrationRisks(prod, current).map((risk) => `not yet generated: ${risk.message}`);
1229
+ for (const rename of obvious) warnings.push(`not yet generated: ${formatRename(rename)} — a rename: the data is kept`);
807
1230
  for (const ambiguity of findAmbiguities(prod, current)) {
808
1231
  const example = exampleRenames(ambiguity)[0];
809
1232
  warnings.push(`not yet generated: ${describeAmbiguity(ambiguity)} — if this is a rename, answer it when you generate${example ? ` (--rename ${example})` : ""}, or the data is dropped`);
@@ -816,7 +1239,7 @@ async function pendingChangeWarnings(migrationsDir, schema) {
816
1239
  * from-scratch schema build (dual-path verification).
817
1240
  */
818
1241
  async function validate(ctx = {}) {
819
- const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations", noDev = false, database: onlyDatabase } = ctx;
1242
+ const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations", noDev = false, database: onlyDatabase, rows = true, accept: acceptFindings = false } = ctx;
820
1243
  let Database;
821
1244
  try {
822
1245
  const mod = await import("libsql");
@@ -839,14 +1262,16 @@ async function validate(ctx = {}) {
839
1262
  const result = await validateDatabase(db, {
840
1263
  projectRoot,
841
1264
  noDev,
842
- Database
1265
+ Database,
1266
+ rows,
1267
+ accept: acceptFindings
843
1268
  });
844
1269
  results.push(result);
845
1270
  }
846
1271
  return results;
847
1272
  }
848
1273
  async function validateDatabase(db, opts) {
849
- const { projectRoot, noDev, Database } = opts;
1274
+ const { projectRoot, noDev, Database, rows, accept: acceptFindings } = opts;
850
1275
  const result = {
851
1276
  database: db.name,
852
1277
  migrationsValid: true,
@@ -855,7 +1280,8 @@ async function validateDatabase(db, opts) {
855
1280
  schemaDiffs: [],
856
1281
  migrationCount: 0,
857
1282
  includesDevMigrations: false,
858
- pendingWarnings: []
1283
+ pendingWarnings: [],
1284
+ rowsWarnings: []
859
1285
  };
860
1286
  const prodMigrationsDir = db.migrationsDir;
861
1287
  const prodMigrations = loadMigrationFiles(prodMigrationsDir);
@@ -892,6 +1318,31 @@ async function validateDatabase(db, opts) {
892
1318
  }
893
1319
  }
894
1320
  }
1321
+ if (rows && result.migrationsValid && sortedNames.length > 0) {
1322
+ const replay = replayWithRows(Database, sortedNames.map((name) => [name, allMigrations.get(name)]));
1323
+ const ofProduction = replay.findings.filter((finding) => prodMigrations.has(finding.migration));
1324
+ const ofDev = replay.findings.filter((finding) => !prodMigrations.has(finding.migration));
1325
+ let accepted = readAccepted(prodMigrationsDir);
1326
+ if (acceptFindings && ofProduction.length > 0) {
1327
+ accepted = accept(accepted, ofProduction);
1328
+ writeAccepted(prodMigrationsDir, accepted);
1329
+ }
1330
+ const sifted = sift(ofProduction, accepted);
1331
+ for (const finding of sifted.open) {
1332
+ result.migrationsValid = false;
1333
+ result.errors.push({
1334
+ migration: finding.migration,
1335
+ chunk: finding.chunk ?? 0,
1336
+ statement: finding.statement ?? "",
1337
+ error: finding.message,
1338
+ rows: finding
1339
+ });
1340
+ }
1341
+ for (const finding of sifted.accepted) result.rowsWarnings.push(`accepted: ${finding.migration} ${finding.message}`);
1342
+ for (const finding of ofDev) result.rowsWarnings.push(`not yet generated: ${finding.message}`);
1343
+ for (const { table, reason } of replay.unseeded) result.rowsWarnings.push(`no row could be made for ${table} (${reason}): what its migrations do to rows is not checked`);
1344
+ if (replay.stopped) result.rowsWarnings.push(`the replay on rows stopped at ${replay.stopped.migration}: ${replay.stopped.error}`);
1345
+ }
895
1346
  if (db.schemaImport && declaresSchema(db)) {
896
1347
  const aliases = await loadViteAliases(projectRoot);
897
1348
  const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
@@ -1037,19 +1488,22 @@ function registerDbCommands(program, defaults = {}) {
1037
1488
  fail(command, error, options.verbose);
1038
1489
  }
1039
1490
  });
1040
- program.command("validate").description("Dry-run migrations against local SQLite to catch errors before deployment").option("--database <db>", "Only validate this database").option("--no-dev", "Skip dev migrations, only validate production").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Show each migration as it is applied").action(async (options, command) => {
1491
+ program.command("validate").description("Dry-run migrations against local SQLite to catch errors before deployment").option("--database <db>", "Only validate this database").option("--no-dev", "Skip dev migrations, only validate production").option("--no-rows", "Skip the replay on a database that has rows").option("--accept", "Record what the replay on rows finds in the production migrations as looked at and let through (_accepted.json)").option("-d, --databases-dir <dir>", "Directory containing databases (default: src/databases)").option("-m, --migrations-dir <dir>", "Directory for production migrations (default: migrations)").option("-v, --verbose", "Show each migration as it is applied").action(async (options, command) => {
1041
1492
  try {
1042
1493
  const results = await validate({
1043
1494
  ...dirs(options),
1044
1495
  verbose: options.verbose,
1045
1496
  noDev: !options.dev,
1046
- database: options.database
1497
+ database: options.database,
1498
+ rows: options.rows !== false,
1499
+ accept: options.accept === true
1047
1500
  });
1048
1501
  if (results.length === 0) {
1049
1502
  console.log("No databases found.");
1050
1503
  return;
1051
1504
  }
1052
1505
  let allValid = true;
1506
+ let onRows = false;
1053
1507
  for (const r of results) {
1054
1508
  const status = r.migrationsValid ? "✓" : "✗";
1055
1509
  const devNote = r.includesDevMigrations ? " (includes dev migrations)" : "";
@@ -1057,7 +1511,8 @@ function registerDbCommands(program, defaults = {}) {
1057
1511
  if (!r.migrationsValid) {
1058
1512
  allValid = false;
1059
1513
  for (const err of r.errors) {
1060
- console.error(` ✗ ${err.migration}[${err.chunk}]: ${err.error}`);
1514
+ if (err.rows) onRows = true;
1515
+ console.error(err.rows ? ` ✗ ${err.migration}: ${err.error}` : ` ✗ ${err.migration}[${err.chunk}]: ${err.error}`);
1061
1516
  if (options.verbose) console.error(` Statement: ${err.statement}`);
1062
1517
  }
1063
1518
  }
@@ -1066,8 +1521,9 @@ function registerDbCommands(program, defaults = {}) {
1066
1521
  console.warn(` ⚠ Schema drift detected:`);
1067
1522
  for (const diff of r.schemaDiffs) console.warn(` ${diff}`);
1068
1523
  } else if (r.migrationsValid) console.log(` Schema matches ✓`);
1069
- for (const warning of r.pendingWarnings) console.warn(` ⚠ ${warning}`);
1524
+ for (const warning of [...r.pendingWarnings, ...r.rowsWarnings]) console.warn(` ⚠ ${warning}`);
1070
1525
  }
1526
+ if (onRows) console.error("\nEvery tenant's database migrates on its own, after the deploy: a migration has to pass on any rows the schema before it allows.\nRepair the rows in the migration, before the statement that fails. Where it already ran everywhere, or the rows it fails on cannot exist: db validate --accept");
1071
1527
  if (!allValid) process.exit(1);
1072
1528
  } catch (error) {
1073
1529
  fail(command, error, options.verbose);
@@ -1088,4 +1544,4 @@ function createDbCommand(defaults = {}) {
1088
1544
  //#region src/cli/index.ts
1089
1545
  init_state();
1090
1546
  //#endregion
1091
- export { discoverDatabases as _, reset as a, reportCliError as b, status as c, generateOne as d, push as f, diffSchema as g, diffDatabases as h, DevServerRunningError as i, UnsafeMigrationError as l, UnknownDatabaseError as m, registerDbCommands as n, resetAndPush as o, pushOne as p, validate as r, formatStatus as s, createDbCommand as t, generate as u, loadSchema as v, selectDatabases as x, loadSchemaTables as y };
1547
+ export { diffSchema as C, reportCliError as D, loadSchemaTables as E, selectDatabases as O, diffDatabases as S, loadSchema as T, sift as _, reset as a, pushOne as b, status as c, generate as d, generateOne as f, replayWithRows as g, readAccepted as h, DevServerRunningError as i, MigrationFailsOnRowsError as l, accept as m, registerDbCommands as n, resetAndPush as o, ACCEPTED_FILE as p, validate as r, formatStatus as s, createDbCommand as t, UnsafeMigrationError as u, writeAccepted as v, discoverDatabases as w, UnknownDatabaseError as x, push as y };
@@ -1,5 +1,5 @@
1
1
  import { s as __toCommonJS } from "../debug-Cz8KzMft.js";
2
- import { d as init_state, v as state_exports } from "../state-DGYycIoJ.js";
2
+ import { f as init_state, y as state_exports } from "../state-UT6GH0JD.js";
3
3
  //#region src/context/index.ts
4
4
  /**
5
5
  * Tenant ID resolver for framework integration.
@@ -1,5 +1,5 @@
1
1
  import { l as type } from "../index-bUUlOWfP.js";
2
- import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "../defineDatabase-BE7YRtLh.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "../defineDatabase-DlgYfwhP.js";
3
3
  import { a as OutboxSinkContext, c as queueOutboxSink, i as OutboxSink, l as tenantOfInstanceKey, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, s as outboxSink, t as Outbox } from "../outbox-D3Q9n7Rt.js";
4
- import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-CUkSkt7G.js";
4
+ import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-B5W4m0Dq.js";
5
5
  export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type AnyRelated, type AnySchema, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type JsonPluginOptions, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };