durable-db 0.3.0 → 0.5.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.
- package/README.md +177 -25
- package/dist/{arktypeConfig-DxP0OcV_.js → actionArgs-1hEaDUia.js} +35 -1
- package/dist/cli/bin.js +1 -1
- package/dist/cli/index.d.ts +204 -62
- package/dist/cli/index.js +4 -3
- package/dist/{cli-BUSZTS2D.js → cli-CVS0b2im.js} +272 -95
- package/dist/context/index.js +14 -8
- package/dist/db/index.d.ts +3 -4
- package/dist/db/index.js +259 -26
- package/dist/defineDatabase-D_RpcKj1.js +109 -0
- package/dist/{defineDatabase-IUthY3Ex.d.ts → defineDatabase-zrUJrMd5.d.ts} +10 -3
- package/dist/{index-BdrcuAU7.d.ts → index-BvSFkwM9.d.ts} +106 -18
- package/dist/index.d.ts +1 -2
- package/dist/index.js +2 -2
- package/dist/{kysely-Be6KwFZC.js → kysely-CYmmiwDm.js} +25 -5
- package/dist/migrations/generator.d.ts +1 -1
- package/dist/migrations/generator.js +1 -1
- package/dist/migrations/snapshot.d.ts +2 -2
- package/dist/migrations/snapshot.js +1 -91
- package/dist/{parser-DR57GOjv.js → parser-DyepmXzE.js} +1 -1
- package/dist/registry.d.ts +29 -2
- package/dist/registry.js +2 -2
- package/dist/snapshot-B9Ae2TrS.d.ts +180 -0
- package/dist/snapshot-D_z95s6E.js +459 -0
- package/dist/{state-OVuoHRC9.js → state-DGYycIoJ.js} +106 -9
- package/dist/testing/index.d.ts +8 -1
- package/dist/testing/index.js +30 -11
- package/dist/vite/durableDb.d.ts +131 -1
- package/dist/vite/durableDb.js +782 -180
- package/package.json +3 -2
- package/virtual.d.ts +4 -2
- package/dist/arktypeConfig-AXvobTPL.d.ts +0 -5
- package/dist/defineDatabase-CHmzpzFf.js +0 -70
- package/dist/snapshot-CaG5xnE2.d.ts +0 -48
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { i as init_debug, o as __exportAll, t as debugCli } from "./debug-Cz8KzMft.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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
4
|
import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, saveSnapshot } from "./migrations/generator.js";
|
|
5
|
-
import {
|
|
5
|
+
import { c as resolveImportPath, l as loadViteAliases, n as parseDatabaseFile, o as discoverDatabaseFiles, s as readFile } from "./parser-DyepmXzE.js";
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
7
|
import * as path$1 from "node:path";
|
|
8
|
-
import { Command } from "commander";
|
|
9
8
|
import * as crypto from "node:crypto";
|
|
9
|
+
import { Command } from "commander";
|
|
10
10
|
//#region src/cli/shared.ts
|
|
11
11
|
init_state();
|
|
12
12
|
init_debug();
|
|
@@ -24,6 +24,31 @@ function reportCliError(error, verbose = false) {
|
|
|
24
24
|
}
|
|
25
25
|
console.error("Error:", error);
|
|
26
26
|
}
|
|
27
|
+
/** A `--database` filter that names no discovered database. */
|
|
28
|
+
var UnknownDatabaseError = class extends Error {
|
|
29
|
+
database;
|
|
30
|
+
known;
|
|
31
|
+
constructor(database, known) {
|
|
32
|
+
super(known.length > 0 ? `Unknown database '${database}'. Databases: ${known.join(", ")}.` : `Unknown database '${database}': no databases were found.`);
|
|
33
|
+
this.database = database;
|
|
34
|
+
this.known = known;
|
|
35
|
+
this.name = "UnknownDatabaseError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* The databases a command works on: every discovered one, or the one a
|
|
40
|
+
* `--database` filter names — an unknown name throws
|
|
41
|
+
* {@link UnknownDatabaseError} listing the valid ones, instead of quietly
|
|
42
|
+
* matching nothing ("No databases found.", exit 0).
|
|
43
|
+
*/
|
|
44
|
+
function selectDatabases(opts) {
|
|
45
|
+
const { database, ...rest } = opts;
|
|
46
|
+
const all = discoverDatabases(rest);
|
|
47
|
+
if (!database) return all;
|
|
48
|
+
const selected = all.filter((db) => db.name === database);
|
|
49
|
+
if (selected.length === 0) throw new UnknownDatabaseError(database, all.map((db) => db.name).sort());
|
|
50
|
+
return selected;
|
|
51
|
+
}
|
|
27
52
|
/**
|
|
28
53
|
* Discover database files, parse them, and resolve migrationsDir.
|
|
29
54
|
* Returns parsed DatabaseInfo[] with migrationsDir already set.
|
|
@@ -82,25 +107,69 @@ async function loadSchema(db, projectRoot) {
|
|
|
82
107
|
}
|
|
83
108
|
/**
|
|
84
109
|
* Diff a schema against the production snapshot in migrationsDir.
|
|
85
|
-
* Returns whether there are changes, the SQL statements,
|
|
110
|
+
* Returns whether there are changes, the SQL statements, both snapshots and
|
|
111
|
+
* what the statements risk on a database with rows. `resolution` answers
|
|
112
|
+
* drizzle-kit's rename questions (see MigrationResolution); an unanswered
|
|
113
|
+
* one without a terminal throws SchemaRenameRequiredError.
|
|
86
114
|
*/
|
|
87
|
-
async function diffSchema(schema, migrationsDir) {
|
|
115
|
+
async function diffSchema(schema, migrationsDir, resolution = {}) {
|
|
88
116
|
const prodSnapshot = loadSnapshot(migrationsDir);
|
|
89
117
|
const currentSnapshot = await generateSnapshotFromSchema(schema);
|
|
90
118
|
if (snapshotsEqual(prodSnapshot, currentSnapshot)) return {
|
|
91
119
|
hasChanges: false,
|
|
92
120
|
statements: [],
|
|
93
121
|
prodSnapshot,
|
|
94
|
-
currentSnapshot
|
|
122
|
+
currentSnapshot,
|
|
123
|
+
risks: []
|
|
95
124
|
};
|
|
96
|
-
const statements = await generateMigrationStatements(prodSnapshot, currentSnapshot);
|
|
125
|
+
const statements = await generateMigrationStatements(prodSnapshot, currentSnapshot, resolution);
|
|
126
|
+
const risks = statements.length > 0 ? analyzeMigrationRisks(prodSnapshot, currentSnapshot, renamesFromStatements(statements)) : [];
|
|
97
127
|
return {
|
|
98
128
|
hasChanges: statements.length > 0,
|
|
99
129
|
statements,
|
|
100
130
|
prodSnapshot,
|
|
101
|
-
currentSnapshot
|
|
131
|
+
currentSnapshot,
|
|
132
|
+
risks
|
|
102
133
|
};
|
|
103
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Diff every database before anything is written, so a refusal (an unanswered
|
|
137
|
+
* rename, an unused `--rename`, an unsafe statement) leaves every file as it
|
|
138
|
+
* was. A rename answer applies to the database(s) where it matches; one that
|
|
139
|
+
* matches no pending change anywhere is an error.
|
|
140
|
+
*/
|
|
141
|
+
async function diffDatabases(projectRoot, databases, resolution = {}) {
|
|
142
|
+
const answers = (resolution.renames ?? []).map((r) => typeof r === "string" ? parseRenameSpec(r) : r);
|
|
143
|
+
const diffs = [];
|
|
144
|
+
for (const db of databases) {
|
|
145
|
+
const schema = await loadSchema(db, projectRoot);
|
|
146
|
+
if (!schema) {
|
|
147
|
+
diffs.push({
|
|
148
|
+
db,
|
|
149
|
+
diff: null
|
|
150
|
+
});
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const diff = await diffSchema(schema, db.migrationsDir, {
|
|
155
|
+
renames: answers,
|
|
156
|
+
noRenames: resolution.noRenames,
|
|
157
|
+
interactive: resolution.interactive
|
|
158
|
+
});
|
|
159
|
+
diffs.push({
|
|
160
|
+
db,
|
|
161
|
+
diff
|
|
162
|
+
});
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (error instanceof SchemaRenameRequiredError) throw error.forDatabase(db.name);
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const performed = diffs.flatMap(({ diff }) => diff ? renamesFromStatements(diff.statements) : []);
|
|
169
|
+
const unused = unusedRenames(answers, performed);
|
|
170
|
+
if (unused.length > 0) throw new Error(`--rename ${unused.map(formatRename).join(", ")} matches no pending change (a column or table that the schema no longer has, and a new one it gained).`);
|
|
171
|
+
return diffs;
|
|
172
|
+
}
|
|
104
173
|
//#endregion
|
|
105
174
|
//#region src/cli/push.ts
|
|
106
175
|
var push_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -124,39 +193,33 @@ init_debug();
|
|
|
124
193
|
async function push(ctx = {}) {
|
|
125
194
|
const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
|
|
126
195
|
const results = [];
|
|
127
|
-
const databases =
|
|
196
|
+
const databases = selectDatabases({
|
|
128
197
|
projectRoot,
|
|
129
198
|
databasesDir,
|
|
130
|
-
migrationsDir
|
|
199
|
+
migrationsDir,
|
|
200
|
+
database: ctx.database
|
|
131
201
|
});
|
|
132
202
|
if (databases.length === 0) {
|
|
133
203
|
debugCli("No databases found");
|
|
134
204
|
return results;
|
|
135
205
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
results.push(result);
|
|
139
|
-
}
|
|
206
|
+
const diffs = await diffDatabases(projectRoot, databases, ctx);
|
|
207
|
+
for (const { db, diff } of diffs) results.push(writeDevMigration(projectRoot, db, diff));
|
|
140
208
|
return results;
|
|
141
209
|
}
|
|
142
210
|
/**
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
* Always diffs from the production snapshot to the current schema,
|
|
146
|
-
* producing a single squashed dev migration with a deterministic
|
|
147
|
-
* content-hash name.
|
|
211
|
+
* Write a database's squashed dev migration: the diff from the production
|
|
212
|
+
* snapshot to the current schema, with a deterministic content-hash name.
|
|
148
213
|
*/
|
|
149
|
-
|
|
214
|
+
function writeDevMigration(projectRoot, db, diff) {
|
|
150
215
|
const result = {
|
|
151
216
|
database: db.name,
|
|
152
217
|
hasChanges: false,
|
|
153
218
|
statements: [],
|
|
154
|
-
migrationName: null
|
|
219
|
+
migrationName: null,
|
|
220
|
+
warnings: []
|
|
155
221
|
};
|
|
156
|
-
|
|
157
|
-
if (!schema) return result;
|
|
158
|
-
const diff = await diffSchema(schema, db.migrationsDir);
|
|
159
|
-
if (!diff.hasChanges) {
|
|
222
|
+
if (!diff || !diff.hasChanges) {
|
|
160
223
|
debugCli("No changes for %s", db.name);
|
|
161
224
|
return result;
|
|
162
225
|
}
|
|
@@ -171,6 +234,7 @@ async function pushDatabase(projectRoot, db) {
|
|
|
171
234
|
result.hasChanges = true;
|
|
172
235
|
result.statements = diff.statements;
|
|
173
236
|
result.migrationName = migrationName;
|
|
237
|
+
result.warnings = diff.risks.map((risk) => risk.message);
|
|
174
238
|
debugCli("Generated %s for %s (%d statements)", migrationName, db.name, diff.statements.length);
|
|
175
239
|
return result;
|
|
176
240
|
}
|
|
@@ -187,13 +251,29 @@ async function pushOne(ctx = {}, dbName) {
|
|
|
187
251
|
database: dbName
|
|
188
252
|
});
|
|
189
253
|
if (databases.length === 0) return null;
|
|
190
|
-
|
|
254
|
+
const [{ db, diff }] = await diffDatabases(projectRoot, databases, ctx);
|
|
255
|
+
return writeDevMigration(projectRoot, db, diff);
|
|
191
256
|
}
|
|
192
257
|
//#endregion
|
|
193
258
|
//#region src/cli/generate.ts
|
|
194
259
|
init_state();
|
|
195
260
|
init_debug();
|
|
196
261
|
/**
|
|
262
|
+
* `db generate` refuses a migration that fails on every table that has rows.
|
|
263
|
+
* Per-tenant databases migrate lazily, so the failure would surface after the
|
|
264
|
+
* deploy, once per tenant with data, each of them broken until a fixed
|
|
265
|
+
* migration ships — and `db validate` cannot catch it: it replays migrations
|
|
266
|
+
* on an empty database.
|
|
267
|
+
*/
|
|
268
|
+
var UnsafeMigrationError = class extends Error {
|
|
269
|
+
risks;
|
|
270
|
+
constructor(risks) {
|
|
271
|
+
super("Refusing to write a migration that fails on every table that has rows:\n" + risks.map((risk) => ` ${risk.database}: ${risk.message}`).join("\n") + "\nFix the schema and run generate again, or pass --force if every such table is empty everywhere.");
|
|
272
|
+
this.risks = risks;
|
|
273
|
+
this.name = "UnsafeMigrationError";
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
/**
|
|
197
277
|
* Generate production migrations from schema changes
|
|
198
278
|
*
|
|
199
279
|
* This command:
|
|
@@ -207,10 +287,10 @@ init_debug();
|
|
|
207
287
|
*/
|
|
208
288
|
async function generate(ctx = {}, options = {}) {
|
|
209
289
|
const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
|
|
210
|
-
const { name: customName, database: targetDb } = options;
|
|
290
|
+
const { name: customName, database: targetDb, force = false } = options;
|
|
211
291
|
const results = [];
|
|
212
292
|
const devState = loadDevState(projectRoot);
|
|
213
|
-
const databases =
|
|
293
|
+
const databases = selectDatabases({
|
|
214
294
|
projectRoot,
|
|
215
295
|
databasesDir,
|
|
216
296
|
migrationsDir,
|
|
@@ -220,32 +300,36 @@ async function generate(ctx = {}, options = {}) {
|
|
|
220
300
|
debugCli("No databases found");
|
|
221
301
|
return results;
|
|
222
302
|
}
|
|
223
|
-
|
|
224
|
-
|
|
303
|
+
const diffs = await diffDatabases(projectRoot, databases, options);
|
|
304
|
+
const blocking = diffs.flatMap(({ db, diff }) => (diff?.risks ?? []).filter((risk) => risk.severity === "error").map((risk) => ({
|
|
305
|
+
...risk,
|
|
306
|
+
database: db.name
|
|
307
|
+
})));
|
|
308
|
+
if (blocking.length > 0 && !force) throw new UnsafeMigrationError(blocking);
|
|
309
|
+
for (const { db, diff } of diffs) {
|
|
310
|
+
const result = writeMigration(db, diff, customName);
|
|
225
311
|
results.push(result);
|
|
226
312
|
if (result.hasChanges) {
|
|
227
313
|
clearDatabaseDevState(projectRoot, db.name);
|
|
228
|
-
|
|
314
|
+
forgetDatabaseDevState(devState, db.name);
|
|
229
315
|
}
|
|
230
316
|
}
|
|
231
317
|
saveDevState(projectRoot, devState);
|
|
232
318
|
return results;
|
|
233
319
|
}
|
|
234
320
|
/**
|
|
235
|
-
*
|
|
321
|
+
* Write a database's migration file and its new production snapshot
|
|
236
322
|
*/
|
|
237
|
-
|
|
323
|
+
function writeMigration(db, diff, customName) {
|
|
238
324
|
const result = {
|
|
239
325
|
database: db.name,
|
|
240
326
|
hasChanges: false,
|
|
241
327
|
statements: [],
|
|
242
328
|
migrationName: null,
|
|
243
|
-
migrationPath: null
|
|
329
|
+
migrationPath: null,
|
|
330
|
+
warnings: []
|
|
244
331
|
};
|
|
245
|
-
|
|
246
|
-
if (!schema) return result;
|
|
247
|
-
const diff = await diffSchema(schema, db.migrationsDir);
|
|
248
|
-
if (!diff.hasChanges) {
|
|
332
|
+
if (!diff || !diff.hasChanges) {
|
|
249
333
|
debugCli("No changes for %s", db.name);
|
|
250
334
|
return result;
|
|
251
335
|
}
|
|
@@ -264,6 +348,7 @@ async function generateDatabase(db, customName, projectRoot) {
|
|
|
264
348
|
result.statements = diff.statements;
|
|
265
349
|
result.migrationName = migrationName;
|
|
266
350
|
result.migrationPath = migrationPath;
|
|
351
|
+
result.warnings = diff.risks.map((risk) => risk.message);
|
|
267
352
|
debugCli("Generated %s for %s (%d statements)", migrationName, db.name, diff.statements.length);
|
|
268
353
|
debugCli("Migration path: %s", migrationPath);
|
|
269
354
|
return result;
|
|
@@ -272,11 +357,16 @@ async function generateDatabase(db, customName, projectRoot) {
|
|
|
272
357
|
* Generate migration for a single database by name
|
|
273
358
|
*/
|
|
274
359
|
async function generateOne(ctx, dbName, options = {}) {
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
360
|
+
try {
|
|
361
|
+
const results = await generate(ctx, {
|
|
362
|
+
...options,
|
|
363
|
+
database: dbName
|
|
364
|
+
});
|
|
365
|
+
return results.length > 0 ? results[0] : null;
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (error instanceof UnknownDatabaseError) return null;
|
|
368
|
+
throw error;
|
|
369
|
+
}
|
|
280
370
|
}
|
|
281
371
|
//#endregion
|
|
282
372
|
//#region src/cli/status.ts
|
|
@@ -298,10 +388,11 @@ async function status(ctx = {}) {
|
|
|
298
388
|
epoch: devState.epoch,
|
|
299
389
|
databases: []
|
|
300
390
|
};
|
|
301
|
-
const databases =
|
|
391
|
+
const databases = selectDatabases({
|
|
302
392
|
projectRoot,
|
|
303
393
|
databasesDir,
|
|
304
|
-
migrationsDir
|
|
394
|
+
migrationsDir,
|
|
395
|
+
database: ctx.database
|
|
305
396
|
});
|
|
306
397
|
if (databases.length === 0) {
|
|
307
398
|
debugCli("No databases found");
|
|
@@ -324,7 +415,10 @@ async function getDatabaseStatus(projectRoot, db, devState) {
|
|
|
324
415
|
hasUncommittedChanges: false,
|
|
325
416
|
pendingStatements: [],
|
|
326
417
|
prodSnapshotChanged: false,
|
|
327
|
-
|
|
418
|
+
needsRenameResolution: [],
|
|
419
|
+
pendingError: null,
|
|
420
|
+
warnings: [],
|
|
421
|
+
epoch: getDatabaseEpoch(devState, db.name),
|
|
328
422
|
lastPush: devState.databases[db.name]?.lastPush ?? null
|
|
329
423
|
};
|
|
330
424
|
dbStatus.prodMigrationCount = loadMigrationFiles(db.migrationsDir).size;
|
|
@@ -334,15 +428,21 @@ async function getDatabaseStatus(projectRoot, db, devState) {
|
|
|
334
428
|
const prodSnapshot = loadSnapshot(db.migrationsDir);
|
|
335
429
|
const prodSnapshotHash = hashSnapshot(prodSnapshot);
|
|
336
430
|
const dbDevState = devState.databases[db.name];
|
|
337
|
-
if (dbDevState && dbDevState.prodSnapshotHash !== prodSnapshotHash) dbStatus.prodSnapshotChanged = true;
|
|
431
|
+
if (dbDevState?.prodSnapshotHash !== void 0 && dbDevState.prodSnapshotHash !== prodSnapshotHash) dbStatus.prodSnapshotChanged = true;
|
|
338
432
|
try {
|
|
339
|
-
const diff = await diffSchema(schema, db.migrationsDir);
|
|
433
|
+
const diff = await diffSchema(schema, db.migrationsDir, { interactive: false });
|
|
340
434
|
if (diff.hasChanges) {
|
|
341
435
|
dbStatus.hasUncommittedChanges = true;
|
|
342
436
|
dbStatus.pendingStatements = diff.statements;
|
|
437
|
+
dbStatus.warnings = diff.risks.map((risk) => risk.message);
|
|
343
438
|
}
|
|
344
439
|
} catch (error) {
|
|
345
|
-
|
|
440
|
+
dbStatus.hasUncommittedChanges = true;
|
|
441
|
+
if (error instanceof SchemaRenameRequiredError) dbStatus.needsRenameResolution = error.ambiguities;
|
|
442
|
+
else {
|
|
443
|
+
dbStatus.pendingError = error instanceof Error ? error.message : String(error);
|
|
444
|
+
debugCli("Failed to generate pending statements for %s: %O", db.name, error);
|
|
445
|
+
}
|
|
346
446
|
}
|
|
347
447
|
return dbStatus;
|
|
348
448
|
}
|
|
@@ -358,11 +458,19 @@ function formatStatus(result) {
|
|
|
358
458
|
return lines.join("\n");
|
|
359
459
|
}
|
|
360
460
|
for (const db of result.databases) {
|
|
461
|
+
const ambiguities = db.needsRenameResolution ?? [];
|
|
361
462
|
lines.push(`\u{1F4E6} ${db.name}`);
|
|
362
463
|
lines.push(` Production migrations: ${db.prodMigrationCount}`);
|
|
363
464
|
lines.push(` Dev migrations: ${db.devMigrationCount}`);
|
|
465
|
+
if (db.epoch && db.epoch !== result.epoch) lines.push(` Dev epoch: ${db.epoch} (own, since 'db reset --database ${db.name}')`);
|
|
364
466
|
if (db.prodSnapshotChanged) lines.push(` \u26A0\uFE0F Production snapshot changed - run 'db:reset' to sync`);
|
|
365
|
-
if (
|
|
467
|
+
if (ambiguities.length > 0) {
|
|
468
|
+
lines.push(` \u{1F4DD} Changes pending — needs rename resolution:`);
|
|
469
|
+
for (const ambiguity of ambiguities) lines.push(` - ${describeAmbiguity(ambiguity)}`);
|
|
470
|
+
const example = ambiguities.flatMap(exampleRenames)[0];
|
|
471
|
+
lines.push(` Answer when you push/generate: in a terminal (it asks), or with ${example ? `--rename ${example} (a rename) or ` : ""}--no-renames (create + drop)`);
|
|
472
|
+
} else if (db.pendingError) lines.push(` \u{1F4DD} Changes pending — the SQL could not be computed: ${db.pendingError}`);
|
|
473
|
+
else if (db.hasUncommittedChanges) {
|
|
366
474
|
lines.push(` \u{1F4DD} Uncommitted changes: ${db.pendingStatements.length} statement(s)`);
|
|
367
475
|
if (db.pendingStatements.length > 0) {
|
|
368
476
|
lines.push(` Pending SQL:`);
|
|
@@ -372,6 +480,7 @@ function formatStatus(result) {
|
|
|
372
480
|
}
|
|
373
481
|
if (db.pendingStatements.length > 5) lines.push(` ... and ${db.pendingStatements.length - 5} more`);
|
|
374
482
|
}
|
|
483
|
+
for (const warning of db.warnings ?? []) lines.push(` \u26A0\uFE0F ${warning}`);
|
|
375
484
|
} else lines.push(` \u2713 Schema is up to date`);
|
|
376
485
|
if (db.lastPush) lines.push(` Last push: ${db.lastPush}`);
|
|
377
486
|
lines.push("");
|
|
@@ -382,6 +491,15 @@ function formatStatus(result) {
|
|
|
382
491
|
//#region src/cli/reset.ts
|
|
383
492
|
init_state();
|
|
384
493
|
init_debug();
|
|
494
|
+
/** `--purge-local-storage` while the project's dev server runs. */
|
|
495
|
+
var DevServerRunningError = class extends Error {
|
|
496
|
+
pid;
|
|
497
|
+
constructor(pid) {
|
|
498
|
+
super(`A dev server is running for this project (pid ${pid}). Purging local Durable Object storage under it breaks every database request until it restarts (workerd keeps the deleted files open). Stop the dev server first, or reset without --purge-local-storage — the new epoch already gives fresh databases. Pass --force to purge anyway.`);
|
|
499
|
+
this.pid = pid;
|
|
500
|
+
this.name = "DevServerRunningError";
|
|
501
|
+
}
|
|
502
|
+
};
|
|
385
503
|
/**
|
|
386
504
|
* Path where wrangler/miniflare persist local Durable Object storage.
|
|
387
505
|
* Both `wrangler dev` and the Cloudflare Vite plugin use this layout.
|
|
@@ -445,34 +563,43 @@ function clearLocalDoStorage(projectRoot, className) {
|
|
|
445
563
|
*/
|
|
446
564
|
async function reset(ctx = {}, options = {}) {
|
|
447
565
|
const { projectRoot = process.cwd(), databasesDir = "src/databases" } = ctx;
|
|
448
|
-
const { database: targetDb, keepEpoch = false, purgeLocalStorage = false } = options;
|
|
566
|
+
const { database: targetDb, keepEpoch = false, purgeLocalStorage = false, force = false } = options;
|
|
449
567
|
const result = {
|
|
450
568
|
newEpoch: null,
|
|
451
569
|
databases: [],
|
|
452
570
|
clearedStorageDirs: []
|
|
453
571
|
};
|
|
572
|
+
const target = targetDb ? selectDatabases({
|
|
573
|
+
projectRoot,
|
|
574
|
+
databasesDir,
|
|
575
|
+
migrationsDir: "migrations",
|
|
576
|
+
database: targetDb
|
|
577
|
+
})[0] : null;
|
|
578
|
+
if (purgeLocalStorage && !force) {
|
|
579
|
+
const server = runningDevServer(projectRoot);
|
|
580
|
+
if (server) throw new DevServerRunningError(server.pid);
|
|
581
|
+
}
|
|
454
582
|
const devState = loadDevState(projectRoot);
|
|
455
|
-
if (
|
|
456
|
-
|
|
457
|
-
devState.
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
delete devState.databases[targetDb];
|
|
464
|
-
result.databases.push(targetDb);
|
|
465
|
-
debugCli("Reset %s", targetDb);
|
|
466
|
-
if (purgeLocalStorage) {
|
|
467
|
-
const className = discoverDatabases({
|
|
468
|
-
projectRoot,
|
|
469
|
-
databasesDir,
|
|
470
|
-
migrationsDir: "migrations",
|
|
471
|
-
database: targetDb
|
|
472
|
-
})[0]?.className;
|
|
473
|
-
if (className) result.clearedStorageDirs = clearLocalDoStorage(projectRoot, className);
|
|
583
|
+
if (target) {
|
|
584
|
+
clearDatabaseDevState(projectRoot, target.name);
|
|
585
|
+
if (keepEpoch) forgetDatabaseDevState(devState, target.name);
|
|
586
|
+
else {
|
|
587
|
+
const newEpoch = freshEpoch(devState);
|
|
588
|
+
devState.databases[target.name] = { epoch: newEpoch };
|
|
589
|
+
result.newEpoch = newEpoch;
|
|
590
|
+
debugCli("New epoch for %s: %s", target.name, newEpoch);
|
|
474
591
|
}
|
|
592
|
+
result.databases.push(target.name);
|
|
593
|
+
debugCli("Reset %s", target.name);
|
|
594
|
+
if (purgeLocalStorage) result.clearedStorageDirs = clearLocalDoStorage(projectRoot, target.className);
|
|
475
595
|
} else {
|
|
596
|
+
if (!keepEpoch) {
|
|
597
|
+
const newEpoch = freshEpoch(devState);
|
|
598
|
+
devState.epoch = newEpoch;
|
|
599
|
+
devState.databases = {};
|
|
600
|
+
result.newEpoch = newEpoch;
|
|
601
|
+
debugCli("New epoch: %s", newEpoch);
|
|
602
|
+
}
|
|
476
603
|
const databases = discoverDatabases({
|
|
477
604
|
projectRoot,
|
|
478
605
|
databasesDir,
|
|
@@ -480,7 +607,7 @@ async function reset(ctx = {}, options = {}) {
|
|
|
480
607
|
});
|
|
481
608
|
for (const db of databases) {
|
|
482
609
|
clearDatabaseDevState(projectRoot, db.name);
|
|
483
|
-
|
|
610
|
+
forgetDatabaseDevState(devState, db.name);
|
|
484
611
|
result.databases.push(db.name);
|
|
485
612
|
debugCli("Reset %s", db.name);
|
|
486
613
|
}
|
|
@@ -489,7 +616,7 @@ async function reset(ctx = {}, options = {}) {
|
|
|
489
616
|
const dirs = fs.readdirSync(databasesPath);
|
|
490
617
|
for (const dir of dirs) if (!result.databases.includes(dir)) {
|
|
491
618
|
clearDatabaseDevState(projectRoot, dir);
|
|
492
|
-
|
|
619
|
+
forgetDatabaseDevState(devState, dir);
|
|
493
620
|
debugCli("Cleaned up orphaned: %s", dir);
|
|
494
621
|
}
|
|
495
622
|
}
|
|
@@ -498,6 +625,13 @@ async function reset(ctx = {}, options = {}) {
|
|
|
498
625
|
saveDevState(projectRoot, devState);
|
|
499
626
|
return result;
|
|
500
627
|
}
|
|
628
|
+
/** A new epoch, distinct from every one in use (two resets can share a millisecond). */
|
|
629
|
+
function freshEpoch(devState) {
|
|
630
|
+
const used = /* @__PURE__ */ new Set([devState.epoch, ...Object.values(devState.databases).map((db) => db?.epoch)]);
|
|
631
|
+
let epoch = generateEpoch();
|
|
632
|
+
for (let n = 1; used.has(epoch); n++) epoch = `${generateEpoch()}${n.toString(36)}`;
|
|
633
|
+
return epoch;
|
|
634
|
+
}
|
|
501
635
|
/**
|
|
502
636
|
* Reset everything and re-run push
|
|
503
637
|
* Convenience function that combines reset + push
|
|
@@ -631,6 +765,22 @@ function diffSchemas(fromMigrations, fromSchema) {
|
|
|
631
765
|
return diffs;
|
|
632
766
|
}
|
|
633
767
|
/**
|
|
768
|
+
* Warnings for the schema change `db generate` has not written yet. Renames
|
|
769
|
+
* are unknown until it runs, so a new name next to a vanished one is reported
|
|
770
|
+
* both as a possible rename and with the risks of create + drop.
|
|
771
|
+
*/
|
|
772
|
+
async function pendingChangeWarnings(migrationsDir, schema) {
|
|
773
|
+
const prod = loadSnapshot(migrationsDir);
|
|
774
|
+
const current = await generateSnapshotFromSchema(schema);
|
|
775
|
+
if (snapshotsEqual(prod, current)) return [];
|
|
776
|
+
const warnings = analyzeMigrationRisks(prod, current).map((risk) => `not yet generated: ${risk.message}`);
|
|
777
|
+
for (const ambiguity of findAmbiguities(prod, current)) {
|
|
778
|
+
const example = exampleRenames(ambiguity)[0];
|
|
779
|
+
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`);
|
|
780
|
+
}
|
|
781
|
+
return warnings;
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
634
784
|
* Dry-run all migrations against a local in-memory SQLite to catch errors
|
|
635
785
|
* before deployment. Optionally compares the migrated schema against a
|
|
636
786
|
* from-scratch schema build (dual-path verification).
|
|
@@ -645,7 +795,7 @@ async function validate(ctx = {}) {
|
|
|
645
795
|
throw new Error("libsql is required for the validate command. Install it with: pnpm add -D libsql");
|
|
646
796
|
}
|
|
647
797
|
const results = [];
|
|
648
|
-
const databases =
|
|
798
|
+
const databases = selectDatabases({
|
|
649
799
|
projectRoot,
|
|
650
800
|
databasesDir,
|
|
651
801
|
migrationsDir,
|
|
@@ -674,7 +824,8 @@ async function validateDatabase(db, opts) {
|
|
|
674
824
|
schemaMatches: true,
|
|
675
825
|
schemaDiffs: [],
|
|
676
826
|
migrationCount: 0,
|
|
677
|
-
includesDevMigrations: false
|
|
827
|
+
includesDevMigrations: false,
|
|
828
|
+
pendingWarnings: []
|
|
678
829
|
};
|
|
679
830
|
const prodMigrationsDir = db.migrationsDir;
|
|
680
831
|
const prodMigrations = loadMigrationFiles(prodMigrationsDir);
|
|
@@ -717,6 +868,7 @@ async function validateDatabase(db, opts) {
|
|
|
717
868
|
if (schemaPath) try {
|
|
718
869
|
const schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
|
|
719
870
|
if (Object.keys(schema).length > 0) {
|
|
871
|
+
result.pendingWarnings = await pendingChangeWarnings(db.migrationsDir, schema);
|
|
720
872
|
const createStatements = await generateCreateTableSQL(schema);
|
|
721
873
|
const schemaDb = new Database(":memory:");
|
|
722
874
|
try {
|
|
@@ -743,16 +895,37 @@ async function validateDatabase(db, opts) {
|
|
|
743
895
|
}
|
|
744
896
|
//#endregion
|
|
745
897
|
//#region src/cli/command.ts
|
|
898
|
+
/** Collect a repeatable option's values. */
|
|
899
|
+
function collect(value, previous = []) {
|
|
900
|
+
return [...previous, value];
|
|
901
|
+
}
|
|
902
|
+
/** The command as the user typed it: `lagerverk db push`, `db push`. */
|
|
903
|
+
function commandPath(command) {
|
|
904
|
+
const names = [];
|
|
905
|
+
for (let current = command; current; current = current.parent) if (current.name()) names.unshift(current.name());
|
|
906
|
+
return names.join(" ");
|
|
907
|
+
}
|
|
908
|
+
/** Print a command's error; a rename question names the command to re-run. */
|
|
909
|
+
function fail(command, error, verbose) {
|
|
910
|
+
if (error instanceof SchemaRenameRequiredError) console.error(`Error: ${error.describe(commandPath(command))}`);
|
|
911
|
+
else reportCliError(error, verbose);
|
|
912
|
+
process.exit(1);
|
|
913
|
+
}
|
|
914
|
+
const RENAME_HELP = "Answer a rename question: <table>.<old>=<new> renames a column, <old>=<new> a table (repeatable)";
|
|
915
|
+
const NO_RENAMES_HELP = "Answer every remaining rename question with \"create\" (the old column/table is dropped, its data lost)";
|
|
746
916
|
function registerDbCommands(program, defaults = {}) {
|
|
747
917
|
const dirs = (options) => ({
|
|
748
918
|
databasesDir: options.databasesDir ?? defaults.databasesDir ?? "src/databases",
|
|
749
919
|
migrationsDir: options.migrationsDir ?? defaults.migrationsDir ?? "migrations"
|
|
750
920
|
});
|
|
751
|
-
program.command("push").description("Push schema changes to dev migrations").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", "Verbose output").action(async (options) => {
|
|
921
|
+
program.command("push").description("Push schema changes to dev migrations").option("--database <db>", "Only push this database").option("--rename <table.old=new>", RENAME_HELP, collect).option("--no-renames", NO_RENAMES_HELP).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", "Verbose output").action(async (options, command) => {
|
|
752
922
|
try {
|
|
753
923
|
const results = await push({
|
|
754
924
|
...dirs(options),
|
|
755
|
-
verbose: options.verbose
|
|
925
|
+
verbose: options.verbose,
|
|
926
|
+
database: options.database,
|
|
927
|
+
renames: options.rename,
|
|
928
|
+
noRenames: options.renames === false
|
|
756
929
|
});
|
|
757
930
|
if (results.length === 0) {
|
|
758
931
|
console.log("No databases found.");
|
|
@@ -762,21 +935,24 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
762
935
|
for (const r of results) if (r.hasChanges) {
|
|
763
936
|
hasChanges = true;
|
|
764
937
|
console.log(`✓ ${r.database}: ${r.migrationName} (${r.statements.length} statements)`);
|
|
938
|
+
for (const warning of r.warnings) console.warn(` ⚠ ${warning}`);
|
|
765
939
|
} else console.log(`· ${r.database}: no changes`);
|
|
766
940
|
if (!hasChanges) console.log("\nAll databases are up to date.");
|
|
767
941
|
} catch (error) {
|
|
768
|
-
|
|
769
|
-
process.exit(1);
|
|
942
|
+
fail(command, error, options.verbose);
|
|
770
943
|
}
|
|
771
944
|
});
|
|
772
|
-
program.command("generate [name]").description("Generate production migration from schema changes").option("--database <db>", "Only generate for this database").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", "Verbose output").action(async (name, options) => {
|
|
945
|
+
program.command("generate [name]").description("Generate production migration from schema changes").option("--database <db>", "Only generate for this database").option("--rename <table.old=new>", RENAME_HELP, collect).option("--no-renames", NO_RENAMES_HELP).option("--force", "Write the migration even when a statement fails on every table that has rows (a NOT NULL column without a default)").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", "Verbose output").action(async (name, options, command) => {
|
|
773
946
|
try {
|
|
774
947
|
const results = await generate({
|
|
775
948
|
...dirs(options),
|
|
776
949
|
verbose: options.verbose
|
|
777
950
|
}, {
|
|
778
951
|
name,
|
|
779
|
-
database: options.database
|
|
952
|
+
database: options.database,
|
|
953
|
+
renames: options.rename,
|
|
954
|
+
noRenames: options.renames === false,
|
|
955
|
+
force: options.force
|
|
780
956
|
});
|
|
781
957
|
if (results.length === 0) {
|
|
782
958
|
console.log("No databases found.");
|
|
@@ -788,26 +964,26 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
788
964
|
console.log(`✓ ${r.database}: ${r.migrationName}`);
|
|
789
965
|
console.log(` → ${r.migrationPath}`);
|
|
790
966
|
console.log(` ${r.statements.length} statement(s)`);
|
|
967
|
+
for (const warning of r.warnings) console.warn(` ⚠ ${warning}`);
|
|
791
968
|
} else console.log(`· ${r.database}: no changes`);
|
|
792
969
|
if (!hasChanges) console.log("\nNo pending changes to generate.");
|
|
793
970
|
} catch (error) {
|
|
794
|
-
|
|
795
|
-
process.exit(1);
|
|
971
|
+
fail(command, error, options.verbose);
|
|
796
972
|
}
|
|
797
973
|
});
|
|
798
|
-
program.command("status").description("Show database migration status").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", "Verbose output").action(async (options) => {
|
|
974
|
+
program.command("status").description("Show database migration status").option("--database <db>", "Only show this database").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", "Verbose output").action(async (options, command) => {
|
|
799
975
|
try {
|
|
800
976
|
const result = await status({
|
|
801
977
|
...dirs(options),
|
|
802
|
-
verbose: options.verbose
|
|
978
|
+
verbose: options.verbose,
|
|
979
|
+
database: options.database
|
|
803
980
|
});
|
|
804
981
|
console.log(formatStatus(result));
|
|
805
982
|
} catch (error) {
|
|
806
|
-
|
|
807
|
-
process.exit(1);
|
|
983
|
+
fail(command, error, options.verbose);
|
|
808
984
|
}
|
|
809
985
|
});
|
|
810
|
-
program.command("reset").description("Reset dev state and create fresh DB instances (via epoch bump)").option("--keep-epoch", "Only clear dev migrations, keep the same epoch").option("--purge-local-storage", "Also delete workerd's persisted DO storage under .wrangler/ (
|
|
986
|
+
program.command("reset").description("Reset dev state and create fresh DB instances (via epoch bump)").option("--keep-epoch", "Only clear dev migrations, keep the same epoch").option("--purge-local-storage", "Also delete workerd's persisted DO storage under .wrangler/ (refused while the dev server runs)").option("--force", "With --purge-local-storage: purge even when a dev server appears to be running").option("--database <db>", "Only reset this database (it alone starts fresh)").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", "Verbose output").action(async (options, command) => {
|
|
811
987
|
try {
|
|
812
988
|
const result = await reset({
|
|
813
989
|
databasesDir: dirs(options).databasesDir,
|
|
@@ -815,9 +991,11 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
815
991
|
}, {
|
|
816
992
|
keepEpoch: options.keepEpoch,
|
|
817
993
|
purgeLocalStorage: options.purgeLocalStorage,
|
|
994
|
+
force: options.force,
|
|
818
995
|
database: options.database
|
|
819
996
|
});
|
|
820
|
-
if (result.newEpoch) console.log(`✓ New epoch: ${result.newEpoch} —
|
|
997
|
+
if (result.newEpoch && options.database) console.log(`✓ New epoch for ${options.database}: ${result.newEpoch} — it starts fresh on the next request (other databases keep their data)`);
|
|
998
|
+
else if (result.newEpoch) console.log(`✓ New epoch: ${result.newEpoch} — databases start fresh on the next request`);
|
|
821
999
|
else console.log(`✓ Epoch unchanged`);
|
|
822
1000
|
if (result.databases.length > 0) console.log(`✓ Reset databases: ${result.databases.join(", ")}`);
|
|
823
1001
|
else console.log(`· No databases to reset`);
|
|
@@ -826,11 +1004,10 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
826
1004
|
console.log(" Note: if a dev server was running, restart it — workerd keeps deleted DO state open until restart.");
|
|
827
1005
|
}
|
|
828
1006
|
} catch (error) {
|
|
829
|
-
|
|
830
|
-
process.exit(1);
|
|
1007
|
+
fail(command, error, options.verbose);
|
|
831
1008
|
}
|
|
832
1009
|
});
|
|
833
|
-
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) => {
|
|
1010
|
+
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) => {
|
|
834
1011
|
try {
|
|
835
1012
|
const results = await validate({
|
|
836
1013
|
...dirs(options),
|
|
@@ -859,11 +1036,11 @@ function registerDbCommands(program, defaults = {}) {
|
|
|
859
1036
|
console.warn(` ⚠ Schema drift detected:`);
|
|
860
1037
|
for (const diff of r.schemaDiffs) console.warn(` ${diff}`);
|
|
861
1038
|
} else if (r.migrationsValid) console.log(` Schema matches ✓`);
|
|
1039
|
+
for (const warning of r.pendingWarnings) console.warn(` ⚠ ${warning}`);
|
|
862
1040
|
}
|
|
863
1041
|
if (!allValid) process.exit(1);
|
|
864
1042
|
} catch (error) {
|
|
865
|
-
|
|
866
|
-
process.exit(1);
|
|
1043
|
+
fail(command, error, options.verbose);
|
|
867
1044
|
}
|
|
868
1045
|
});
|
|
869
1046
|
return program;
|
|
@@ -881,4 +1058,4 @@ function createDbCommand(defaults = {}) {
|
|
|
881
1058
|
//#region src/cli/index.ts
|
|
882
1059
|
init_state();
|
|
883
1060
|
//#endregion
|
|
884
|
-
export {
|
|
1061
|
+
export { discoverDatabases as _, reset as a, selectDatabases 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, reportCliError as y };
|