durable-db 0.3.0 → 0.4.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 +175 -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 +2 -3
- package/dist/db/index.js +216 -25
- 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-CJ6Focq4.d.ts} +70 -17
- 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 +130 -1
- package/dist/vite/durableDb.js +725 -178
- 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
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
//#region src/migrations/renames.ts
|
|
3
|
+
/** A snapshot, read through {@link SnapshotShape}. */
|
|
4
|
+
function shape(snapshot) {
|
|
5
|
+
const s = snapshot;
|
|
6
|
+
return {
|
|
7
|
+
tables: s.tables ?? {},
|
|
8
|
+
views: s.views ?? {}
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Parse a rename answer as typed on the command line:
|
|
13
|
+
* `<table>.<old>=<new>` renames a column, `<old>=<new>` a table. Names are the
|
|
14
|
+
* SQL names (snake_case, as in the migration files); a camelCase property name
|
|
15
|
+
* is accepted too and converted the way durable-db's schema does.
|
|
16
|
+
*/
|
|
17
|
+
function parseRenameSpec(spec) {
|
|
18
|
+
const match = /^\s*([^=\s]+)\s*=\s*([^=\s]+)\s*$/.exec(spec);
|
|
19
|
+
if (!match) throw new Error(`Invalid rename '${spec}': expected <table>.<old>=<new> for a column or <old>=<new> for a table (e.g. products.description=summary).`);
|
|
20
|
+
const [, left, right] = match;
|
|
21
|
+
const leftParts = left.split(".");
|
|
22
|
+
if (leftParts.length === 2 && leftParts[0] && leftParts[1]) {
|
|
23
|
+
const to = right.includes(".") ? right.split(".").pop() : right;
|
|
24
|
+
return {
|
|
25
|
+
kind: "column",
|
|
26
|
+
table: leftParts[0],
|
|
27
|
+
from: leftParts[1],
|
|
28
|
+
to
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
if (leftParts.length === 1 && !right.includes(".")) return {
|
|
32
|
+
kind: "table",
|
|
33
|
+
from: left,
|
|
34
|
+
to: right
|
|
35
|
+
};
|
|
36
|
+
throw new Error(`Invalid rename '${spec}': expected <table>.<old>=<new> for a column or <old>=<new> for a table.`);
|
|
37
|
+
}
|
|
38
|
+
function formatRename(answer) {
|
|
39
|
+
return answer.kind === "column" ? `${answer.table}.${answer.from}=${answer.to}` : `${answer.from}=${answer.to}`;
|
|
40
|
+
}
|
|
41
|
+
/** drizzle's snake_case conversion (`casing: 'snake_case'`), for camelCase input. */
|
|
42
|
+
function toSnakeCase(input) {
|
|
43
|
+
return (input.replace(/['’]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).map((word) => word.toLowerCase()).join("_");
|
|
44
|
+
}
|
|
45
|
+
/** The name as it appears in `names`: verbatim, else its snake_case form. */
|
|
46
|
+
function matchName(name, names) {
|
|
47
|
+
const set = new Set(names);
|
|
48
|
+
if (set.has(name)) return name;
|
|
49
|
+
const snake = toSnakeCase(name);
|
|
50
|
+
return set.has(snake) ? snake : null;
|
|
51
|
+
}
|
|
52
|
+
function keysOnlyIn(a, b) {
|
|
53
|
+
return Object.keys(a ?? {}).filter((key) => !(key in (b ?? {})));
|
|
54
|
+
}
|
|
55
|
+
/** Every question drizzle-kit would ask to diff `prev` → `cur`. */
|
|
56
|
+
function findAmbiguities(prevSnapshot, curSnapshot) {
|
|
57
|
+
const prev = shape(prevSnapshot);
|
|
58
|
+
const cur = shape(curSnapshot);
|
|
59
|
+
const ambiguities = [];
|
|
60
|
+
const createdTables = keysOnlyIn(cur.tables, prev.tables);
|
|
61
|
+
const deletedTables = keysOnlyIn(prev.tables, cur.tables);
|
|
62
|
+
if (createdTables.length > 0 && deletedTables.length > 0) ambiguities.push({
|
|
63
|
+
kind: "table",
|
|
64
|
+
created: createdTables,
|
|
65
|
+
deleted: deletedTables
|
|
66
|
+
});
|
|
67
|
+
for (const [name, table] of Object.entries(cur.tables ?? {})) {
|
|
68
|
+
const before = prev.tables?.[name];
|
|
69
|
+
if (!before) continue;
|
|
70
|
+
const created = keysOnlyIn(table.columns, before.columns);
|
|
71
|
+
const deleted = keysOnlyIn(before.columns, table.columns);
|
|
72
|
+
if (created.length > 0 && deleted.length > 0) ambiguities.push({
|
|
73
|
+
kind: "column",
|
|
74
|
+
table: name,
|
|
75
|
+
created,
|
|
76
|
+
deleted
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const createdViews = keysOnlyIn(cur.views, prev.views);
|
|
80
|
+
const deletedViews = keysOnlyIn(prev.views, cur.views);
|
|
81
|
+
if (createdViews.length > 0 && deletedViews.length > 0) ambiguities.push({
|
|
82
|
+
kind: "view",
|
|
83
|
+
created: createdViews,
|
|
84
|
+
deleted: deletedViews
|
|
85
|
+
});
|
|
86
|
+
return ambiguities;
|
|
87
|
+
}
|
|
88
|
+
/** One line per ambiguity: `products: summary added, description removed`. */
|
|
89
|
+
function describeAmbiguity(ambiguity) {
|
|
90
|
+
return `${ambiguity.kind === "column" ? `${ambiguity.table}: ` : `${ambiguity.kind}s: `}${ambiguity.created.join(", ")} added, ${ambiguity.deleted.join(", ")} removed`;
|
|
91
|
+
}
|
|
92
|
+
/** Example `--rename` answers for an ambiguity (each new name from the first vanished one). */
|
|
93
|
+
function exampleRenames(ambiguity) {
|
|
94
|
+
if (ambiguity.kind === "view") return [];
|
|
95
|
+
const from = ambiguity.deleted[0];
|
|
96
|
+
return ambiguity.created.slice(0, 1).map((to) => ambiguity.kind === "column" ? `${ambiguity.table}.${from}=${to}` : `${from}=${to}`);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The diff needs answers drizzle-kit can only ask for in a terminal: no TTY,
|
|
100
|
+
* or a caller that asked for no prompts, and no `--rename` / `--no-renames`
|
|
101
|
+
* answer for these.
|
|
102
|
+
*/
|
|
103
|
+
var SchemaRenameRequiredError = class extends Error {
|
|
104
|
+
ambiguities;
|
|
105
|
+
/** Set by the CLI to the database the diff belongs to. */
|
|
106
|
+
database;
|
|
107
|
+
constructor(ambiguities) {
|
|
108
|
+
super("");
|
|
109
|
+
this.ambiguities = ambiguities;
|
|
110
|
+
this.name = "SchemaRenameRequiredError";
|
|
111
|
+
this.message = this.describe();
|
|
112
|
+
}
|
|
113
|
+
/** Name the database the diff belongs to (in the message too). */
|
|
114
|
+
forDatabase(database) {
|
|
115
|
+
this.database = database;
|
|
116
|
+
this.message = this.describe();
|
|
117
|
+
return this;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The message, naming the command to re-run (`lagerverk db generate`, `db push`…).
|
|
121
|
+
*/
|
|
122
|
+
describe(command = "db push / db generate") {
|
|
123
|
+
const examples = this.ambiguities.flatMap(exampleRenames);
|
|
124
|
+
return [
|
|
125
|
+
`${this.database ? `${this.database}: ` : ""}the schema change needs rename resolution — drizzle-kit asks whether these are renames, and its prompts need an interactive terminal (TTY):`,
|
|
126
|
+
...this.ambiguities.map((a) => ` ${describeAmbiguity(a)}`),
|
|
127
|
+
`Answer in a terminal by running \`${command}\` there, or on the command line:`,
|
|
128
|
+
...examples.length > 0 ? [` ${command} --rename ${examples[0]} (a rename: the data is kept; repeat --rename for each)`] : [],
|
|
129
|
+
` ${command} --no-renames (create + drop: the removed ones' data is lost)`
|
|
130
|
+
].join("\n");
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
function clone(value) {
|
|
134
|
+
return JSON.parse(JSON.stringify(value));
|
|
135
|
+
}
|
|
136
|
+
function renameTableRefs(snapshot, from, to) {
|
|
137
|
+
for (const table of Object.values(snapshot.tables ?? {})) for (const fk of Object.values(table.foreignKeys ?? {})) {
|
|
138
|
+
if (fk.tableFrom === from) fk.tableFrom = to;
|
|
139
|
+
if (fk.tableTo === from) fk.tableTo = to;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function renameColumnRefs(snapshot, tableName, from, to) {
|
|
143
|
+
const swap = (columns) => columns.map((c) => c === from ? to : c);
|
|
144
|
+
const table = snapshot.tables[tableName];
|
|
145
|
+
for (const index of Object.values(table.indexes ?? {})) index.columns = swap(index.columns);
|
|
146
|
+
for (const pk of Object.values(table.compositePrimaryKeys ?? {})) pk.columns = swap(pk.columns);
|
|
147
|
+
for (const unique of Object.values(table.uniqueConstraints ?? {})) unique.columns = swap(unique.columns);
|
|
148
|
+
for (const other of Object.values(snapshot.tables ?? {})) for (const fk of Object.values(other.foreignKeys ?? {})) {
|
|
149
|
+
if (fk.tableFrom === tableName) fk.columnsFrom = swap(fk.columnsFrom);
|
|
150
|
+
if (fk.tableTo === tableName) fk.columnsTo = swap(fk.columnsTo);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Apply rename answers to `prev`, as SQLite's `ALTER TABLE … RENAME` does
|
|
155
|
+
* (references in indexes, keys and foreign keys follow the new name). An
|
|
156
|
+
* answer applies when its old name exists only in `prev` and its new name
|
|
157
|
+
* only in `cur`; answers that match nothing here are left out of `applied`
|
|
158
|
+
* (the caller decides whether an unused answer is an error — with several
|
|
159
|
+
* databases, an answer usually belongs to one of them).
|
|
160
|
+
*/
|
|
161
|
+
function applyRenames(prevSnapshot, curSnapshot, answers) {
|
|
162
|
+
const copy = clone(prevSnapshot);
|
|
163
|
+
const snapshot = shape(copy);
|
|
164
|
+
const cur = shape(curSnapshot);
|
|
165
|
+
const statements = [];
|
|
166
|
+
const applied = [];
|
|
167
|
+
for (const answer of answers) {
|
|
168
|
+
if (answer.kind !== "table") continue;
|
|
169
|
+
const from = matchName(answer.from, keysOnlyIn(snapshot.tables, cur.tables));
|
|
170
|
+
const to = matchName(answer.to, keysOnlyIn(cur.tables, snapshot.tables));
|
|
171
|
+
if (!from || !to) continue;
|
|
172
|
+
const table = snapshot.tables[from];
|
|
173
|
+
delete snapshot.tables[from];
|
|
174
|
+
table.name = to;
|
|
175
|
+
snapshot.tables[to] = table;
|
|
176
|
+
renameTableRefs(snapshot, from, to);
|
|
177
|
+
statements.push(`ALTER TABLE \`${from}\` RENAME TO \`${to}\`;`);
|
|
178
|
+
applied.push({
|
|
179
|
+
kind: "table",
|
|
180
|
+
from,
|
|
181
|
+
to
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
const renamedTo = new Map(applied.flatMap((a) => a.kind === "table" ? [[a.from, a.to]] : []));
|
|
185
|
+
const resolveTable = (name) => {
|
|
186
|
+
const current = matchName(name, Object.keys(snapshot.tables ?? {}));
|
|
187
|
+
if (current) return current;
|
|
188
|
+
const old = matchName(name, renamedTo.keys());
|
|
189
|
+
return old ? renamedTo.get(old) : null;
|
|
190
|
+
};
|
|
191
|
+
for (const answer of answers) {
|
|
192
|
+
if (answer.kind !== "column") continue;
|
|
193
|
+
const tableName = resolveTable(answer.table);
|
|
194
|
+
if (!tableName || !cur.tables?.[tableName]) continue;
|
|
195
|
+
const table = snapshot.tables[tableName];
|
|
196
|
+
const from = matchName(answer.from, keysOnlyIn(table.columns, cur.tables[tableName].columns));
|
|
197
|
+
const to = matchName(answer.to, keysOnlyIn(cur.tables[tableName].columns, table.columns));
|
|
198
|
+
if (!from || !to) continue;
|
|
199
|
+
const columns = {};
|
|
200
|
+
for (const [key, column] of Object.entries(table.columns)) if (key === from) columns[to] = {
|
|
201
|
+
...column,
|
|
202
|
+
name: to
|
|
203
|
+
};
|
|
204
|
+
else columns[key] = column;
|
|
205
|
+
table.columns = columns;
|
|
206
|
+
renameColumnRefs(snapshot, tableName, from, to);
|
|
207
|
+
statements.push(`ALTER TABLE \`${tableName}\` RENAME COLUMN "${from}" TO "${to}";`);
|
|
208
|
+
applied.push({
|
|
209
|
+
kind: "column",
|
|
210
|
+
table: tableName,
|
|
211
|
+
from,
|
|
212
|
+
to
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
snapshot: copy,
|
|
217
|
+
statements,
|
|
218
|
+
applied
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* `prev` minus every table, view and column that is not in `cur` — along with
|
|
223
|
+
* the indexes, keys and foreign keys that name them. Diffing `prev` → this
|
|
224
|
+
* yields only drops, and this → `cur` only additions: the "create + drop"
|
|
225
|
+
* answer to every remaining rename question, without one.
|
|
226
|
+
*/
|
|
227
|
+
function withoutRemoved(prevSnapshot, curSnapshot) {
|
|
228
|
+
const copy = clone(prevSnapshot);
|
|
229
|
+
const snapshot = shape(copy);
|
|
230
|
+
const cur = shape(curSnapshot);
|
|
231
|
+
const removedTables = new Set(keysOnlyIn(snapshot.tables, cur.tables));
|
|
232
|
+
const removedColumns = /* @__PURE__ */ new Map();
|
|
233
|
+
for (const name of removedTables) delete snapshot.tables[name];
|
|
234
|
+
for (const name of keysOnlyIn(snapshot.views, cur.views)) delete snapshot.views[name];
|
|
235
|
+
for (const [name, table] of Object.entries(snapshot.tables)) {
|
|
236
|
+
const gone = new Set(keysOnlyIn(table.columns, cur.tables[name]?.columns));
|
|
237
|
+
if (gone.size === 0) continue;
|
|
238
|
+
removedColumns.set(name, gone);
|
|
239
|
+
for (const column of gone) delete table.columns[column];
|
|
240
|
+
}
|
|
241
|
+
const touches = (tableName, columns) => columns.some((c) => removedColumns.get(tableName)?.has(c));
|
|
242
|
+
for (const [name, table] of Object.entries(snapshot.tables)) {
|
|
243
|
+
for (const [key, index] of Object.entries(table.indexes ?? {})) if (touches(name, index.columns)) delete table.indexes[key];
|
|
244
|
+
for (const [key, pk] of Object.entries(table.compositePrimaryKeys ?? {})) if (touches(name, pk.columns)) delete table.compositePrimaryKeys[key];
|
|
245
|
+
for (const [key, unique] of Object.entries(table.uniqueConstraints ?? {})) if (touches(name, unique.columns)) delete table.uniqueConstraints[key];
|
|
246
|
+
for (const [key, fk] of Object.entries(table.foreignKeys ?? {})) if (removedTables.has(fk.tableTo) || touches(name, fk.columnsFrom) || touches(fk.tableTo, fk.columnsTo)) delete table.foreignKeys[key];
|
|
247
|
+
}
|
|
248
|
+
return copy;
|
|
249
|
+
}
|
|
250
|
+
function sameName(a, b) {
|
|
251
|
+
return a === b || toSnakeCase(a) === b;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* The answers no diff used — an answer that matches no pending change is a
|
|
255
|
+
* typo or a stale flag, worth an error rather than silence. `performed` are
|
|
256
|
+
* the renames the generated statements carry ({@link renamesFromStatements}).
|
|
257
|
+
*/
|
|
258
|
+
function unusedRenames(answers, performed) {
|
|
259
|
+
const tableRenames = performed.filter((r) => r.kind === "table");
|
|
260
|
+
const tableAliases = (name) => [name, ...tableRenames.filter((r) => sameName(name, r.from)).map((r) => r.to)];
|
|
261
|
+
return answers.filter((answer) => !performed.some((rename) => {
|
|
262
|
+
if (answer.kind !== rename.kind) return false;
|
|
263
|
+
if (answer.kind === "table") return sameName(answer.from, rename.from) && sameName(answer.to, rename.to);
|
|
264
|
+
const r = rename;
|
|
265
|
+
return tableAliases(answer.table).some((t) => sameName(t, r.table)) && sameName(answer.from, r.from) && sameName(answer.to, r.to);
|
|
266
|
+
}));
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* The renames a statement list performs (drizzle-kit's own, after an
|
|
270
|
+
* interactive answer, or durable-db's). drizzle-kit's table recreation
|
|
271
|
+
* (`__new_<table>` renamed back) is not a rename.
|
|
272
|
+
*/
|
|
273
|
+
function renamesFromStatements(statements) {
|
|
274
|
+
const renames = [];
|
|
275
|
+
for (const statement of statements) {
|
|
276
|
+
const column = /^\s*ALTER TABLE [`"]([^`"]+)[`"] RENAME COLUMN [`"]([^`"]+)[`"] TO [`"]([^`"]+)[`"]/i.exec(statement);
|
|
277
|
+
if (column) {
|
|
278
|
+
renames.push({
|
|
279
|
+
kind: "column",
|
|
280
|
+
table: column[1],
|
|
281
|
+
from: column[2],
|
|
282
|
+
to: column[3]
|
|
283
|
+
});
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const table = /^\s*ALTER TABLE [`"]([^`"]+)[`"] RENAME TO [`"]([^`"]+)[`"]/i.exec(statement);
|
|
287
|
+
if (table && !table[1].startsWith("__new_")) renames.push({
|
|
288
|
+
kind: "table",
|
|
289
|
+
from: table[1],
|
|
290
|
+
to: table[2]
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
return renames;
|
|
294
|
+
}
|
|
295
|
+
//#endregion
|
|
296
|
+
//#region src/migrations/risks.ts
|
|
297
|
+
/** The remedy `db generate` prints when it refuses a NOT NULL column without a default. */
|
|
298
|
+
const NOT_NULL_WITHOUT_DEFAULT_HINT = "fails on every table that has rows: add .default(...) or add it nullable and backfill";
|
|
299
|
+
/**
|
|
300
|
+
* What the change `prev` → `cur` risks on a database that has rows, given the
|
|
301
|
+
* renames it performs (pass {@link renamesFromStatements} of the generated
|
|
302
|
+
* SQL, so interactive answers count too).
|
|
303
|
+
*/
|
|
304
|
+
function analyzeMigrationRisks(prevSnapshot, curSnapshot, renames = []) {
|
|
305
|
+
const before = shape(renames.length > 0 ? applyRenames(prevSnapshot, curSnapshot, renames).snapshot : prevSnapshot);
|
|
306
|
+
const cur = shape(curSnapshot);
|
|
307
|
+
const risks = [];
|
|
308
|
+
for (const [name, table] of Object.entries(before.tables ?? {})) {
|
|
309
|
+
const after = cur.tables?.[name];
|
|
310
|
+
if (!after) {
|
|
311
|
+
risks.push({
|
|
312
|
+
kind: "drop-table",
|
|
313
|
+
severity: "warning",
|
|
314
|
+
table: name,
|
|
315
|
+
message: `table ${name} is dropped — its rows are lost`
|
|
316
|
+
});
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
for (const column of Object.keys(table.columns)) if (!(column in after.columns)) risks.push({
|
|
320
|
+
kind: "drop-column",
|
|
321
|
+
severity: "warning",
|
|
322
|
+
table: name,
|
|
323
|
+
column,
|
|
324
|
+
message: `${name}.${column} is dropped — its data is lost`
|
|
325
|
+
});
|
|
326
|
+
for (const [column, definition] of Object.entries(after.columns)) {
|
|
327
|
+
const existing = table.columns[column];
|
|
328
|
+
const hasDefault = definition.default !== void 0;
|
|
329
|
+
if (!existing) {
|
|
330
|
+
const rowid = definition.primaryKey && definition.type.toLowerCase() === "integer";
|
|
331
|
+
if (definition.notNull && !hasDefault && !definition.generated && !rowid) risks.push({
|
|
332
|
+
kind: "add-not-null-without-default",
|
|
333
|
+
severity: "error",
|
|
334
|
+
table: name,
|
|
335
|
+
column,
|
|
336
|
+
message: `${name}.${column} is added NOT NULL without a default — the migration ${NOT_NULL_WITHOUT_DEFAULT_HINT}`
|
|
337
|
+
});
|
|
338
|
+
} else if (definition.notNull && !existing.notNull && !definition.primaryKey) risks.push({
|
|
339
|
+
kind: "set-not-null",
|
|
340
|
+
severity: "warning",
|
|
341
|
+
table: name,
|
|
342
|
+
column,
|
|
343
|
+
message: `${name}.${column} becomes NOT NULL — the migration fails on a database where a row holds NULL there: backfill it first`
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return risks;
|
|
348
|
+
}
|
|
349
|
+
//#endregion
|
|
350
|
+
//#region src/migrations/snapshot.ts
|
|
351
|
+
const { generateSQLiteDrizzleJson, generateSQLiteMigration } = createRequire(import.meta.url)("drizzle-kit/api");
|
|
352
|
+
/** Whether drizzle-kit's prompts can run (it checks the same). */
|
|
353
|
+
function canPrompt() {
|
|
354
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Create an empty snapshot (for initial migration from nothing)
|
|
358
|
+
*/
|
|
359
|
+
function createEmptySnapshot() {
|
|
360
|
+
return {
|
|
361
|
+
views: {},
|
|
362
|
+
version: "6",
|
|
363
|
+
dialect: "sqlite",
|
|
364
|
+
id: "0000000000000",
|
|
365
|
+
prevId: "",
|
|
366
|
+
tables: {},
|
|
367
|
+
enums: {},
|
|
368
|
+
_meta: {
|
|
369
|
+
tables: {},
|
|
370
|
+
columns: {}
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Generate a unique snapshot ID based on timestamp
|
|
376
|
+
*/
|
|
377
|
+
function generateSnapshotId() {
|
|
378
|
+
return Date.now().toString(36).padStart(13, "0");
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Generate a snapshot from Drizzle schema objects
|
|
382
|
+
*
|
|
383
|
+
* @param schema - Object containing Drizzle table definitions
|
|
384
|
+
* @returns Snapshot representing the current schema state
|
|
385
|
+
*
|
|
386
|
+
* @example
|
|
387
|
+
* ```ts
|
|
388
|
+
* import { users, posts } from './schema';
|
|
389
|
+
* const snapshot = await generateSnapshotFromSchema({ users, posts });
|
|
390
|
+
* ```
|
|
391
|
+
*/
|
|
392
|
+
async function generateSnapshotFromSchema(schema) {
|
|
393
|
+
return generateSQLiteDrizzleJson(schema, void 0, "snake_case");
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Generate SQL migration statements from two snapshots
|
|
397
|
+
*
|
|
398
|
+
* @param from - Previous schema state (or empty for initial migration)
|
|
399
|
+
* @param to - Target schema state
|
|
400
|
+
* @returns Array of SQL statements to migrate from `from` to `to`
|
|
401
|
+
*
|
|
402
|
+
* @example
|
|
403
|
+
* ```ts
|
|
404
|
+
* const statements = await generateMigrationStatements(prevSnapshot, newSnapshot);
|
|
405
|
+
* // ['CREATE TABLE users (...)', 'CREATE INDEX ...']
|
|
406
|
+
* ```
|
|
407
|
+
*/
|
|
408
|
+
async function generateMigrationStatements(from, to, resolution = {}) {
|
|
409
|
+
const answers = (resolution.renames ?? []).map((r) => typeof r === "string" ? parseRenameSpec(r) : r);
|
|
410
|
+
const renamed = answers.length > 0 ? applyRenames(from, to, answers) : {
|
|
411
|
+
snapshot: from,
|
|
412
|
+
statements: []
|
|
413
|
+
};
|
|
414
|
+
const ambiguities = findAmbiguities(renamed.snapshot, to);
|
|
415
|
+
if (ambiguities.length === 0) return [...renamed.statements, ...await generateSQLiteMigration(renamed.snapshot, to)];
|
|
416
|
+
if (resolution.noRenames) {
|
|
417
|
+
const dropped = withoutRemoved(renamed.snapshot, to);
|
|
418
|
+
return [
|
|
419
|
+
...renamed.statements,
|
|
420
|
+
...await generateSQLiteMigration(renamed.snapshot, dropped),
|
|
421
|
+
...await generateSQLiteMigration(dropped, to)
|
|
422
|
+
];
|
|
423
|
+
}
|
|
424
|
+
if (!(resolution.interactive ?? canPrompt())) throw new SchemaRenameRequiredError(ambiguities);
|
|
425
|
+
return [...renamed.statements, ...await generateSQLiteMigration(renamed.snapshot, to)];
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Serialize the schema-relevant parts of a snapshot for comparison/hashing.
|
|
429
|
+
* Includes tables, views, and enums so that changes to any of them are
|
|
430
|
+
* detected — previously only `tables` was considered.
|
|
431
|
+
*/
|
|
432
|
+
function serializeSchemaShape(snapshot) {
|
|
433
|
+
return JSON.stringify({
|
|
434
|
+
tables: snapshot.tables ?? {},
|
|
435
|
+
views: snapshot.views ?? {},
|
|
436
|
+
enums: snapshot.enums ?? {}
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Check if two snapshots are equivalent (no migration needed)
|
|
441
|
+
*/
|
|
442
|
+
function snapshotsEqual(a, b) {
|
|
443
|
+
return serializeSchemaShape(a) === serializeSchemaShape(b);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Create a hash of a snapshot for quick comparison
|
|
447
|
+
*/
|
|
448
|
+
function hashSnapshot(snapshot) {
|
|
449
|
+
const content = serializeSchemaShape(snapshot);
|
|
450
|
+
let hash = 0;
|
|
451
|
+
for (let i = 0; i < content.length; i++) {
|
|
452
|
+
const char = content.charCodeAt(i);
|
|
453
|
+
hash = (hash << 5) - hash + char;
|
|
454
|
+
hash = hash & hash;
|
|
455
|
+
}
|
|
456
|
+
return Math.abs(hash).toString(36);
|
|
457
|
+
}
|
|
458
|
+
//#endregion
|
|
459
|
+
export { renamesFromStatements as _, generateSnapshotId as a, NOT_NULL_WITHOUT_DEFAULT_HINT as c, applyRenames as d, describeAmbiguity as f, parseRenameSpec as g, formatRename as h, generateSnapshotFromSchema as i, analyzeMigrationRisks as l, findAmbiguities as m, createEmptySnapshot as n, hashSnapshot as o, exampleRenames as p, generateMigrationStatements as r, snapshotsEqual as s, canPrompt as t, SchemaRenameRequiredError as u, unusedRenames as v };
|
|
@@ -1,24 +1,34 @@
|
|
|
1
1
|
import { a as __esmMin, i as init_debug, o as __exportAll, t as debugCli } from "./debug-Cz8KzMft.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path$1 from "node:path";
|
|
4
|
+
import * as crypto from "node:crypto";
|
|
4
5
|
//#region src/cli/state.ts
|
|
5
6
|
var state_exports = /* @__PURE__ */ __exportAll({
|
|
7
|
+
DEV_SERVER_LOCK_FILE: () => DEV_SERVER_LOCK_FILE,
|
|
6
8
|
clearDatabaseDevState: () => clearDatabaseDevState,
|
|
7
9
|
clearDevMigrations: () => clearDevMigrations,
|
|
8
10
|
createEmptyDevState: () => createEmptyDevState,
|
|
9
11
|
findNodeModules: () => findNodeModules,
|
|
12
|
+
forgetDatabaseDevState: () => forgetDatabaseDevState,
|
|
10
13
|
generateEpoch: () => generateEpoch,
|
|
11
14
|
getDatabaseDevState: () => getDatabaseDevState,
|
|
15
|
+
getDatabaseEpoch: () => getDatabaseEpoch,
|
|
16
|
+
getDatabaseEpochs: () => getDatabaseEpochs,
|
|
12
17
|
getDevEpoch: () => getDevEpoch,
|
|
13
18
|
getDevPaths: () => getDevPaths,
|
|
14
19
|
getInstanceKey: () => getInstanceKey,
|
|
15
20
|
hasProdSnapshotChanged: () => hasProdSnapshotChanged,
|
|
21
|
+
isProcessAlive: () => isProcessAlive,
|
|
16
22
|
loadDevMigrations: () => loadDevMigrations,
|
|
17
23
|
loadDevSnapshot: () => loadDevSnapshot,
|
|
18
24
|
loadDevState: () => loadDevState,
|
|
25
|
+
readDevServerLock: () => readDevServerLock,
|
|
26
|
+
removeDevServerLock: () => removeDevServerLock,
|
|
27
|
+
runningDevServer: () => runningDevServer,
|
|
19
28
|
saveDevMigration: () => saveDevMigration,
|
|
20
29
|
saveDevSnapshot: () => saveDevSnapshot,
|
|
21
|
-
saveDevState: () => saveDevState
|
|
30
|
+
saveDevState: () => saveDevState,
|
|
31
|
+
writeDevServerLock: () => writeDevServerLock
|
|
22
32
|
});
|
|
23
33
|
/**
|
|
24
34
|
* Find the node_modules directory for the current project
|
|
@@ -69,7 +79,9 @@ function loadDevState(projectRoot) {
|
|
|
69
79
|
if (!fs.existsSync(paths.stateFile)) return createEmptyDevState();
|
|
70
80
|
try {
|
|
71
81
|
const content = fs.readFileSync(paths.stateFile, "utf-8");
|
|
72
|
-
|
|
82
|
+
const state = JSON.parse(content);
|
|
83
|
+
state.databases ??= {};
|
|
84
|
+
return state;
|
|
73
85
|
} catch (error) {
|
|
74
86
|
debugCli("Failed to load dev state, starting fresh: %O", error);
|
|
75
87
|
return createEmptyDevState();
|
|
@@ -87,9 +99,11 @@ function saveDevState(projectRoot, state) {
|
|
|
87
99
|
* Get or create database-specific dev state
|
|
88
100
|
*/
|
|
89
101
|
function getDatabaseDevState(state, dbName, prodSnapshotHash) {
|
|
90
|
-
|
|
102
|
+
const existing = state.databases[dbName];
|
|
103
|
+
if (!existing || existing.prodSnapshotHash === void 0) state.databases[dbName] = {
|
|
104
|
+
...existing,
|
|
91
105
|
prodSnapshotHash,
|
|
92
|
-
lastPush: null
|
|
106
|
+
lastPush: existing?.lastPush ?? null
|
|
93
107
|
};
|
|
94
108
|
return state.databases[dbName];
|
|
95
109
|
}
|
|
@@ -98,10 +112,33 @@ function getDatabaseDevState(state, dbName, prodSnapshotHash) {
|
|
|
98
112
|
*/
|
|
99
113
|
function hasProdSnapshotChanged(state, dbName, currentProdHash) {
|
|
100
114
|
const dbState = state.databases[dbName];
|
|
101
|
-
if (!dbState) return false;
|
|
115
|
+
if (!dbState || dbState.prodSnapshotHash === void 0) return false;
|
|
102
116
|
return dbState.prodSnapshotHash !== currentProdHash;
|
|
103
117
|
}
|
|
104
118
|
/**
|
|
119
|
+
* The dev epoch a database's instance keys are suffixed with: its own epoch
|
|
120
|
+
* (after `db reset --database <name>`), else the project epoch.
|
|
121
|
+
*/
|
|
122
|
+
function getDatabaseEpoch(state, dbName) {
|
|
123
|
+
return state.databases[dbName]?.epoch ?? state.epoch;
|
|
124
|
+
}
|
|
125
|
+
/** Every database that has its own dev epoch, by name. */
|
|
126
|
+
function getDatabaseEpochs(state) {
|
|
127
|
+
const epochs = {};
|
|
128
|
+
for (const [name, dbState] of Object.entries(state.databases)) if (dbState?.epoch) epochs[name] = dbState.epoch;
|
|
129
|
+
return epochs;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Forget a database's dev bookkeeping (snapshot hash, last push) but keep
|
|
133
|
+
* its own epoch: dropping the epoch would move the database back to the
|
|
134
|
+
* project epoch — to the instances it had before its last reset.
|
|
135
|
+
*/
|
|
136
|
+
function forgetDatabaseDevState(state, dbName) {
|
|
137
|
+
const epoch = state.databases[dbName]?.epoch;
|
|
138
|
+
if (epoch) state.databases[dbName] = { epoch };
|
|
139
|
+
else delete state.databases[dbName];
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
105
142
|
* Load dev migrations for a database
|
|
106
143
|
*/
|
|
107
144
|
function loadDevMigrations(projectRoot, dbName) {
|
|
@@ -172,9 +209,10 @@ function saveDevSnapshot(projectRoot, dbName, snapshot) {
|
|
|
172
209
|
* Get the dev epoch for instance key suffixing
|
|
173
210
|
* Returns null in production or if no dev state exists
|
|
174
211
|
*/
|
|
175
|
-
function getDevEpoch(projectRoot) {
|
|
212
|
+
function getDevEpoch(projectRoot, dbName) {
|
|
176
213
|
if (process.env.NODE_ENV === "production") return null;
|
|
177
|
-
|
|
214
|
+
const state = loadDevState(projectRoot);
|
|
215
|
+
return dbName ? getDatabaseEpoch(state, dbName) : state.epoch;
|
|
178
216
|
}
|
|
179
217
|
/**
|
|
180
218
|
* Get a database instance key with optional dev epoch suffix
|
|
@@ -183,19 +221,78 @@ function getInstanceKey(baseKey, epoch) {
|
|
|
183
221
|
if (!epoch) return baseKey;
|
|
184
222
|
return `${baseKey}__dev_${epoch}`;
|
|
185
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Record that a dev server runs in this process. The Vite plugin calls this
|
|
226
|
+
* in `configureServer` and {@link removeDevServerLock} when that server
|
|
227
|
+
* closes, so CLI commands that must not run under a live dev server (purging
|
|
228
|
+
* workerd's storage) can refuse. Returns the lock's token.
|
|
229
|
+
*/
|
|
230
|
+
function writeDevServerLock(projectRoot) {
|
|
231
|
+
const paths = getDevPaths(projectRoot);
|
|
232
|
+
const lock = {
|
|
233
|
+
pid: process.pid,
|
|
234
|
+
token: crypto.randomUUID(),
|
|
235
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
236
|
+
};
|
|
237
|
+
fs.mkdirSync(paths.cacheDir, { recursive: true });
|
|
238
|
+
fs.writeFileSync(path$1.join(paths.cacheDir, DEV_SERVER_LOCK_FILE), JSON.stringify(lock, null, 2));
|
|
239
|
+
return lock.token;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Remove the dev-server lock — only when it is still the one `token` wrote:
|
|
243
|
+
* a restarted server writes its own lock before the old server closes, and
|
|
244
|
+
* the old server's close must not delete the new one.
|
|
245
|
+
*/
|
|
246
|
+
function removeDevServerLock(projectRoot, token) {
|
|
247
|
+
const lock = readDevServerLock(projectRoot);
|
|
248
|
+
if (!lock || lock.token !== token) return;
|
|
249
|
+
try {
|
|
250
|
+
fs.rmSync(path$1.join(getDevPaths(projectRoot).cacheDir, DEV_SERVER_LOCK_FILE), { force: true });
|
|
251
|
+
} catch (error) {
|
|
252
|
+
debugCli("Could not remove the dev-server lock: %O", error);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function readDevServerLock(projectRoot) {
|
|
256
|
+
const file = path$1.join(getDevPaths(projectRoot).cacheDir, DEV_SERVER_LOCK_FILE);
|
|
257
|
+
try {
|
|
258
|
+
const lock = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
259
|
+
return typeof lock.pid === "number" && typeof lock.token === "string" ? lock : null;
|
|
260
|
+
} catch {
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** Whether a process with this id exists (signal 0 only probes). */
|
|
265
|
+
function isProcessAlive(pid) {
|
|
266
|
+
try {
|
|
267
|
+
process.kill(pid, 0);
|
|
268
|
+
return true;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
return error.code === "EPERM";
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The dev server running for this project, from the lock the Vite plugin
|
|
275
|
+
* writes — null when there is none, or its process is gone (a crashed or
|
|
276
|
+
* killed server never removed its lock).
|
|
277
|
+
*/
|
|
278
|
+
function runningDevServer(projectRoot) {
|
|
279
|
+
const lock = readDevServerLock(projectRoot);
|
|
280
|
+
return lock && isProcessAlive(lock.pid) ? lock : null;
|
|
281
|
+
}
|
|
186
282
|
function parseSqlMigration(content) {
|
|
187
283
|
return content.split(BREAKPOINT_MARKER).map((chunk) => {
|
|
188
284
|
return chunk.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(/;(?:\s*\n|\s*$)/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
189
285
|
}).filter((chunk) => chunk.length > 0);
|
|
190
286
|
}
|
|
191
|
-
var CACHE_DIR_NAME, STATE_FILE_NAME, DEV_MIGRATIONS_DIR, DEV_SNAPSHOT_FILE, BREAKPOINT_MARKER;
|
|
287
|
+
var CACHE_DIR_NAME, STATE_FILE_NAME, DEV_SERVER_LOCK_FILE, DEV_MIGRATIONS_DIR, DEV_SNAPSHOT_FILE, BREAKPOINT_MARKER;
|
|
192
288
|
var init_state = __esmMin((() => {
|
|
193
289
|
init_debug();
|
|
194
290
|
CACHE_DIR_NAME = ".cache/durable-db";
|
|
195
291
|
STATE_FILE_NAME = "state.json";
|
|
292
|
+
DEV_SERVER_LOCK_FILE = "dev-server.json";
|
|
196
293
|
DEV_MIGRATIONS_DIR = "migrations";
|
|
197
294
|
DEV_SNAPSHOT_FILE = "_snapshot.json";
|
|
198
295
|
BREAKPOINT_MARKER = /^-->\s*breakpoint\s*$/im;
|
|
199
296
|
}));
|
|
200
297
|
//#endregion
|
|
201
|
-
export {
|
|
298
|
+
export { saveDevState as _, generateEpoch as a, getDevEpoch as c, init_state as d, loadDevMigrations as f, saveDevMigration as g, runningDevServer as h, forgetDatabaseDevState as i, getDevPaths as l, removeDevServerLock as m, clearDatabaseDevState as n, getDatabaseEpoch as o, loadDevState as p, clearDevMigrations as r, getDatabaseEpochs as s, DEV_SERVER_LOCK_FILE as t, getInstanceKey as u, state_exports as v, writeDevServerLock as y };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -28,11 +28,18 @@ export interface TestDatabase<TSchema = any> {
|
|
|
28
28
|
* Run an `action()` the way production does: validate `args` with the
|
|
29
29
|
* action's arktype schema, then invoke its handler against {@link db}.
|
|
30
30
|
* Throws the same "Invalid args" error as production on a bad payload.
|
|
31
|
+
*
|
|
32
|
+
* Calling the action directly does the same while this database is live:
|
|
33
|
+
* an action call runs against the newest live test database created with
|
|
34
|
+
* every table of the action's database.
|
|
31
35
|
*/
|
|
32
36
|
run<TArgs, TResult>(action: (args: TArgs) => Promise<TResult>, args: TArgs): Promise<TResult>;
|
|
33
37
|
/** The raw `node:sqlite` handle, for escape-hatch SQL. */
|
|
34
38
|
sqlite: DatabaseSync;
|
|
35
|
-
/**
|
|
39
|
+
/**
|
|
40
|
+
* Close the database, stop routing direct action calls to it and clear the
|
|
41
|
+
* tenant resolver.
|
|
42
|
+
*/
|
|
36
43
|
destroy(): void;
|
|
37
44
|
}
|
|
38
45
|
/**
|