durable-db 0.0.1
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 +1052 -0
- package/dist/cli/bin.d.ts +1 -0
- package/dist/cli/bin.js +18 -0
- package/dist/cli/index.d.ts +330 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli-Cr9686BF.js +630 -0
- package/dist/context/index.d.ts +2 -0
- package/dist/context/index.js +5 -0
- package/dist/context-BuIiIQ6K.js +103 -0
- package/dist/db/index.d.ts +3 -0
- package/dist/db/index.js +760 -0
- package/dist/debug-BZJbKybf.js +49 -0
- package/dist/defineDatabase-CONf4xFC.js +54 -0
- package/dist/defineDatabase-jBv90-Pk.d.ts +188 -0
- package/dist/generator-BUPP9scJ.js +180 -0
- package/dist/index-BFM5d0FP.d.ts +328 -0
- package/dist/index-CqVMaMYY.d.ts +65 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/migrations/generator.d.ts +101 -0
- package/dist/migrations/generator.js +5 -0
- package/dist/migrations/snapshot.d.ts +2 -0
- package/dist/migrations/snapshot.js +3 -0
- package/dist/parser-CbX54Flt.js +293 -0
- package/dist/protocol-g_plhPOY.js +35 -0
- package/dist/push-BgQ5cnfH.js +184 -0
- package/dist/push-BkkaslPd.js +8 -0
- package/dist/registry.d.ts +28 -0
- package/dist/registry.js +72 -0
- package/dist/schema-BOtrGnzM.js +8 -0
- package/dist/schema-CpzTOfZ6.d.ts +6 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +3 -0
- package/dist/snapshot-C162qYoA.d.ts +125 -0
- package/dist/snapshot-D170nL7i.js +93 -0
- package/dist/state-BCcvNN-M.js +5 -0
- package/dist/state-FOEjpgJ6.js +203 -0
- package/dist/transport/protocol.d.ts +27 -0
- package/dist/transport/protocol.js +3 -0
- package/dist/transport/websocket.d.ts +31 -0
- package/dist/transport/websocket.js +3 -0
- package/dist/vite/durableDb.d.ts +20 -0
- package/dist/vite/durableDb.js +933 -0
- package/dist/websocket-Dx1fqwnF.js +104 -0
- package/package.json +114 -0
- package/virtual.d.ts +15 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
import { i as init_debug, t as debugCli } from "./debug-BZJbKybf.js";
|
|
2
|
+
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, m as loadDevState, t as clearDatabaseDevState } from "./state-FOEjpgJ6.js";
|
|
3
|
+
import { a as hashSnapshot } from "./snapshot-D170nL7i.js";
|
|
4
|
+
import { a as loadMigrationFiles, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, s as loadSnapshot, t as buildAndLoadSchema } from "./generator-BUPP9scJ.js";
|
|
5
|
+
import { a as resolveImportPath } from "./parser-CbX54Flt.js";
|
|
6
|
+
import { a as loadSchema, i as discoverDatabases, o as reportCliError, r as diffSchema, t as push } from "./push-BgQ5cnfH.js";
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
import { Command } from "commander";
|
|
10
|
+
|
|
11
|
+
//#region src/cli/generate.ts
|
|
12
|
+
init_state();
|
|
13
|
+
init_debug();
|
|
14
|
+
/**
|
|
15
|
+
* Generate production migrations from schema changes
|
|
16
|
+
*
|
|
17
|
+
* This command:
|
|
18
|
+
* 1. Compares current schema to production snapshot
|
|
19
|
+
* 2. Generates a single migration file with all changes
|
|
20
|
+
* 3. Updates the production snapshot
|
|
21
|
+
* 4. Clears dev migrations (they're now consolidated)
|
|
22
|
+
*
|
|
23
|
+
* Unlike `push`, this writes to the actual migrations directory
|
|
24
|
+
* that gets committed to git.
|
|
25
|
+
*/
|
|
26
|
+
async function generate(ctx = {}, options = {}) {
|
|
27
|
+
const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
|
|
28
|
+
const { name: customName, database: targetDb } = options;
|
|
29
|
+
const results = [];
|
|
30
|
+
const devState = loadDevState(projectRoot);
|
|
31
|
+
const databases = discoverDatabases({
|
|
32
|
+
projectRoot,
|
|
33
|
+
databasesDir,
|
|
34
|
+
migrationsDir,
|
|
35
|
+
database: targetDb
|
|
36
|
+
});
|
|
37
|
+
if (databases.length === 0) {
|
|
38
|
+
debugCli("No databases found");
|
|
39
|
+
return results;
|
|
40
|
+
}
|
|
41
|
+
for (const db of databases) {
|
|
42
|
+
const result = await generateDatabase(db, customName);
|
|
43
|
+
results.push(result);
|
|
44
|
+
if (result.hasChanges) {
|
|
45
|
+
clearDatabaseDevState(projectRoot, db.name);
|
|
46
|
+
if (devState.databases[db.name]) delete devState.databases[db.name];
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
saveDevState(projectRoot, devState);
|
|
50
|
+
return results;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Generate migration for a single database
|
|
54
|
+
*/
|
|
55
|
+
async function generateDatabase(db, customName) {
|
|
56
|
+
const result = {
|
|
57
|
+
database: db.name,
|
|
58
|
+
hasChanges: false,
|
|
59
|
+
statements: [],
|
|
60
|
+
migrationName: null,
|
|
61
|
+
migrationPath: null
|
|
62
|
+
};
|
|
63
|
+
const schema = await loadSchema(db);
|
|
64
|
+
if (!schema) return result;
|
|
65
|
+
const diff = await diffSchema(schema, db.migrationsDir);
|
|
66
|
+
if (!diff.hasChanges) {
|
|
67
|
+
debugCli("No changes for %s", db.name);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
const migrationName = generateMigrationName(customName ?? "migration");
|
|
71
|
+
fs.mkdirSync(db.migrationsDir, { recursive: true });
|
|
72
|
+
const migrationPath = path.join(db.migrationsDir, `${migrationName}.sql`);
|
|
73
|
+
const sqlContent = diff.statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
|
|
74
|
+
fs.writeFileSync(migrationPath, sqlContent);
|
|
75
|
+
const newSnapshot = {
|
|
76
|
+
...diff.currentSnapshot,
|
|
77
|
+
id: Date.now().toString(36).padStart(13, "0"),
|
|
78
|
+
prevId: diff.prodSnapshot.id
|
|
79
|
+
};
|
|
80
|
+
saveSnapshot(db.migrationsDir, newSnapshot);
|
|
81
|
+
result.hasChanges = true;
|
|
82
|
+
result.statements = diff.statements;
|
|
83
|
+
result.migrationName = migrationName;
|
|
84
|
+
result.migrationPath = migrationPath;
|
|
85
|
+
debugCli("Generated %s for %s (%d statements)", migrationName, db.name, diff.statements.length);
|
|
86
|
+
debugCli("Migration path: %s", migrationPath);
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Generate migration for a single database by name
|
|
91
|
+
*/
|
|
92
|
+
async function generateOne(ctx, dbName, options = {}) {
|
|
93
|
+
const results = await generate(ctx, {
|
|
94
|
+
...options,
|
|
95
|
+
database: dbName
|
|
96
|
+
});
|
|
97
|
+
return results.length > 0 ? results[0] : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region src/cli/status.ts
|
|
102
|
+
init_state();
|
|
103
|
+
init_debug();
|
|
104
|
+
/**
|
|
105
|
+
* Get the current status of all databases
|
|
106
|
+
*
|
|
107
|
+
* Shows:
|
|
108
|
+
* - Number of production migrations
|
|
109
|
+
* - Number of dev migrations
|
|
110
|
+
* - Whether there are uncommitted schema changes
|
|
111
|
+
* - What SQL would be generated
|
|
112
|
+
*/
|
|
113
|
+
async function status(ctx = {}) {
|
|
114
|
+
const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
|
|
115
|
+
const devState = loadDevState(projectRoot);
|
|
116
|
+
const result = {
|
|
117
|
+
epoch: devState.epoch,
|
|
118
|
+
databases: []
|
|
119
|
+
};
|
|
120
|
+
const databases = discoverDatabases({
|
|
121
|
+
projectRoot,
|
|
122
|
+
databasesDir,
|
|
123
|
+
migrationsDir
|
|
124
|
+
});
|
|
125
|
+
if (databases.length === 0) {
|
|
126
|
+
debugCli("No databases found");
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
for (const db of databases) {
|
|
130
|
+
const dbStatus = await getDatabaseStatus(projectRoot, db, devState);
|
|
131
|
+
result.databases.push(dbStatus);
|
|
132
|
+
}
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Get status for a single database
|
|
137
|
+
*/
|
|
138
|
+
async function getDatabaseStatus(projectRoot, db, devState) {
|
|
139
|
+
const dbStatus = {
|
|
140
|
+
name: db.name,
|
|
141
|
+
prodMigrationCount: 0,
|
|
142
|
+
devMigrationCount: 0,
|
|
143
|
+
hasUncommittedChanges: false,
|
|
144
|
+
pendingStatements: [],
|
|
145
|
+
prodSnapshotChanged: false,
|
|
146
|
+
epoch: devState.epoch,
|
|
147
|
+
lastPush: devState.databases[db.name]?.lastPush ?? null
|
|
148
|
+
};
|
|
149
|
+
dbStatus.prodMigrationCount = loadMigrationFiles(db.migrationsDir).size;
|
|
150
|
+
dbStatus.devMigrationCount = loadDevMigrations(projectRoot, db.name).size;
|
|
151
|
+
const schema = await loadSchema(db);
|
|
152
|
+
if (!schema) return dbStatus;
|
|
153
|
+
const prodSnapshotHash = hashSnapshot(loadSnapshot(db.migrationsDir));
|
|
154
|
+
const dbDevState = devState.databases[db.name];
|
|
155
|
+
if (dbDevState && dbDevState.prodSnapshotHash !== prodSnapshotHash) dbStatus.prodSnapshotChanged = true;
|
|
156
|
+
try {
|
|
157
|
+
const diff = await diffSchema(schema, db.migrationsDir);
|
|
158
|
+
if (diff.hasChanges) {
|
|
159
|
+
dbStatus.hasUncommittedChanges = true;
|
|
160
|
+
dbStatus.pendingStatements = diff.statements;
|
|
161
|
+
}
|
|
162
|
+
} catch (error) {
|
|
163
|
+
debugCli("Failed to generate pending statements for %s: %O", db.name, error);
|
|
164
|
+
}
|
|
165
|
+
return dbStatus;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Format status for display
|
|
169
|
+
*/
|
|
170
|
+
function formatStatus(result) {
|
|
171
|
+
const lines = [];
|
|
172
|
+
lines.push(`Dev Epoch: ${result.epoch}`);
|
|
173
|
+
lines.push("");
|
|
174
|
+
if (result.databases.length === 0) {
|
|
175
|
+
lines.push("No databases found.");
|
|
176
|
+
return lines.join("\n");
|
|
177
|
+
}
|
|
178
|
+
for (const db of result.databases) {
|
|
179
|
+
lines.push(`\u{1F4E6} ${db.name}`);
|
|
180
|
+
lines.push(` Production migrations: ${db.prodMigrationCount}`);
|
|
181
|
+
lines.push(` Dev migrations: ${db.devMigrationCount}`);
|
|
182
|
+
if (db.prodSnapshotChanged) lines.push(` \u26A0\uFE0F Production snapshot changed - run 'db:reset' to sync`);
|
|
183
|
+
if (db.hasUncommittedChanges) {
|
|
184
|
+
lines.push(` \u{1F4DD} Uncommitted changes: ${db.pendingStatements.length} statement(s)`);
|
|
185
|
+
if (db.pendingStatements.length > 0) {
|
|
186
|
+
lines.push(` Pending SQL:`);
|
|
187
|
+
for (const stmt of db.pendingStatements.slice(0, 5)) {
|
|
188
|
+
const shortStmt = stmt.length > 60 ? stmt.slice(0, 60) + "..." : stmt;
|
|
189
|
+
lines.push(` - ${shortStmt}`);
|
|
190
|
+
}
|
|
191
|
+
if (db.pendingStatements.length > 5) lines.push(` ... and ${db.pendingStatements.length - 5} more`);
|
|
192
|
+
}
|
|
193
|
+
} else lines.push(` \u2713 Schema is up to date`);
|
|
194
|
+
if (db.lastPush) lines.push(` Last push: ${db.lastPush}`);
|
|
195
|
+
lines.push("");
|
|
196
|
+
}
|
|
197
|
+
return lines.join("\n");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
//#endregion
|
|
201
|
+
//#region src/cli/reset.ts
|
|
202
|
+
init_state();
|
|
203
|
+
init_debug();
|
|
204
|
+
/**
|
|
205
|
+
* Path where wrangler/miniflare persist local Durable Object storage.
|
|
206
|
+
* Both `wrangler dev` and the Cloudflare Vite plugin use this layout.
|
|
207
|
+
*/
|
|
208
|
+
function localDoStorageDir(projectRoot) {
|
|
209
|
+
return path.join(projectRoot, ".wrangler", "state", "v3", "do");
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Delete workerd's persisted Durable Object storage.
|
|
213
|
+
*
|
|
214
|
+
* Opt-in via `--purge-local-storage`: a normal reset doesn't need this —
|
|
215
|
+
* the epoch bump gives every database a fresh DO instance — but the old
|
|
216
|
+
* instances' SQLite files stay on disk until purged. Must not run while
|
|
217
|
+
* the dev server is up: workerd keeps deleted storage open and the DO
|
|
218
|
+
* breaks until restart.
|
|
219
|
+
*
|
|
220
|
+
* When `className` is given, only storage directories whose name contains
|
|
221
|
+
* that database's DO class name are removed; otherwise the whole DO
|
|
222
|
+
* storage directory is removed.
|
|
223
|
+
*
|
|
224
|
+
* Returns the directories that were deleted.
|
|
225
|
+
*/
|
|
226
|
+
function clearLocalDoStorage(projectRoot, className) {
|
|
227
|
+
const doDir = localDoStorageDir(projectRoot);
|
|
228
|
+
if (!fs.existsSync(doDir)) return [];
|
|
229
|
+
if (!className) {
|
|
230
|
+
fs.rmSync(doDir, {
|
|
231
|
+
recursive: true,
|
|
232
|
+
force: true
|
|
233
|
+
});
|
|
234
|
+
debugCli("Cleared local DO storage: %s", doDir);
|
|
235
|
+
return [doDir];
|
|
236
|
+
}
|
|
237
|
+
const cleared = [];
|
|
238
|
+
for (const entry of fs.readdirSync(doDir)) if (entry.includes(className)) {
|
|
239
|
+
const dir = path.join(doDir, entry);
|
|
240
|
+
fs.rmSync(dir, {
|
|
241
|
+
recursive: true,
|
|
242
|
+
force: true
|
|
243
|
+
});
|
|
244
|
+
debugCli("Cleared local DO storage: %s", dir);
|
|
245
|
+
cleared.push(dir);
|
|
246
|
+
}
|
|
247
|
+
return cleared;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Reset dev state and optionally bump the epoch
|
|
251
|
+
*
|
|
252
|
+
* This command:
|
|
253
|
+
* 1. Bumps the epoch (unless keepEpoch is true)
|
|
254
|
+
* 2. Clears all dev migrations
|
|
255
|
+
* 3. Clears dev snapshots
|
|
256
|
+
*
|
|
257
|
+
* When the epoch changes, all local DO instances will use a new
|
|
258
|
+
* instance key suffix, effectively giving you fresh databases.
|
|
259
|
+
*
|
|
260
|
+
* This is useful when:
|
|
261
|
+
* - You want to start fresh with a clean database
|
|
262
|
+
* - Your local DB is in a broken state
|
|
263
|
+
* - Someone else committed migrations and you pulled
|
|
264
|
+
*/
|
|
265
|
+
async function reset(ctx = {}, options = {}) {
|
|
266
|
+
const { projectRoot = process.cwd(), databasesDir = "src/databases" } = ctx;
|
|
267
|
+
const { database: targetDb, keepEpoch = false, purgeLocalStorage = false } = options;
|
|
268
|
+
const result = {
|
|
269
|
+
newEpoch: null,
|
|
270
|
+
databases: [],
|
|
271
|
+
clearedStorageDirs: []
|
|
272
|
+
};
|
|
273
|
+
const devState = loadDevState(projectRoot);
|
|
274
|
+
if (!keepEpoch) {
|
|
275
|
+
const newEpoch = generateEpoch();
|
|
276
|
+
devState.epoch = newEpoch;
|
|
277
|
+
result.newEpoch = newEpoch;
|
|
278
|
+
debugCli("New epoch: %s", newEpoch);
|
|
279
|
+
}
|
|
280
|
+
if (targetDb) {
|
|
281
|
+
clearDatabaseDevState(projectRoot, targetDb);
|
|
282
|
+
delete devState.databases[targetDb];
|
|
283
|
+
result.databases.push(targetDb);
|
|
284
|
+
debugCli("Reset %s", targetDb);
|
|
285
|
+
if (purgeLocalStorage) {
|
|
286
|
+
const className = discoverDatabases({
|
|
287
|
+
projectRoot,
|
|
288
|
+
databasesDir,
|
|
289
|
+
migrationsDir: "migrations",
|
|
290
|
+
database: targetDb
|
|
291
|
+
})[0]?.className;
|
|
292
|
+
if (className) result.clearedStorageDirs = clearLocalDoStorage(projectRoot, className);
|
|
293
|
+
}
|
|
294
|
+
} else {
|
|
295
|
+
const databases = discoverDatabases({
|
|
296
|
+
projectRoot,
|
|
297
|
+
databasesDir,
|
|
298
|
+
migrationsDir: "migrations"
|
|
299
|
+
});
|
|
300
|
+
for (const db of databases) {
|
|
301
|
+
clearDatabaseDevState(projectRoot, db.name);
|
|
302
|
+
delete devState.databases[db.name];
|
|
303
|
+
result.databases.push(db.name);
|
|
304
|
+
debugCli("Reset %s", db.name);
|
|
305
|
+
}
|
|
306
|
+
const databasesPath = `${getDevPaths(projectRoot).cacheDir}/databases`;
|
|
307
|
+
if (fs.existsSync(databasesPath)) {
|
|
308
|
+
const dirs = fs.readdirSync(databasesPath);
|
|
309
|
+
for (const dir of dirs) if (!result.databases.includes(dir)) {
|
|
310
|
+
clearDatabaseDevState(projectRoot, dir);
|
|
311
|
+
delete devState.databases[dir];
|
|
312
|
+
debugCli("Cleaned up orphaned: %s", dir);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (purgeLocalStorage) result.clearedStorageDirs = clearLocalDoStorage(projectRoot);
|
|
316
|
+
}
|
|
317
|
+
saveDevState(projectRoot, devState);
|
|
318
|
+
return result;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Reset everything and re-run push
|
|
322
|
+
* Convenience function that combines reset + push
|
|
323
|
+
*/
|
|
324
|
+
async function resetAndPush(ctx = {}, options = {}) {
|
|
325
|
+
const { push: push$1 } = await import("./push-BkkaslPd.js");
|
|
326
|
+
return {
|
|
327
|
+
reset: await reset(ctx, options),
|
|
328
|
+
push: await push$1(ctx)
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
//#endregion
|
|
333
|
+
//#region src/cli/validate.ts
|
|
334
|
+
init_state();
|
|
335
|
+
init_debug();
|
|
336
|
+
/**
|
|
337
|
+
* Extract and normalize schema from a SQLite database.
|
|
338
|
+
* Returns a sorted list of CREATE statements from sqlite_master.
|
|
339
|
+
*/
|
|
340
|
+
function extractSchema(db) {
|
|
341
|
+
return db.prepare(`SELECT type, name, tbl_name, sql FROM sqlite_master
|
|
342
|
+
WHERE type IN ('table', 'index', 'view', 'trigger')
|
|
343
|
+
AND name NOT LIKE 'sqlite_%'
|
|
344
|
+
AND name NOT LIKE '\\_\\_%' ESCAPE '\\'
|
|
345
|
+
ORDER BY type, name`).all().filter((r) => r.sql != null).map((r) => normalizeSql(r.sql));
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Normalize SQL for comparison — collapse whitespace, remove trailing semicolons.
|
|
349
|
+
*/
|
|
350
|
+
function normalizeSql(sql) {
|
|
351
|
+
return sql.replace(/\s+/g, " ").replace(/;\s*$/, "").trim();
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Diff two sorted schema arrays. Returns a list of human-readable differences.
|
|
355
|
+
*/
|
|
356
|
+
function diffSchemas(fromMigrations, fromSchema) {
|
|
357
|
+
const diffs = [];
|
|
358
|
+
const migrationSet = new Set(fromMigrations);
|
|
359
|
+
const schemaSet = new Set(fromSchema);
|
|
360
|
+
for (const stmt of fromMigrations) if (!schemaSet.has(stmt)) diffs.push(`Only in migrations: ${stmt}`);
|
|
361
|
+
for (const stmt of fromSchema) if (!migrationSet.has(stmt)) diffs.push(`Only in schema: ${stmt}`);
|
|
362
|
+
return diffs;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Dry-run all migrations against a local in-memory SQLite to catch errors
|
|
366
|
+
* before deployment. Optionally compares the migrated schema against a
|
|
367
|
+
* from-scratch schema build (dual-path verification).
|
|
368
|
+
*/
|
|
369
|
+
async function validate(ctx = {}) {
|
|
370
|
+
const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations", noDev = false, database: onlyDatabase } = ctx;
|
|
371
|
+
let Database;
|
|
372
|
+
try {
|
|
373
|
+
const mod = await import("libsql");
|
|
374
|
+
Database = mod.default ?? mod;
|
|
375
|
+
} catch {
|
|
376
|
+
throw new Error("libsql is required for the validate command. Install it with: pnpm add -D libsql");
|
|
377
|
+
}
|
|
378
|
+
const results = [];
|
|
379
|
+
const databases = discoverDatabases({
|
|
380
|
+
projectRoot,
|
|
381
|
+
databasesDir,
|
|
382
|
+
migrationsDir,
|
|
383
|
+
database: onlyDatabase
|
|
384
|
+
});
|
|
385
|
+
if (databases.length === 0) {
|
|
386
|
+
debugCli("No databases found");
|
|
387
|
+
return results;
|
|
388
|
+
}
|
|
389
|
+
for (const db of databases) {
|
|
390
|
+
const result = await validateDatabase(db, {
|
|
391
|
+
projectRoot,
|
|
392
|
+
noDev,
|
|
393
|
+
Database
|
|
394
|
+
});
|
|
395
|
+
results.push(result);
|
|
396
|
+
}
|
|
397
|
+
return results;
|
|
398
|
+
}
|
|
399
|
+
async function validateDatabase(db, opts) {
|
|
400
|
+
const { projectRoot, noDev, Database } = opts;
|
|
401
|
+
const result = {
|
|
402
|
+
database: db.name,
|
|
403
|
+
migrationsValid: true,
|
|
404
|
+
errors: [],
|
|
405
|
+
schemaMatches: true,
|
|
406
|
+
schemaDiffs: [],
|
|
407
|
+
migrationCount: 0,
|
|
408
|
+
includesDevMigrations: false
|
|
409
|
+
};
|
|
410
|
+
const prodMigrationsDir = db.migrationsDir;
|
|
411
|
+
const prodMigrations = loadMigrationFiles(prodMigrationsDir);
|
|
412
|
+
let devMigrations = /* @__PURE__ */ new Map();
|
|
413
|
+
if (!noDev) {
|
|
414
|
+
devMigrations = loadDevMigrations(projectRoot, db.name);
|
|
415
|
+
if (devMigrations.size > 0) result.includesDevMigrations = true;
|
|
416
|
+
}
|
|
417
|
+
result.migrationCount = prodMigrations.size + devMigrations.size;
|
|
418
|
+
const migrationsDb = new Database(":memory:");
|
|
419
|
+
try {
|
|
420
|
+
const sortedNames = [...[...prodMigrations.keys()].sort(), ...[...devMigrations.keys()].sort()];
|
|
421
|
+
const allMigrations = new Map([...prodMigrations, ...devMigrations]);
|
|
422
|
+
for (const migName of sortedNames) {
|
|
423
|
+
const chunks = allMigrations.get(migName);
|
|
424
|
+
for (let chunkIdx = 0; chunkIdx < chunks.length; chunkIdx++) {
|
|
425
|
+
const statements = chunks[chunkIdx];
|
|
426
|
+
for (const stmt of statements) {
|
|
427
|
+
if (!stmt.trim()) continue;
|
|
428
|
+
try {
|
|
429
|
+
migrationsDb.exec(stmt);
|
|
430
|
+
debugCli("[ok] %s[%d]: %s...", migName, chunkIdx, stmt.substring(0, 80));
|
|
431
|
+
} catch (err) {
|
|
432
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
433
|
+
result.migrationsValid = false;
|
|
434
|
+
result.errors.push({
|
|
435
|
+
migration: migName,
|
|
436
|
+
chunk: chunkIdx,
|
|
437
|
+
statement: stmt,
|
|
438
|
+
error: errorMessage
|
|
439
|
+
});
|
|
440
|
+
debugCli("[FAIL] %s[%d]: %s", migName, chunkIdx, errorMessage);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (db.schemaImport && db.schemaTableNames.length > 0) {
|
|
446
|
+
const schemaPath = resolveImportPath(db.filePath, db.schemaImport);
|
|
447
|
+
if (schemaPath) try {
|
|
448
|
+
const schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
|
|
449
|
+
if (Object.keys(schema).length > 0) {
|
|
450
|
+
const createStatements = await generateCreateTableSQL(schema);
|
|
451
|
+
const schemaDb = new Database(":memory:");
|
|
452
|
+
try {
|
|
453
|
+
for (const stmt of createStatements) schemaDb.exec(stmt.endsWith(";") ? stmt : `${stmt};`);
|
|
454
|
+
const diffs = diffSchemas(extractSchema(migrationsDb), extractSchema(schemaDb));
|
|
455
|
+
if (diffs.length > 0) {
|
|
456
|
+
result.schemaMatches = false;
|
|
457
|
+
result.schemaDiffs = diffs;
|
|
458
|
+
}
|
|
459
|
+
} finally {
|
|
460
|
+
schemaDb.close();
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
} catch (err) {
|
|
464
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
465
|
+
console.warn(`[db] Schema drift check skipped for '${db.name}': ${message}. Migration replay still validated. Run with DEBUG=database:cli for a stack trace.`);
|
|
466
|
+
debugCli("Could not build schema for dual-path comparison: %O", err);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
} finally {
|
|
470
|
+
migrationsDb.close();
|
|
471
|
+
}
|
|
472
|
+
return result;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
//#endregion
|
|
476
|
+
//#region src/cli/command.ts
|
|
477
|
+
/**
|
|
478
|
+
* Register all database subcommands (push, generate, status, reset,
|
|
479
|
+
* validate) directly on the given Commander command.
|
|
480
|
+
*
|
|
481
|
+
* Use this to flatten the commands onto your own program — the standalone
|
|
482
|
+
* `db` binary does this so `db push` works without a nested group:
|
|
483
|
+
*
|
|
484
|
+
* registerDbCommands(program); // → `mycli push`
|
|
485
|
+
*
|
|
486
|
+
* Or use {@link createDbCommand} to mount them as a `db` group:
|
|
487
|
+
*
|
|
488
|
+
* program.addCommand(createDbCommand()); // → `mycli db push`
|
|
489
|
+
*/
|
|
490
|
+
function registerDbCommands(program) {
|
|
491
|
+
program.command("push").description("Push schema changes to dev migrations").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (options) => {
|
|
492
|
+
try {
|
|
493
|
+
const results = await push({
|
|
494
|
+
databasesDir: options.databasesDir,
|
|
495
|
+
migrationsDir: options.migrationsDir,
|
|
496
|
+
verbose: options.verbose
|
|
497
|
+
});
|
|
498
|
+
if (results.length === 0) {
|
|
499
|
+
console.log("No databases found.");
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
let hasChanges = false;
|
|
503
|
+
for (const r of results) if (r.hasChanges) {
|
|
504
|
+
hasChanges = true;
|
|
505
|
+
console.log(`✓ ${r.database}: ${r.migrationName} (${r.statements.length} statements)`);
|
|
506
|
+
} else console.log(`· ${r.database}: no changes`);
|
|
507
|
+
if (!hasChanges) console.log("\nAll databases are up to date.");
|
|
508
|
+
} catch (error) {
|
|
509
|
+
reportCliError(error, options.verbose);
|
|
510
|
+
process.exit(1);
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
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", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (name, options) => {
|
|
514
|
+
try {
|
|
515
|
+
const results = await generate({
|
|
516
|
+
databasesDir: options.databasesDir,
|
|
517
|
+
migrationsDir: options.migrationsDir,
|
|
518
|
+
verbose: options.verbose
|
|
519
|
+
}, {
|
|
520
|
+
name,
|
|
521
|
+
database: options.database
|
|
522
|
+
});
|
|
523
|
+
if (results.length === 0) {
|
|
524
|
+
console.log("No databases found.");
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
let hasChanges = false;
|
|
528
|
+
for (const r of results) if (r.hasChanges) {
|
|
529
|
+
hasChanges = true;
|
|
530
|
+
console.log(`✓ ${r.database}: ${r.migrationName}`);
|
|
531
|
+
console.log(` → ${r.migrationPath}`);
|
|
532
|
+
console.log(` ${r.statements.length} statement(s)`);
|
|
533
|
+
} else console.log(`· ${r.database}: no changes`);
|
|
534
|
+
if (!hasChanges) console.log("\nNo pending changes to generate.");
|
|
535
|
+
} catch (error) {
|
|
536
|
+
reportCliError(error, options.verbose);
|
|
537
|
+
process.exit(1);
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
program.command("status").description("Show database migration status").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (options) => {
|
|
541
|
+
try {
|
|
542
|
+
const result = await status({
|
|
543
|
+
databasesDir: options.databasesDir,
|
|
544
|
+
migrationsDir: options.migrationsDir,
|
|
545
|
+
verbose: options.verbose
|
|
546
|
+
});
|
|
547
|
+
console.log(formatStatus(result));
|
|
548
|
+
} catch (error) {
|
|
549
|
+
reportCliError(error, options.verbose);
|
|
550
|
+
process.exit(1);
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
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/ (requires the dev server to be stopped)").option("--database <db>", "Only reset this database").option("-d, --databases-dir <dir>", "Directory containing databases", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Verbose output").action(async (options) => {
|
|
554
|
+
try {
|
|
555
|
+
const result = await reset({
|
|
556
|
+
databasesDir: options.databasesDir,
|
|
557
|
+
verbose: options.verbose
|
|
558
|
+
}, {
|
|
559
|
+
keepEpoch: options.keepEpoch,
|
|
560
|
+
purgeLocalStorage: options.purgeLocalStorage,
|
|
561
|
+
database: options.database
|
|
562
|
+
});
|
|
563
|
+
if (result.newEpoch) console.log(`✓ New epoch: ${result.newEpoch} — databases start fresh on the next request`);
|
|
564
|
+
else console.log(`✓ Epoch unchanged`);
|
|
565
|
+
if (result.databases.length > 0) console.log(`✓ Reset databases: ${result.databases.join(", ")}`);
|
|
566
|
+
else console.log(`· No databases to reset`);
|
|
567
|
+
if (result.clearedStorageDirs.length > 0) {
|
|
568
|
+
console.log(`✓ Purged local DO storage: ${result.clearedStorageDirs.join(", ")}`);
|
|
569
|
+
console.log(" Note: if a dev server was running, restart it — workerd keeps deleted DO state open until restart.");
|
|
570
|
+
}
|
|
571
|
+
} catch (error) {
|
|
572
|
+
reportCliError(error, options.verbose);
|
|
573
|
+
process.exit(1);
|
|
574
|
+
}
|
|
575
|
+
});
|
|
576
|
+
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", "src/databases").option("-m, --migrations-dir <dir>", "Directory for production migrations", "migrations").option("-v, --verbose", "Show each migration as it is applied").action(async (options) => {
|
|
577
|
+
try {
|
|
578
|
+
const results = await validate({
|
|
579
|
+
databasesDir: options.databasesDir,
|
|
580
|
+
migrationsDir: options.migrationsDir,
|
|
581
|
+
verbose: options.verbose,
|
|
582
|
+
noDev: !options.dev,
|
|
583
|
+
database: options.database
|
|
584
|
+
});
|
|
585
|
+
if (results.length === 0) {
|
|
586
|
+
console.log("No databases found.");
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
let allValid = true;
|
|
590
|
+
for (const r of results) {
|
|
591
|
+
const status$1 = r.migrationsValid ? "✓" : "✗";
|
|
592
|
+
const devNote = r.includesDevMigrations ? " (includes dev migrations)" : "";
|
|
593
|
+
console.log(`${status$1} ${r.database}: ${r.migrationCount} migration(s)${devNote}`);
|
|
594
|
+
if (!r.migrationsValid) {
|
|
595
|
+
allValid = false;
|
|
596
|
+
for (const err of r.errors) {
|
|
597
|
+
console.error(` ✗ ${err.migration}[${err.chunk}]: ${err.error}`);
|
|
598
|
+
if (options.verbose) console.error(` Statement: ${err.statement}`);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (!r.schemaMatches) {
|
|
602
|
+
allValid = false;
|
|
603
|
+
console.warn(` ⚠ Schema drift detected:`);
|
|
604
|
+
for (const diff of r.schemaDiffs) console.warn(` ${diff}`);
|
|
605
|
+
} else if (r.migrationsValid) console.log(` Schema matches ✓`);
|
|
606
|
+
}
|
|
607
|
+
if (!allValid) process.exit(1);
|
|
608
|
+
} catch (error) {
|
|
609
|
+
reportCliError(error, options.verbose);
|
|
610
|
+
process.exit(1);
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
return program;
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Create a Commander command group named `db` with all database
|
|
617
|
+
* subcommands. Mount it in a host CLI with
|
|
618
|
+
* `program.addCommand(createDbCommand())` so the commands live under a
|
|
619
|
+
* `db` prefix (e.g. `mycli db push`).
|
|
620
|
+
*/
|
|
621
|
+
function createDbCommand() {
|
|
622
|
+
return registerDbCommands(new Command("db").description("Database migration management"));
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
//#endregion
|
|
626
|
+
//#region src/cli/index.ts
|
|
627
|
+
init_state();
|
|
628
|
+
|
|
629
|
+
//#endregion
|
|
630
|
+
export { resetAndPush as a, generate as c, reset as i, generateOne as l, registerDbCommands as n, formatStatus as o, validate as r, status as s, createDbCommand as t };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import "../debug-BZJbKybf.js";
|
|
2
|
+
import "../state-FOEjpgJ6.js";
|
|
3
|
+
import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../context-BuIiIQ6K.js";
|
|
4
|
+
|
|
5
|
+
export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
|