@forinda/kickjs-db 5.2.0 → 5.2.2
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 +1 -1
- package/dist/devtools-events.d.mts +1 -1
- package/dist/devtools-events.mjs +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +33 -2006
- package/dist/index.mjs.map +1 -1
- package/dist/pg.mjs +2 -45
- package/dist/pg.mjs.map +1 -1
- package/dist/types-Cxh6cDtw.mjs +12 -0
- package/dist/{types-DBmUL5LM.mjs.map → types-Cxh6cDtw.mjs.map} +1 -1
- package/dist/{types-snBo_IiR.d.mts → types-DlFKeljT.d.mts} +2 -2
- package/dist/{types-snBo_IiR.d.mts.map → types-DlFKeljT.d.mts.map} +1 -1
- package/package.json +3 -3
- package/dist/types-DBmUL5LM.mjs +0 -106
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v5.2.
|
|
2
|
+
* @forinda/kickjs-db v5.2.2
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,598 +8,14 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
import { pathToFileURL } from "node:url";
|
|
20
|
-
//#region src/snapshot/extract.ts
|
|
21
|
-
function isTable(v) {
|
|
22
|
-
return Boolean(v && typeof v === "object" && v.__isTable === true);
|
|
23
|
-
}
|
|
24
|
-
function isPgEnum(v) {
|
|
25
|
-
if (typeof v !== "function") return false;
|
|
26
|
-
const f = v;
|
|
27
|
-
return typeof f.enumName === "string" && Array.isArray(f.values);
|
|
28
|
-
}
|
|
29
|
-
function extractSnapshot(schema, dialect) {
|
|
30
|
-
const tables = {};
|
|
31
|
-
const enums = {};
|
|
32
|
-
for (const value of Object.values(schema)) if (isTable(value)) tables[value.__name] = extractTable(value);
|
|
33
|
-
else if (isPgEnum(value)) enums[value.enumName] = {
|
|
34
|
-
name: value.enumName,
|
|
35
|
-
values: [...value.values]
|
|
36
|
-
};
|
|
37
|
-
if (dialect === "postgres" && Object.keys(enums).length > 0) return {
|
|
38
|
-
version: 1,
|
|
39
|
-
dialect,
|
|
40
|
-
tables,
|
|
41
|
-
enums
|
|
42
|
-
};
|
|
43
|
-
return {
|
|
44
|
-
version: 1,
|
|
45
|
-
dialect,
|
|
46
|
-
tables
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
function extractTable(t) {
|
|
50
|
-
const columns = {};
|
|
51
|
-
const indexes = [...t.__indexes];
|
|
52
|
-
const foreignKeys = [];
|
|
53
|
-
for (const [colKey, builder] of Object.entries(t.__columns)) {
|
|
54
|
-
columns[colKey] = builder.toJSON(colKey);
|
|
55
|
-
const state = builder.__state();
|
|
56
|
-
if (state.unique) indexes.push({
|
|
57
|
-
name: `${t.__name}_${colKey}_unique`,
|
|
58
|
-
columns: [colKey],
|
|
59
|
-
unique: true
|
|
60
|
-
});
|
|
61
|
-
if (state.references) {
|
|
62
|
-
const ref = state.references.thunk();
|
|
63
|
-
foreignKeys.push({
|
|
64
|
-
name: `${t.__name}_${colKey}_fk`,
|
|
65
|
-
columns: [colKey],
|
|
66
|
-
refTable: ref.__tableName,
|
|
67
|
-
refColumns: [ref.__name],
|
|
68
|
-
onDelete: state.references.onDelete,
|
|
69
|
-
onUpdate: state.references.onUpdate
|
|
70
|
-
});
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
return {
|
|
74
|
-
name: t.__name,
|
|
75
|
-
columns,
|
|
76
|
-
indexes,
|
|
77
|
-
foreignKeys,
|
|
78
|
-
checks: []
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
//#endregion
|
|
82
|
-
//#region src/snapshot/render.ts
|
|
83
|
-
/**
|
|
84
|
-
* Render a SchemaSnapshot to TypeScript source matching the kickjs-db DSL.
|
|
85
|
-
* Inverse of extractSnapshot().
|
|
86
|
-
*
|
|
87
|
-
* Naming: tables become exported `const`s with the same name. Constants
|
|
88
|
-
* starting with digits get an underscore prefix to stay JS-valid.
|
|
89
|
-
*
|
|
90
|
-
* Limits (M1 — refined in M2/M3):
|
|
91
|
-
* - No relations() emission. Adopter adds them manually post-introspect.
|
|
92
|
-
* - No checks (M1 doesn't model CHECK constraints in the snapshot).
|
|
93
|
-
* - Default values pass through as-is. The DSL accepts string defaults,
|
|
94
|
-
* so 'true' / 'CURRENT_TIMESTAMP' / "'foo'" all round-trip.
|
|
95
|
-
* - Auto-derived constraint names (`<table>_<col>_unique`, `<table>_<col>_fk`)
|
|
96
|
-
* are detected and rendered as the chained .unique() / .references() form.
|
|
97
|
-
* Custom-named constraints fall back to the third-arg callback / FK helper.
|
|
98
|
-
*/
|
|
99
|
-
function renderSchemaSource(snapshot) {
|
|
100
|
-
const usedColumnHelpers = /* @__PURE__ */ new Set();
|
|
101
|
-
const tableSources = [];
|
|
102
|
-
for (const table of Object.values(snapshot.tables)) tableSources.push(renderTable(table, usedColumnHelpers));
|
|
103
|
-
const helpers = ["table", ...Array.from(usedColumnHelpers).toSorted()];
|
|
104
|
-
if (Object.values(snapshot.tables).some((t) => t.indexes.some((i) => !isAutoUniqueName(t.name, i)))) helpers.push("index");
|
|
105
|
-
if (Object.values(snapshot.tables).some((t) => t.indexes.some((i) => i.unique && !isAutoUniqueName(t.name, i))) && !helpers.includes("unique")) helpers.push("unique");
|
|
106
|
-
return [
|
|
107
|
-
`import { ${helpers.join(", ")} } from '@forinda/kickjs-db'`,
|
|
108
|
-
"",
|
|
109
|
-
...tableSources
|
|
110
|
-
].join("\n").trimEnd() + "\n";
|
|
111
|
-
}
|
|
112
|
-
function renderTable(table, helpers) {
|
|
113
|
-
const ident = jsIdent(table.name);
|
|
114
|
-
const columns = [];
|
|
115
|
-
for (const col of Object.values(table.columns)) {
|
|
116
|
-
const fk = table.foreignKeys.find((f) => f.columns.length === 1 && f.columns[0] === col.name && f.name === `${table.name}_${col.name}_fk`);
|
|
117
|
-
const inlineUnique = table.indexes.find((i) => i.unique && i.columns.length === 1 && i.columns[0] === col.name && isAutoUniqueName(table.name, i)) !== void 0;
|
|
118
|
-
columns.push(` ${jsKey(col.name)}: ${renderColumn(col, helpers, fk, inlineUnique)},`);
|
|
119
|
-
}
|
|
120
|
-
const explicitIndexes = table.indexes.filter((i) => !isAutoUniqueName(table.name, i));
|
|
121
|
-
const explicitFks = table.foreignKeys.filter((f) => f.name !== `${table.name}_${f.columns[0]}_fk` || f.columns.length !== 1);
|
|
122
|
-
const hasThirdArg = explicitIndexes.length > 0;
|
|
123
|
-
const tableArgs = [`'${table.name}'`, `{\n${columns.join("\n")}\n}`];
|
|
124
|
-
if (hasThirdArg) {
|
|
125
|
-
const callbacks = explicitIndexes.map((i) => ` ${jsKey(i.name)}: ${renderIndexCall(i)}`).join(",\n");
|
|
126
|
-
tableArgs.push(`(t) => ({\n${callbacks},\n })`);
|
|
127
|
-
}
|
|
128
|
-
let src = `export const ${ident} = table(${tableArgs.join(", ")})`;
|
|
129
|
-
if (explicitFks.length > 0) {
|
|
130
|
-
src += "\n// TODO: kick db introspect — composite or custom-named foreign keys not auto-rendered:\n";
|
|
131
|
-
for (const f of explicitFks) src += `// ${f.name}: (${f.columns.join(", ")}) → ${f.refTable}(${f.refColumns.join(", ")})\n`;
|
|
132
|
-
}
|
|
133
|
-
return src;
|
|
134
|
-
}
|
|
135
|
-
function renderColumn(col, helpers, fk, inlineUnique) {
|
|
136
|
-
const { helperName, args } = pickColumnHelper(col);
|
|
137
|
-
helpers.add(helperName);
|
|
138
|
-
let chain = `${helperName}(${args})`;
|
|
139
|
-
if (col.primaryKey) chain += ".primaryKey()";
|
|
140
|
-
if (!col.primaryKey && !col.nullable) chain += ".notNull()";
|
|
141
|
-
if (col.default !== null) chain += `.default(${JSON.stringify(col.default)})`;
|
|
142
|
-
if (inlineUnique) chain += ".unique()";
|
|
143
|
-
if (fk) {
|
|
144
|
-
const ref = `${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`;
|
|
145
|
-
const onDelete = fk.onDelete === "no_action" ? "" : `, { onDelete: '${fk.onDelete}' }`;
|
|
146
|
-
chain += `.references(() => ${ref}${onDelete})`;
|
|
147
|
-
}
|
|
148
|
-
return chain;
|
|
149
|
-
}
|
|
150
|
-
function pickColumnHelper(col) {
|
|
151
|
-
const t = col.type;
|
|
152
|
-
if (t === "serial") return {
|
|
153
|
-
helperName: "serial",
|
|
154
|
-
args: ""
|
|
155
|
-
};
|
|
156
|
-
if (t === "bigserial") return {
|
|
157
|
-
helperName: "bigSerial",
|
|
158
|
-
args: ""
|
|
159
|
-
};
|
|
160
|
-
if (t === "smallserial") return {
|
|
161
|
-
helperName: "serial",
|
|
162
|
-
args: ""
|
|
163
|
-
};
|
|
164
|
-
if (t === "integer") return {
|
|
165
|
-
helperName: "integer",
|
|
166
|
-
args: ""
|
|
167
|
-
};
|
|
168
|
-
if (t === "bigint") return {
|
|
169
|
-
helperName: "bigint",
|
|
170
|
-
args: ""
|
|
171
|
-
};
|
|
172
|
-
if (t === "smallint") return {
|
|
173
|
-
helperName: "smallint",
|
|
174
|
-
args: ""
|
|
175
|
-
};
|
|
176
|
-
if (t === "real") return {
|
|
177
|
-
helperName: "real",
|
|
178
|
-
args: ""
|
|
179
|
-
};
|
|
180
|
-
if (t === "double precision") return {
|
|
181
|
-
helperName: "doublePrecision",
|
|
182
|
-
args: ""
|
|
183
|
-
};
|
|
184
|
-
if (/^numeric(\(.+\))?$/.test(t)) return {
|
|
185
|
-
helperName: "numeric",
|
|
186
|
-
args: extractParens(t)
|
|
187
|
-
};
|
|
188
|
-
if (/^varchar(\(\d+\))?$/.test(t)) return {
|
|
189
|
-
helperName: "varchar",
|
|
190
|
-
args: extractParens(t)
|
|
191
|
-
};
|
|
192
|
-
if (/^char(\(\d+\))?$/.test(t)) return {
|
|
193
|
-
helperName: "char",
|
|
194
|
-
args: extractParens(t)
|
|
195
|
-
};
|
|
196
|
-
if (t === "text") return {
|
|
197
|
-
helperName: "text",
|
|
198
|
-
args: ""
|
|
199
|
-
};
|
|
200
|
-
if (t === "boolean") return {
|
|
201
|
-
helperName: "boolean",
|
|
202
|
-
args: ""
|
|
203
|
-
};
|
|
204
|
-
if (t === "timestamp") return {
|
|
205
|
-
helperName: "timestamp",
|
|
206
|
-
args: ""
|
|
207
|
-
};
|
|
208
|
-
if (t === "timestamptz") return {
|
|
209
|
-
helperName: "timestamptz",
|
|
210
|
-
args: ""
|
|
211
|
-
};
|
|
212
|
-
if (t === "date") return {
|
|
213
|
-
helperName: "date",
|
|
214
|
-
args: ""
|
|
215
|
-
};
|
|
216
|
-
if (t === "time") return {
|
|
217
|
-
helperName: "time",
|
|
218
|
-
args: ""
|
|
219
|
-
};
|
|
220
|
-
if (t === "interval") return {
|
|
221
|
-
helperName: "interval",
|
|
222
|
-
args: ""
|
|
223
|
-
};
|
|
224
|
-
if (t === "uuid") return {
|
|
225
|
-
helperName: "uuid",
|
|
226
|
-
args: ""
|
|
227
|
-
};
|
|
228
|
-
if (t === "jsonb") return {
|
|
229
|
-
helperName: "jsonb",
|
|
230
|
-
args: ""
|
|
231
|
-
};
|
|
232
|
-
if (t === "json") return {
|
|
233
|
-
helperName: "json",
|
|
234
|
-
args: ""
|
|
235
|
-
};
|
|
236
|
-
if (t === "bytea") return {
|
|
237
|
-
helperName: "bytea",
|
|
238
|
-
args: ""
|
|
239
|
-
};
|
|
240
|
-
return {
|
|
241
|
-
helperName: "text",
|
|
242
|
-
args: `/* TODO: ${t} */`
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
function extractParens(t) {
|
|
246
|
-
const m = t.match(/\(([^)]+)\)/);
|
|
247
|
-
return m ? m[1] : "";
|
|
248
|
-
}
|
|
249
|
-
function renderIndexCall(idx) {
|
|
250
|
-
const helper = idx.unique ? "unique" : "index";
|
|
251
|
-
const cols = idx.columns.map((c) => `t.${jsIdent(c)}`).join(", ");
|
|
252
|
-
return `${helper}('${idx.name}').on(${cols})`;
|
|
253
|
-
}
|
|
254
|
-
function isAutoUniqueName(tableName, idx) {
|
|
255
|
-
return idx.unique && idx.columns.length === 1 && idx.name === `${tableName}_${idx.columns[0]}_unique`;
|
|
256
|
-
}
|
|
257
|
-
/** Make a JS-safe identifier from a snake_case column/table name. */
|
|
258
|
-
function jsIdent(raw) {
|
|
259
|
-
if (/^[A-Za-z_$][\w$]*$/.test(raw)) return raw;
|
|
260
|
-
return `_${raw.replace(/[^\w$]/g, "_")}`;
|
|
261
|
-
}
|
|
262
|
-
/** Render a record key — quoted if not a valid identifier. */
|
|
263
|
-
function jsKey(raw) {
|
|
264
|
-
return /^[A-Za-z_$][\w$]*$/.test(raw) ? raw : JSON.stringify(raw);
|
|
265
|
-
}
|
|
266
|
-
//#endregion
|
|
267
|
-
//#region src/diff/engine.ts
|
|
268
|
-
function diff(prev, next) {
|
|
269
|
-
const changes = [];
|
|
270
|
-
const prevTables = new Set(Object.keys(prev.tables));
|
|
271
|
-
const nextTables = new Set(Object.keys(next.tables));
|
|
272
|
-
diffEnumsCreatePhase(prev, next, changes);
|
|
273
|
-
for (const name of prevTables) if (!nextTables.has(name)) changes.push({
|
|
274
|
-
kind: "dropTable",
|
|
275
|
-
table: prev.tables[name]
|
|
276
|
-
});
|
|
277
|
-
const newTableNames = [...nextTables].filter((n) => !prevTables.has(n));
|
|
278
|
-
for (const name of newTableNames) changes.push({
|
|
279
|
-
kind: "createTable",
|
|
280
|
-
table: next.tables[name]
|
|
281
|
-
});
|
|
282
|
-
for (const name of newTableNames) for (const i of next.tables[name].indexes) changes.push({
|
|
283
|
-
kind: "addIndex",
|
|
284
|
-
table: name,
|
|
285
|
-
index: i
|
|
286
|
-
});
|
|
287
|
-
for (const name of newTableNames) for (const f of next.tables[name].foreignKeys) changes.push({
|
|
288
|
-
kind: "addForeignKey",
|
|
289
|
-
table: name,
|
|
290
|
-
fk: f
|
|
291
|
-
});
|
|
292
|
-
for (const name of nextTables) {
|
|
293
|
-
if (!prevTables.has(name)) continue;
|
|
294
|
-
diffTable(prev.tables[name], next.tables[name], changes);
|
|
295
|
-
}
|
|
296
|
-
diffEnumsDropPhase(prev, next, changes);
|
|
297
|
-
return changes;
|
|
298
|
-
}
|
|
299
|
-
function diffEnumsCreatePhase(prev, next, changes) {
|
|
300
|
-
const prevEnums = prev.enums ?? {};
|
|
301
|
-
const nextEnums = next.enums ?? {};
|
|
302
|
-
for (const [name, e] of Object.entries(nextEnums)) {
|
|
303
|
-
if (prevEnums[name]) continue;
|
|
304
|
-
changes.push({
|
|
305
|
-
kind: "createEnum",
|
|
306
|
-
enum: e
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
for (const [name, e] of Object.entries(nextEnums)) {
|
|
310
|
-
const prior = prevEnums[name];
|
|
311
|
-
if (!prior) continue;
|
|
312
|
-
const priorValues = new Set(prior.values);
|
|
313
|
-
const nextValues = new Set(e.values);
|
|
314
|
-
const nextValueList = e.values;
|
|
315
|
-
for (let i = 0; i < nextValueList.length; i++) {
|
|
316
|
-
const value = nextValueList[i];
|
|
317
|
-
if (priorValues.has(value)) continue;
|
|
318
|
-
const before = nextValueList[i + 1];
|
|
319
|
-
const beforeIsExisting = before != null && priorValues.has(before);
|
|
320
|
-
changes.push({
|
|
321
|
-
kind: "addEnumValue",
|
|
322
|
-
enum: name,
|
|
323
|
-
value,
|
|
324
|
-
...beforeIsExisting ? { before } : {}
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
const removed = prior.values.filter((v) => !nextValues.has(v));
|
|
328
|
-
if (removed.length > 0) changes.push({
|
|
329
|
-
kind: "removeEnumValue",
|
|
330
|
-
enum: name,
|
|
331
|
-
removed
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
function diffEnumsDropPhase(prev, next, changes) {
|
|
336
|
-
const prevEnums = prev.enums ?? {};
|
|
337
|
-
const nextEnums = next.enums ?? {};
|
|
338
|
-
for (const [name, e] of Object.entries(prevEnums)) {
|
|
339
|
-
if (nextEnums[name]) continue;
|
|
340
|
-
changes.push({
|
|
341
|
-
kind: "dropEnum",
|
|
342
|
-
enum: e
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
function diffTable(prev, next, changes) {
|
|
347
|
-
const prevCols = new Map(Object.entries(prev.columns));
|
|
348
|
-
const nextCols = new Map(Object.entries(next.columns));
|
|
349
|
-
const drops = [];
|
|
350
|
-
const adds = [];
|
|
351
|
-
for (const c of prevCols.keys()) if (!nextCols.has(c)) drops.push(c);
|
|
352
|
-
for (const c of nextCols.keys()) if (!prevCols.has(c)) adds.push(c);
|
|
353
|
-
if (drops.length === 1 && adds.length === 1) {
|
|
354
|
-
if (columnAttrsEqual(prevCols.get(drops[0]), nextCols.get(adds[0]))) {
|
|
355
|
-
changes.push({
|
|
356
|
-
kind: "renameColumn",
|
|
357
|
-
table: next.name,
|
|
358
|
-
from: drops[0],
|
|
359
|
-
to: adds[0]
|
|
360
|
-
});
|
|
361
|
-
drops.length = 0;
|
|
362
|
-
adds.length = 0;
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
for (const c of drops) changes.push({
|
|
366
|
-
kind: "dropColumn",
|
|
367
|
-
table: next.name,
|
|
368
|
-
column: prevCols.get(c)
|
|
369
|
-
});
|
|
370
|
-
for (const c of adds) changes.push({
|
|
371
|
-
kind: "addColumn",
|
|
372
|
-
table: next.name,
|
|
373
|
-
column: nextCols.get(c)
|
|
374
|
-
});
|
|
375
|
-
for (const c of nextCols.keys()) {
|
|
376
|
-
if (!prevCols.has(c)) continue;
|
|
377
|
-
const before = prevCols.get(c);
|
|
378
|
-
const after = nextCols.get(c);
|
|
379
|
-
if (!columnsEqual(before, after)) changes.push({
|
|
380
|
-
kind: "alterColumn",
|
|
381
|
-
table: next.name,
|
|
382
|
-
column: c,
|
|
383
|
-
before,
|
|
384
|
-
after
|
|
385
|
-
});
|
|
386
|
-
}
|
|
387
|
-
diffByName(prev.indexes, next.indexes, (i) => changes.push({
|
|
388
|
-
kind: "dropIndex",
|
|
389
|
-
table: next.name,
|
|
390
|
-
index: i
|
|
391
|
-
}), (i) => changes.push({
|
|
392
|
-
kind: "addIndex",
|
|
393
|
-
table: next.name,
|
|
394
|
-
index: i
|
|
395
|
-
}));
|
|
396
|
-
diffByName(prev.foreignKeys, next.foreignKeys, (f) => changes.push({
|
|
397
|
-
kind: "dropForeignKey",
|
|
398
|
-
table: next.name,
|
|
399
|
-
fk: f
|
|
400
|
-
}), (f) => changes.push({
|
|
401
|
-
kind: "addForeignKey",
|
|
402
|
-
table: next.name,
|
|
403
|
-
fk: f
|
|
404
|
-
}));
|
|
405
|
-
}
|
|
406
|
-
function diffByName(prev, next, onDrop, onAdd) {
|
|
407
|
-
const prevByName = new Map(prev.map((p) => [p.name, p]));
|
|
408
|
-
const nextByName = new Map(next.map((n) => [n.name, n]));
|
|
409
|
-
for (const [n, p] of prevByName) if (!nextByName.has(n)) onDrop(p);
|
|
410
|
-
for (const [n, x] of nextByName) if (!prevByName.has(n)) onAdd(x);
|
|
411
|
-
}
|
|
412
|
-
function columnsEqual(a, b) {
|
|
413
|
-
return a.type === b.type && a.nullable === b.nullable && a.default === b.default && a.primaryKey === b.primaryKey;
|
|
414
|
-
}
|
|
415
|
-
function columnAttrsEqual(a, b) {
|
|
416
|
-
return a.type === b.type && a.nullable === b.nullable && a.default === b.default && a.primaryKey === b.primaryKey;
|
|
417
|
-
}
|
|
418
|
-
//#endregion
|
|
419
|
-
//#region src/diff/invert.ts
|
|
420
|
-
/**
|
|
421
|
-
* Reverse a forward ChangeSet so emitting it produces the SQL that undoes
|
|
422
|
-
* the forward migration.
|
|
423
|
-
*
|
|
424
|
-
* The reverse of an *unambiguous* change is exact (rename → rename swapped,
|
|
425
|
-
* add → drop, drop → add). The reverse of an *ambiguous* change (drop column,
|
|
426
|
-
* drop table, type widen, NOT NULL gain without default) is a defensible
|
|
427
|
-
* best-effort derived from the snapshot the forward change carried — the
|
|
428
|
-
* runner refuses to apply a non-reviewed migration in non-dev so the operator
|
|
429
|
-
* always sees the draft before it touches a DB.
|
|
430
|
-
*
|
|
431
|
-
* The order is reversed too: drop FK before drop index before drop table is
|
|
432
|
-
* the safe sequence for tearing down what create-FK / create-index / create-
|
|
433
|
-
* table built up.
|
|
434
|
-
*/
|
|
435
|
-
function invertChanges(forward) {
|
|
436
|
-
const reversed = [];
|
|
437
|
-
for (const change of forward) reversed.push(invert(change));
|
|
438
|
-
return reversed.toReversed();
|
|
439
|
-
}
|
|
440
|
-
function invert(change) {
|
|
441
|
-
switch (change.kind) {
|
|
442
|
-
case "createTable": return {
|
|
443
|
-
kind: "dropTable",
|
|
444
|
-
table: change.table
|
|
445
|
-
};
|
|
446
|
-
case "dropTable": return {
|
|
447
|
-
kind: "createTable",
|
|
448
|
-
table: change.table
|
|
449
|
-
};
|
|
450
|
-
case "renameTable": return {
|
|
451
|
-
kind: "renameTable",
|
|
452
|
-
from: change.to,
|
|
453
|
-
to: change.from
|
|
454
|
-
};
|
|
455
|
-
case "addColumn": return {
|
|
456
|
-
kind: "dropColumn",
|
|
457
|
-
table: change.table,
|
|
458
|
-
column: change.column
|
|
459
|
-
};
|
|
460
|
-
case "dropColumn": return {
|
|
461
|
-
kind: "addColumn",
|
|
462
|
-
table: change.table,
|
|
463
|
-
column: change.column
|
|
464
|
-
};
|
|
465
|
-
case "renameColumn": return {
|
|
466
|
-
kind: "renameColumn",
|
|
467
|
-
table: change.table,
|
|
468
|
-
from: change.to,
|
|
469
|
-
to: change.from
|
|
470
|
-
};
|
|
471
|
-
case "alterColumn": return {
|
|
472
|
-
kind: "alterColumn",
|
|
473
|
-
table: change.table,
|
|
474
|
-
column: change.column,
|
|
475
|
-
before: change.after,
|
|
476
|
-
after: change.before
|
|
477
|
-
};
|
|
478
|
-
case "addIndex": return {
|
|
479
|
-
kind: "dropIndex",
|
|
480
|
-
table: change.table,
|
|
481
|
-
index: change.index
|
|
482
|
-
};
|
|
483
|
-
case "dropIndex": return {
|
|
484
|
-
kind: "addIndex",
|
|
485
|
-
table: change.table,
|
|
486
|
-
index: change.index
|
|
487
|
-
};
|
|
488
|
-
case "addForeignKey": return {
|
|
489
|
-
kind: "dropForeignKey",
|
|
490
|
-
table: change.table,
|
|
491
|
-
fk: change.fk
|
|
492
|
-
};
|
|
493
|
-
case "dropForeignKey": return {
|
|
494
|
-
kind: "addForeignKey",
|
|
495
|
-
table: change.table,
|
|
496
|
-
fk: change.fk
|
|
497
|
-
};
|
|
498
|
-
case "createEnum": return {
|
|
499
|
-
kind: "dropEnum",
|
|
500
|
-
enum: change.enum
|
|
501
|
-
};
|
|
502
|
-
case "dropEnum": return {
|
|
503
|
-
kind: "createEnum",
|
|
504
|
-
enum: change.enum
|
|
505
|
-
};
|
|
506
|
-
case "addEnumValue": return change;
|
|
507
|
-
case "removeEnumValue": return change;
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
/**
|
|
511
|
-
* Returns the change kinds that produce ambiguous reverses — drop column,
|
|
512
|
-
* drop table, type widen — so the generator can flag the down.sql as a draft
|
|
513
|
-
* even if every individual statement is technically valid SQL.
|
|
514
|
-
*/
|
|
515
|
-
const AMBIGUOUS_REVERSE_KINDS = new Set([
|
|
516
|
-
"dropTable",
|
|
517
|
-
"dropColumn",
|
|
518
|
-
"alterColumn",
|
|
519
|
-
"addEnumValue",
|
|
520
|
-
"removeEnumValue"
|
|
521
|
-
]);
|
|
522
|
-
function hasAmbiguousReverse(forward) {
|
|
523
|
-
return forward.some((c) => AMBIGUOUS_REVERSE_KINDS.has(c.kind));
|
|
524
|
-
}
|
|
525
|
-
//#endregion
|
|
526
|
-
//#region src/errors.ts
|
|
527
|
-
var KickDbError = class extends Error {
|
|
528
|
-
code;
|
|
529
|
-
constructor(code, message) {
|
|
530
|
-
super(message);
|
|
531
|
-
this.name = this.constructor.name;
|
|
532
|
-
this.code = code;
|
|
533
|
-
}
|
|
534
|
-
};
|
|
535
|
-
//#endregion
|
|
536
|
-
//#region src/migrate/errors.ts
|
|
537
|
-
var MigrationError = class extends KickDbError {};
|
|
538
|
-
var MigrationLockError = class extends MigrationError {
|
|
539
|
-
constructor(message) {
|
|
540
|
-
super("migration_lock_held", message);
|
|
541
|
-
}
|
|
542
|
-
};
|
|
543
|
-
var MigrationDriftError = class extends MigrationError {
|
|
544
|
-
diff;
|
|
545
|
-
constructor(message, diff) {
|
|
546
|
-
super("migration_drift", message);
|
|
547
|
-
this.diff = diff;
|
|
548
|
-
}
|
|
549
|
-
};
|
|
550
|
-
var MigrationHashError = class extends MigrationError {
|
|
551
|
-
id;
|
|
552
|
-
expected;
|
|
553
|
-
actual;
|
|
554
|
-
constructor(id, expected, actual) {
|
|
555
|
-
super("migration_hash_mismatch", `Hash mismatch for migration ${id}`);
|
|
556
|
-
this.id = id;
|
|
557
|
-
this.expected = expected;
|
|
558
|
-
this.actual = actual;
|
|
559
|
-
}
|
|
560
|
-
};
|
|
561
|
-
var UnreviewedMigrationError = class extends MigrationError {
|
|
562
|
-
id;
|
|
563
|
-
constructor(id) {
|
|
564
|
-
super("migration_unreviewed", `Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`);
|
|
565
|
-
this.id = id;
|
|
566
|
-
}
|
|
567
|
-
};
|
|
568
|
-
//#endregion
|
|
569
|
-
//#region src/migrate/journal.ts
|
|
570
|
-
const FILE = "_journal.json";
|
|
571
|
-
async function readJournal(migrationsDir, dialect) {
|
|
572
|
-
const file = path.join(migrationsDir, FILE);
|
|
573
|
-
if (!existsSync(file)) return {
|
|
574
|
-
version: 1,
|
|
575
|
-
dialect,
|
|
576
|
-
entries: []
|
|
577
|
-
};
|
|
578
|
-
const raw = JSON.parse(await readFile(file, "utf8"));
|
|
579
|
-
if (raw.version !== 1) throw new Error(`_journal.json version ${raw.version} unsupported (expected 1)`);
|
|
580
|
-
return raw;
|
|
581
|
-
}
|
|
582
|
-
async function appendJournalEntry(migrationsDir, dialect, entry) {
|
|
583
|
-
const j = await readJournal(migrationsDir, dialect);
|
|
584
|
-
j.entries.push(entry);
|
|
585
|
-
await writeFile(path.join(migrationsDir, FILE), JSON.stringify(j, null, 2) + "\n", "utf8");
|
|
586
|
-
}
|
|
587
|
-
async function computeMigrationHash(migrationDir) {
|
|
588
|
-
const up = await readFile(path.join(migrationDir, "up.sql"), "utf8");
|
|
589
|
-
const down = await readFile(path.join(migrationDir, "down.sql"), "utf8");
|
|
590
|
-
const snap = await readFile(path.join(migrationDir, "snapshot.json"), "utf8");
|
|
591
|
-
return `sha256:${createHash("sha256").update(up).update("|").update(down).update("|").update(snap).digest("hex")}`;
|
|
592
|
-
}
|
|
593
|
-
async function verifyMigrationHash(migrationDir, expected) {
|
|
594
|
-
return await computeMigrationHash(migrationDir) === expected;
|
|
595
|
-
}
|
|
596
|
-
//#endregion
|
|
597
|
-
//#region src/migrate/schema.ts
|
|
598
|
-
const KICK_MIGRATIONS_TABLE = "kick_migrations";
|
|
599
|
-
const KICK_LOCK_TABLE = "kick_migrations_lock";
|
|
600
|
-
function migrationsTableDdl(dialect) {
|
|
601
|
-
switch (dialect) {
|
|
602
|
-
case "postgres": return `CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
|
|
11
|
+
import{n as KICK_GENERATED,r as KICK_NOT_NULL,t as ColumnBuilder}from"./types-Cxh6cDtw.mjs";import{createHash}from"node:crypto";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{createToken,defineAdapter}from"@forinda/kickjs";import{ColumnNode,ColumnUpdateNode,InsertQueryNode,Kysely,PrimitiveValueListNode,ReferenceNode,SelectAllNode,SelectQueryNode,SelectionNode,TableNode,UpdateQueryNode,ValueListNode,ValueNode,ValuesNode,sql}from"kysely";import{EventEmitter}from"node:events";import{pathToFileURL}from"node:url";function isTable(v){return!!(v&&typeof v==`object`&&v.__isTable===!0)}function isPgEnum(v){if(typeof v!=`function`)return!1;let f=v;return typeof f.enumName==`string`&&Array.isArray(f.values)}function extractSnapshot(schema,dialect){let tables={},enums={};for(let value of Object.values(schema))isTable(value)?tables[value.__name]=extractTable(value):isPgEnum(value)&&(enums[value.enumName]={name:value.enumName,values:[...value.values]});return dialect===`postgres`&&Object.keys(enums).length>0?{version:1,dialect,tables,enums}:{version:1,dialect,tables}}function extractTable(t){let columns={},indexes=[...t.__indexes],foreignKeys=[];for(let[colKey,builder]of Object.entries(t.__columns)){columns[colKey]=builder.toJSON(colKey);let state=builder.__state();if(state.unique&&indexes.push({name:`${t.__name}_${colKey}_unique`,columns:[colKey],unique:!0}),state.references){let ref=state.references.thunk();foreignKeys.push({name:`${t.__name}_${colKey}_fk`,columns:[colKey],refTable:ref.__tableName,refColumns:[ref.__name],onDelete:state.references.onDelete,onUpdate:state.references.onUpdate})}}return{name:t.__name,columns,indexes,foreignKeys,checks:[]}}function renderSchemaSource(snapshot){let usedColumnHelpers=new Set,tableSources=[];for(let table of Object.values(snapshot.tables))tableSources.push(renderTable(table,usedColumnHelpers));let helpers=[`table`,...Array.from(usedColumnHelpers).toSorted()];return Object.values(snapshot.tables).some(t=>t.indexes.some(i=>!isAutoUniqueName(t.name,i)))&&helpers.push(`index`),Object.values(snapshot.tables).some(t=>t.indexes.some(i=>i.unique&&!isAutoUniqueName(t.name,i)))&&!helpers.includes(`unique`)&&helpers.push(`unique`),[`import { ${helpers.join(`, `)} } from '@forinda/kickjs-db'`,``,...tableSources].join(`
|
|
12
|
+
`).trimEnd()+`
|
|
13
|
+
`}function renderTable(table,helpers){let ident=jsIdent(table.name),columns=[];for(let col of Object.values(table.columns)){let fk=table.foreignKeys.find(f=>f.columns.length===1&&f.columns[0]===col.name&&f.name===`${table.name}_${col.name}_fk`),inlineUnique=table.indexes.find(i=>i.unique&&i.columns.length===1&&i.columns[0]===col.name&&isAutoUniqueName(table.name,i))!==void 0;columns.push(` ${jsKey(col.name)}: ${renderColumn(col,helpers,fk,inlineUnique)},`)}let explicitIndexes=table.indexes.filter(i=>!isAutoUniqueName(table.name,i)),explicitFks=table.foreignKeys.filter(f=>f.name!==`${table.name}_${f.columns[0]}_fk`||f.columns.length!==1),hasThirdArg=explicitIndexes.length>0,tableArgs=[`'${table.name}'`,`{\n${columns.join(`
|
|
14
|
+
`)}\n}`];if(hasThirdArg){let callbacks=explicitIndexes.map(i=>` ${jsKey(i.name)}: ${renderIndexCall(i)}`).join(`,
|
|
15
|
+
`);tableArgs.push(`(t) => ({\n${callbacks},\n })`)}let src=`export const ${ident} = table(${tableArgs.join(`, `)})`;if(explicitFks.length>0){src+=`
|
|
16
|
+
// TODO: kick db introspect — composite or custom-named foreign keys not auto-rendered:
|
|
17
|
+
`;for(let f of explicitFks)src+=`// ${f.name}: (${f.columns.join(`, `)}) → ${f.refTable}(${f.refColumns.join(`, `)})\n`}return src}function renderColumn(col,helpers,fk,inlineUnique){let{helperName,args}=pickColumnHelper(col);helpers.add(helperName);let chain=`${helperName}(${args})`;if(col.primaryKey&&(chain+=`.primaryKey()`),!col.primaryKey&&!col.nullable&&(chain+=`.notNull()`),col.default!==null&&(chain+=`.default(${JSON.stringify(col.default)})`),inlineUnique&&(chain+=`.unique()`),fk){let ref=`${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`,onDelete=fk.onDelete===`no_action`?``:`, { onDelete: '${fk.onDelete}' }`;chain+=`.references(() => ${ref}${onDelete})`}return chain}function pickColumnHelper(col){let t=col.type;return t===`serial`?{helperName:`serial`,args:``}:t===`bigserial`?{helperName:`bigSerial`,args:``}:t===`smallserial`?{helperName:`serial`,args:``}:t===`integer`?{helperName:`integer`,args:``}:t===`bigint`?{helperName:`bigint`,args:``}:t===`smallint`?{helperName:`smallint`,args:``}:t===`real`?{helperName:`real`,args:``}:t===`double precision`?{helperName:`doublePrecision`,args:``}:/^numeric(\(.+\))?$/.test(t)?{helperName:`numeric`,args:extractParens(t)}:/^varchar(\(\d+\))?$/.test(t)?{helperName:`varchar`,args:extractParens(t)}:/^char(\(\d+\))?$/.test(t)?{helperName:`char`,args:extractParens(t)}:t===`text`?{helperName:`text`,args:``}:t===`boolean`?{helperName:`boolean`,args:``}:t===`timestamp`?{helperName:`timestamp`,args:``}:t===`timestamptz`?{helperName:`timestamptz`,args:``}:t===`date`?{helperName:`date`,args:``}:t===`time`?{helperName:`time`,args:``}:t===`interval`?{helperName:`interval`,args:``}:t===`uuid`?{helperName:`uuid`,args:``}:t===`jsonb`?{helperName:`jsonb`,args:``}:t===`json`?{helperName:`json`,args:``}:t===`bytea`?{helperName:`bytea`,args:``}:{helperName:`text`,args:`/* TODO: ${t} */`}}function extractParens(t){let m=t.match(/\(([^)]+)\)/);return m?m[1]:``}function renderIndexCall(idx){let helper=idx.unique?`unique`:`index`,cols=idx.columns.map(c=>`t.${jsIdent(c)}`).join(`, `);return`${helper}('${idx.name}').on(${cols})`}function isAutoUniqueName(tableName,idx){return idx.unique&&idx.columns.length===1&&idx.name===`${tableName}_${idx.columns[0]}_unique`}function jsIdent(raw){return/^[A-Za-z_$][\w$]*$/.test(raw)?raw:`_${raw.replace(/[^\w$]/g,`_`)}`}function jsKey(raw){return/^[A-Za-z_$][\w$]*$/.test(raw)?raw:JSON.stringify(raw)}function diff(prev,next){let changes=[],prevTables=new Set(Object.keys(prev.tables)),nextTables=new Set(Object.keys(next.tables));diffEnumsCreatePhase(prev,next,changes);for(let name of prevTables)nextTables.has(name)||changes.push({kind:`dropTable`,table:prev.tables[name]});let newTableNames=[...nextTables].filter(n=>!prevTables.has(n));for(let name of newTableNames)changes.push({kind:`createTable`,table:next.tables[name]});for(let name of newTableNames)for(let i of next.tables[name].indexes)changes.push({kind:`addIndex`,table:name,index:i});for(let name of newTableNames)for(let f of next.tables[name].foreignKeys)changes.push({kind:`addForeignKey`,table:name,fk:f});for(let name of nextTables)prevTables.has(name)&&diffTable(prev.tables[name],next.tables[name],changes);return diffEnumsDropPhase(prev,next,changes),changes}function diffEnumsCreatePhase(prev,next,changes){let prevEnums=prev.enums??{},nextEnums=next.enums??{};for(let[name,e]of Object.entries(nextEnums))prevEnums[name]||changes.push({kind:`createEnum`,enum:e});for(let[name,e]of Object.entries(nextEnums)){let prior=prevEnums[name];if(!prior)continue;let priorValues=new Set(prior.values),nextValues=new Set(e.values),nextValueList=e.values;for(let i=0;i<nextValueList.length;i++){let value=nextValueList[i];if(priorValues.has(value))continue;let before=nextValueList[i+1],beforeIsExisting=before!=null&&priorValues.has(before);changes.push({kind:`addEnumValue`,enum:name,value,...beforeIsExisting?{before}:{}})}let removed=prior.values.filter(v=>!nextValues.has(v));removed.length>0&&changes.push({kind:`removeEnumValue`,enum:name,removed})}}function diffEnumsDropPhase(prev,next,changes){let prevEnums=prev.enums??{},nextEnums=next.enums??{};for(let[name,e]of Object.entries(prevEnums))nextEnums[name]||changes.push({kind:`dropEnum`,enum:e})}function diffTable(prev,next,changes){let prevCols=new Map(Object.entries(prev.columns)),nextCols=new Map(Object.entries(next.columns)),drops=[],adds=[];for(let c of prevCols.keys())nextCols.has(c)||drops.push(c);for(let c of nextCols.keys())prevCols.has(c)||adds.push(c);drops.length===1&&adds.length===1&&columnAttrsEqual(prevCols.get(drops[0]),nextCols.get(adds[0]))&&(changes.push({kind:`renameColumn`,table:next.name,from:drops[0],to:adds[0]}),drops.length=0,adds.length=0);for(let c of drops)changes.push({kind:`dropColumn`,table:next.name,column:prevCols.get(c)});for(let c of adds)changes.push({kind:`addColumn`,table:next.name,column:nextCols.get(c)});for(let c of nextCols.keys()){if(!prevCols.has(c))continue;let before=prevCols.get(c),after=nextCols.get(c);columnsEqual(before,after)||changes.push({kind:`alterColumn`,table:next.name,column:c,before,after})}diffByName(prev.indexes,next.indexes,i=>changes.push({kind:`dropIndex`,table:next.name,index:i}),i=>changes.push({kind:`addIndex`,table:next.name,index:i})),diffByName(prev.foreignKeys,next.foreignKeys,f=>changes.push({kind:`dropForeignKey`,table:next.name,fk:f}),f=>changes.push({kind:`addForeignKey`,table:next.name,fk:f}))}function diffByName(prev,next,onDrop,onAdd){let prevByName=new Map(prev.map(p=>[p.name,p])),nextByName=new Map(next.map(n=>[n.name,n]));for(let[n,p]of prevByName)nextByName.has(n)||onDrop(p);for(let[n,x]of nextByName)prevByName.has(n)||onAdd(x)}function columnsEqual(a,b){return a.type===b.type&&a.nullable===b.nullable&&a.default===b.default&&a.primaryKey===b.primaryKey}function columnAttrsEqual(a,b){return a.type===b.type&&a.nullable===b.nullable&&a.default===b.default&&a.primaryKey===b.primaryKey}function invertChanges(forward){let reversed=[];for(let change of forward)reversed.push(invert(change));return reversed.toReversed()}function invert(change){switch(change.kind){case`createTable`:return{kind:`dropTable`,table:change.table};case`dropTable`:return{kind:`createTable`,table:change.table};case`renameTable`:return{kind:`renameTable`,from:change.to,to:change.from};case`addColumn`:return{kind:`dropColumn`,table:change.table,column:change.column};case`dropColumn`:return{kind:`addColumn`,table:change.table,column:change.column};case`renameColumn`:return{kind:`renameColumn`,table:change.table,from:change.to,to:change.from};case`alterColumn`:return{kind:`alterColumn`,table:change.table,column:change.column,before:change.after,after:change.before};case`addIndex`:return{kind:`dropIndex`,table:change.table,index:change.index};case`dropIndex`:return{kind:`addIndex`,table:change.table,index:change.index};case`addForeignKey`:return{kind:`dropForeignKey`,table:change.table,fk:change.fk};case`dropForeignKey`:return{kind:`addForeignKey`,table:change.table,fk:change.fk};case`createEnum`:return{kind:`dropEnum`,enum:change.enum};case`dropEnum`:return{kind:`createEnum`,enum:change.enum};case`addEnumValue`:return change;case`removeEnumValue`:return change}}const AMBIGUOUS_REVERSE_KINDS=new Set([`dropTable`,`dropColumn`,`alterColumn`,`addEnumValue`,`removeEnumValue`]);function hasAmbiguousReverse(forward){return forward.some(c=>AMBIGUOUS_REVERSE_KINDS.has(c.kind))}var KickDbError=class extends Error{code;constructor(code,message){super(message),this.name=this.constructor.name,this.code=code}},MigrationError=class extends KickDbError{},MigrationLockError=class extends MigrationError{constructor(message){super(`migration_lock_held`,message)}},MigrationDriftError=class extends MigrationError{diff;constructor(message,diff){super(`migration_drift`,message),this.diff=diff}},MigrationHashError=class extends MigrationError{id;expected;actual;constructor(id,expected,actual){super(`migration_hash_mismatch`,`Hash mismatch for migration ${id}`),this.id=id,this.expected=expected,this.actual=actual}},UnreviewedMigrationError=class extends MigrationError{id;constructor(id){super(`migration_unreviewed`,`Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`),this.id=id}};const FILE=`_journal.json`;async function readJournal(migrationsDir,dialect){let file=path.join(migrationsDir,FILE);if(!existsSync(file))return{version:1,dialect,entries:[]};let raw=JSON.parse(await readFile(file,`utf8`));if(raw.version!==1)throw Error(`_journal.json version ${raw.version} unsupported (expected 1)`);return raw}async function appendJournalEntry(migrationsDir,dialect,entry){let j=await readJournal(migrationsDir,dialect);j.entries.push(entry),await writeFile(path.join(migrationsDir,FILE),JSON.stringify(j,null,2)+`
|
|
18
|
+
`,`utf8`)}async function computeMigrationHash(migrationDir){let up=await readFile(path.join(migrationDir,`up.sql`),`utf8`),down=await readFile(path.join(migrationDir,`down.sql`),`utf8`),snap=await readFile(path.join(migrationDir,`snapshot.json`),`utf8`);return`sha256:${createHash(`sha256`).update(up).update(`|`).update(down).update(`|`).update(snap).digest(`hex`)}`}async function verifyMigrationHash(migrationDir,expected){return await computeMigrationHash(migrationDir)===expected}const KICK_MIGRATIONS_TABLE=`kick_migrations`,KICK_LOCK_TABLE=`kick_migrations_lock`;function migrationsTableDdl(dialect){switch(dialect){case`postgres`:return`CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
|
|
603
19
|
"id" varchar(128) PRIMARY KEY,
|
|
604
20
|
"name" text NOT NULL,
|
|
605
21
|
"hash" text NOT NULL,
|
|
@@ -607,8 +23,7 @@ function migrationsTableDdl(dialect) {
|
|
|
607
23
|
"applied_at" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
608
24
|
"direction" varchar(8) NOT NULL DEFAULT 'up'
|
|
609
25
|
);
|
|
610
|
-
CREATE INDEX IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}_batch_idx" ON "${KICK_MIGRATIONS_TABLE}" ("batch");`;
|
|
611
|
-
case "sqlite": return `CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
|
|
26
|
+
CREATE INDEX IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}_batch_idx" ON "${KICK_MIGRATIONS_TABLE}" ("batch");`;case`sqlite`:return`CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
|
|
612
27
|
"id" text PRIMARY KEY,
|
|
613
28
|
"name" text NOT NULL,
|
|
614
29
|
"hash" text NOT NULL,
|
|
@@ -616,8 +31,7 @@ function migrationsTableDdl(dialect) {
|
|
|
616
31
|
"applied_at" text NOT NULL DEFAULT (datetime('now')),
|
|
617
32
|
"direction" text NOT NULL DEFAULT 'up'
|
|
618
33
|
);
|
|
619
|
-
CREATE INDEX IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}_batch_idx" ON "${KICK_MIGRATIONS_TABLE}" ("batch");`;
|
|
620
|
-
case "mysql": return `CREATE TABLE IF NOT EXISTS \`${KICK_MIGRATIONS_TABLE}\` (
|
|
34
|
+
CREATE INDEX IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}_batch_idx" ON "${KICK_MIGRATIONS_TABLE}" ("batch");`;case`mysql`:return`CREATE TABLE IF NOT EXISTS \`${KICK_MIGRATIONS_TABLE}\` (
|
|
621
35
|
\`id\` varchar(128) PRIMARY KEY,
|
|
622
36
|
\`name\` text NOT NULL,
|
|
623
37
|
\`hash\` text NOT NULL,
|
|
@@ -625,182 +39,35 @@ function migrationsTableDdl(dialect) {
|
|
|
625
39
|
\`applied_at\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
626
40
|
\`direction\` varchar(8) NOT NULL DEFAULT 'up',
|
|
627
41
|
INDEX \`${KICK_MIGRATIONS_TABLE}_batch_idx\` (\`batch\`)
|
|
628
|
-
)
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
function lockTableDdl(dialect) {
|
|
632
|
-
switch (dialect) {
|
|
633
|
-
case "postgres": return `CREATE TABLE IF NOT EXISTS "${KICK_LOCK_TABLE}" (
|
|
42
|
+
);`}}function lockTableDdl(dialect){switch(dialect){case`postgres`:return`CREATE TABLE IF NOT EXISTS "${KICK_LOCK_TABLE}" (
|
|
634
43
|
"id" smallint PRIMARY KEY,
|
|
635
44
|
"locked_at" timestamptz,
|
|
636
45
|
"locked_by" text
|
|
637
46
|
);
|
|
638
|
-
INSERT INTO "${KICK_LOCK_TABLE}" ("id") VALUES (1) ON CONFLICT DO NOTHING;`;
|
|
639
|
-
case "sqlite": return `CREATE TABLE IF NOT EXISTS "${KICK_LOCK_TABLE}" (
|
|
47
|
+
INSERT INTO "${KICK_LOCK_TABLE}" ("id") VALUES (1) ON CONFLICT DO NOTHING;`;case`sqlite`:return`CREATE TABLE IF NOT EXISTS "${KICK_LOCK_TABLE}" (
|
|
640
48
|
"id" integer PRIMARY KEY,
|
|
641
49
|
"locked_at" text,
|
|
642
50
|
"locked_by" text
|
|
643
51
|
);
|
|
644
|
-
INSERT OR IGNORE INTO "${KICK_LOCK_TABLE}" ("id") VALUES (1);`;
|
|
645
|
-
case "mysql": return `CREATE TABLE IF NOT EXISTS \`${KICK_LOCK_TABLE}\` (
|
|
52
|
+
INSERT OR IGNORE INTO "${KICK_LOCK_TABLE}" ("id") VALUES (1);`;case`mysql`:return`CREATE TABLE IF NOT EXISTS \`${KICK_LOCK_TABLE}\` (
|
|
646
53
|
\`id\` smallint PRIMARY KEY,
|
|
647
54
|
\`locked_at\` timestamp NULL,
|
|
648
55
|
\`locked_by\` text
|
|
649
56
|
);
|
|
650
|
-
INSERT IGNORE INTO \`${KICK_LOCK_TABLE}\` (\`id\`) VALUES (1)
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
//#endregion
|
|
654
|
-
//#region src/migrate/memory-adapter.ts
|
|
655
|
-
/**
|
|
656
|
-
* In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-
|
|
657
|
-
* holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as
|
|
658
|
-
* test-only stubs — the real DB-bound semantics are validated in db-pg's
|
|
659
|
-
* integration tests, not here.
|
|
660
|
-
*/
|
|
661
|
-
var MemoryMigrationAdapter = class {
|
|
662
|
-
dialect = "postgres";
|
|
663
|
-
rows = [];
|
|
664
|
-
locked = null;
|
|
665
|
-
appliedSql = [];
|
|
666
|
-
currentSchema = {
|
|
667
|
-
version: 1,
|
|
668
|
-
dialect: "postgres",
|
|
669
|
-
tables: {}
|
|
670
|
-
};
|
|
671
|
-
async ensureMigrationTables() {}
|
|
672
|
-
async listApplied() {
|
|
673
|
-
return [...this.rows];
|
|
674
|
-
}
|
|
675
|
-
async recordApplied(row) {
|
|
676
|
-
this.rows.push({
|
|
677
|
-
...row,
|
|
678
|
-
appliedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
679
|
-
});
|
|
680
|
-
}
|
|
681
|
-
async removeApplied(id) {
|
|
682
|
-
this.rows = this.rows.filter((r) => r.id !== id);
|
|
683
|
-
}
|
|
684
|
-
async acquireLock(owner) {
|
|
685
|
-
if (this.locked) return false;
|
|
686
|
-
this.locked = {
|
|
687
|
-
by: owner,
|
|
688
|
-
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
689
|
-
};
|
|
690
|
-
return true;
|
|
691
|
-
}
|
|
692
|
-
async releaseLock() {
|
|
693
|
-
this.locked = null;
|
|
694
|
-
}
|
|
695
|
-
async applySqlInTx(sql) {
|
|
696
|
-
this.appliedSql.push(sql);
|
|
697
|
-
}
|
|
698
|
-
async applySqlNoTx(sql) {
|
|
699
|
-
this.appliedSql.push(sql);
|
|
700
|
-
}
|
|
701
|
-
async introspect() {
|
|
702
|
-
return this.currentSchema;
|
|
703
|
-
}
|
|
704
|
-
async close() {}
|
|
705
|
-
/** Test-only setter — let drift tests stage a "live" schema state. */
|
|
706
|
-
__setIntrospectedSchema(snap) {
|
|
707
|
-
this.currentSchema = snap;
|
|
708
|
-
}
|
|
709
|
-
/** Test-only inspector — what SQL we received. */
|
|
710
|
-
__appliedSql() {
|
|
711
|
-
return this.appliedSql;
|
|
712
|
-
}
|
|
713
|
-
};
|
|
714
|
-
//#endregion
|
|
715
|
-
//#region src/migrate/introspect-pg.ts
|
|
716
|
-
const DEFAULT_EXCLUDED = ["kick_migrations", "kick_migrations_lock"];
|
|
717
|
-
async function introspectPg(client, opts = {}) {
|
|
718
|
-
const schema = opts.schema ?? "public";
|
|
719
|
-
const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED;
|
|
720
|
-
const tableRows = await client.query(`SELECT table_name
|
|
57
|
+
INSERT IGNORE INTO \`${KICK_LOCK_TABLE}\` (\`id\`) VALUES (1);`}}var MemoryMigrationAdapter=class{dialect=`postgres`;rows=[];locked=null;appliedSql=[];currentSchema={version:1,dialect:`postgres`,tables:{}};async ensureMigrationTables(){}async listApplied(){return[...this.rows]}async recordApplied(row){this.rows.push({...row,appliedAt:new Date().toISOString()})}async removeApplied(id){this.rows=this.rows.filter(r=>r.id!==id)}async acquireLock(owner){return this.locked?!1:(this.locked={by:owner,at:new Date().toISOString()},!0)}async releaseLock(){this.locked=null}async applySqlInTx(sql){this.appliedSql.push(sql)}async applySqlNoTx(sql){this.appliedSql.push(sql)}async introspect(){return this.currentSchema}async close(){}__setIntrospectedSchema(snap){this.currentSchema=snap}__appliedSql(){return this.appliedSql}};const DEFAULT_EXCLUDED=[`kick_migrations`,`kick_migrations_lock`];async function introspectPg(client,opts={}){let schema=opts.schema??`public`,excluded=opts.excludeTables??DEFAULT_EXCLUDED,tableRows=await client.query(`SELECT table_name
|
|
721
58
|
FROM information_schema.tables
|
|
722
59
|
WHERE table_schema = $1 AND table_type = 'BASE TABLE'
|
|
723
|
-
ORDER BY table_name`, [schema]);
|
|
724
|
-
const tables = {};
|
|
725
|
-
for (const t of tableRows.rows) {
|
|
726
|
-
if (excluded.includes(t.table_name)) continue;
|
|
727
|
-
tables[t.table_name] = {
|
|
728
|
-
name: t.table_name,
|
|
729
|
-
columns: await readColumns(client, schema, t.table_name),
|
|
730
|
-
indexes: await readIndexes(client, schema, t.table_name),
|
|
731
|
-
foreignKeys: await readForeignKeys(client, schema, t.table_name),
|
|
732
|
-
checks: []
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
return {
|
|
736
|
-
version: 1,
|
|
737
|
-
dialect: "postgres",
|
|
738
|
-
tables
|
|
739
|
-
};
|
|
740
|
-
}
|
|
741
|
-
async function readColumns(client, schema, table) {
|
|
742
|
-
const cols = await client.query(`SELECT column_name, data_type, udt_name, is_nullable, column_default,
|
|
60
|
+
ORDER BY table_name`,[schema]),tables={};for(let t of tableRows.rows)excluded.includes(t.table_name)||(tables[t.table_name]={name:t.table_name,columns:await readColumns(client,schema,t.table_name),indexes:await readIndexes(client,schema,t.table_name),foreignKeys:await readForeignKeys(client,schema,t.table_name),checks:[]});return{version:1,dialect:`postgres`,tables}}async function readColumns(client,schema,table){let cols=await client.query(`SELECT column_name, data_type, udt_name, is_nullable, column_default,
|
|
743
61
|
character_maximum_length, numeric_precision, numeric_scale
|
|
744
62
|
FROM information_schema.columns
|
|
745
63
|
WHERE table_schema = $1 AND table_name = $2
|
|
746
|
-
ORDER BY ordinal_position`,
|
|
747
|
-
const pkCols = await client.query(`SELECT k.column_name
|
|
64
|
+
ORDER BY ordinal_position`,[schema,table]),pkCols=await client.query(`SELECT k.column_name
|
|
748
65
|
FROM information_schema.table_constraints c
|
|
749
66
|
JOIN information_schema.key_column_usage k
|
|
750
67
|
ON k.constraint_name = c.constraint_name
|
|
751
68
|
AND k.table_schema = c.table_schema
|
|
752
69
|
WHERE c.table_schema = $1 AND c.table_name = $2 AND c.constraint_type = 'PRIMARY KEY'
|
|
753
|
-
ORDER BY k.ordinal_position`,
|
|
754
|
-
const pkSet = new Set(pkCols.rows.map((r) => r.column_name));
|
|
755
|
-
const out = {};
|
|
756
|
-
for (const r of cols.rows) {
|
|
757
|
-
const isSerial = isSerialColumn(r);
|
|
758
|
-
out[r.column_name] = {
|
|
759
|
-
name: r.column_name,
|
|
760
|
-
type: isSerial ? serialTypeFor(r) : normalizeType(r),
|
|
761
|
-
nullable: r.is_nullable === "YES",
|
|
762
|
-
default: isSerial ? null : normalizeDefault(r.column_default),
|
|
763
|
-
primaryKey: pkSet.has(r.column_name)
|
|
764
|
-
};
|
|
765
|
-
}
|
|
766
|
-
return out;
|
|
767
|
-
}
|
|
768
|
-
function isSerialColumn(r) {
|
|
769
|
-
if (!r.column_default) return false;
|
|
770
|
-
if (!r.column_default.startsWith("nextval(")) return false;
|
|
771
|
-
return r.udt_name === "int2" || r.udt_name === "int4" || r.udt_name === "int8";
|
|
772
|
-
}
|
|
773
|
-
function serialTypeFor(r) {
|
|
774
|
-
if (r.udt_name === "int8") return "bigserial";
|
|
775
|
-
if (r.udt_name === "int2") return "smallserial";
|
|
776
|
-
return "serial";
|
|
777
|
-
}
|
|
778
|
-
function normalizeType(r) {
|
|
779
|
-
if (r.data_type === "character varying") return r.character_maximum_length ? `varchar(${r.character_maximum_length})` : "varchar";
|
|
780
|
-
if (r.data_type === "character") return r.character_maximum_length ? `char(${r.character_maximum_length})` : "char(1)";
|
|
781
|
-
if (r.data_type === "numeric") {
|
|
782
|
-
if (r.numeric_precision !== null && r.numeric_scale !== null) return `numeric(${r.numeric_precision}, ${r.numeric_scale})`;
|
|
783
|
-
if (r.numeric_precision !== null) return `numeric(${r.numeric_precision})`;
|
|
784
|
-
return "numeric";
|
|
785
|
-
}
|
|
786
|
-
if (r.data_type === "timestamp with time zone") return "timestamptz";
|
|
787
|
-
if (r.data_type === "timestamp without time zone") return "timestamp";
|
|
788
|
-
if (r.data_type === "time without time zone") return "time";
|
|
789
|
-
if (r.data_type === "double precision") return "double precision";
|
|
790
|
-
if (r.data_type === "USER-DEFINED") return r.udt_name;
|
|
791
|
-
if (r.data_type === "ARRAY") return `${r.udt_name.replace(/^_/, "")}[]`;
|
|
792
|
-
return r.data_type;
|
|
793
|
-
}
|
|
794
|
-
function normalizeDefault(raw) {
|
|
795
|
-
if (!raw) return null;
|
|
796
|
-
const stripped = raw.replace(/::[\w" ]+(\([^)]*\))?$/, "");
|
|
797
|
-
const upper = stripped.toUpperCase();
|
|
798
|
-
if (upper === "NOW()" || upper === "CURRENT_TIMESTAMP") return "CURRENT_TIMESTAMP";
|
|
799
|
-
if (upper === "GEN_RANDOM_UUID()") return "gen_random_uuid()";
|
|
800
|
-
return stripped.replace(/^'(.*)'$/, "$1");
|
|
801
|
-
}
|
|
802
|
-
async function readIndexes(client, schema, table) {
|
|
803
|
-
const rows = await client.query(`SELECT i.relname AS index_name,
|
|
70
|
+
ORDER BY k.ordinal_position`,[schema,table]),pkSet=new Set(pkCols.rows.map(r=>r.column_name)),out={};for(let r of cols.rows){let isSerial=isSerialColumn(r);out[r.column_name]={name:r.column_name,type:isSerial?serialTypeFor(r):normalizeType(r),nullable:r.is_nullable===`YES`,default:isSerial?null:normalizeDefault(r.column_default),primaryKey:pkSet.has(r.column_name)}}return out}function isSerialColumn(r){return!r.column_default||!r.column_default.startsWith(`nextval(`)?!1:r.udt_name===`int2`||r.udt_name===`int4`||r.udt_name===`int8`}function serialTypeFor(r){return r.udt_name===`int8`?`bigserial`:r.udt_name===`int2`?`smallserial`:`serial`}function normalizeType(r){return r.data_type===`character varying`?r.character_maximum_length?`varchar(${r.character_maximum_length})`:`varchar`:r.data_type===`character`?r.character_maximum_length?`char(${r.character_maximum_length})`:`char(1)`:r.data_type===`numeric`?r.numeric_precision!==null&&r.numeric_scale!==null?`numeric(${r.numeric_precision}, ${r.numeric_scale})`:r.numeric_precision===null?`numeric`:`numeric(${r.numeric_precision})`:r.data_type===`timestamp with time zone`?`timestamptz`:r.data_type===`timestamp without time zone`?`timestamp`:r.data_type===`time without time zone`?`time`:r.data_type===`double precision`?`double precision`:r.data_type===`USER-DEFINED`?r.udt_name:r.data_type===`ARRAY`?`${r.udt_name.replace(/^_/,``)}[]`:r.data_type}function normalizeDefault(raw){if(!raw)return null;let stripped=raw.replace(/::[\w" ]+(\([^)]*\))?$/,``),upper=stripped.toUpperCase();return upper===`NOW()`||upper===`CURRENT_TIMESTAMP`?`CURRENT_TIMESTAMP`:upper===`GEN_RANDOM_UUID()`?`gen_random_uuid()`:stripped.replace(/^'(.*)'$/,`$1`)}async function readIndexes(client,schema,table){let rows=await client.query(`SELECT i.relname AS index_name,
|
|
804
71
|
a.attname AS column_name,
|
|
805
72
|
ix.indisunique AS is_unique,
|
|
806
73
|
ix.indisprimary AS is_primary
|
|
@@ -811,25 +78,7 @@ async function readIndexes(client, schema, table) {
|
|
|
811
78
|
JOIN unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) ON true
|
|
812
79
|
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
813
80
|
WHERE n.nspname = $1 AND t.relname = $2 AND t.relkind = 'r'
|
|
814
|
-
ORDER BY i.relname, k.ord`,
|
|
815
|
-
const byIndex = /* @__PURE__ */ new Map();
|
|
816
|
-
for (const r of rows.rows) {
|
|
817
|
-
let entry = byIndex.get(r.index_name);
|
|
818
|
-
if (!entry) {
|
|
819
|
-
entry = {
|
|
820
|
-
name: r.index_name,
|
|
821
|
-
columns: [],
|
|
822
|
-
unique: r.is_unique,
|
|
823
|
-
_isPrimary: r.is_primary
|
|
824
|
-
};
|
|
825
|
-
byIndex.set(r.index_name, entry);
|
|
826
|
-
}
|
|
827
|
-
entry.columns.push(r.column_name);
|
|
828
|
-
}
|
|
829
|
-
return [...byIndex.values()].filter((i) => !i._isPrimary).map(({ _isPrimary, ...rest }) => rest).toSorted((a, b) => a.name.localeCompare(b.name));
|
|
830
|
-
}
|
|
831
|
-
async function readForeignKeys(client, schema, table) {
|
|
832
|
-
const rows = await client.query(`SELECT tc.constraint_name,
|
|
81
|
+
ORDER BY i.relname, k.ord`,[schema,table]),byIndex=new Map;for(let r of rows.rows){let entry=byIndex.get(r.index_name);entry||(entry={name:r.index_name,columns:[],unique:r.is_unique,_isPrimary:r.is_primary},byIndex.set(r.index_name,entry)),entry.columns.push(r.column_name)}return[...byIndex.values()].filter(i=>!i._isPrimary).map(({_isPrimary,...rest})=>rest).toSorted((a,b)=>a.name.localeCompare(b.name))}async function readForeignKeys(client,schema,table){let rows=await client.query(`SELECT tc.constraint_name,
|
|
833
82
|
kcu.column_name,
|
|
834
83
|
ccu.table_name AS ref_table,
|
|
835
84
|
ccu.column_name AS ref_column,
|
|
@@ -848,1240 +97,18 @@ async function readForeignKeys(client, schema, table) {
|
|
|
848
97
|
WHERE tc.table_schema = $1
|
|
849
98
|
AND tc.table_name = $2
|
|
850
99
|
AND tc.constraint_type = 'FOREIGN KEY'
|
|
851
|
-
ORDER BY tc.constraint_name, kcu.ordinal_position`, [schema, table]);
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
}
|
|
866
|
-
fk.columns.push(r.column_name);
|
|
867
|
-
fk.refColumns.push(r.ref_column);
|
|
868
|
-
}
|
|
869
|
-
return [...byName.values()].toSorted((a, b) => a.name.localeCompare(b.name));
|
|
870
|
-
}
|
|
871
|
-
function mapFkAction(raw) {
|
|
872
|
-
switch (raw.toUpperCase()) {
|
|
873
|
-
case "CASCADE": return "cascade";
|
|
874
|
-
case "RESTRICT": return "restrict";
|
|
875
|
-
case "SET NULL": return "set_null";
|
|
876
|
-
case "SET DEFAULT": return "set_default";
|
|
877
|
-
default: return "no_action";
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
//#endregion
|
|
881
|
-
//#region src/migrate/drift.ts
|
|
882
|
-
async function checkDrift(liveSnapshot, expectedSnapshot, behavior, log = console) {
|
|
883
|
-
if (behavior === "ignore") return;
|
|
884
|
-
const changes = diff(expectedSnapshot, liveSnapshot);
|
|
885
|
-
if (changes.length === 0) return;
|
|
886
|
-
const summary = summarize(changes);
|
|
887
|
-
const message = `Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`;
|
|
888
|
-
if (behavior === "warn") {
|
|
889
|
-
log.warn(message);
|
|
890
|
-
return;
|
|
891
|
-
}
|
|
892
|
-
throw new MigrationDriftError(message, summary);
|
|
893
|
-
}
|
|
894
|
-
function summarize(changes) {
|
|
895
|
-
const added = [];
|
|
896
|
-
const removed = [];
|
|
897
|
-
const changed = [];
|
|
898
|
-
for (const c of changes) switch (c.kind) {
|
|
899
|
-
case "createTable":
|
|
900
|
-
added.push(c.table.name);
|
|
901
|
-
break;
|
|
902
|
-
case "dropTable":
|
|
903
|
-
removed.push(c.table.name);
|
|
904
|
-
break;
|
|
905
|
-
case "addColumn":
|
|
906
|
-
added.push(`${c.table}.${c.column.name}`);
|
|
907
|
-
break;
|
|
908
|
-
case "dropColumn":
|
|
909
|
-
removed.push(`${c.table}.${c.column.name}`);
|
|
910
|
-
break;
|
|
911
|
-
case "alterColumn":
|
|
912
|
-
changed.push(`${c.table}.${c.column}`);
|
|
913
|
-
break;
|
|
914
|
-
case "renameColumn":
|
|
915
|
-
changed.push(`${c.table}.${c.from}→${c.to}`);
|
|
916
|
-
break;
|
|
917
|
-
case "renameTable":
|
|
918
|
-
changed.push(`${c.from}→${c.to}`);
|
|
919
|
-
break;
|
|
920
|
-
case "addIndex":
|
|
921
|
-
added.push(`${c.table}#${c.index.name}`);
|
|
922
|
-
break;
|
|
923
|
-
case "dropIndex":
|
|
924
|
-
removed.push(`${c.table}#${c.index.name}`);
|
|
925
|
-
break;
|
|
926
|
-
case "addForeignKey":
|
|
927
|
-
added.push(`${c.table}!${c.fk.name}`);
|
|
928
|
-
break;
|
|
929
|
-
case "dropForeignKey":
|
|
930
|
-
removed.push(`${c.table}!${c.fk.name}`);
|
|
931
|
-
break;
|
|
932
|
-
}
|
|
933
|
-
return {
|
|
934
|
-
added,
|
|
935
|
-
removed,
|
|
936
|
-
changed
|
|
937
|
-
};
|
|
938
|
-
}
|
|
939
|
-
//#endregion
|
|
940
|
-
//#region src/migrate/runner.ts
|
|
941
|
-
async function withLock(opts, fn) {
|
|
942
|
-
const owner = opts.owner ?? `${process.pid}@${(/* @__PURE__ */ new Date()).toISOString()}`;
|
|
943
|
-
if (!await opts.adapter.acquireLock(owner)) throw new MigrationLockError("Another process holds the migration lock");
|
|
944
|
-
try {
|
|
945
|
-
return await fn();
|
|
946
|
-
} finally {
|
|
947
|
-
await opts.adapter.releaseLock();
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
/**
|
|
951
|
-
* Verify pending entries: hash matches stored, meta.reviewed is true (if
|
|
952
|
-
* requireReviewed). Throws MigrationHashError or UnreviewedMigrationError on
|
|
953
|
-
* the first failure.
|
|
954
|
-
*/
|
|
955
|
-
async function verifyPending(pending, migrationsDir, requireReviewed) {
|
|
956
|
-
for (const entry of pending) {
|
|
957
|
-
const dir = path.join(migrationsDir, entry.id);
|
|
958
|
-
const actualHash = await computeMigrationHash(dir);
|
|
959
|
-
if (actualHash !== entry.hash) throw new MigrationHashError(entry.id, entry.hash, actualHash);
|
|
960
|
-
if (requireReviewed) {
|
|
961
|
-
if (JSON.parse(await readFile(path.join(dir, "meta.json"), "utf8")).reviewed !== true) throw new UnreviewedMigrationError(entry.id);
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
}
|
|
965
|
-
async function applyEntry(entry, batch, opts) {
|
|
966
|
-
const dir = path.join(opts.migrationsDir, entry.id);
|
|
967
|
-
const upSql = await readFile(path.join(dir, "up.sql"), "utf8");
|
|
968
|
-
if (JSON.parse(await readFile(path.join(dir, "meta.json"), "utf8")).transaction !== false) await opts.adapter.applySqlInTx(upSql);
|
|
969
|
-
else await opts.adapter.applySqlNoTx(upSql);
|
|
970
|
-
await opts.adapter.recordApplied({
|
|
971
|
-
id: entry.id,
|
|
972
|
-
name: entry.tag,
|
|
973
|
-
hash: entry.hash,
|
|
974
|
-
batch,
|
|
975
|
-
direction: "up"
|
|
976
|
-
});
|
|
977
|
-
}
|
|
978
|
-
async function runForward(opts, pending) {
|
|
979
|
-
if (pending.length === 0) return {
|
|
980
|
-
applied: [],
|
|
981
|
-
batch: null
|
|
982
|
-
};
|
|
983
|
-
const requireReviewed = opts.requireReviewed ?? process.env.NODE_ENV !== "development";
|
|
984
|
-
await verifyPending(pending, opts.migrationsDir, requireReviewed);
|
|
985
|
-
const applied = await opts.adapter.listApplied();
|
|
986
|
-
const nextBatch = (applied.length === 0 ? 0 : Math.max(...applied.map((r) => r.batch))) + 1;
|
|
987
|
-
const ids = [];
|
|
988
|
-
for (const entry of pending) {
|
|
989
|
-
await applyEntry(entry, nextBatch, opts);
|
|
990
|
-
ids.push(entry.id);
|
|
991
|
-
}
|
|
992
|
-
return {
|
|
993
|
-
applied: ids,
|
|
994
|
-
batch: nextBatch
|
|
995
|
-
};
|
|
996
|
-
}
|
|
997
|
-
async function listPending(opts) {
|
|
998
|
-
const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect);
|
|
999
|
-
const applied = await opts.adapter.listApplied();
|
|
1000
|
-
const appliedIds = new Set(applied.map((r) => r.id));
|
|
1001
|
-
return journal.entries.filter((e) => !appliedIds.has(e.id)).map((e) => ({
|
|
1002
|
-
id: e.id,
|
|
1003
|
-
tag: e.tag,
|
|
1004
|
-
hash: e.hash
|
|
1005
|
-
}));
|
|
1006
|
-
}
|
|
1007
|
-
async function maybeCheckDrift(opts) {
|
|
1008
|
-
const behavior = opts.driftCheck ?? "error";
|
|
1009
|
-
if (behavior === "ignore") return;
|
|
1010
|
-
const applied = await opts.adapter.listApplied();
|
|
1011
|
-
if (applied.length === 0) return;
|
|
1012
|
-
const sorted = [...applied].toSorted((a, b) => a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt));
|
|
1013
|
-
const last = sorted[sorted.length - 1];
|
|
1014
|
-
let expected;
|
|
1015
|
-
try {
|
|
1016
|
-
expected = JSON.parse(await readFile(path.join(opts.migrationsDir, last.id, "snapshot.json"), "utf8"));
|
|
1017
|
-
} catch {
|
|
1018
|
-
return;
|
|
1019
|
-
}
|
|
1020
|
-
await checkDrift(await opts.adapter.introspect(), expected, behavior, opts.log);
|
|
1021
|
-
}
|
|
1022
|
-
async function migrateLatest(opts) {
|
|
1023
|
-
await opts.adapter.ensureMigrationTables();
|
|
1024
|
-
return withLock(opts, async () => {
|
|
1025
|
-
await maybeCheckDrift(opts);
|
|
1026
|
-
return runForward(opts, await listPending(opts));
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
async function migrateUp(opts) {
|
|
1030
|
-
await opts.adapter.ensureMigrationTables();
|
|
1031
|
-
return withLock(opts, async () => {
|
|
1032
|
-
await maybeCheckDrift(opts);
|
|
1033
|
-
return runForward(opts, (await listPending(opts)).slice(0, 1));
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
async function applyReverse(id, opts) {
|
|
1037
|
-
const dir = path.join(opts.migrationsDir, id);
|
|
1038
|
-
const downSql = await readFile(path.join(dir, "down.sql"), "utf8");
|
|
1039
|
-
const meta = JSON.parse(await readFile(path.join(dir, "meta.json"), "utf8"));
|
|
1040
|
-
if ((opts.requireReviewed ?? process.env.NODE_ENV !== "development") && meta.reviewed !== true) throw new UnreviewedMigrationError(id);
|
|
1041
|
-
if (meta.transaction !== false) await opts.adapter.applySqlInTx(downSql);
|
|
1042
|
-
else await opts.adapter.applySqlNoTx(downSql);
|
|
1043
|
-
await opts.adapter.removeApplied(id);
|
|
1044
|
-
}
|
|
1045
|
-
async function migrateDown(opts) {
|
|
1046
|
-
await opts.adapter.ensureMigrationTables();
|
|
1047
|
-
return withLock(opts, async () => {
|
|
1048
|
-
const applied = await opts.adapter.listApplied();
|
|
1049
|
-
if (applied.length === 0) return { reversed: null };
|
|
1050
|
-
const sorted = [...applied].toSorted((a, b) => a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt));
|
|
1051
|
-
const last = sorted[sorted.length - 1];
|
|
1052
|
-
await applyReverse(last.id, opts);
|
|
1053
|
-
return { reversed: last.id };
|
|
1054
|
-
});
|
|
1055
|
-
}
|
|
1056
|
-
async function migrateStatus(opts) {
|
|
1057
|
-
await opts.adapter.ensureMigrationTables();
|
|
1058
|
-
const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect);
|
|
1059
|
-
const applied = await opts.adapter.listApplied();
|
|
1060
|
-
const byId = new Map(applied.map((r) => [r.id, r]));
|
|
1061
|
-
const entries = [];
|
|
1062
|
-
for (const e of journal.entries) {
|
|
1063
|
-
const row = byId.get(e.id);
|
|
1064
|
-
let reviewed = false;
|
|
1065
|
-
try {
|
|
1066
|
-
reviewed = JSON.parse(await readFile(path.join(opts.migrationsDir, e.id, "meta.json"), "utf8")).reviewed === true;
|
|
1067
|
-
} catch {}
|
|
1068
|
-
entries.push({
|
|
1069
|
-
id: e.id,
|
|
1070
|
-
tag: e.tag,
|
|
1071
|
-
hash: e.hash,
|
|
1072
|
-
state: row ? "applied" : "pending",
|
|
1073
|
-
batch: row?.batch ?? null,
|
|
1074
|
-
appliedAt: row?.appliedAt ?? null,
|
|
1075
|
-
reviewed
|
|
1076
|
-
});
|
|
1077
|
-
}
|
|
1078
|
-
return entries;
|
|
1079
|
-
}
|
|
1080
|
-
async function migrateRollback(opts) {
|
|
1081
|
-
await opts.adapter.ensureMigrationTables();
|
|
1082
|
-
return withLock(opts, async () => {
|
|
1083
|
-
const applied = await opts.adapter.listApplied();
|
|
1084
|
-
if (applied.length === 0) return {
|
|
1085
|
-
reversed: [],
|
|
1086
|
-
batch: null
|
|
1087
|
-
};
|
|
1088
|
-
const lastBatch = Math.max(...applied.map((r) => r.batch));
|
|
1089
|
-
const targets = applied.filter((r) => r.batch === lastBatch).toSorted((a, b) => a.appliedAt.localeCompare(b.appliedAt)).toReversed();
|
|
1090
|
-
const reversed = [];
|
|
1091
|
-
for (const row of targets) {
|
|
1092
|
-
await applyReverse(row.id, opts);
|
|
1093
|
-
reversed.push(row.id);
|
|
1094
|
-
}
|
|
1095
|
-
return {
|
|
1096
|
-
reversed,
|
|
1097
|
-
batch: lastBatch
|
|
1098
|
-
};
|
|
1099
|
-
});
|
|
1100
|
-
}
|
|
1101
|
-
//#endregion
|
|
1102
|
-
//#region src/adapter.ts
|
|
1103
|
-
/**
|
|
1104
|
-
* KickJS lifecycle adapter for kickjs-db. Three jobs:
|
|
1105
|
-
*
|
|
1106
|
-
* 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.
|
|
1107
|
-
* - 'fail-if-pending' (default): throw if any pending exists. Operators
|
|
1108
|
-
* run `kick db migrate latest` explicitly before deploys land. Avoids
|
|
1109
|
-
* the prisma footgun where migrations silently apply on deploy.
|
|
1110
|
-
* - 'apply': run migrateLatest() automatically. Useful for dev / preview
|
|
1111
|
-
* environments where convenience matters more than safety.
|
|
1112
|
-
* - 'ignore': boot regardless. Last-resort escape hatch.
|
|
1113
|
-
* 2. On shutdown, close the migrationAdapter (drains the pool, etc).
|
|
1114
|
-
* 3. Register the migrationAdapter under an optional DI token so adopters
|
|
1115
|
-
* can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers
|
|
1116
|
-
* separately under DB_PRIMARY.
|
|
1117
|
-
*/
|
|
1118
|
-
const kickDbAdapter = defineAdapter({
|
|
1119
|
-
name: "kickjs-db",
|
|
1120
|
-
build: (config) => ({
|
|
1121
|
-
async beforeStart({ container }) {
|
|
1122
|
-
const policy = config.migrationsOnBoot ?? "fail-if-pending";
|
|
1123
|
-
const pending = (await migrateStatus({
|
|
1124
|
-
adapter: config.migrationAdapter,
|
|
1125
|
-
migrationsDir: config.migrationsDir
|
|
1126
|
-
})).filter((s) => s.state === "pending");
|
|
1127
|
-
if (pending.length > 0) {
|
|
1128
|
-
if (policy === "fail-if-pending") throw new Error(`kickjs-db: ${pending.length} pending migration(s); run \`kick db migrate latest\` before boot`);
|
|
1129
|
-
if (policy === "apply") {
|
|
1130
|
-
const result = await migrateLatest({
|
|
1131
|
-
adapter: config.migrationAdapter,
|
|
1132
|
-
migrationsDir: config.migrationsDir,
|
|
1133
|
-
requireReviewed: config.requireReviewed,
|
|
1134
|
-
driftCheck: config.driftCheck
|
|
1135
|
-
});
|
|
1136
|
-
if (config.bus) config.bus.emit("db:migration-applied", {
|
|
1137
|
-
applied: result.applied,
|
|
1138
|
-
batch: result.batch
|
|
1139
|
-
});
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
if (config.token) container.registerFactory(config.token, () => config.migrationAdapter);
|
|
1143
|
-
},
|
|
1144
|
-
async shutdown() {
|
|
1145
|
-
await config.migrationAdapter.close();
|
|
1146
|
-
}
|
|
1147
|
-
})
|
|
1148
|
-
});
|
|
1149
|
-
//#endregion
|
|
1150
|
-
//#region src/tokens.ts
|
|
1151
|
-
const DB_PRIMARY = createToken("kick/db/primary");
|
|
1152
|
-
const DB_REPLICA = createToken("kick/db/replica");
|
|
1153
|
-
/**
|
|
1154
|
-
* Alias for the default DB. Adopters who only have one database can inject
|
|
1155
|
-
* `DB_CLIENT` instead of remembering whether it's primary/replica.
|
|
1156
|
-
*/
|
|
1157
|
-
const DB_CLIENT = DB_PRIMARY;
|
|
1158
|
-
//#endregion
|
|
1159
|
-
//#region src/client/events.ts
|
|
1160
|
-
/**
|
|
1161
|
-
* Per-client typed event emitter. Wraps a Node EventEmitter to keep the
|
|
1162
|
-
* surface narrow (no `addListener`, no `removeAllListeners`, no `setMaxListeners`).
|
|
1163
|
-
*
|
|
1164
|
-
* The Kysely query interceptor surface is intentionally minimal in M1:
|
|
1165
|
-
* transactionStart/Commit/Rollback fire from createDbClient's transaction()
|
|
1166
|
-
* wrapper. The full beforeQuery / query / queryError emit pipeline lands in
|
|
1167
|
-
* M2 alongside `$extends` since it requires a proper Kysely query plugin
|
|
1168
|
-
* with access to the compiled SQL string + parameters. The types are stable
|
|
1169
|
-
* now so adopter code can wire listeners; only the runtime emit is deferred.
|
|
1170
|
-
*/
|
|
1171
|
-
var KickDbEventEmitter = class {
|
|
1172
|
-
emitter = new EventEmitter();
|
|
1173
|
-
on(event, listener) {
|
|
1174
|
-
this.emitter.on(event, listener);
|
|
1175
|
-
}
|
|
1176
|
-
off(event, listener) {
|
|
1177
|
-
this.emitter.off(event, listener);
|
|
1178
|
-
}
|
|
1179
|
-
emit(event, payload) {
|
|
1180
|
-
this.emitter.emit(event, payload);
|
|
1181
|
-
}
|
|
1182
|
-
};
|
|
1183
|
-
//#endregion
|
|
1184
|
-
//#region src/custom-type.ts
|
|
1185
|
-
/**
|
|
1186
|
-
* ColumnBuilder subclass produced by `customType()`. Carries the
|
|
1187
|
-
* driver codecs so the (future) hooks pipeline can wire them through
|
|
1188
|
-
* a Kysely plugin without each consumer re-declaring its mapping.
|
|
1189
|
-
*
|
|
1190
|
-
* The phantom `T` flows through `SchemaToTypes<S>` exactly like any
|
|
1191
|
-
* other ColumnBuilder<T>, so adopters get full row-shape inference
|
|
1192
|
-
* for free.
|
|
1193
|
-
*/
|
|
1194
|
-
var CustomColumnBuilder = class extends ColumnBuilder {
|
|
1195
|
-
/** Encode hook — run on values heading into the database. */
|
|
1196
|
-
toDriver;
|
|
1197
|
-
/** Decode hook — run on row values coming out of the database. */
|
|
1198
|
-
fromDriver;
|
|
1199
|
-
constructor(opts) {
|
|
1200
|
-
super(opts.dataType());
|
|
1201
|
-
this.toDriver = opts.toDriver;
|
|
1202
|
-
this.fromDriver = opts.fromDriver;
|
|
1203
|
-
}
|
|
1204
|
-
};
|
|
1205
|
-
/**
|
|
1206
|
-
* Build a reusable column factory for a custom type. The returned
|
|
1207
|
-
* function is what callers use inside `table('foo', { col: factory() })`
|
|
1208
|
-
* — same shape as the built-in `varchar()`, `text()`, etc.
|
|
1209
|
-
*
|
|
1210
|
-
* @example
|
|
1211
|
-
* ```ts
|
|
1212
|
-
* const ulid = customType<string>({
|
|
1213
|
-
* dataType: () => 'char(26)',
|
|
1214
|
-
* toDriver: (s) => s,
|
|
1215
|
-
* fromDriver: (raw) => String(raw),
|
|
1216
|
-
* })
|
|
1217
|
-
*
|
|
1218
|
-
* const events = table('events', {
|
|
1219
|
-
* id: ulid().primaryKey(),
|
|
1220
|
-
* ts: timestamp().notNull().defaultNow(),
|
|
1221
|
-
* })
|
|
1222
|
-
* ```
|
|
1223
|
-
*/
|
|
1224
|
-
function customType(opts) {
|
|
1225
|
-
return () => new CustomColumnBuilder(opts);
|
|
1226
|
-
}
|
|
1227
|
-
//#endregion
|
|
1228
|
-
//#region src/client/codec-plugin.ts
|
|
1229
|
-
var CodecPlugin = class {
|
|
1230
|
-
constructor(encoders, decoders) {
|
|
1231
|
-
this.encoders = encoders;
|
|
1232
|
-
this.decoders = decoders;
|
|
1233
|
-
}
|
|
1234
|
-
transformQuery(args) {
|
|
1235
|
-
if (this.encoders.size === 0) return args.node;
|
|
1236
|
-
const node = args.node;
|
|
1237
|
-
if (InsertQueryNode.is(node)) return this.transformInsert(node);
|
|
1238
|
-
if (UpdateQueryNode.is(node)) return this.transformUpdate(node);
|
|
1239
|
-
return node;
|
|
1240
|
-
}
|
|
1241
|
-
async transformResult(args) {
|
|
1242
|
-
if (this.decoders.size === 0) return args.result;
|
|
1243
|
-
const rows = args.result.rows.map((row) => this.decodeRow(row));
|
|
1244
|
-
return {
|
|
1245
|
-
...args.result,
|
|
1246
|
-
rows
|
|
1247
|
-
};
|
|
1248
|
-
}
|
|
1249
|
-
transformInsert(node) {
|
|
1250
|
-
const cols = node.columns;
|
|
1251
|
-
const values = node.values;
|
|
1252
|
-
if (!cols || !values) return node;
|
|
1253
|
-
const positional = this.positionalEncoders(cols);
|
|
1254
|
-
if (!positional) return node;
|
|
1255
|
-
if (ValuesNode.is(values)) {
|
|
1256
|
-
const items = values.values.map((item) => this.encodeValuesItem(item, positional));
|
|
1257
|
-
if (!items.some((item, i) => item !== values.values[i])) return node;
|
|
1258
|
-
return InsertQueryNode.cloneWith(node, { values: ValuesNode.create(items) });
|
|
1259
|
-
}
|
|
1260
|
-
return node;
|
|
1261
|
-
}
|
|
1262
|
-
transformUpdate(node) {
|
|
1263
|
-
const updates = node.updates;
|
|
1264
|
-
if (!updates || updates.length === 0) return node;
|
|
1265
|
-
let changed = false;
|
|
1266
|
-
const next = updates.map((u) => {
|
|
1267
|
-
const col = u.column;
|
|
1268
|
-
if (!ColumnNode.is(col)) return u;
|
|
1269
|
-
const encoder = this.encoders.get(col.column.name);
|
|
1270
|
-
if (!encoder) return u;
|
|
1271
|
-
const encoded = this.encodeValueNode(u.value, encoder);
|
|
1272
|
-
if (encoded === u.value) return u;
|
|
1273
|
-
changed = true;
|
|
1274
|
-
return ColumnUpdateNode.create(col, encoded);
|
|
1275
|
-
});
|
|
1276
|
-
if (!changed) return node;
|
|
1277
|
-
return {
|
|
1278
|
-
...node,
|
|
1279
|
-
updates: next
|
|
1280
|
-
};
|
|
1281
|
-
}
|
|
1282
|
-
positionalEncoders(cols) {
|
|
1283
|
-
const out = Array.from({ length: cols.length });
|
|
1284
|
-
let any = false;
|
|
1285
|
-
for (let i = 0; i < cols.length; i++) {
|
|
1286
|
-
const enc = this.encoders.get(cols[i].column.name) ?? null;
|
|
1287
|
-
out[i] = enc;
|
|
1288
|
-
if (enc) any = true;
|
|
1289
|
-
}
|
|
1290
|
-
return any ? out : null;
|
|
1291
|
-
}
|
|
1292
|
-
encodeValuesItem(item, positional) {
|
|
1293
|
-
if (ValueListNode.is(item)) {
|
|
1294
|
-
const next = item.values.map((v, i) => {
|
|
1295
|
-
const enc = positional[i];
|
|
1296
|
-
if (!enc) return v;
|
|
1297
|
-
return this.encodeValueNode(v, enc);
|
|
1298
|
-
});
|
|
1299
|
-
return next.some((v, i) => v !== item.values[i]) ? ValueListNode.create(next) : item;
|
|
1300
|
-
}
|
|
1301
|
-
if (PrimitiveValueListNode.is(item)) {
|
|
1302
|
-
const next = item.values.map((v, i) => {
|
|
1303
|
-
const enc = positional[i];
|
|
1304
|
-
if (!enc) return v;
|
|
1305
|
-
return this.encodePrimitive(v, enc);
|
|
1306
|
-
});
|
|
1307
|
-
return next.some((v, i) => v !== item.values[i]) ? PrimitiveValueListNode.create(next) : item;
|
|
1308
|
-
}
|
|
1309
|
-
return item;
|
|
1310
|
-
}
|
|
1311
|
-
encodeValueNode(node, encoder) {
|
|
1312
|
-
if (!ValueNode.is(node)) return node;
|
|
1313
|
-
const value = node.value;
|
|
1314
|
-
if (value === null || value === void 0) return node;
|
|
1315
|
-
const encoded = encoder(value);
|
|
1316
|
-
if (encoded === value) return node;
|
|
1317
|
-
return ValueNode.create(encoded);
|
|
1318
|
-
}
|
|
1319
|
-
encodePrimitive(value, encoder) {
|
|
1320
|
-
if (value === null || value === void 0) return value;
|
|
1321
|
-
return encoder(value);
|
|
1322
|
-
}
|
|
1323
|
-
decodeRow(row) {
|
|
1324
|
-
let mutated = false;
|
|
1325
|
-
const out = {};
|
|
1326
|
-
for (const key of Object.keys(row)) {
|
|
1327
|
-
const value = row[key];
|
|
1328
|
-
const decoder = this.decoders.get(key);
|
|
1329
|
-
if (decoder && value !== null && value !== void 0) {
|
|
1330
|
-
out[key] = decoder(value);
|
|
1331
|
-
mutated = true;
|
|
1332
|
-
} else out[key] = value;
|
|
1333
|
-
}
|
|
1334
|
-
return mutated ? out : row;
|
|
1335
|
-
}
|
|
1336
|
-
};
|
|
1337
|
-
/**
|
|
1338
|
-
* Walk a schema record and collect decoders from every column whose
|
|
1339
|
-
* builder is a `CustomColumnBuilder` with a `fromDriver` codec set.
|
|
1340
|
-
*/
|
|
1341
|
-
function buildDecoderMap(schema) {
|
|
1342
|
-
return collectCodecs(schema, "fromDriver");
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Walk a schema record and collect encoders from every column whose
|
|
1346
|
-
* builder is a `CustomColumnBuilder` with a `toDriver` codec set.
|
|
1347
|
-
*/
|
|
1348
|
-
function buildEncoderMap(schema) {
|
|
1349
|
-
return collectCodecs(schema, "toDriver");
|
|
1350
|
-
}
|
|
1351
|
-
function collectCodecs(schema, key) {
|
|
1352
|
-
const out = /* @__PURE__ */ new Map();
|
|
1353
|
-
if (!schema || typeof schema !== "object") return out;
|
|
1354
|
-
for (const value of Object.values(schema)) {
|
|
1355
|
-
if (!isTableDecl(value)) continue;
|
|
1356
|
-
for (const [colName, col] of Object.entries(value.__columns)) if (col instanceof CustomColumnBuilder) {
|
|
1357
|
-
const fn = col[key];
|
|
1358
|
-
if (fn) out.set(colName, fn);
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
return out;
|
|
1362
|
-
}
|
|
1363
|
-
function isTableDecl(value) {
|
|
1364
|
-
return typeof value === "object" && value !== null && value.__isTable === true;
|
|
1365
|
-
}
|
|
1366
|
-
//#endregion
|
|
1367
|
-
//#region src/extend/result-plugin.ts
|
|
1368
|
-
var ResultExtensionPlugin = class {
|
|
1369
|
-
byTable;
|
|
1370
|
-
/**
|
|
1371
|
-
* Map of queryId → table name the query targets. Populated in
|
|
1372
|
-
* transformQuery, consumed in transformResult, deleted after use so
|
|
1373
|
-
* it doesn't leak across long-lived clients.
|
|
1374
|
-
*/
|
|
1375
|
-
pending = /* @__PURE__ */ new Map();
|
|
1376
|
-
constructor(extensions) {
|
|
1377
|
-
this.byTable = /* @__PURE__ */ new Map();
|
|
1378
|
-
for (const [tableName, bag] of Object.entries(extensions)) {
|
|
1379
|
-
if (!bag) continue;
|
|
1380
|
-
const entries = Object.entries(bag);
|
|
1381
|
-
if (entries.length === 0) continue;
|
|
1382
|
-
this.byTable.set(tableName, Object.fromEntries(entries));
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
transformQuery(args) {
|
|
1386
|
-
const { node, queryId } = args;
|
|
1387
|
-
if (!SelectQueryNode.is(node)) return node;
|
|
1388
|
-
const tableName = singleTableTarget(node);
|
|
1389
|
-
if (!tableName) return node;
|
|
1390
|
-
const bag = this.byTable.get(tableName);
|
|
1391
|
-
if (!bag) return node;
|
|
1392
|
-
this.pending.set(queryId, tableName);
|
|
1393
|
-
return injectNeeds(node, bag);
|
|
1394
|
-
}
|
|
1395
|
-
async transformResult(args) {
|
|
1396
|
-
const tableName = this.pending.get(args.queryId);
|
|
1397
|
-
if (!tableName) return args.result;
|
|
1398
|
-
this.pending.delete(args.queryId);
|
|
1399
|
-
const bag = this.byTable.get(tableName);
|
|
1400
|
-
if (!bag) return args.result;
|
|
1401
|
-
const computeds = Object.entries(bag);
|
|
1402
|
-
if (computeds.length === 0) return args.result;
|
|
1403
|
-
const rows = args.result.rows.map((row) => {
|
|
1404
|
-
if (row === null || row === void 0) return row;
|
|
1405
|
-
const base = row;
|
|
1406
|
-
const next = { ...base };
|
|
1407
|
-
for (const [key, ext] of computeds) try {
|
|
1408
|
-
next[key] = ext.compute(base);
|
|
1409
|
-
} catch {
|
|
1410
|
-
next[key] = void 0;
|
|
1411
|
-
}
|
|
1412
|
-
return next;
|
|
1413
|
-
});
|
|
1414
|
-
return {
|
|
1415
|
-
...args.result,
|
|
1416
|
-
rows
|
|
1417
|
-
};
|
|
1418
|
-
}
|
|
1419
|
-
};
|
|
1420
|
-
/**
|
|
1421
|
-
* Detect the single table this select reads from. Returns the table
|
|
1422
|
-
* name when from has exactly one TableNode (or AliasNode wrapping
|
|
1423
|
-
* one); returns null for joins, sub-selects, multi-table selects,
|
|
1424
|
-
* and anything we can't reliably attribute. The plugin only acts on
|
|
1425
|
-
* single-table selects in v1.
|
|
1426
|
-
*/
|
|
1427
|
-
function singleTableTarget(node) {
|
|
1428
|
-
const from = node.from;
|
|
1429
|
-
if (!from || from.froms.length !== 1) return null;
|
|
1430
|
-
const target = unwrapAlias(from.froms[0]);
|
|
1431
|
-
if (!TableNode.is(target)) return null;
|
|
1432
|
-
return target.table.identifier.name;
|
|
1433
|
-
}
|
|
1434
|
-
function unwrapAlias(node) {
|
|
1435
|
-
if (node.kind === "AliasNode") return node.node;
|
|
1436
|
-
return node;
|
|
1437
|
-
}
|
|
1438
|
-
/**
|
|
1439
|
-
* Inject every needs column not already represented in the select
|
|
1440
|
-
* list. SelectAllNode (the `*` wildcard) means "all columns", in
|
|
1441
|
-
* which case there's nothing to add. Specific column references are
|
|
1442
|
-
* deduped by name so a column already selected explicitly stays put
|
|
1443
|
-
* exactly once.
|
|
1444
|
-
*/
|
|
1445
|
-
function injectNeeds(node, bag) {
|
|
1446
|
-
const selections = node.selections ?? [];
|
|
1447
|
-
if (selections.some(isSelectAll)) return node;
|
|
1448
|
-
const have = /* @__PURE__ */ new Set();
|
|
1449
|
-
for (const sel of selections) {
|
|
1450
|
-
const inner = sel.selection;
|
|
1451
|
-
if (ReferenceNode.is(inner) && ColumnNode.is(inner.column)) have.add(inner.column.column.name);
|
|
1452
|
-
else if (ColumnNode.is(inner)) have.add(inner.column.name);
|
|
1453
|
-
}
|
|
1454
|
-
const allNeeded = /* @__PURE__ */ new Set();
|
|
1455
|
-
for (const ext of Object.values(bag)) for (const col of Object.keys(ext.needs)) allNeeded.add(col);
|
|
1456
|
-
const missing = [...allNeeded].filter((c) => !have.has(c));
|
|
1457
|
-
if (missing.length === 0) return node;
|
|
1458
|
-
const additions = missing.map((col) => SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))));
|
|
1459
|
-
return SelectQueryNode.cloneWithSelections(node, additions);
|
|
1460
|
-
}
|
|
1461
|
-
function isSelectAll(node) {
|
|
1462
|
-
const inner = node.selection;
|
|
1463
|
-
if (SelectAllNode.is(inner)) return true;
|
|
1464
|
-
if (ReferenceNode.is(inner) && SelectAllNode.is(inner.column)) return true;
|
|
1465
|
-
return false;
|
|
1466
|
-
}
|
|
1467
|
-
//#endregion
|
|
1468
|
-
//#region src/extend/apply.ts
|
|
1469
|
-
function applyExtensions(client, ctx, ext) {
|
|
1470
|
-
let baseClient = client;
|
|
1471
|
-
if (hasResultExtensions(ext.result)) {
|
|
1472
|
-
const plugin = new ResultExtensionPlugin(ext.result);
|
|
1473
|
-
baseClient = wrap(client.qb.withPlugin(plugin), ctx);
|
|
1474
|
-
}
|
|
1475
|
-
let proxy;
|
|
1476
|
-
const modelBag = {};
|
|
1477
|
-
const model = ext.model ?? {};
|
|
1478
|
-
for (const tableName of Object.keys(model)) {
|
|
1479
|
-
const methods = model[tableName];
|
|
1480
|
-
if (!methods) continue;
|
|
1481
|
-
const bound = {};
|
|
1482
|
-
for (const [methodName, fn] of Object.entries(methods)) bound[methodName] = (...args) => fn.call(proxy, ...args);
|
|
1483
|
-
modelBag[tableName] = bound;
|
|
1484
|
-
}
|
|
1485
|
-
proxy = new Proxy(baseClient, { get(target, prop) {
|
|
1486
|
-
if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(modelBag, prop)) return modelBag[prop];
|
|
1487
|
-
return target[prop];
|
|
1488
|
-
} });
|
|
1489
|
-
return proxy;
|
|
1490
|
-
}
|
|
1491
|
-
function hasResultExtensions(result) {
|
|
1492
|
-
if (!result || typeof result !== "object") return false;
|
|
1493
|
-
for (const bag of Object.values(result)) if (bag && typeof bag === "object" && Object.keys(bag).length > 0) return true;
|
|
1494
|
-
return false;
|
|
1495
|
-
}
|
|
1496
|
-
//#endregion
|
|
1497
|
-
//#region src/client/wrap.ts
|
|
1498
|
-
function wrap(qb, ctx) {
|
|
1499
|
-
const client = {
|
|
1500
|
-
qb,
|
|
1501
|
-
dialect: ctx.dialect,
|
|
1502
|
-
selectFrom: qb.selectFrom.bind(qb),
|
|
1503
|
-
insertInto: qb.insertInto.bind(qb),
|
|
1504
|
-
updateTable: qb.updateTable.bind(qb),
|
|
1505
|
-
deleteFrom: qb.deleteFrom.bind(qb),
|
|
1506
|
-
on(event, listener) {
|
|
1507
|
-
ctx.events?.on(event, listener);
|
|
1508
|
-
return client;
|
|
1509
|
-
},
|
|
1510
|
-
off(event, listener) {
|
|
1511
|
-
ctx.events?.off(event, listener);
|
|
1512
|
-
return client;
|
|
1513
|
-
},
|
|
1514
|
-
transaction: ((a, b) => {
|
|
1515
|
-
const txOpts = typeof a === "function" ? {} : a;
|
|
1516
|
-
const fn = typeof a === "function" ? a : b;
|
|
1517
|
-
const run = async () => {
|
|
1518
|
-
ctx.events?.emit("transactionStart", { isolation: txOpts.isolation });
|
|
1519
|
-
try {
|
|
1520
|
-
const result = await qb.transaction().execute(async (tx) => {
|
|
1521
|
-
if (txOpts.isolation) {
|
|
1522
|
-
const level = txOpts.isolation.toUpperCase();
|
|
1523
|
-
await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx);
|
|
1524
|
-
}
|
|
1525
|
-
return await fn(wrap(tx, ctx));
|
|
1526
|
-
});
|
|
1527
|
-
ctx.events?.emit("transactionCommit", { isolation: txOpts.isolation });
|
|
1528
|
-
return result;
|
|
1529
|
-
} catch (err) {
|
|
1530
|
-
ctx.events?.emit("transactionRollback", {
|
|
1531
|
-
isolation: txOpts.isolation,
|
|
1532
|
-
error: err
|
|
1533
|
-
});
|
|
1534
|
-
throw err;
|
|
1535
|
-
}
|
|
1536
|
-
};
|
|
1537
|
-
return run();
|
|
1538
|
-
}),
|
|
1539
|
-
$extends(ext) {
|
|
1540
|
-
return applyExtensions(client, ctx, ext);
|
|
1541
|
-
},
|
|
1542
|
-
async savepoint(fn) {
|
|
1543
|
-
const name = `sp_${++ctx.savepointCounter.value}`;
|
|
1544
|
-
await sql.raw(`SAVEPOINT ${name}`).execute(qb);
|
|
1545
|
-
try {
|
|
1546
|
-
const result = await fn(wrap(qb, ctx));
|
|
1547
|
-
await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb);
|
|
1548
|
-
return result;
|
|
1549
|
-
} catch (err) {
|
|
1550
|
-
await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb);
|
|
1551
|
-
throw err;
|
|
1552
|
-
}
|
|
1553
|
-
},
|
|
1554
|
-
async destroy() {
|
|
1555
|
-
await qb.destroy();
|
|
1556
|
-
}
|
|
1557
|
-
};
|
|
1558
|
-
return client;
|
|
1559
|
-
}
|
|
1560
|
-
//#endregion
|
|
1561
|
-
//#region src/client/create.ts
|
|
1562
|
-
function createDbClient(opts) {
|
|
1563
|
-
const events = opts.events || opts.slowQueryThresholdMs != null || opts.bus != null ? new KickDbEventEmitter() : null;
|
|
1564
|
-
const slowThreshold = opts.slowQueryThresholdMs ?? null;
|
|
1565
|
-
const bus = opts.bus ?? null;
|
|
1566
|
-
if (events && bus) {
|
|
1567
|
-
events.on("slowQuery", (payload) => {
|
|
1568
|
-
bus.emit("db:slow-query", payload);
|
|
1569
|
-
});
|
|
1570
|
-
events.on("queryError", (payload) => {
|
|
1571
|
-
bus.emit("db:query-error", payload);
|
|
1572
|
-
});
|
|
1573
|
-
}
|
|
1574
|
-
const decoders = buildDecoderMap(opts.schema);
|
|
1575
|
-
const encoders = buildEncoderMap(opts.schema);
|
|
1576
|
-
const codecPlugin = decoders.size > 0 || encoders.size > 0 ? new CodecPlugin(encoders, decoders) : null;
|
|
1577
|
-
return wrap(new Kysely({
|
|
1578
|
-
dialect: opts.dialect,
|
|
1579
|
-
plugins: codecPlugin ? [codecPlugin] : void 0,
|
|
1580
|
-
log: events ? (event) => {
|
|
1581
|
-
if (event.level === "query") {
|
|
1582
|
-
const durationMs = event.queryDurationMillis;
|
|
1583
|
-
const payload = {
|
|
1584
|
-
sql: event.query.sql,
|
|
1585
|
-
parameters: event.query.parameters,
|
|
1586
|
-
durationMs
|
|
1587
|
-
};
|
|
1588
|
-
events.emit("query", payload);
|
|
1589
|
-
if (slowThreshold != null && durationMs >= slowThreshold) events.emit("slowQuery", {
|
|
1590
|
-
...payload,
|
|
1591
|
-
thresholdMs: slowThreshold
|
|
1592
|
-
});
|
|
1593
|
-
} else if (event.level === "error") events.emit("queryError", {
|
|
1594
|
-
sql: event.query.sql,
|
|
1595
|
-
parameters: event.query.parameters,
|
|
1596
|
-
error: event.error
|
|
1597
|
-
});
|
|
1598
|
-
} : void 0
|
|
1599
|
-
}), {
|
|
1600
|
-
events,
|
|
1601
|
-
dialect: detectDialect(opts.dialect),
|
|
1602
|
-
savepointCounter: { value: 0 }
|
|
1603
|
-
});
|
|
1604
|
-
}
|
|
1605
|
-
function detectDialect(dialect) {
|
|
1606
|
-
const name = dialect.constructor?.name ?? "";
|
|
1607
|
-
if (name.includes("Postgres")) return "postgres";
|
|
1608
|
-
if (name.includes("Mysql") || name.includes("MySql")) return "mysql";
|
|
1609
|
-
return "sqlite";
|
|
1610
|
-
}
|
|
1611
|
-
//#endregion
|
|
1612
|
-
//#region src/emit/identifiers.ts
|
|
1613
|
-
function quoteIdent(name) {
|
|
1614
|
-
return name.split(".").map((part) => "\"" + part.replace(/"/g, "\"\"") + "\"").join(".");
|
|
1615
|
-
}
|
|
1616
|
-
function quoteLiteral(value) {
|
|
1617
|
-
return "'" + value.replace(/'/g, "''") + "'";
|
|
1618
|
-
}
|
|
1619
|
-
//#endregion
|
|
1620
|
-
//#region src/emit/pg.ts
|
|
1621
|
-
function emitPg(changes) {
|
|
1622
|
-
return changes.map(emitChange).join("\n");
|
|
1623
|
-
}
|
|
1624
|
-
function emitChange(change) {
|
|
1625
|
-
switch (change.kind) {
|
|
1626
|
-
case "createTable": return emitCreateTable(change.table);
|
|
1627
|
-
case "dropTable": return `DROP TABLE ${quoteIdent(change.table.name)};`;
|
|
1628
|
-
case "renameTable": return `ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`;
|
|
1629
|
-
case "addColumn": return emitAddColumn(change.table, change.column);
|
|
1630
|
-
case "dropColumn": return `ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`;
|
|
1631
|
-
case "renameColumn": return `ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`;
|
|
1632
|
-
case "alterColumn": return emitAlterColumn(change.table, change.before, change.after);
|
|
1633
|
-
case "addIndex": return emitAddIndex(change.table, change.index);
|
|
1634
|
-
case "dropIndex": return `DROP INDEX ${quoteIdent(change.index.name)};`;
|
|
1635
|
-
case "addForeignKey": return emitAddFk(change.table, change.fk);
|
|
1636
|
-
case "dropForeignKey": return `ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`;
|
|
1637
|
-
case "createEnum": {
|
|
1638
|
-
const values = change.enum.values.map((v) => quoteLiteral(v)).join(", ");
|
|
1639
|
-
return `CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`;
|
|
1640
|
-
}
|
|
1641
|
-
case "dropEnum": return `DROP TYPE ${quoteIdent(change.enum.name)};`;
|
|
1642
|
-
case "addEnumValue": {
|
|
1643
|
-
const before = change.before ? ` BEFORE ${quoteLiteral(change.before)}` : "";
|
|
1644
|
-
return `ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`;
|
|
1645
|
-
}
|
|
1646
|
-
case "removeEnumValue": return emitRemoveEnumValueAdvisory(change.enum, change.removed);
|
|
1647
|
-
}
|
|
1648
|
-
}
|
|
1649
|
-
/**
|
|
1650
|
-
* PostgreSQL has no `ALTER TYPE … DROP VALUE` — emitting silently
|
|
1651
|
-
* here would drop these values from the schema's intent without
|
|
1652
|
-
* reflecting in the database. Instead we render a multi-line SQL
|
|
1653
|
-
* comment with the manual migration steps the operator must take.
|
|
1654
|
-
*
|
|
1655
|
-
* The migration file still applies cleanly; the comment block makes
|
|
1656
|
-
* the missing operation visible in code review and in the generated
|
|
1657
|
-
* SQL output.
|
|
1658
|
-
*/
|
|
1659
|
-
function emitRemoveEnumValueAdvisory(name, removed) {
|
|
1660
|
-
const safeName = sanitizeForLineComment(quoteIdent(name));
|
|
1661
|
-
return [
|
|
1662
|
-
`-- WARNING: enum ${safeName} dropped value(s): ${removed.map((v) => sanitizeForLineComment(quoteLiteral(v))).join(", ")}.`,
|
|
1663
|
-
`-- PostgreSQL has no ALTER TYPE ... DROP VALUE. To round-trip this`,
|
|
1664
|
-
`-- removal you must:`,
|
|
1665
|
-
`-- 1. Drop or migrate every column whose type is ${safeName} (or any`,
|
|
1666
|
-
`-- composite that references it).`,
|
|
1667
|
-
`-- 2. DROP TYPE ${safeName};`,
|
|
1668
|
-
`-- 3. CREATE TYPE ${safeName} AS ENUM (...) with the new value list.`,
|
|
1669
|
-
`-- 4. Recreate the columns + restore data, mapping any rows that held`,
|
|
1670
|
-
`-- one of the dropped value(s) to a still-valid replacement first.`,
|
|
1671
|
-
`-- This migration emits no SQL for this change — write the steps above`,
|
|
1672
|
-
`-- by hand if the removal is intentional, or restore the value(s) in`,
|
|
1673
|
-
`-- the schema definition to silence this warning.`
|
|
1674
|
-
].join("\n");
|
|
1675
|
-
}
|
|
1676
|
-
/**
|
|
1677
|
-
* Make a value safe to interpolate into a single-line `--` SQL
|
|
1678
|
-
* comment. Identifiers and quoted literals normally don't carry
|
|
1679
|
-
* line breaks, but the user-supplied portion (enum name + values)
|
|
1680
|
-
* can contain anything an adopter passes to `pgEnum()`. A literal
|
|
1681
|
-
* `\n` would terminate the comment early and turn the rest of the
|
|
1682
|
-
* line into executable SQL.
|
|
1683
|
-
*
|
|
1684
|
-
* Scope of the sanitiser:
|
|
1685
|
-
* - Line-break code points (`\r`, `\n`, `U+2028`, `U+2029`) collapse
|
|
1686
|
-
* runs to a single space so the comment stays on one line.
|
|
1687
|
-
* - C0 control bytes excluding tab (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F)
|
|
1688
|
-
* plus DEL (0x7F) escape to `\x<hh>`.
|
|
1689
|
-
* - Tab (0x09) passes through — visually fine inside a `--` comment.
|
|
1690
|
-
*
|
|
1691
|
-
* Out of scope on purpose: C1 controls (U+0080-U+009F) and other
|
|
1692
|
-
* non-ASCII characters pass through unchanged. Adopters do legitimately
|
|
1693
|
-
* pass UTF-8 enum names + values (`'café'`, `'naïve'`); aggressively
|
|
1694
|
-
* escaping them would degrade the migration file's readability without
|
|
1695
|
-
* adding security — only line terminators can break out of a `--`
|
|
1696
|
-
* comment, and those are handled above.
|
|
1697
|
-
*/
|
|
1698
|
-
function sanitizeForLineComment(value) {
|
|
1699
|
-
let out = "";
|
|
1700
|
-
let prevWasLineBreak = false;
|
|
1701
|
-
for (let i = 0; i < value.length; i++) {
|
|
1702
|
-
const code = value.charCodeAt(i);
|
|
1703
|
-
if (code === 10 || code === 13 || code === 8232 || code === 8233) {
|
|
1704
|
-
if (!prevWasLineBreak) out += " ";
|
|
1705
|
-
prevWasLineBreak = true;
|
|
1706
|
-
continue;
|
|
1707
|
-
}
|
|
1708
|
-
prevWasLineBreak = false;
|
|
1709
|
-
if (code >= 0 && code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127) {
|
|
1710
|
-
out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
1711
|
-
continue;
|
|
1712
|
-
}
|
|
1713
|
-
out += value[i];
|
|
1714
|
-
}
|
|
1715
|
-
return out;
|
|
1716
|
-
}
|
|
1717
|
-
function emitAddColumn(table, c) {
|
|
1718
|
-
return `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`;
|
|
1719
|
-
}
|
|
1720
|
-
function emitAlterColumn(table, before, after) {
|
|
1721
|
-
const stmts = [];
|
|
1722
|
-
const t = quoteIdent(table);
|
|
1723
|
-
const c = quoteIdent(after.name);
|
|
1724
|
-
const typeChanged = before.type !== after.type;
|
|
1725
|
-
const nullChanged = before.nullable !== after.nullable;
|
|
1726
|
-
const defaultChanged = before.default !== after.default;
|
|
1727
|
-
const losingNotNull = !before.nullable && after.nullable;
|
|
1728
|
-
if (typeChanged) stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`);
|
|
1729
|
-
const emitDefault = () => {
|
|
1730
|
-
if (!defaultChanged) return;
|
|
1731
|
-
stmts.push(after.default === null ? `ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;` : `ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`);
|
|
1732
|
-
};
|
|
1733
|
-
const emitNullable = () => {
|
|
1734
|
-
if (!nullChanged) return;
|
|
1735
|
-
stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable ? "DROP NOT NULL" : "SET NOT NULL"};`);
|
|
1736
|
-
};
|
|
1737
|
-
if (losingNotNull) {
|
|
1738
|
-
emitDefault();
|
|
1739
|
-
emitNullable();
|
|
1740
|
-
} else {
|
|
1741
|
-
emitNullable();
|
|
1742
|
-
emitDefault();
|
|
1743
|
-
}
|
|
1744
|
-
return stmts.join("\n");
|
|
1745
|
-
}
|
|
1746
|
-
function emitAddIndex(table, i) {
|
|
1747
|
-
const cols = i.columns.map(quoteIdent).join(", ");
|
|
1748
|
-
return `CREATE${i.unique ? " UNIQUE" : ""} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`;
|
|
1749
|
-
}
|
|
1750
|
-
const FK_ACTIONS = {
|
|
1751
|
-
cascade: "CASCADE",
|
|
1752
|
-
restrict: "RESTRICT",
|
|
1753
|
-
set_null: "SET NULL",
|
|
1754
|
-
set_default: "SET DEFAULT",
|
|
1755
|
-
no_action: "NO ACTION"
|
|
1756
|
-
};
|
|
1757
|
-
function emitAddFk(table, fk) {
|
|
1758
|
-
const cols = fk.columns.map(quoteIdent).join(", ");
|
|
1759
|
-
const refCols = fk.refColumns.map(quoteIdent).join(", ");
|
|
1760
|
-
return `ALTER TABLE ${quoteIdent(table)} ADD CONSTRAINT ${quoteIdent(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${quoteIdent(fk.refTable)} (${refCols}) ON DELETE ${FK_ACTIONS[fk.onDelete]} ON UPDATE ${FK_ACTIONS[fk.onUpdate]};`;
|
|
1761
|
-
}
|
|
1762
|
-
function emitCreateTable(t) {
|
|
1763
|
-
const cols = Object.values(t.columns).map(emitColumnDecl);
|
|
1764
|
-
const pk = Object.values(t.columns).filter((c) => c.primaryKey).map((c) => quoteIdent(c.name));
|
|
1765
|
-
const lines = [...cols];
|
|
1766
|
-
if (pk.length > 0) lines.push(`PRIMARY KEY (${pk.join(", ")})`);
|
|
1767
|
-
return `CREATE TABLE ${quoteIdent(t.name)} (\n ${lines.join(",\n ")}\n);`;
|
|
1768
|
-
}
|
|
1769
|
-
function emitColumnDecl(c) {
|
|
1770
|
-
let s = `${quoteIdent(c.name)} ${c.type}`;
|
|
1771
|
-
if (!c.nullable) s += " NOT NULL";
|
|
1772
|
-
if (c.default !== null) s += ` DEFAULT ${formatDefault(c.default)}`;
|
|
1773
|
-
return s;
|
|
1774
|
-
}
|
|
1775
|
-
function formatDefault(value) {
|
|
1776
|
-
if (/^[A-Z_]+$/.test(value)) return value;
|
|
1777
|
-
if (/^[a-z_][a-z0-9_]*\s*\([^)]*\)$/i.test(value)) return value;
|
|
1778
|
-
if (/^-?\d+(\.\d+)?$/.test(value)) return value;
|
|
1779
|
-
if (value === "true" || value === "false") return value;
|
|
1780
|
-
return quoteLiteral(value);
|
|
1781
|
-
}
|
|
1782
|
-
//#endregion
|
|
1783
|
-
//#region src/cli/config.ts
|
|
1784
|
-
async function resolveDbConfig(opts) {
|
|
1785
|
-
const mod = await import(pathToFileURL(path.resolve(opts.configPath)).href);
|
|
1786
|
-
const db = (mod.default ?? mod)?.db ?? {};
|
|
1787
|
-
return {
|
|
1788
|
-
schemaPath: db.schemaPath ?? "src/db/schema.ts",
|
|
1789
|
-
migrationsDir: db.migrationsDir ?? "db/migrations",
|
|
1790
|
-
dialect: db.dialect ?? "postgres",
|
|
1791
|
-
connectionString: db.connectionString ?? process.env.DATABASE_URL,
|
|
1792
|
-
adapter: db.adapter
|
|
1793
|
-
};
|
|
1794
|
-
}
|
|
1795
|
-
//#endregion
|
|
1796
|
-
//#region src/cli/generate.ts
|
|
1797
|
-
async function generate(opts) {
|
|
1798
|
-
const migrationsAbs = path.resolve(opts.cwd, opts.config.migrationsDir);
|
|
1799
|
-
const { snapshot: prev, id: previousId } = await readLatestSnapshotEntry(migrationsAbs);
|
|
1800
|
-
if (opts.empty) return await writeMigration({
|
|
1801
|
-
opts,
|
|
1802
|
-
migrationsAbs,
|
|
1803
|
-
previousId,
|
|
1804
|
-
target: prev,
|
|
1805
|
-
upBody: "",
|
|
1806
|
-
downBody: "",
|
|
1807
|
-
changeCount: 0,
|
|
1808
|
-
draft: false,
|
|
1809
|
-
empty: true
|
|
1810
|
-
});
|
|
1811
|
-
const target = extractSnapshot(await import(pathToFileURL(path.resolve(opts.cwd, opts.config.schemaPath)).href), opts.config.dialect);
|
|
1812
|
-
const changes = diff(prev, target);
|
|
1813
|
-
if (changes.length === 0) return {
|
|
1814
|
-
status: "no-changes",
|
|
1815
|
-
changeCount: 0
|
|
1816
|
-
};
|
|
1817
|
-
return await writeMigration({
|
|
1818
|
-
opts,
|
|
1819
|
-
migrationsAbs,
|
|
1820
|
-
previousId,
|
|
1821
|
-
target,
|
|
1822
|
-
upBody: emitPg(changes),
|
|
1823
|
-
downBody: emitPg(invertChanges(changes)),
|
|
1824
|
-
changeCount: changes.length,
|
|
1825
|
-
draft: hasAmbiguousReverse(changes),
|
|
1826
|
-
empty: false
|
|
1827
|
-
});
|
|
1828
|
-
}
|
|
1829
|
-
async function writeMigration(p) {
|
|
1830
|
-
const id = formatId(p.opts.now?.() ?? /* @__PURE__ */ new Date(), p.opts.name);
|
|
1831
|
-
const dir = path.join(p.migrationsAbs, id);
|
|
1832
|
-
await mkdir(dir, { recursive: true });
|
|
1833
|
-
const upSql = "-- REVIEWED: false\n" + (p.empty ? "-- Empty migration — author SQL below (data migration, seed, etc).\n" : "") + p.upBody + (p.upBody ? "\n" : "");
|
|
1834
|
-
await writeFile(path.join(dir, "up.sql"), upSql, "utf8");
|
|
1835
|
-
const downHeader = "-- REVIEWED: false\n";
|
|
1836
|
-
const downDraft = p.draft ? "-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.\n" : "";
|
|
1837
|
-
const downHint = p.empty ? "-- Empty migration — author the reverse SQL here.\n" : "";
|
|
1838
|
-
const downSql = downHeader + downDraft + downHint + p.downBody + (p.downBody ? "\n" : "");
|
|
1839
|
-
await writeFile(path.join(dir, "down.sql"), downSql, "utf8");
|
|
1840
|
-
await writeFile(path.join(dir, "snapshot.json"), JSON.stringify(p.target, null, 2) + "\n", "utf8");
|
|
1841
|
-
await writeFile(path.join(dir, "meta.json"), JSON.stringify({
|
|
1842
|
-
id,
|
|
1843
|
-
name: p.opts.name,
|
|
1844
|
-
createdAt: (p.opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1845
|
-
reviewed: false,
|
|
1846
|
-
dialect: p.opts.config.dialect,
|
|
1847
|
-
previousId: p.previousId,
|
|
1848
|
-
downIsDraft: p.draft,
|
|
1849
|
-
empty: p.empty
|
|
1850
|
-
}, null, 2) + "\n", "utf8");
|
|
1851
|
-
const hash = await computeMigrationHash(dir);
|
|
1852
|
-
await appendJournalEntry(p.migrationsAbs, p.opts.config.dialect, {
|
|
1853
|
-
id,
|
|
1854
|
-
tag: p.opts.name,
|
|
1855
|
-
hash,
|
|
1856
|
-
createdAt: (p.opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
|
|
1857
|
-
});
|
|
1858
|
-
return {
|
|
1859
|
-
status: "created",
|
|
1860
|
-
migrationDir: dir,
|
|
1861
|
-
changeCount: p.changeCount,
|
|
1862
|
-
empty: p.empty
|
|
1863
|
-
};
|
|
1864
|
-
}
|
|
1865
|
-
async function readLatestSnapshotEntry(migrationsDir) {
|
|
1866
|
-
const empty = {
|
|
1867
|
-
version: 1,
|
|
1868
|
-
dialect: "postgres",
|
|
1869
|
-
tables: {}
|
|
1870
|
-
};
|
|
1871
|
-
if (!existsSync(migrationsDir)) return {
|
|
1872
|
-
snapshot: empty,
|
|
1873
|
-
id: null
|
|
1874
|
-
};
|
|
1875
|
-
const dirs = (await readdir(migrationsDir)).filter((e) => /^\d{8}_\d{6}_/.test(e)).toSorted();
|
|
1876
|
-
if (dirs.length === 0) return {
|
|
1877
|
-
snapshot: empty,
|
|
1878
|
-
id: null
|
|
1879
|
-
};
|
|
1880
|
-
const latest = dirs[dirs.length - 1];
|
|
1881
|
-
const file = path.join(migrationsDir, latest, "snapshot.json");
|
|
1882
|
-
return {
|
|
1883
|
-
snapshot: JSON.parse(await readFile(file, "utf8")),
|
|
1884
|
-
id: latest
|
|
1885
|
-
};
|
|
1886
|
-
}
|
|
1887
|
-
function formatId(date, name) {
|
|
1888
|
-
const pad = (n) => n.toString().padStart(2, "0");
|
|
1889
|
-
return `${date.getUTCFullYear().toString() + pad(date.getUTCMonth() + 1) + pad(date.getUTCDate()) + "_" + pad(date.getUTCHours()) + pad(date.getUTCMinutes()) + pad(date.getUTCSeconds())}_${name.replace(/[^a-z0-9]+/gi, "_").toLowerCase()}`;
|
|
1890
|
-
}
|
|
1891
|
-
//#endregion
|
|
1892
|
-
//#region src/dsl/columns/builders.ts
|
|
1893
|
-
/**
|
|
1894
|
-
* Type-level brand stamps. Runtime is identity; the cast attaches the
|
|
1895
|
-
* relevant brand so `SchemaToTypes<S>` reads them per column.
|
|
1896
|
-
*/
|
|
1897
|
-
function brandGenerated(col) {
|
|
1898
|
-
return col;
|
|
1899
|
-
}
|
|
1900
|
-
function brandNotNull(col) {
|
|
1901
|
-
return col;
|
|
1902
|
-
}
|
|
1903
|
-
function formatNumeric(base, precision, scale) {
|
|
1904
|
-
if (precision === void 0) return base;
|
|
1905
|
-
if (scale === void 0) return `${base}(${precision})`;
|
|
1906
|
-
return `${base}(${precision}, ${scale})`;
|
|
1907
|
-
}
|
|
1908
|
-
function serial() {
|
|
1909
|
-
return brandNotNull(brandGenerated(new ColumnBuilder("serial", { nullable: false })));
|
|
1910
|
-
}
|
|
1911
|
-
function bigSerial() {
|
|
1912
|
-
return brandNotNull(brandGenerated(new ColumnBuilder("bigserial", { nullable: false })));
|
|
1913
|
-
}
|
|
1914
|
-
function smallSerial() {
|
|
1915
|
-
return brandNotNull(brandGenerated(new ColumnBuilder("smallserial", { nullable: false })));
|
|
1916
|
-
}
|
|
1917
|
-
function integer() {
|
|
1918
|
-
return new ColumnBuilder("integer");
|
|
1919
|
-
}
|
|
1920
|
-
function bigint() {
|
|
1921
|
-
return new ColumnBuilder("bigint");
|
|
1922
|
-
}
|
|
1923
|
-
function smallint() {
|
|
1924
|
-
return new ColumnBuilder("smallint");
|
|
1925
|
-
}
|
|
1926
|
-
function decimal(precision, scale) {
|
|
1927
|
-
return new ColumnBuilder(formatNumeric("decimal", precision, scale));
|
|
1928
|
-
}
|
|
1929
|
-
function numeric(precision, scale) {
|
|
1930
|
-
return new ColumnBuilder(formatNumeric("numeric", precision, scale));
|
|
1931
|
-
}
|
|
1932
|
-
function real() {
|
|
1933
|
-
return new ColumnBuilder("real");
|
|
1934
|
-
}
|
|
1935
|
-
function doublePrecision() {
|
|
1936
|
-
return new ColumnBuilder("double precision");
|
|
1937
|
-
}
|
|
1938
|
-
function varchar(length = 255) {
|
|
1939
|
-
return new ColumnBuilder(`varchar(${length})`);
|
|
1940
|
-
}
|
|
1941
|
-
function char(length = 1) {
|
|
1942
|
-
return new ColumnBuilder(`char(${length})`);
|
|
1943
|
-
}
|
|
1944
|
-
function text() {
|
|
1945
|
-
return new ColumnBuilder("text");
|
|
1946
|
-
}
|
|
1947
|
-
function boolean() {
|
|
1948
|
-
return new ColumnBuilder("boolean");
|
|
1949
|
-
}
|
|
1950
|
-
/**
|
|
1951
|
-
* Subtype builder so `defaultNow()` can mark the resulting column as
|
|
1952
|
-
* generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter
|
|
1953
|
-
* omits the column on insert. Returns `this & GeneratedBrand` so the
|
|
1954
|
-
* subclass identity is preserved through the chain.
|
|
1955
|
-
*/
|
|
1956
|
-
var TimestampBuilder = class extends ColumnBuilder {
|
|
1957
|
-
constructor(typeName = "timestamp") {
|
|
1958
|
-
super(typeName);
|
|
1959
|
-
}
|
|
1960
|
-
defaultNow() {
|
|
1961
|
-
this.state.default = "CURRENT_TIMESTAMP";
|
|
1962
|
-
return brandGenerated(this);
|
|
1963
|
-
}
|
|
1964
|
-
};
|
|
1965
|
-
function timestamp() {
|
|
1966
|
-
return new TimestampBuilder("timestamp");
|
|
1967
|
-
}
|
|
1968
|
-
function timestamptz() {
|
|
1969
|
-
return new TimestampBuilder("timestamptz");
|
|
1970
|
-
}
|
|
1971
|
-
function date() {
|
|
1972
|
-
return new ColumnBuilder("date");
|
|
1973
|
-
}
|
|
1974
|
-
function time() {
|
|
1975
|
-
return new ColumnBuilder("time");
|
|
1976
|
-
}
|
|
1977
|
-
function interval() {
|
|
1978
|
-
return new ColumnBuilder("interval");
|
|
1979
|
-
}
|
|
1980
|
-
/**
|
|
1981
|
-
* Subtype builder so `defaultRandom()` can mark the resulting column as
|
|
1982
|
-
* generated — when the DB fills in `gen_random_uuid()` for omitted columns.
|
|
1983
|
-
* Returns `this & GeneratedBrand` so chaining works in either order:
|
|
1984
|
-
* uuid().defaultRandom().primaryKey()
|
|
1985
|
-
* uuid().primaryKey().defaultRandom() ← also works
|
|
1986
|
-
*/
|
|
1987
|
-
var UuidBuilder = class extends ColumnBuilder {
|
|
1988
|
-
constructor() {
|
|
1989
|
-
super("uuid");
|
|
1990
|
-
}
|
|
1991
|
-
defaultRandom() {
|
|
1992
|
-
this.state.default = "gen_random_uuid()";
|
|
1993
|
-
return brandGenerated(this);
|
|
1994
|
-
}
|
|
1995
|
-
};
|
|
1996
|
-
function uuid() {
|
|
1997
|
-
return new UuidBuilder();
|
|
1998
|
-
}
|
|
1999
|
-
/**
|
|
2000
|
-
* The `T` generic exists so adopters can declare their JSON shape:
|
|
2001
|
-
*
|
|
2002
|
-
* meta: jsonb<{ tags: string[] }>()
|
|
2003
|
-
*
|
|
2004
|
-
* `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the
|
|
2005
|
-
* row type narrows to `{ tags: string[] } | null`.
|
|
2006
|
-
*/
|
|
2007
|
-
function json() {
|
|
2008
|
-
return new ColumnBuilder("json");
|
|
2009
|
-
}
|
|
2010
|
-
function jsonb() {
|
|
2011
|
-
return new ColumnBuilder("jsonb");
|
|
2012
|
-
}
|
|
2013
|
-
function bytea() {
|
|
2014
|
-
return new ColumnBuilder("bytea");
|
|
2015
|
-
}
|
|
2016
|
-
//#endregion
|
|
2017
|
-
//#region src/dsl/table.ts
|
|
2018
|
-
/**
|
|
2019
|
-
* Declare a typed table. The `TName extends string` generic narrows to the
|
|
2020
|
-
* literal table name so `SchemaToTypes<S>` can index by it without losing
|
|
2021
|
-
* the constant — `table('users', …)` widens to `TableDecl<'users', …>`,
|
|
2022
|
-
* not `TableDecl<string, …>`.
|
|
2023
|
-
*/
|
|
2024
|
-
function table(name, columns, constraints) {
|
|
2025
|
-
const decl = {
|
|
2026
|
-
__isTable: true,
|
|
2027
|
-
__name: name,
|
|
2028
|
-
__columns: columns,
|
|
2029
|
-
__indexes: []
|
|
2030
|
-
};
|
|
2031
|
-
const refs = {};
|
|
2032
|
-
for (const [key, builder] of Object.entries(columns)) refs[key] = {
|
|
2033
|
-
__tableName: name,
|
|
2034
|
-
__name: key,
|
|
2035
|
-
__builder: builder,
|
|
2036
|
-
__state: () => builder.__state()
|
|
2037
|
-
};
|
|
2038
|
-
if (constraints) {
|
|
2039
|
-
const declared = constraints(refs);
|
|
2040
|
-
decl.__indexes = Object.values(declared);
|
|
2041
|
-
}
|
|
2042
|
-
return Object.assign(decl, refs);
|
|
2043
|
-
}
|
|
2044
|
-
//#endregion
|
|
2045
|
-
//#region src/dsl/constraints.ts
|
|
2046
|
-
function index(name) {
|
|
2047
|
-
return { on(...cols) {
|
|
2048
|
-
return {
|
|
2049
|
-
name,
|
|
2050
|
-
columns: cols.map((c) => c.__name),
|
|
2051
|
-
unique: false
|
|
2052
|
-
};
|
|
2053
|
-
} };
|
|
2054
|
-
}
|
|
2055
|
-
function unique(name) {
|
|
2056
|
-
return { on(...cols) {
|
|
2057
|
-
return {
|
|
2058
|
-
name,
|
|
2059
|
-
columns: cols.map((c) => c.__name),
|
|
2060
|
-
unique: true
|
|
2061
|
-
};
|
|
2062
|
-
} };
|
|
2063
|
-
}
|
|
2064
|
-
//#endregion
|
|
2065
|
-
//#region src/dsl/relations.ts
|
|
2066
|
-
function relations(source, builder) {
|
|
2067
|
-
return {
|
|
2068
|
-
__isRelations: true,
|
|
2069
|
-
__sourceTable: source.__name,
|
|
2070
|
-
__relations: builder({
|
|
2071
|
-
one: (target, opts) => ({
|
|
2072
|
-
kind: "one",
|
|
2073
|
-
target,
|
|
2074
|
-
fields: opts.fields,
|
|
2075
|
-
references: opts.references
|
|
2076
|
-
}),
|
|
2077
|
-
many: (target) => ({
|
|
2078
|
-
kind: "many",
|
|
2079
|
-
target
|
|
2080
|
-
})
|
|
2081
|
-
})
|
|
2082
|
-
};
|
|
2083
|
-
}
|
|
2084
|
-
//#endregion
|
|
2085
|
-
export { ColumnBuilder, CustomColumnBuilder, DB_CLIENT, DB_PRIMARY, DB_REPLICA, KICK_GENERATED, KICK_LOCK_TABLE, KICK_MIGRATIONS_TABLE, KICK_NOT_NULL, KickDbError, MemoryMigrationAdapter, MigrationDriftError, MigrationError, MigrationHashError, MigrationLockError, TimestampBuilder, UnreviewedMigrationError, UuidBuilder, appendJournalEntry, bigSerial, bigint, boolean, bytea, char, checkDrift, computeMigrationHash, createDbClient, customType, date, decimal, diff, doublePrecision, emitPg, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectPg, invertChanges, json, jsonb, kickDbAdapter, lockTableDdl, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, readJournal, real, relations, renderSchemaSource, resolveDbConfig, serial, smallSerial, smallint, table, text, time, timestamp, timestamptz, unique, uuid, varchar, verifyMigrationHash };
|
|
2086
|
-
|
|
100
|
+
ORDER BY tc.constraint_name, kcu.ordinal_position`,[schema,table]),byName=new Map;for(let r of rows.rows){let fk=byName.get(r.constraint_name);fk||(fk={name:r.constraint_name,columns:[],refTable:r.ref_table,refColumns:[],onDelete:mapFkAction(r.delete_rule),onUpdate:mapFkAction(r.update_rule)},byName.set(r.constraint_name,fk)),fk.columns.push(r.column_name),fk.refColumns.push(r.ref_column)}return[...byName.values()].toSorted((a,b)=>a.name.localeCompare(b.name))}function mapFkAction(raw){switch(raw.toUpperCase()){case`CASCADE`:return`cascade`;case`RESTRICT`:return`restrict`;case`SET NULL`:return`set_null`;case`SET DEFAULT`:return`set_default`;default:return`no_action`}}async function checkDrift(liveSnapshot,expectedSnapshot,behavior,log=console){if(behavior===`ignore`)return;let changes=diff(expectedSnapshot,liveSnapshot);if(changes.length===0)return;let summary=summarize(changes),message=`Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`;if(behavior===`warn`){log.warn(message);return}throw new MigrationDriftError(message,summary)}function summarize(changes){let added=[],removed=[],changed=[];for(let c of changes)switch(c.kind){case`createTable`:added.push(c.table.name);break;case`dropTable`:removed.push(c.table.name);break;case`addColumn`:added.push(`${c.table}.${c.column.name}`);break;case`dropColumn`:removed.push(`${c.table}.${c.column.name}`);break;case`alterColumn`:changed.push(`${c.table}.${c.column}`);break;case`renameColumn`:changed.push(`${c.table}.${c.from}→${c.to}`);break;case`renameTable`:changed.push(`${c.from}→${c.to}`);break;case`addIndex`:added.push(`${c.table}#${c.index.name}`);break;case`dropIndex`:removed.push(`${c.table}#${c.index.name}`);break;case`addForeignKey`:added.push(`${c.table}!${c.fk.name}`);break;case`dropForeignKey`:removed.push(`${c.table}!${c.fk.name}`);break}return{added,removed,changed}}async function withLock(opts,fn){let owner=opts.owner??`${process.pid}@${new Date().toISOString()}`;if(!await opts.adapter.acquireLock(owner))throw new MigrationLockError(`Another process holds the migration lock`);try{return await fn()}finally{await opts.adapter.releaseLock()}}async function verifyPending(pending,migrationsDir,requireReviewed){for(let entry of pending){let dir=path.join(migrationsDir,entry.id),actualHash=await computeMigrationHash(dir);if(actualHash!==entry.hash)throw new MigrationHashError(entry.id,entry.hash,actualHash);if(requireReviewed&&JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`)).reviewed!==!0)throw new UnreviewedMigrationError(entry.id)}}async function applyEntry(entry,batch,opts){let dir=path.join(opts.migrationsDir,entry.id),upSql=await readFile(path.join(dir,`up.sql`),`utf8`);JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`)).transaction===!1?await opts.adapter.applySqlNoTx(upSql):await opts.adapter.applySqlInTx(upSql),await opts.adapter.recordApplied({id:entry.id,name:entry.tag,hash:entry.hash,batch,direction:`up`})}async function runForward(opts,pending){if(pending.length===0)return{applied:[],batch:null};let requireReviewed=opts.requireReviewed??process.env.NODE_ENV!==`development`;await verifyPending(pending,opts.migrationsDir,requireReviewed);let applied=await opts.adapter.listApplied(),nextBatch=(applied.length===0?0:Math.max(...applied.map(r=>r.batch)))+1,ids=[];for(let entry of pending)await applyEntry(entry,nextBatch,opts),ids.push(entry.id);return{applied:ids,batch:nextBatch}}async function listPending(opts){let journal=await readJournal(opts.migrationsDir,opts.adapter.dialect),applied=await opts.adapter.listApplied(),appliedIds=new Set(applied.map(r=>r.id));return journal.entries.filter(e=>!appliedIds.has(e.id)).map(e=>({id:e.id,tag:e.tag,hash:e.hash}))}async function maybeCheckDrift(opts){let behavior=opts.driftCheck??`error`;if(behavior===`ignore`)return;let applied=await opts.adapter.listApplied();if(applied.length===0)return;let sorted=[...applied].toSorted((a,b)=>a.batch===b.batch?a.appliedAt.localeCompare(b.appliedAt):a.batch-b.batch),last=sorted[sorted.length-1],expected;try{expected=JSON.parse(await readFile(path.join(opts.migrationsDir,last.id,`snapshot.json`),`utf8`))}catch{return}await checkDrift(await opts.adapter.introspect(),expected,behavior,opts.log)}async function migrateLatest(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>(await maybeCheckDrift(opts),runForward(opts,await listPending(opts))))}async function migrateUp(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>(await maybeCheckDrift(opts),runForward(opts,(await listPending(opts)).slice(0,1))))}async function applyReverse(id,opts){let dir=path.join(opts.migrationsDir,id),downSql=await readFile(path.join(dir,`down.sql`),`utf8`),meta=JSON.parse(await readFile(path.join(dir,`meta.json`),`utf8`));if((opts.requireReviewed??process.env.NODE_ENV!==`development`)&&meta.reviewed!==!0)throw new UnreviewedMigrationError(id);meta.transaction===!1?await opts.adapter.applySqlNoTx(downSql):await opts.adapter.applySqlInTx(downSql),await opts.adapter.removeApplied(id)}async function migrateDown(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>{let applied=await opts.adapter.listApplied();if(applied.length===0)return{reversed:null};let sorted=[...applied].toSorted((a,b)=>a.batch===b.batch?a.appliedAt.localeCompare(b.appliedAt):a.batch-b.batch),last=sorted[sorted.length-1];return await applyReverse(last.id,opts),{reversed:last.id}})}async function migrateStatus(opts){await opts.adapter.ensureMigrationTables();let journal=await readJournal(opts.migrationsDir,opts.adapter.dialect),applied=await opts.adapter.listApplied(),byId=new Map(applied.map(r=>[r.id,r])),entries=[];for(let e of journal.entries){let row=byId.get(e.id),reviewed=!1;try{reviewed=JSON.parse(await readFile(path.join(opts.migrationsDir,e.id,`meta.json`),`utf8`)).reviewed===!0}catch{}entries.push({id:e.id,tag:e.tag,hash:e.hash,state:row?`applied`:`pending`,batch:row?.batch??null,appliedAt:row?.appliedAt??null,reviewed})}return entries}async function migrateRollback(opts){return await opts.adapter.ensureMigrationTables(),withLock(opts,async()=>{let applied=await opts.adapter.listApplied();if(applied.length===0)return{reversed:[],batch:null};let lastBatch=Math.max(...applied.map(r=>r.batch)),targets=applied.filter(r=>r.batch===lastBatch).toSorted((a,b)=>a.appliedAt.localeCompare(b.appliedAt)).toReversed(),reversed=[];for(let row of targets)await applyReverse(row.id,opts),reversed.push(row.id);return{reversed,batch:lastBatch}})}const kickDbAdapter=defineAdapter({name:`kickjs-db`,build:config=>({async beforeStart({container}){let policy=config.migrationsOnBoot??`fail-if-pending`,pending=(await migrateStatus({adapter:config.migrationAdapter,migrationsDir:config.migrationsDir})).filter(s=>s.state===`pending`);if(pending.length>0){if(policy===`fail-if-pending`)throw Error(`kickjs-db: ${pending.length} pending migration(s); run \`kick db migrate latest\` before boot`);if(policy===`apply`){let result=await migrateLatest({adapter:config.migrationAdapter,migrationsDir:config.migrationsDir,requireReviewed:config.requireReviewed,driftCheck:config.driftCheck});config.bus&&config.bus.emit(`db:migration-applied`,{applied:result.applied,batch:result.batch})}}config.token&&container.registerFactory(config.token,()=>config.migrationAdapter)},async shutdown(){await config.migrationAdapter.close()}})}),DB_PRIMARY=createToken(`kick/db/primary`),DB_REPLICA=createToken(`kick/db/replica`),DB_CLIENT=DB_PRIMARY;var KickDbEventEmitter=class{emitter=new EventEmitter;on(event,listener){this.emitter.on(event,listener)}off(event,listener){this.emitter.off(event,listener)}emit(event,payload){this.emitter.emit(event,payload)}},CustomColumnBuilder=class extends ColumnBuilder{toDriver;fromDriver;constructor(opts){super(opts.dataType()),this.toDriver=opts.toDriver,this.fromDriver=opts.fromDriver}};function customType(opts){return()=>new CustomColumnBuilder(opts)}var CodecPlugin=class{constructor(encoders,decoders){this.encoders=encoders,this.decoders=decoders}transformQuery(args){if(this.encoders.size===0)return args.node;let node=args.node;return InsertQueryNode.is(node)?this.transformInsert(node):UpdateQueryNode.is(node)?this.transformUpdate(node):node}async transformResult(args){if(this.decoders.size===0)return args.result;let rows=args.result.rows.map(row=>this.decodeRow(row));return{...args.result,rows}}transformInsert(node){let cols=node.columns,values=node.values;if(!cols||!values)return node;let positional=this.positionalEncoders(cols);if(!positional)return node;if(ValuesNode.is(values)){let items=values.values.map(item=>this.encodeValuesItem(item,positional));return items.some((item,i)=>item!==values.values[i])?InsertQueryNode.cloneWith(node,{values:ValuesNode.create(items)}):node}return node}transformUpdate(node){let updates=node.updates;if(!updates||updates.length===0)return node;let changed=!1,next=updates.map(u=>{let col=u.column;if(!ColumnNode.is(col))return u;let encoder=this.encoders.get(col.column.name);if(!encoder)return u;let encoded=this.encodeValueNode(u.value,encoder);return encoded===u.value?u:(changed=!0,ColumnUpdateNode.create(col,encoded))});return changed?{...node,updates:next}:node}positionalEncoders(cols){let out=Array.from({length:cols.length}),any=!1;for(let i=0;i<cols.length;i++){let enc=this.encoders.get(cols[i].column.name)??null;out[i]=enc,enc&&(any=!0)}return any?out:null}encodeValuesItem(item,positional){if(ValueListNode.is(item)){let next=item.values.map((v,i)=>{let enc=positional[i];return enc?this.encodeValueNode(v,enc):v});return next.some((v,i)=>v!==item.values[i])?ValueListNode.create(next):item}if(PrimitiveValueListNode.is(item)){let next=item.values.map((v,i)=>{let enc=positional[i];return enc?this.encodePrimitive(v,enc):v});return next.some((v,i)=>v!==item.values[i])?PrimitiveValueListNode.create(next):item}return item}encodeValueNode(node,encoder){if(!ValueNode.is(node))return node;let value=node.value;if(value==null)return node;let encoded=encoder(value);return encoded===value?node:ValueNode.create(encoded)}encodePrimitive(value,encoder){return value==null?value:encoder(value)}decodeRow(row){let mutated=!1,out={};for(let key of Object.keys(row)){let value=row[key],decoder=this.decoders.get(key);decoder&&value!=null?(out[key]=decoder(value),mutated=!0):out[key]=value}return mutated?out:row}};function buildDecoderMap(schema){return collectCodecs(schema,`fromDriver`)}function buildEncoderMap(schema){return collectCodecs(schema,`toDriver`)}function collectCodecs(schema,key){let out=new Map;if(!schema||typeof schema!=`object`)return out;for(let value of Object.values(schema))if(isTableDecl(value)){for(let[colName,col]of Object.entries(value.__columns))if(col instanceof CustomColumnBuilder){let fn=col[key];fn&&out.set(colName,fn)}}return out}function isTableDecl(value){return typeof value==`object`&&!!value&&value.__isTable===!0}var ResultExtensionPlugin=class{byTable;pending=new Map;constructor(extensions){this.byTable=new Map;for(let[tableName,bag]of Object.entries(extensions)){if(!bag)continue;let entries=Object.entries(bag);entries.length!==0&&this.byTable.set(tableName,Object.fromEntries(entries))}}transformQuery(args){let{node,queryId}=args;if(!SelectQueryNode.is(node))return node;let tableName=singleTableTarget(node);if(!tableName)return node;let bag=this.byTable.get(tableName);return bag?(this.pending.set(queryId,tableName),injectNeeds(node,bag)):node}async transformResult(args){let tableName=this.pending.get(args.queryId);if(!tableName)return args.result;this.pending.delete(args.queryId);let bag=this.byTable.get(tableName);if(!bag)return args.result;let computeds=Object.entries(bag);if(computeds.length===0)return args.result;let rows=args.result.rows.map(row=>{if(row==null)return row;let base=row,next={...base};for(let[key,ext]of computeds)try{next[key]=ext.compute(base)}catch{next[key]=void 0}return next});return{...args.result,rows}}};function singleTableTarget(node){let from=node.from;if(!from||from.froms.length!==1)return null;let target=unwrapAlias(from.froms[0]);return TableNode.is(target)?target.table.identifier.name:null}function unwrapAlias(node){return node.kind===`AliasNode`?node.node:node}function injectNeeds(node,bag){let selections=node.selections??[];if(selections.some(isSelectAll))return node;let have=new Set;for(let sel of selections){let inner=sel.selection;ReferenceNode.is(inner)&&ColumnNode.is(inner.column)?have.add(inner.column.column.name):ColumnNode.is(inner)&&have.add(inner.column.name)}let allNeeded=new Set;for(let ext of Object.values(bag))for(let col of Object.keys(ext.needs))allNeeded.add(col);let missing=[...allNeeded].filter(c=>!have.has(c));if(missing.length===0)return node;let additions=missing.map(col=>SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))));return SelectQueryNode.cloneWithSelections(node,additions)}function isSelectAll(node){let inner=node.selection;return!!(SelectAllNode.is(inner)||ReferenceNode.is(inner)&&SelectAllNode.is(inner.column))}function applyExtensions(client,ctx,ext){let baseClient=client;if(hasResultExtensions(ext.result)){let plugin=new ResultExtensionPlugin(ext.result);baseClient=wrap(client.qb.withPlugin(plugin),ctx)}let proxy,modelBag={},model=ext.model??{};for(let tableName of Object.keys(model)){let methods=model[tableName];if(!methods)continue;let bound={};for(let[methodName,fn]of Object.entries(methods))bound[methodName]=(...args)=>fn.call(proxy,...args);modelBag[tableName]=bound}return proxy=new Proxy(baseClient,{get(target,prop){return typeof prop==`string`&&Object.prototype.hasOwnProperty.call(modelBag,prop)?modelBag[prop]:target[prop]}}),proxy}function hasResultExtensions(result){if(!result||typeof result!=`object`)return!1;for(let bag of Object.values(result))if(bag&&typeof bag==`object`&&Object.keys(bag).length>0)return!0;return!1}function wrap(qb,ctx){let client={qb,dialect:ctx.dialect,selectFrom:qb.selectFrom.bind(qb),insertInto:qb.insertInto.bind(qb),updateTable:qb.updateTable.bind(qb),deleteFrom:qb.deleteFrom.bind(qb),on(event,listener){return ctx.events?.on(event,listener),client},off(event,listener){return ctx.events?.off(event,listener),client},transaction:((a,b)=>{let txOpts=typeof a==`function`?{}:a,fn=typeof a==`function`?a:b;return(async()=>{ctx.events?.emit(`transactionStart`,{isolation:txOpts.isolation});try{let result=await qb.transaction().execute(async tx=>{if(txOpts.isolation){let level=txOpts.isolation.toUpperCase();await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx)}return await fn(wrap(tx,ctx))});return ctx.events?.emit(`transactionCommit`,{isolation:txOpts.isolation}),result}catch(err){throw ctx.events?.emit(`transactionRollback`,{isolation:txOpts.isolation,error:err}),err}})()}),$extends(ext){return applyExtensions(client,ctx,ext)},async savepoint(fn){let name=`sp_${++ctx.savepointCounter.value}`;await sql.raw(`SAVEPOINT ${name}`).execute(qb);try{let result=await fn(wrap(qb,ctx));return await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb),result}catch(err){throw await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb),err}},async destroy(){await qb.destroy()}};return client}function createDbClient(opts){let events=opts.events||opts.slowQueryThresholdMs!=null||opts.bus!=null?new KickDbEventEmitter:null,slowThreshold=opts.slowQueryThresholdMs??null,bus=opts.bus??null;events&&bus&&(events.on(`slowQuery`,payload=>{bus.emit(`db:slow-query`,payload)}),events.on(`queryError`,payload=>{bus.emit(`db:query-error`,payload)}));let decoders=buildDecoderMap(opts.schema),encoders=buildEncoderMap(opts.schema),codecPlugin=decoders.size>0||encoders.size>0?new CodecPlugin(encoders,decoders):null;return wrap(new Kysely({dialect:opts.dialect,plugins:codecPlugin?[codecPlugin]:void 0,log:events?event=>{if(event.level===`query`){let durationMs=event.queryDurationMillis,payload={sql:event.query.sql,parameters:event.query.parameters,durationMs};events.emit(`query`,payload),slowThreshold!=null&&durationMs>=slowThreshold&&events.emit(`slowQuery`,{...payload,thresholdMs:slowThreshold})}else event.level===`error`&&events.emit(`queryError`,{sql:event.query.sql,parameters:event.query.parameters,error:event.error})}:void 0}),{events,dialect:detectDialect(opts.dialect),savepointCounter:{value:0}})}function detectDialect(dialect){let name=dialect.constructor?.name??``;return name.includes(`Postgres`)?`postgres`:name.includes(`Mysql`)||name.includes(`MySql`)?`mysql`:`sqlite`}function quoteIdent(name){return name.split(`.`).map(part=>`"`+part.replace(/"/g,`""`)+`"`).join(`.`)}function quoteLiteral(value){return`'`+value.replace(/'/g,`''`)+`'`}function emitPg(changes){return changes.map(emitChange).join(`
|
|
101
|
+
`)}function emitChange(change){switch(change.kind){case`createTable`:return emitCreateTable(change.table);case`dropTable`:return`DROP TABLE ${quoteIdent(change.table.name)};`;case`renameTable`:return`ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`;case`addColumn`:return emitAddColumn(change.table,change.column);case`dropColumn`:return`ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`;case`renameColumn`:return`ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`;case`alterColumn`:return emitAlterColumn(change.table,change.before,change.after);case`addIndex`:return emitAddIndex(change.table,change.index);case`dropIndex`:return`DROP INDEX ${quoteIdent(change.index.name)};`;case`addForeignKey`:return emitAddFk(change.table,change.fk);case`dropForeignKey`:return`ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`;case`createEnum`:{let values=change.enum.values.map(v=>quoteLiteral(v)).join(`, `);return`CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`}case`dropEnum`:return`DROP TYPE ${quoteIdent(change.enum.name)};`;case`addEnumValue`:{let before=change.before?` BEFORE ${quoteLiteral(change.before)}`:``;return`ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`}case`removeEnumValue`:return emitRemoveEnumValueAdvisory(change.enum,change.removed)}}function emitRemoveEnumValueAdvisory(name,removed){let safeName=sanitizeForLineComment(quoteIdent(name));return[`-- WARNING: enum ${safeName} dropped value(s): ${removed.map(v=>sanitizeForLineComment(quoteLiteral(v))).join(`, `)}.`,`-- PostgreSQL has no ALTER TYPE ... DROP VALUE. To round-trip this`,`-- removal you must:`,`-- 1. Drop or migrate every column whose type is ${safeName} (or any`,`-- composite that references it).`,`-- 2. DROP TYPE ${safeName};`,`-- 3. CREATE TYPE ${safeName} AS ENUM (...) with the new value list.`,`-- 4. Recreate the columns + restore data, mapping any rows that held`,`-- one of the dropped value(s) to a still-valid replacement first.`,`-- This migration emits no SQL for this change — write the steps above`,`-- by hand if the removal is intentional, or restore the value(s) in`,`-- the schema definition to silence this warning.`].join(`
|
|
102
|
+
`)}function sanitizeForLineComment(value){let out=``,prevWasLineBreak=!1;for(let i=0;i<value.length;i++){let code=value.charCodeAt(i);if(code===10||code===13||code===8232||code===8233){prevWasLineBreak||(out+=` `),prevWasLineBreak=!0;continue}if(prevWasLineBreak=!1,code>=0&&code<=8||code===11||code===12||code>=14&&code<=31||code===127){out+=`\\x${code.toString(16).padStart(2,`0`)}`;continue}out+=value[i]}return out}function emitAddColumn(table,c){return`ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`}function emitAlterColumn(table,before,after){let stmts=[],t=quoteIdent(table),c=quoteIdent(after.name),typeChanged=before.type!==after.type,nullChanged=before.nullable!==after.nullable,defaultChanged=before.default!==after.default,losingNotNull=!before.nullable&&after.nullable;typeChanged&&stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`);let emitDefault=()=>{defaultChanged&&stmts.push(after.default===null?`ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;`:`ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`)},emitNullable=()=>{nullChanged&&stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable?`DROP NOT NULL`:`SET NOT NULL`};`)};return losingNotNull?(emitDefault(),emitNullable()):(emitNullable(),emitDefault()),stmts.join(`
|
|
103
|
+
`)}function emitAddIndex(table,i){let cols=i.columns.map(quoteIdent).join(`, `);return`CREATE${i.unique?` UNIQUE`:``} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`}const FK_ACTIONS={cascade:`CASCADE`,restrict:`RESTRICT`,set_null:`SET NULL`,set_default:`SET DEFAULT`,no_action:`NO ACTION`};function emitAddFk(table,fk){let cols=fk.columns.map(quoteIdent).join(`, `),refCols=fk.refColumns.map(quoteIdent).join(`, `);return`ALTER TABLE ${quoteIdent(table)} ADD CONSTRAINT ${quoteIdent(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${quoteIdent(fk.refTable)} (${refCols}) ON DELETE ${FK_ACTIONS[fk.onDelete]} ON UPDATE ${FK_ACTIONS[fk.onUpdate]};`}function emitCreateTable(t){let cols=Object.values(t.columns).map(emitColumnDecl),pk=Object.values(t.columns).filter(c=>c.primaryKey).map(c=>quoteIdent(c.name)),lines=[...cols];return pk.length>0&&lines.push(`PRIMARY KEY (${pk.join(`, `)})`),`CREATE TABLE ${quoteIdent(t.name)} (\n ${lines.join(`,
|
|
104
|
+
`)}\n);`}function emitColumnDecl(c){let s=`${quoteIdent(c.name)} ${c.type}`;return c.nullable||(s+=` NOT NULL`),c.default!==null&&(s+=` DEFAULT ${formatDefault(c.default)}`),s}function formatDefault(value){return/^[A-Z_]+$/.test(value)||/^[a-z_][a-z0-9_]*\s*\([^)]*\)$/i.test(value)||/^-?\d+(\.\d+)?$/.test(value)||value===`true`||value===`false`?value:quoteLiteral(value)}async function resolveDbConfig(opts){let mod=await import(pathToFileURL(path.resolve(opts.configPath)).href),db=(mod.default??mod)?.db??{};return{schemaPath:db.schemaPath??`src/db/schema.ts`,migrationsDir:db.migrationsDir??`db/migrations`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter}}async function generate(opts){let migrationsAbs=path.resolve(opts.cwd,opts.config.migrationsDir),{snapshot:prev,id:previousId}=await readLatestSnapshotEntry(migrationsAbs);if(opts.empty)return await writeMigration({opts,migrationsAbs,previousId,target:prev,upBody:``,downBody:``,changeCount:0,draft:!1,empty:!0});let target=extractSnapshot(await import(pathToFileURL(path.resolve(opts.cwd,opts.config.schemaPath)).href),opts.config.dialect),changes=diff(prev,target);return changes.length===0?{status:`no-changes`,changeCount:0}:await writeMigration({opts,migrationsAbs,previousId,target,upBody:emitPg(changes),downBody:emitPg(invertChanges(changes)),changeCount:changes.length,draft:hasAmbiguousReverse(changes),empty:!1})}async function writeMigration(p){let id=formatId(p.opts.now?.()??new Date,p.opts.name),dir=path.join(p.migrationsAbs,id);await mkdir(dir,{recursive:!0});let upSql=`-- REVIEWED: false
|
|
105
|
+
`+(p.empty?`-- Empty migration — author SQL below (data migration, seed, etc).
|
|
106
|
+
`:``)+p.upBody+(p.upBody?`
|
|
107
|
+
`:``);await writeFile(path.join(dir,`up.sql`),upSql,`utf8`);let downDraft=p.draft?`-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.
|
|
108
|
+
`:``,downHint=p.empty?`-- Empty migration — author the reverse SQL here.
|
|
109
|
+
`:``,downSql=`-- REVIEWED: false
|
|
110
|
+
`+downDraft+downHint+p.downBody+(p.downBody?`
|
|
111
|
+
`:``);await writeFile(path.join(dir,`down.sql`),downSql,`utf8`),await writeFile(path.join(dir,`snapshot.json`),JSON.stringify(p.target,null,2)+`
|
|
112
|
+
`,`utf8`),await writeFile(path.join(dir,`meta.json`),JSON.stringify({id,name:p.opts.name,createdAt:(p.opts.now?.()??new Date).toISOString(),reviewed:!1,dialect:p.opts.config.dialect,previousId:p.previousId,downIsDraft:p.draft,empty:p.empty},null,2)+`
|
|
113
|
+
`,`utf8`);let hash=await computeMigrationHash(dir);return await appendJournalEntry(p.migrationsAbs,p.opts.config.dialect,{id,tag:p.opts.name,hash,createdAt:(p.opts.now?.()??new Date).toISOString()}),{status:`created`,migrationDir:dir,changeCount:p.changeCount,empty:p.empty}}async function readLatestSnapshotEntry(migrationsDir){let empty={version:1,dialect:`postgres`,tables:{}};if(!existsSync(migrationsDir))return{snapshot:empty,id:null};let dirs=(await readdir(migrationsDir)).filter(e=>/^\d{8}_\d{6}_/.test(e)).toSorted();if(dirs.length===0)return{snapshot:empty,id:null};let latest=dirs[dirs.length-1],file=path.join(migrationsDir,latest,`snapshot.json`);return{snapshot:JSON.parse(await readFile(file,`utf8`)),id:latest}}function formatId(date,name){let pad=n=>n.toString().padStart(2,`0`);return`${date.getUTCFullYear().toString()+pad(date.getUTCMonth()+1)+pad(date.getUTCDate())+`_`+pad(date.getUTCHours())+pad(date.getUTCMinutes())+pad(date.getUTCSeconds())}_${name.replace(/[^a-z0-9]+/gi,`_`).toLowerCase()}`}function brandGenerated(col){return col}function brandNotNull(col){return col}function formatNumeric(base,precision,scale){return precision===void 0?base:scale===void 0?`${base}(${precision})`:`${base}(${precision}, ${scale})`}function serial(){return brandNotNull(brandGenerated(new ColumnBuilder(`serial`,{nullable:!1})))}function bigSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`bigserial`,{nullable:!1})))}function smallSerial(){return brandNotNull(brandGenerated(new ColumnBuilder(`smallserial`,{nullable:!1})))}function integer(){return new ColumnBuilder(`integer`)}function bigint(){return new ColumnBuilder(`bigint`)}function smallint(){return new ColumnBuilder(`smallint`)}function decimal(precision,scale){return new ColumnBuilder(formatNumeric(`decimal`,precision,scale))}function numeric(precision,scale){return new ColumnBuilder(formatNumeric(`numeric`,precision,scale))}function real(){return new ColumnBuilder(`real`)}function doublePrecision(){return new ColumnBuilder(`double precision`)}function varchar(length=255){return new ColumnBuilder(`varchar(${length})`)}function char(length=1){return new ColumnBuilder(`char(${length})`)}function text(){return new ColumnBuilder(`text`)}function boolean(){return new ColumnBuilder(`boolean`)}var TimestampBuilder=class extends ColumnBuilder{constructor(typeName=`timestamp`){super(typeName)}defaultNow(){return this.state.default=`CURRENT_TIMESTAMP`,brandGenerated(this)}};function timestamp(){return new TimestampBuilder(`timestamp`)}function timestamptz(){return new TimestampBuilder(`timestamptz`)}function date(){return new ColumnBuilder(`date`)}function time(){return new ColumnBuilder(`time`)}function interval(){return new ColumnBuilder(`interval`)}var UuidBuilder=class extends ColumnBuilder{constructor(){super(`uuid`)}defaultRandom(){return this.state.default=`gen_random_uuid()`,brandGenerated(this)}};function uuid(){return new UuidBuilder}function json(){return new ColumnBuilder(`json`)}function jsonb(){return new ColumnBuilder(`jsonb`)}function bytea(){return new ColumnBuilder(`bytea`)}function table(name,columns,constraints){let decl={__isTable:!0,__name:name,__columns:columns,__indexes:[]},refs={};for(let[key,builder]of Object.entries(columns))refs[key]={__tableName:name,__name:key,__builder:builder,__state:()=>builder.__state()};if(constraints){let declared=constraints(refs);decl.__indexes=Object.values(declared)}return Object.assign(decl,refs)}function index(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!1}}}}function unique(name){return{on(...cols){return{name,columns:cols.map(c=>c.__name),unique:!0}}}}function relations(source,builder){return{__isRelations:!0,__sourceTable:source.__name,__relations:builder({one:(target,opts)=>({kind:`one`,target,fields:opts.fields,references:opts.references}),many:target=>({kind:`many`,target})})}}export{ColumnBuilder,CustomColumnBuilder,DB_CLIENT,DB_PRIMARY,DB_REPLICA,KICK_GENERATED,KICK_LOCK_TABLE,KICK_MIGRATIONS_TABLE,KICK_NOT_NULL,KickDbError,MemoryMigrationAdapter,MigrationDriftError,MigrationError,MigrationHashError,MigrationLockError,TimestampBuilder,UnreviewedMigrationError,UuidBuilder,appendJournalEntry,bigSerial,bigint,boolean,bytea,char,checkDrift,computeMigrationHash,createDbClient,customType,date,decimal,diff,doublePrecision,emitPg,extractSnapshot,generate,hasAmbiguousReverse,index,integer,interval,introspectPg,invertChanges,json,jsonb,kickDbAdapter,lockTableDdl,migrateDown,migrateLatest,migrateRollback,migrateStatus,migrateUp,migrationsTableDdl,numeric,readJournal,real,relations,renderSchemaSource,resolveDbConfig,serial,smallSerial,smallint,table,text,time,timestamp,timestamptz,unique,uuid,varchar,verifyMigrationHash};
|
|
2087
114
|
//# sourceMappingURL=index.mjs.map
|