@forinda/kickjs-db 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1793 @@
1
+ /**
2
+ * @forinda/kickjs-db v5.1.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import { n as KICK_GENERATED, r as KICK_NOT_NULL, t as ColumnBuilder } from "./types-BcfY4esK.mjs";
12
+ import { createHash } from "node:crypto";
13
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
14
+ import { existsSync } from "node:fs";
15
+ import path from "node:path";
16
+ import { createToken, defineAdapter } from "@forinda/kickjs";
17
+ import { Kysely, sql } from "kysely";
18
+ import { EventEmitter } from "node:events";
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).sort()];
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 nextValueList = e.values;
314
+ for (let i = 0; i < nextValueList.length; i++) {
315
+ const value = nextValueList[i];
316
+ if (priorValues.has(value)) continue;
317
+ const before = nextValueList[i + 1];
318
+ const beforeIsExisting = before != null && priorValues.has(before);
319
+ changes.push({
320
+ kind: "addEnumValue",
321
+ enum: name,
322
+ value,
323
+ ...beforeIsExisting ? { before } : {}
324
+ });
325
+ }
326
+ }
327
+ }
328
+ function diffEnumsDropPhase(prev, next, changes) {
329
+ const prevEnums = prev.enums ?? {};
330
+ const nextEnums = next.enums ?? {};
331
+ for (const [name, e] of Object.entries(prevEnums)) {
332
+ if (nextEnums[name]) continue;
333
+ changes.push({
334
+ kind: "dropEnum",
335
+ enum: e
336
+ });
337
+ }
338
+ }
339
+ function diffTable(prev, next, changes) {
340
+ const prevCols = new Map(Object.entries(prev.columns));
341
+ const nextCols = new Map(Object.entries(next.columns));
342
+ const drops = [];
343
+ const adds = [];
344
+ for (const c of prevCols.keys()) if (!nextCols.has(c)) drops.push(c);
345
+ for (const c of nextCols.keys()) if (!prevCols.has(c)) adds.push(c);
346
+ if (drops.length === 1 && adds.length === 1) {
347
+ if (columnAttrsEqual(prevCols.get(drops[0]), nextCols.get(adds[0]))) {
348
+ changes.push({
349
+ kind: "renameColumn",
350
+ table: next.name,
351
+ from: drops[0],
352
+ to: adds[0]
353
+ });
354
+ drops.length = 0;
355
+ adds.length = 0;
356
+ }
357
+ }
358
+ for (const c of drops) changes.push({
359
+ kind: "dropColumn",
360
+ table: next.name,
361
+ column: prevCols.get(c)
362
+ });
363
+ for (const c of adds) changes.push({
364
+ kind: "addColumn",
365
+ table: next.name,
366
+ column: nextCols.get(c)
367
+ });
368
+ for (const c of nextCols.keys()) {
369
+ if (!prevCols.has(c)) continue;
370
+ const before = prevCols.get(c);
371
+ const after = nextCols.get(c);
372
+ if (!columnsEqual(before, after)) changes.push({
373
+ kind: "alterColumn",
374
+ table: next.name,
375
+ column: c,
376
+ before,
377
+ after
378
+ });
379
+ }
380
+ diffByName(prev.indexes, next.indexes, (i) => changes.push({
381
+ kind: "dropIndex",
382
+ table: next.name,
383
+ index: i
384
+ }), (i) => changes.push({
385
+ kind: "addIndex",
386
+ table: next.name,
387
+ index: i
388
+ }));
389
+ diffByName(prev.foreignKeys, next.foreignKeys, (f) => changes.push({
390
+ kind: "dropForeignKey",
391
+ table: next.name,
392
+ fk: f
393
+ }), (f) => changes.push({
394
+ kind: "addForeignKey",
395
+ table: next.name,
396
+ fk: f
397
+ }));
398
+ }
399
+ function diffByName(prev, next, onDrop, onAdd) {
400
+ const prevByName = new Map(prev.map((p) => [p.name, p]));
401
+ const nextByName = new Map(next.map((n) => [n.name, n]));
402
+ for (const [n, p] of prevByName) if (!nextByName.has(n)) onDrop(p);
403
+ for (const [n, x] of nextByName) if (!prevByName.has(n)) onAdd(x);
404
+ }
405
+ function columnsEqual(a, b) {
406
+ return a.type === b.type && a.nullable === b.nullable && a.default === b.default && a.primaryKey === b.primaryKey;
407
+ }
408
+ function columnAttrsEqual(a, b) {
409
+ return a.type === b.type && a.nullable === b.nullable && a.default === b.default && a.primaryKey === b.primaryKey;
410
+ }
411
+ //#endregion
412
+ //#region src/diff/invert.ts
413
+ /**
414
+ * Reverse a forward ChangeSet so emitting it produces the SQL that undoes
415
+ * the forward migration.
416
+ *
417
+ * The reverse of an *unambiguous* change is exact (rename → rename swapped,
418
+ * add → drop, drop → add). The reverse of an *ambiguous* change (drop column,
419
+ * drop table, type widen, NOT NULL gain without default) is a defensible
420
+ * best-effort derived from the snapshot the forward change carried — the
421
+ * runner refuses to apply a non-reviewed migration in non-dev so the operator
422
+ * always sees the draft before it touches a DB.
423
+ *
424
+ * The order is reversed too: drop FK before drop index before drop table is
425
+ * the safe sequence for tearing down what create-FK / create-index / create-
426
+ * table built up.
427
+ */
428
+ function invertChanges(forward) {
429
+ const reversed = [];
430
+ for (const change of forward) reversed.push(invert(change));
431
+ return reversed.reverse();
432
+ }
433
+ function invert(change) {
434
+ switch (change.kind) {
435
+ case "createTable": return {
436
+ kind: "dropTable",
437
+ table: change.table
438
+ };
439
+ case "dropTable": return {
440
+ kind: "createTable",
441
+ table: change.table
442
+ };
443
+ case "renameTable": return {
444
+ kind: "renameTable",
445
+ from: change.to,
446
+ to: change.from
447
+ };
448
+ case "addColumn": return {
449
+ kind: "dropColumn",
450
+ table: change.table,
451
+ column: change.column
452
+ };
453
+ case "dropColumn": return {
454
+ kind: "addColumn",
455
+ table: change.table,
456
+ column: change.column
457
+ };
458
+ case "renameColumn": return {
459
+ kind: "renameColumn",
460
+ table: change.table,
461
+ from: change.to,
462
+ to: change.from
463
+ };
464
+ case "alterColumn": return {
465
+ kind: "alterColumn",
466
+ table: change.table,
467
+ column: change.column,
468
+ before: change.after,
469
+ after: change.before
470
+ };
471
+ case "addIndex": return {
472
+ kind: "dropIndex",
473
+ table: change.table,
474
+ index: change.index
475
+ };
476
+ case "dropIndex": return {
477
+ kind: "addIndex",
478
+ table: change.table,
479
+ index: change.index
480
+ };
481
+ case "addForeignKey": return {
482
+ kind: "dropForeignKey",
483
+ table: change.table,
484
+ fk: change.fk
485
+ };
486
+ case "dropForeignKey": return {
487
+ kind: "addForeignKey",
488
+ table: change.table,
489
+ fk: change.fk
490
+ };
491
+ case "createEnum": return {
492
+ kind: "dropEnum",
493
+ enum: change.enum
494
+ };
495
+ case "dropEnum": return {
496
+ kind: "createEnum",
497
+ enum: change.enum
498
+ };
499
+ case "addEnumValue": return change;
500
+ }
501
+ }
502
+ /**
503
+ * Returns the change kinds that produce ambiguous reverses — drop column,
504
+ * drop table, type widen — so the generator can flag the down.sql as a draft
505
+ * even if every individual statement is technically valid SQL.
506
+ */
507
+ const AMBIGUOUS_REVERSE_KINDS = new Set([
508
+ "dropTable",
509
+ "dropColumn",
510
+ "alterColumn",
511
+ "addEnumValue"
512
+ ]);
513
+ function hasAmbiguousReverse(forward) {
514
+ return forward.some((c) => AMBIGUOUS_REVERSE_KINDS.has(c.kind));
515
+ }
516
+ //#endregion
517
+ //#region src/errors.ts
518
+ var KickDbError = class extends Error {
519
+ code;
520
+ constructor(code, message) {
521
+ super(message);
522
+ this.name = this.constructor.name;
523
+ this.code = code;
524
+ }
525
+ };
526
+ //#endregion
527
+ //#region src/migrate/errors.ts
528
+ var MigrationError = class extends KickDbError {};
529
+ var MigrationLockError = class extends MigrationError {
530
+ constructor(message) {
531
+ super("migration_lock_held", message);
532
+ }
533
+ };
534
+ var MigrationDriftError = class extends MigrationError {
535
+ diff;
536
+ constructor(message, diff) {
537
+ super("migration_drift", message);
538
+ this.diff = diff;
539
+ }
540
+ };
541
+ var MigrationHashError = class extends MigrationError {
542
+ id;
543
+ expected;
544
+ actual;
545
+ constructor(id, expected, actual) {
546
+ super("migration_hash_mismatch", `Hash mismatch for migration ${id}`);
547
+ this.id = id;
548
+ this.expected = expected;
549
+ this.actual = actual;
550
+ }
551
+ };
552
+ var UnreviewedMigrationError = class extends MigrationError {
553
+ id;
554
+ constructor(id) {
555
+ super("migration_unreviewed", `Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`);
556
+ this.id = id;
557
+ }
558
+ };
559
+ //#endregion
560
+ //#region src/migrate/journal.ts
561
+ const FILE = "_journal.json";
562
+ async function readJournal(migrationsDir, dialect) {
563
+ const file = path.join(migrationsDir, FILE);
564
+ if (!existsSync(file)) return {
565
+ version: 1,
566
+ dialect,
567
+ entries: []
568
+ };
569
+ const raw = JSON.parse(await readFile(file, "utf8"));
570
+ if (raw.version !== 1) throw new Error(`_journal.json version ${raw.version} unsupported (expected 1)`);
571
+ return raw;
572
+ }
573
+ async function appendJournalEntry(migrationsDir, dialect, entry) {
574
+ const j = await readJournal(migrationsDir, dialect);
575
+ j.entries.push(entry);
576
+ await writeFile(path.join(migrationsDir, FILE), JSON.stringify(j, null, 2) + "\n", "utf8");
577
+ }
578
+ async function computeMigrationHash(migrationDir) {
579
+ const up = await readFile(path.join(migrationDir, "up.sql"), "utf8");
580
+ const down = await readFile(path.join(migrationDir, "down.sql"), "utf8");
581
+ const snap = await readFile(path.join(migrationDir, "snapshot.json"), "utf8");
582
+ return `sha256:${createHash("sha256").update(up).update("|").update(down).update("|").update(snap).digest("hex")}`;
583
+ }
584
+ async function verifyMigrationHash(migrationDir, expected) {
585
+ return await computeMigrationHash(migrationDir) === expected;
586
+ }
587
+ //#endregion
588
+ //#region src/migrate/schema.ts
589
+ const KICK_MIGRATIONS_TABLE = "kick_migrations";
590
+ const KICK_LOCK_TABLE = "kick_migrations_lock";
591
+ function migrationsTableDdl(dialect) {
592
+ switch (dialect) {
593
+ case "postgres": return `CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
594
+ "id" varchar(128) PRIMARY KEY,
595
+ "name" text NOT NULL,
596
+ "hash" text NOT NULL,
597
+ "batch" integer NOT NULL,
598
+ "applied_at" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
599
+ "direction" varchar(8) NOT NULL DEFAULT 'up'
600
+ );
601
+ CREATE INDEX IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}_batch_idx" ON "${KICK_MIGRATIONS_TABLE}" ("batch");`;
602
+ case "sqlite": return `CREATE TABLE IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}" (
603
+ "id" text PRIMARY KEY,
604
+ "name" text NOT NULL,
605
+ "hash" text NOT NULL,
606
+ "batch" integer NOT NULL,
607
+ "applied_at" text NOT NULL DEFAULT (datetime('now')),
608
+ "direction" text NOT NULL DEFAULT 'up'
609
+ );
610
+ CREATE INDEX IF NOT EXISTS "${KICK_MIGRATIONS_TABLE}_batch_idx" ON "${KICK_MIGRATIONS_TABLE}" ("batch");`;
611
+ case "mysql": return `CREATE TABLE IF NOT EXISTS \`${KICK_MIGRATIONS_TABLE}\` (
612
+ \`id\` varchar(128) PRIMARY KEY,
613
+ \`name\` text NOT NULL,
614
+ \`hash\` text NOT NULL,
615
+ \`batch\` int NOT NULL,
616
+ \`applied_at\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
617
+ \`direction\` varchar(8) NOT NULL DEFAULT 'up',
618
+ INDEX \`${KICK_MIGRATIONS_TABLE}_batch_idx\` (\`batch\`)
619
+ );`;
620
+ }
621
+ }
622
+ function lockTableDdl(dialect) {
623
+ switch (dialect) {
624
+ case "postgres": return `CREATE TABLE IF NOT EXISTS "${KICK_LOCK_TABLE}" (
625
+ "id" smallint PRIMARY KEY,
626
+ "locked_at" timestamptz,
627
+ "locked_by" text
628
+ );
629
+ INSERT INTO "${KICK_LOCK_TABLE}" ("id") VALUES (1) ON CONFLICT DO NOTHING;`;
630
+ case "sqlite": return `CREATE TABLE IF NOT EXISTS "${KICK_LOCK_TABLE}" (
631
+ "id" integer PRIMARY KEY,
632
+ "locked_at" text,
633
+ "locked_by" text
634
+ );
635
+ INSERT OR IGNORE INTO "${KICK_LOCK_TABLE}" ("id") VALUES (1);`;
636
+ case "mysql": return `CREATE TABLE IF NOT EXISTS \`${KICK_LOCK_TABLE}\` (
637
+ \`id\` smallint PRIMARY KEY,
638
+ \`locked_at\` timestamp NULL,
639
+ \`locked_by\` text
640
+ );
641
+ INSERT IGNORE INTO \`${KICK_LOCK_TABLE}\` (\`id\`) VALUES (1);`;
642
+ }
643
+ }
644
+ //#endregion
645
+ //#region src/migrate/memory-adapter.ts
646
+ /**
647
+ * In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-
648
+ * holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as
649
+ * test-only stubs — the real DB-bound semantics are validated in db-pg's
650
+ * integration tests, not here.
651
+ */
652
+ var MemoryMigrationAdapter = class {
653
+ dialect = "postgres";
654
+ rows = [];
655
+ locked = null;
656
+ appliedSql = [];
657
+ currentSchema = {
658
+ version: 1,
659
+ dialect: "postgres",
660
+ tables: {}
661
+ };
662
+ async ensureMigrationTables() {}
663
+ async listApplied() {
664
+ return [...this.rows];
665
+ }
666
+ async recordApplied(row) {
667
+ this.rows.push({
668
+ ...row,
669
+ appliedAt: (/* @__PURE__ */ new Date()).toISOString()
670
+ });
671
+ }
672
+ async removeApplied(id) {
673
+ this.rows = this.rows.filter((r) => r.id !== id);
674
+ }
675
+ async acquireLock(owner) {
676
+ if (this.locked) return false;
677
+ this.locked = {
678
+ by: owner,
679
+ at: (/* @__PURE__ */ new Date()).toISOString()
680
+ };
681
+ return true;
682
+ }
683
+ async releaseLock() {
684
+ this.locked = null;
685
+ }
686
+ async applySqlInTx(sql) {
687
+ this.appliedSql.push(sql);
688
+ }
689
+ async applySqlNoTx(sql) {
690
+ this.appliedSql.push(sql);
691
+ }
692
+ async introspect() {
693
+ return this.currentSchema;
694
+ }
695
+ async close() {}
696
+ /** Test-only setter — let drift tests stage a "live" schema state. */
697
+ __setIntrospectedSchema(snap) {
698
+ this.currentSchema = snap;
699
+ }
700
+ /** Test-only inspector — what SQL we received. */
701
+ __appliedSql() {
702
+ return this.appliedSql;
703
+ }
704
+ };
705
+ //#endregion
706
+ //#region src/migrate/introspect-pg.ts
707
+ const DEFAULT_EXCLUDED = ["kick_migrations", "kick_migrations_lock"];
708
+ async function introspectPg(client, opts = {}) {
709
+ const schema = opts.schema ?? "public";
710
+ const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED;
711
+ const tableRows = await client.query(`SELECT table_name
712
+ FROM information_schema.tables
713
+ WHERE table_schema = $1 AND table_type = 'BASE TABLE'
714
+ ORDER BY table_name`, [schema]);
715
+ const tables = {};
716
+ for (const t of tableRows.rows) {
717
+ if (excluded.includes(t.table_name)) continue;
718
+ tables[t.table_name] = {
719
+ name: t.table_name,
720
+ columns: await readColumns(client, schema, t.table_name),
721
+ indexes: await readIndexes(client, schema, t.table_name),
722
+ foreignKeys: await readForeignKeys(client, schema, t.table_name),
723
+ checks: []
724
+ };
725
+ }
726
+ return {
727
+ version: 1,
728
+ dialect: "postgres",
729
+ tables
730
+ };
731
+ }
732
+ async function readColumns(client, schema, table) {
733
+ const cols = await client.query(`SELECT column_name, data_type, udt_name, is_nullable, column_default,
734
+ character_maximum_length, numeric_precision, numeric_scale
735
+ FROM information_schema.columns
736
+ WHERE table_schema = $1 AND table_name = $2
737
+ ORDER BY ordinal_position`, [schema, table]);
738
+ const pkCols = await client.query(`SELECT k.column_name
739
+ FROM information_schema.table_constraints c
740
+ JOIN information_schema.key_column_usage k
741
+ ON k.constraint_name = c.constraint_name
742
+ AND k.table_schema = c.table_schema
743
+ WHERE c.table_schema = $1 AND c.table_name = $2 AND c.constraint_type = 'PRIMARY KEY'
744
+ ORDER BY k.ordinal_position`, [schema, table]);
745
+ const pkSet = new Set(pkCols.rows.map((r) => r.column_name));
746
+ const out = {};
747
+ for (const r of cols.rows) {
748
+ const isSerial = isSerialColumn(r);
749
+ out[r.column_name] = {
750
+ name: r.column_name,
751
+ type: isSerial ? serialTypeFor(r) : normalizeType(r),
752
+ nullable: r.is_nullable === "YES",
753
+ default: isSerial ? null : normalizeDefault(r.column_default),
754
+ primaryKey: pkSet.has(r.column_name)
755
+ };
756
+ }
757
+ return out;
758
+ }
759
+ function isSerialColumn(r) {
760
+ if (!r.column_default) return false;
761
+ if (!/^nextval\(/.test(r.column_default)) return false;
762
+ return r.udt_name === "int2" || r.udt_name === "int4" || r.udt_name === "int8";
763
+ }
764
+ function serialTypeFor(r) {
765
+ if (r.udt_name === "int8") return "bigserial";
766
+ if (r.udt_name === "int2") return "smallserial";
767
+ return "serial";
768
+ }
769
+ function normalizeType(r) {
770
+ if (r.data_type === "character varying") return r.character_maximum_length ? `varchar(${r.character_maximum_length})` : "varchar";
771
+ if (r.data_type === "character") return r.character_maximum_length ? `char(${r.character_maximum_length})` : "char(1)";
772
+ if (r.data_type === "numeric") {
773
+ if (r.numeric_precision !== null && r.numeric_scale !== null) return `numeric(${r.numeric_precision}, ${r.numeric_scale})`;
774
+ if (r.numeric_precision !== null) return `numeric(${r.numeric_precision})`;
775
+ return "numeric";
776
+ }
777
+ if (r.data_type === "timestamp with time zone") return "timestamptz";
778
+ if (r.data_type === "timestamp without time zone") return "timestamp";
779
+ if (r.data_type === "time without time zone") return "time";
780
+ if (r.data_type === "double precision") return "double precision";
781
+ if (r.data_type === "USER-DEFINED") return r.udt_name;
782
+ if (r.data_type === "ARRAY") return `${r.udt_name.replace(/^_/, "")}[]`;
783
+ return r.data_type;
784
+ }
785
+ function normalizeDefault(raw) {
786
+ if (!raw) return null;
787
+ const stripped = raw.replace(/::[\w" ]+(\([^)]*\))?$/, "");
788
+ const upper = stripped.toUpperCase();
789
+ if (upper === "NOW()" || upper === "CURRENT_TIMESTAMP") return "CURRENT_TIMESTAMP";
790
+ if (upper === "GEN_RANDOM_UUID()") return "gen_random_uuid()";
791
+ return stripped.replace(/^'(.*)'$/, "$1");
792
+ }
793
+ async function readIndexes(client, schema, table) {
794
+ const rows = await client.query(`SELECT i.relname AS index_name,
795
+ a.attname AS column_name,
796
+ ix.indisunique AS is_unique,
797
+ ix.indisprimary AS is_primary
798
+ FROM pg_class t
799
+ JOIN pg_namespace n ON n.oid = t.relnamespace
800
+ JOIN pg_index ix ON ix.indrelid = t.oid
801
+ JOIN pg_class i ON i.oid = ix.indexrelid
802
+ JOIN unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) ON true
803
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
804
+ WHERE n.nspname = $1 AND t.relname = $2 AND t.relkind = 'r'
805
+ ORDER BY i.relname, k.ord`, [schema, table]);
806
+ const byIndex = /* @__PURE__ */ new Map();
807
+ for (const r of rows.rows) {
808
+ let entry = byIndex.get(r.index_name);
809
+ if (!entry) {
810
+ entry = {
811
+ name: r.index_name,
812
+ columns: [],
813
+ unique: r.is_unique,
814
+ _isPrimary: r.is_primary
815
+ };
816
+ byIndex.set(r.index_name, entry);
817
+ }
818
+ entry.columns.push(r.column_name);
819
+ }
820
+ return [...byIndex.values()].filter((i) => !i._isPrimary).map(({ _isPrimary, ...rest }) => rest).sort((a, b) => a.name.localeCompare(b.name));
821
+ }
822
+ async function readForeignKeys(client, schema, table) {
823
+ const rows = await client.query(`SELECT tc.constraint_name,
824
+ kcu.column_name,
825
+ ccu.table_name AS ref_table,
826
+ ccu.column_name AS ref_column,
827
+ rc.delete_rule,
828
+ rc.update_rule
829
+ FROM information_schema.table_constraints tc
830
+ JOIN information_schema.key_column_usage kcu
831
+ ON kcu.constraint_name = tc.constraint_name
832
+ AND kcu.table_schema = tc.table_schema
833
+ JOIN information_schema.referential_constraints rc
834
+ ON rc.constraint_name = tc.constraint_name
835
+ AND rc.constraint_schema = tc.table_schema
836
+ JOIN information_schema.constraint_column_usage ccu
837
+ ON ccu.constraint_name = rc.unique_constraint_name
838
+ AND ccu.constraint_schema = rc.unique_constraint_schema
839
+ WHERE tc.table_schema = $1
840
+ AND tc.table_name = $2
841
+ AND tc.constraint_type = 'FOREIGN KEY'
842
+ ORDER BY tc.constraint_name, kcu.ordinal_position`, [schema, table]);
843
+ const byName = /* @__PURE__ */ new Map();
844
+ for (const r of rows.rows) {
845
+ let fk = byName.get(r.constraint_name);
846
+ if (!fk) {
847
+ fk = {
848
+ name: r.constraint_name,
849
+ columns: [],
850
+ refTable: r.ref_table,
851
+ refColumns: [],
852
+ onDelete: mapFkAction(r.delete_rule),
853
+ onUpdate: mapFkAction(r.update_rule)
854
+ };
855
+ byName.set(r.constraint_name, fk);
856
+ }
857
+ fk.columns.push(r.column_name);
858
+ fk.refColumns.push(r.ref_column);
859
+ }
860
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
861
+ }
862
+ function mapFkAction(raw) {
863
+ switch (raw.toUpperCase()) {
864
+ case "CASCADE": return "cascade";
865
+ case "RESTRICT": return "restrict";
866
+ case "SET NULL": return "set_null";
867
+ case "SET DEFAULT": return "set_default";
868
+ default: return "no_action";
869
+ }
870
+ }
871
+ //#endregion
872
+ //#region src/migrate/drift.ts
873
+ async function checkDrift(liveSnapshot, expectedSnapshot, behavior, log = console) {
874
+ if (behavior === "ignore") return;
875
+ const changes = diff(expectedSnapshot, liveSnapshot);
876
+ if (changes.length === 0) return;
877
+ const summary = summarize(changes);
878
+ const message = `Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`;
879
+ if (behavior === "warn") {
880
+ log.warn(message);
881
+ return;
882
+ }
883
+ throw new MigrationDriftError(message, summary);
884
+ }
885
+ function summarize(changes) {
886
+ const added = [];
887
+ const removed = [];
888
+ const changed = [];
889
+ for (const c of changes) switch (c.kind) {
890
+ case "createTable":
891
+ added.push(c.table.name);
892
+ break;
893
+ case "dropTable":
894
+ removed.push(c.table.name);
895
+ break;
896
+ case "addColumn":
897
+ added.push(`${c.table}.${c.column.name}`);
898
+ break;
899
+ case "dropColumn":
900
+ removed.push(`${c.table}.${c.column.name}`);
901
+ break;
902
+ case "alterColumn":
903
+ changed.push(`${c.table}.${c.column}`);
904
+ break;
905
+ case "renameColumn":
906
+ changed.push(`${c.table}.${c.from}→${c.to}`);
907
+ break;
908
+ case "renameTable":
909
+ changed.push(`${c.from}→${c.to}`);
910
+ break;
911
+ case "addIndex":
912
+ added.push(`${c.table}#${c.index.name}`);
913
+ break;
914
+ case "dropIndex":
915
+ removed.push(`${c.table}#${c.index.name}`);
916
+ break;
917
+ case "addForeignKey":
918
+ added.push(`${c.table}!${c.fk.name}`);
919
+ break;
920
+ case "dropForeignKey":
921
+ removed.push(`${c.table}!${c.fk.name}`);
922
+ break;
923
+ }
924
+ return {
925
+ added,
926
+ removed,
927
+ changed
928
+ };
929
+ }
930
+ //#endregion
931
+ //#region src/migrate/runner.ts
932
+ async function withLock(opts, fn) {
933
+ const owner = opts.owner ?? `${process.pid}@${(/* @__PURE__ */ new Date()).toISOString()}`;
934
+ if (!await opts.adapter.acquireLock(owner)) throw new MigrationLockError("Another process holds the migration lock");
935
+ try {
936
+ return await fn();
937
+ } finally {
938
+ await opts.adapter.releaseLock();
939
+ }
940
+ }
941
+ /**
942
+ * Verify pending entries: hash matches stored, meta.reviewed is true (if
943
+ * requireReviewed). Throws MigrationHashError or UnreviewedMigrationError on
944
+ * the first failure.
945
+ */
946
+ async function verifyPending(pending, migrationsDir, requireReviewed) {
947
+ for (const entry of pending) {
948
+ const dir = path.join(migrationsDir, entry.id);
949
+ const actualHash = await computeMigrationHash(dir);
950
+ if (actualHash !== entry.hash) throw new MigrationHashError(entry.id, entry.hash, actualHash);
951
+ if (requireReviewed) {
952
+ if (JSON.parse(await readFile(path.join(dir, "meta.json"), "utf8")).reviewed !== true) throw new UnreviewedMigrationError(entry.id);
953
+ }
954
+ }
955
+ }
956
+ async function applyEntry(entry, batch, opts) {
957
+ const dir = path.join(opts.migrationsDir, entry.id);
958
+ const upSql = await readFile(path.join(dir, "up.sql"), "utf8");
959
+ if (JSON.parse(await readFile(path.join(dir, "meta.json"), "utf8")).transaction !== false) await opts.adapter.applySqlInTx(upSql);
960
+ else await opts.adapter.applySqlNoTx(upSql);
961
+ await opts.adapter.recordApplied({
962
+ id: entry.id,
963
+ name: entry.tag,
964
+ hash: entry.hash,
965
+ batch,
966
+ direction: "up"
967
+ });
968
+ }
969
+ async function runForward(opts, pending) {
970
+ if (pending.length === 0) return {
971
+ applied: [],
972
+ batch: null
973
+ };
974
+ const requireReviewed = opts.requireReviewed ?? process.env.NODE_ENV !== "development";
975
+ await verifyPending(pending, opts.migrationsDir, requireReviewed);
976
+ const applied = await opts.adapter.listApplied();
977
+ const nextBatch = (applied.length === 0 ? 0 : Math.max(...applied.map((r) => r.batch))) + 1;
978
+ const ids = [];
979
+ for (const entry of pending) {
980
+ await applyEntry(entry, nextBatch, opts);
981
+ ids.push(entry.id);
982
+ }
983
+ return {
984
+ applied: ids,
985
+ batch: nextBatch
986
+ };
987
+ }
988
+ async function listPending(opts) {
989
+ const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect);
990
+ const applied = await opts.adapter.listApplied();
991
+ const appliedIds = new Set(applied.map((r) => r.id));
992
+ return journal.entries.filter((e) => !appliedIds.has(e.id)).map((e) => ({
993
+ id: e.id,
994
+ tag: e.tag,
995
+ hash: e.hash
996
+ }));
997
+ }
998
+ async function maybeCheckDrift(opts) {
999
+ const behavior = opts.driftCheck ?? "error";
1000
+ if (behavior === "ignore") return;
1001
+ const applied = await opts.adapter.listApplied();
1002
+ if (applied.length === 0) return;
1003
+ const sorted = [...applied].sort((a, b) => a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt));
1004
+ const last = sorted[sorted.length - 1];
1005
+ let expected;
1006
+ try {
1007
+ expected = JSON.parse(await readFile(path.join(opts.migrationsDir, last.id, "snapshot.json"), "utf8"));
1008
+ } catch {
1009
+ return;
1010
+ }
1011
+ await checkDrift(await opts.adapter.introspect(), expected, behavior, opts.log);
1012
+ }
1013
+ async function migrateLatest(opts) {
1014
+ await opts.adapter.ensureMigrationTables();
1015
+ return withLock(opts, async () => {
1016
+ await maybeCheckDrift(opts);
1017
+ return runForward(opts, await listPending(opts));
1018
+ });
1019
+ }
1020
+ async function migrateUp(opts) {
1021
+ await opts.adapter.ensureMigrationTables();
1022
+ return withLock(opts, async () => {
1023
+ await maybeCheckDrift(opts);
1024
+ return runForward(opts, (await listPending(opts)).slice(0, 1));
1025
+ });
1026
+ }
1027
+ async function applyReverse(id, opts) {
1028
+ const dir = path.join(opts.migrationsDir, id);
1029
+ const downSql = await readFile(path.join(dir, "down.sql"), "utf8");
1030
+ const meta = JSON.parse(await readFile(path.join(dir, "meta.json"), "utf8"));
1031
+ if ((opts.requireReviewed ?? process.env.NODE_ENV !== "development") && meta.reviewed !== true) throw new UnreviewedMigrationError(id);
1032
+ if (meta.transaction !== false) await opts.adapter.applySqlInTx(downSql);
1033
+ else await opts.adapter.applySqlNoTx(downSql);
1034
+ await opts.adapter.removeApplied(id);
1035
+ }
1036
+ async function migrateDown(opts) {
1037
+ await opts.adapter.ensureMigrationTables();
1038
+ return withLock(opts, async () => {
1039
+ const applied = await opts.adapter.listApplied();
1040
+ if (applied.length === 0) return { reversed: null };
1041
+ const sorted = [...applied].sort((a, b) => a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt));
1042
+ const last = sorted[sorted.length - 1];
1043
+ await applyReverse(last.id, opts);
1044
+ return { reversed: last.id };
1045
+ });
1046
+ }
1047
+ async function migrateStatus(opts) {
1048
+ await opts.adapter.ensureMigrationTables();
1049
+ const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect);
1050
+ const applied = await opts.adapter.listApplied();
1051
+ const byId = new Map(applied.map((r) => [r.id, r]));
1052
+ const entries = [];
1053
+ for (const e of journal.entries) {
1054
+ const row = byId.get(e.id);
1055
+ let reviewed = false;
1056
+ try {
1057
+ reviewed = JSON.parse(await readFile(path.join(opts.migrationsDir, e.id, "meta.json"), "utf8")).reviewed === true;
1058
+ } catch {}
1059
+ entries.push({
1060
+ id: e.id,
1061
+ tag: e.tag,
1062
+ hash: e.hash,
1063
+ state: row ? "applied" : "pending",
1064
+ batch: row?.batch ?? null,
1065
+ appliedAt: row?.appliedAt ?? null,
1066
+ reviewed
1067
+ });
1068
+ }
1069
+ return entries;
1070
+ }
1071
+ async function migrateRollback(opts) {
1072
+ await opts.adapter.ensureMigrationTables();
1073
+ return withLock(opts, async () => {
1074
+ const applied = await opts.adapter.listApplied();
1075
+ if (applied.length === 0) return {
1076
+ reversed: [],
1077
+ batch: null
1078
+ };
1079
+ const lastBatch = Math.max(...applied.map((r) => r.batch));
1080
+ const targets = applied.filter((r) => r.batch === lastBatch).sort((a, b) => a.appliedAt.localeCompare(b.appliedAt)).reverse();
1081
+ const reversed = [];
1082
+ for (const row of targets) {
1083
+ await applyReverse(row.id, opts);
1084
+ reversed.push(row.id);
1085
+ }
1086
+ return {
1087
+ reversed,
1088
+ batch: lastBatch
1089
+ };
1090
+ });
1091
+ }
1092
+ //#endregion
1093
+ //#region src/adapter.ts
1094
+ /**
1095
+ * KickJS lifecycle adapter for kickjs-db. Three jobs:
1096
+ *
1097
+ * 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.
1098
+ * - 'fail-if-pending' (default): throw if any pending exists. Operators
1099
+ * run `kick db migrate latest` explicitly before deploys land. Avoids
1100
+ * the prisma footgun where migrations silently apply on deploy.
1101
+ * - 'apply': run migrateLatest() automatically. Useful for dev / preview
1102
+ * environments where convenience matters more than safety.
1103
+ * - 'ignore': boot regardless. Last-resort escape hatch.
1104
+ * 2. On shutdown, close the migrationAdapter (drains the pool, etc).
1105
+ * 3. Register the migrationAdapter under an optional DI token so adopters
1106
+ * can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers
1107
+ * separately under DB_PRIMARY.
1108
+ */
1109
+ const kickDbAdapter = defineAdapter({
1110
+ name: "kickjs-db",
1111
+ build: (config) => ({
1112
+ async beforeStart({ container }) {
1113
+ const policy = config.migrationsOnBoot ?? "fail-if-pending";
1114
+ const pending = (await migrateStatus({
1115
+ adapter: config.migrationAdapter,
1116
+ migrationsDir: config.migrationsDir
1117
+ })).filter((s) => s.state === "pending");
1118
+ if (pending.length > 0) {
1119
+ if (policy === "fail-if-pending") throw new Error(`kickjs-db: ${pending.length} pending migration(s); run \`kick db migrate latest\` before boot`);
1120
+ if (policy === "apply") await migrateLatest({
1121
+ adapter: config.migrationAdapter,
1122
+ migrationsDir: config.migrationsDir,
1123
+ requireReviewed: config.requireReviewed,
1124
+ driftCheck: config.driftCheck
1125
+ });
1126
+ }
1127
+ if (config.token) container.registerFactory(config.token, () => config.migrationAdapter);
1128
+ },
1129
+ async shutdown() {
1130
+ await config.migrationAdapter.close();
1131
+ }
1132
+ })
1133
+ });
1134
+ //#endregion
1135
+ //#region src/tokens.ts
1136
+ const DB_PRIMARY = createToken("kick/db/primary");
1137
+ const DB_REPLICA = createToken("kick/db/replica");
1138
+ /**
1139
+ * Alias for the default DB. Adopters who only have one database can inject
1140
+ * `DB_CLIENT` instead of remembering whether it's primary/replica.
1141
+ */
1142
+ const DB_CLIENT = DB_PRIMARY;
1143
+ //#endregion
1144
+ //#region src/client/events.ts
1145
+ /**
1146
+ * Per-client typed event emitter. Wraps a Node EventEmitter to keep the
1147
+ * surface narrow (no `addListener`, no `removeAllListeners`, no `setMaxListeners`).
1148
+ *
1149
+ * The Kysely query interceptor surface is intentionally minimal in M1:
1150
+ * transactionStart/Commit/Rollback fire from createDbClient's transaction()
1151
+ * wrapper. The full beforeQuery / query / queryError emit pipeline lands in
1152
+ * M2 alongside `$extends` since it requires a proper Kysely query plugin
1153
+ * with access to the compiled SQL string + parameters. The types are stable
1154
+ * now so adopter code can wire listeners; only the runtime emit is deferred.
1155
+ */
1156
+ var KickDbEventEmitter = class {
1157
+ emitter = new EventEmitter();
1158
+ on(event, listener) {
1159
+ this.emitter.on(event, listener);
1160
+ }
1161
+ off(event, listener) {
1162
+ this.emitter.off(event, listener);
1163
+ }
1164
+ emit(event, payload) {
1165
+ this.emitter.emit(event, payload);
1166
+ }
1167
+ };
1168
+ //#endregion
1169
+ //#region src/custom-type.ts
1170
+ /**
1171
+ * ColumnBuilder subclass produced by `customType()`. Carries the
1172
+ * driver codecs so the (future) hooks pipeline can wire them through
1173
+ * a Kysely plugin without each consumer re-declaring its mapping.
1174
+ *
1175
+ * The phantom `T` flows through `SchemaToTypes<S>` exactly like any
1176
+ * other ColumnBuilder<T>, so adopters get full row-shape inference
1177
+ * for free.
1178
+ */
1179
+ var CustomColumnBuilder = class extends ColumnBuilder {
1180
+ /** Encode hook — run on values heading into the database. */
1181
+ toDriver;
1182
+ /** Decode hook — run on row values coming out of the database. */
1183
+ fromDriver;
1184
+ constructor(opts) {
1185
+ super(opts.dataType());
1186
+ this.toDriver = opts.toDriver;
1187
+ this.fromDriver = opts.fromDriver;
1188
+ }
1189
+ };
1190
+ /**
1191
+ * Build a reusable column factory for a custom type. The returned
1192
+ * function is what callers use inside `table('foo', { col: factory() })`
1193
+ * — same shape as the built-in `varchar()`, `text()`, etc.
1194
+ *
1195
+ * @example
1196
+ * ```ts
1197
+ * const ulid = customType<string>({
1198
+ * dataType: () => 'char(26)',
1199
+ * toDriver: (s) => s,
1200
+ * fromDriver: (raw) => String(raw),
1201
+ * })
1202
+ *
1203
+ * const events = table('events', {
1204
+ * id: ulid().primaryKey(),
1205
+ * ts: timestamp().notNull().defaultNow(),
1206
+ * })
1207
+ * ```
1208
+ */
1209
+ function customType(opts) {
1210
+ return () => new CustomColumnBuilder(opts);
1211
+ }
1212
+ //#endregion
1213
+ //#region src/client/codec-plugin.ts
1214
+ var CodecResultPlugin = class {
1215
+ constructor(decoders) {
1216
+ this.decoders = decoders;
1217
+ }
1218
+ transformQuery(args) {
1219
+ return args.node;
1220
+ }
1221
+ async transformResult(args) {
1222
+ if (this.decoders.size === 0) return args.result;
1223
+ const rows = args.result.rows.map((row) => this.decodeRow(row));
1224
+ return {
1225
+ ...args.result,
1226
+ rows
1227
+ };
1228
+ }
1229
+ decodeRow(row) {
1230
+ let mutated = false;
1231
+ const out = {};
1232
+ for (const key of Object.keys(row)) {
1233
+ const value = row[key];
1234
+ const decoder = this.decoders.get(key);
1235
+ if (decoder && value !== null && value !== void 0) {
1236
+ out[key] = decoder(value);
1237
+ mutated = true;
1238
+ } else out[key] = value;
1239
+ }
1240
+ return mutated ? out : row;
1241
+ }
1242
+ };
1243
+ /**
1244
+ * Walk a schema record and collect decoders from every column whose
1245
+ * builder is a `CustomColumnBuilder` with a `fromDriver` codec set.
1246
+ *
1247
+ * Schema entries that aren't table declarations (e.g. `relations()`
1248
+ * registrations) are skipped. Columns without a fromDriver are
1249
+ * skipped — registering an entry without one would still cost a
1250
+ * Map lookup per row for no payoff.
1251
+ */
1252
+ function buildDecoderMap(schema) {
1253
+ const decoders = /* @__PURE__ */ new Map();
1254
+ if (!schema || typeof schema !== "object") return decoders;
1255
+ for (const value of Object.values(schema)) {
1256
+ if (!isTableDecl(value)) continue;
1257
+ for (const [colName, col] of Object.entries(value.__columns)) if (col instanceof CustomColumnBuilder && col.fromDriver) decoders.set(colName, col.fromDriver);
1258
+ }
1259
+ return decoders;
1260
+ }
1261
+ function isTableDecl(value) {
1262
+ return typeof value === "object" && value !== null && value.__isTable === true;
1263
+ }
1264
+ //#endregion
1265
+ //#region src/extend/apply.ts
1266
+ function applyExtensions(client, ext) {
1267
+ let proxy;
1268
+ const modelBag = {};
1269
+ const model = ext.model ?? {};
1270
+ for (const tableName of Object.keys(model)) {
1271
+ const methods = model[tableName];
1272
+ if (!methods) continue;
1273
+ const bound = {};
1274
+ for (const [methodName, fn] of Object.entries(methods)) bound[methodName] = (...args) => fn.call(proxy, ...args);
1275
+ modelBag[tableName] = bound;
1276
+ }
1277
+ proxy = new Proxy(client, { get(target, prop) {
1278
+ if (typeof prop === "string" && prop in modelBag) return modelBag[prop];
1279
+ return target[prop];
1280
+ } });
1281
+ return proxy;
1282
+ }
1283
+ //#endregion
1284
+ //#region src/client/create.ts
1285
+ function createDbClient(opts) {
1286
+ const events = opts.events || opts.slowQueryThresholdMs != null ? new KickDbEventEmitter() : null;
1287
+ const slowThreshold = opts.slowQueryThresholdMs ?? null;
1288
+ const decoders = buildDecoderMap(opts.schema);
1289
+ const codecPlugin = decoders.size > 0 ? new CodecResultPlugin(decoders) : null;
1290
+ return wrap(new Kysely({
1291
+ dialect: opts.dialect,
1292
+ plugins: codecPlugin ? [codecPlugin] : void 0,
1293
+ log: events ? (event) => {
1294
+ if (event.level === "query") {
1295
+ const durationMs = event.queryDurationMillis;
1296
+ const payload = {
1297
+ sql: event.query.sql,
1298
+ parameters: event.query.parameters,
1299
+ durationMs
1300
+ };
1301
+ events.emit("query", payload);
1302
+ if (slowThreshold != null && durationMs >= slowThreshold) events.emit("slowQuery", {
1303
+ ...payload,
1304
+ thresholdMs: slowThreshold
1305
+ });
1306
+ } else if (event.level === "error") events.emit("queryError", {
1307
+ sql: event.query.sql,
1308
+ parameters: event.query.parameters,
1309
+ error: event.error
1310
+ });
1311
+ } : void 0
1312
+ }), {
1313
+ events,
1314
+ dialect: detectDialect(opts.dialect),
1315
+ savepointCounter: { value: 0 }
1316
+ });
1317
+ }
1318
+ function detectDialect(dialect) {
1319
+ const name = dialect.constructor?.name ?? "";
1320
+ if (name.includes("Postgres")) return "postgres";
1321
+ if (name.includes("Mysql") || name.includes("MySql")) return "mysql";
1322
+ return "sqlite";
1323
+ }
1324
+ function wrap(qb, ctx) {
1325
+ const client = {
1326
+ qb,
1327
+ dialect: ctx.dialect,
1328
+ selectFrom: qb.selectFrom.bind(qb),
1329
+ insertInto: qb.insertInto.bind(qb),
1330
+ updateTable: qb.updateTable.bind(qb),
1331
+ deleteFrom: qb.deleteFrom.bind(qb),
1332
+ on(event, listener) {
1333
+ ctx.events?.on(event, listener);
1334
+ return client;
1335
+ },
1336
+ off(event, listener) {
1337
+ ctx.events?.off(event, listener);
1338
+ return client;
1339
+ },
1340
+ transaction: ((a, b) => {
1341
+ const txOpts = typeof a === "function" ? {} : a;
1342
+ const fn = typeof a === "function" ? a : b;
1343
+ const run = async () => {
1344
+ ctx.events?.emit("transactionStart", { isolation: txOpts.isolation });
1345
+ try {
1346
+ const result = await qb.transaction().execute(async (tx) => {
1347
+ if (txOpts.isolation) {
1348
+ const level = txOpts.isolation.toUpperCase();
1349
+ await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx);
1350
+ }
1351
+ return await fn(wrap(tx, ctx));
1352
+ });
1353
+ ctx.events?.emit("transactionCommit", { isolation: txOpts.isolation });
1354
+ return result;
1355
+ } catch (err) {
1356
+ ctx.events?.emit("transactionRollback", {
1357
+ isolation: txOpts.isolation,
1358
+ error: err
1359
+ });
1360
+ throw err;
1361
+ }
1362
+ };
1363
+ return run();
1364
+ }),
1365
+ $extends(ext) {
1366
+ return applyExtensions(client, ext);
1367
+ },
1368
+ async savepoint(fn) {
1369
+ const name = `sp_${++ctx.savepointCounter.value}`;
1370
+ await sql.raw(`SAVEPOINT ${name}`).execute(qb);
1371
+ try {
1372
+ const result = await fn(wrap(qb, ctx));
1373
+ await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb);
1374
+ return result;
1375
+ } catch (err) {
1376
+ await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb);
1377
+ throw err;
1378
+ }
1379
+ },
1380
+ async destroy() {
1381
+ await qb.destroy();
1382
+ }
1383
+ };
1384
+ return client;
1385
+ }
1386
+ //#endregion
1387
+ //#region src/emit/identifiers.ts
1388
+ function quoteIdent(name) {
1389
+ return name.split(".").map((part) => "\"" + part.replace(/"/g, "\"\"") + "\"").join(".");
1390
+ }
1391
+ function quoteLiteral(value) {
1392
+ return "'" + value.replace(/'/g, "''") + "'";
1393
+ }
1394
+ //#endregion
1395
+ //#region src/emit/pg.ts
1396
+ function emitPg(changes) {
1397
+ return changes.map(emitChange).join("\n");
1398
+ }
1399
+ function emitChange(change) {
1400
+ switch (change.kind) {
1401
+ case "createTable": return emitCreateTable(change.table);
1402
+ case "dropTable": return `DROP TABLE ${quoteIdent(change.table.name)};`;
1403
+ case "renameTable": return `ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`;
1404
+ case "addColumn": return emitAddColumn(change.table, change.column);
1405
+ case "dropColumn": return `ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`;
1406
+ case "renameColumn": return `ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`;
1407
+ case "alterColumn": return emitAlterColumn(change.table, change.before, change.after);
1408
+ case "addIndex": return emitAddIndex(change.table, change.index);
1409
+ case "dropIndex": return `DROP INDEX ${quoteIdent(change.index.name)};`;
1410
+ case "addForeignKey": return emitAddFk(change.table, change.fk);
1411
+ case "dropForeignKey": return `ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`;
1412
+ case "createEnum": {
1413
+ const values = change.enum.values.map((v) => quoteLiteral(v)).join(", ");
1414
+ return `CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`;
1415
+ }
1416
+ case "dropEnum": return `DROP TYPE ${quoteIdent(change.enum.name)};`;
1417
+ case "addEnumValue": {
1418
+ const before = change.before ? ` BEFORE ${quoteLiteral(change.before)}` : "";
1419
+ return `ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`;
1420
+ }
1421
+ }
1422
+ }
1423
+ function emitAddColumn(table, c) {
1424
+ return `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`;
1425
+ }
1426
+ function emitAlterColumn(table, before, after) {
1427
+ const stmts = [];
1428
+ const t = quoteIdent(table);
1429
+ const c = quoteIdent(after.name);
1430
+ const typeChanged = before.type !== after.type;
1431
+ const nullChanged = before.nullable !== after.nullable;
1432
+ const defaultChanged = before.default !== after.default;
1433
+ const losingNotNull = !before.nullable && after.nullable;
1434
+ if (typeChanged) stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`);
1435
+ const emitDefault = () => {
1436
+ if (!defaultChanged) return;
1437
+ stmts.push(after.default === null ? `ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;` : `ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`);
1438
+ };
1439
+ const emitNullable = () => {
1440
+ if (!nullChanged) return;
1441
+ stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable ? "DROP NOT NULL" : "SET NOT NULL"};`);
1442
+ };
1443
+ if (losingNotNull) {
1444
+ emitDefault();
1445
+ emitNullable();
1446
+ } else {
1447
+ emitNullable();
1448
+ emitDefault();
1449
+ }
1450
+ return stmts.join("\n");
1451
+ }
1452
+ function emitAddIndex(table, i) {
1453
+ const cols = i.columns.map(quoteIdent).join(", ");
1454
+ return `CREATE${i.unique ? " UNIQUE" : ""} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`;
1455
+ }
1456
+ const FK_ACTIONS = {
1457
+ cascade: "CASCADE",
1458
+ restrict: "RESTRICT",
1459
+ set_null: "SET NULL",
1460
+ set_default: "SET DEFAULT",
1461
+ no_action: "NO ACTION"
1462
+ };
1463
+ function emitAddFk(table, fk) {
1464
+ const cols = fk.columns.map(quoteIdent).join(", ");
1465
+ const refCols = fk.refColumns.map(quoteIdent).join(", ");
1466
+ 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]};`;
1467
+ }
1468
+ function emitCreateTable(t) {
1469
+ const cols = Object.values(t.columns).map(emitColumnDecl);
1470
+ const pk = Object.values(t.columns).filter((c) => c.primaryKey).map((c) => quoteIdent(c.name));
1471
+ const lines = [...cols];
1472
+ if (pk.length > 0) lines.push(`PRIMARY KEY (${pk.join(", ")})`);
1473
+ return `CREATE TABLE ${quoteIdent(t.name)} (\n ${lines.join(",\n ")}\n);`;
1474
+ }
1475
+ function emitColumnDecl(c) {
1476
+ let s = `${quoteIdent(c.name)} ${c.type}`;
1477
+ if (!c.nullable) s += " NOT NULL";
1478
+ if (c.default !== null) s += ` DEFAULT ${formatDefault(c.default)}`;
1479
+ return s;
1480
+ }
1481
+ function formatDefault(value) {
1482
+ if (/^[A-Z_]+$/.test(value)) return value;
1483
+ if (/^[a-z_][a-z0-9_]*\s*\([^)]*\)$/i.test(value)) return value;
1484
+ if (/^-?\d+(\.\d+)?$/.test(value)) return value;
1485
+ if (value === "true" || value === "false") return value;
1486
+ return quoteLiteral(value);
1487
+ }
1488
+ //#endregion
1489
+ //#region src/cli/config.ts
1490
+ async function resolveDbConfig(opts) {
1491
+ const mod = await import(pathToFileURL(path.resolve(opts.configPath)).href);
1492
+ const db = (mod.default ?? mod)?.db ?? {};
1493
+ return {
1494
+ schemaPath: db.schemaPath ?? "src/db/schema.ts",
1495
+ migrationsDir: db.migrationsDir ?? "db/migrations",
1496
+ dialect: db.dialect ?? "postgres",
1497
+ connectionString: db.connectionString ?? process.env.DATABASE_URL,
1498
+ adapter: db.adapter
1499
+ };
1500
+ }
1501
+ //#endregion
1502
+ //#region src/cli/generate.ts
1503
+ async function generate(opts) {
1504
+ const migrationsAbs = path.resolve(opts.cwd, opts.config.migrationsDir);
1505
+ const { snapshot: prev, id: previousId } = await readLatestSnapshotEntry(migrationsAbs);
1506
+ if (opts.empty) return await writeMigration({
1507
+ opts,
1508
+ migrationsAbs,
1509
+ previousId,
1510
+ target: prev,
1511
+ upBody: "",
1512
+ downBody: "",
1513
+ changeCount: 0,
1514
+ draft: false,
1515
+ empty: true
1516
+ });
1517
+ const target = extractSnapshot(await import(pathToFileURL(path.resolve(opts.cwd, opts.config.schemaPath)).href), opts.config.dialect);
1518
+ const changes = diff(prev, target);
1519
+ if (changes.length === 0) return {
1520
+ status: "no-changes",
1521
+ changeCount: 0
1522
+ };
1523
+ return await writeMigration({
1524
+ opts,
1525
+ migrationsAbs,
1526
+ previousId,
1527
+ target,
1528
+ upBody: emitPg(changes),
1529
+ downBody: emitPg(invertChanges(changes)),
1530
+ changeCount: changes.length,
1531
+ draft: hasAmbiguousReverse(changes),
1532
+ empty: false
1533
+ });
1534
+ }
1535
+ async function writeMigration(p) {
1536
+ const id = formatId(p.opts.now?.() ?? /* @__PURE__ */ new Date(), p.opts.name);
1537
+ const dir = path.join(p.migrationsAbs, id);
1538
+ await mkdir(dir, { recursive: true });
1539
+ const upSql = "-- REVIEWED: false\n" + (p.empty ? "-- Empty migration — author SQL below (data migration, seed, etc).\n" : "") + p.upBody + (p.upBody ? "\n" : "");
1540
+ await writeFile(path.join(dir, "up.sql"), upSql, "utf8");
1541
+ const downHeader = "-- REVIEWED: false\n";
1542
+ const downDraft = p.draft ? "-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.\n" : "";
1543
+ const downHint = p.empty ? "-- Empty migration — author the reverse SQL here.\n" : "";
1544
+ const downSql = downHeader + downDraft + downHint + p.downBody + (p.downBody ? "\n" : "");
1545
+ await writeFile(path.join(dir, "down.sql"), downSql, "utf8");
1546
+ await writeFile(path.join(dir, "snapshot.json"), JSON.stringify(p.target, null, 2) + "\n", "utf8");
1547
+ await writeFile(path.join(dir, "meta.json"), JSON.stringify({
1548
+ id,
1549
+ name: p.opts.name,
1550
+ createdAt: (p.opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
1551
+ reviewed: false,
1552
+ dialect: p.opts.config.dialect,
1553
+ previousId: p.previousId,
1554
+ downIsDraft: p.draft,
1555
+ empty: p.empty
1556
+ }, null, 2) + "\n", "utf8");
1557
+ const hash = await computeMigrationHash(dir);
1558
+ await appendJournalEntry(p.migrationsAbs, p.opts.config.dialect, {
1559
+ id,
1560
+ tag: p.opts.name,
1561
+ hash,
1562
+ createdAt: (p.opts.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
1563
+ });
1564
+ return {
1565
+ status: "created",
1566
+ migrationDir: dir,
1567
+ changeCount: p.changeCount,
1568
+ empty: p.empty
1569
+ };
1570
+ }
1571
+ async function readLatestSnapshotEntry(migrationsDir) {
1572
+ const empty = {
1573
+ version: 1,
1574
+ dialect: "postgres",
1575
+ tables: {}
1576
+ };
1577
+ if (!existsSync(migrationsDir)) return {
1578
+ snapshot: empty,
1579
+ id: null
1580
+ };
1581
+ const dirs = (await readdir(migrationsDir)).filter((e) => /^\d{8}_\d{6}_/.test(e)).sort();
1582
+ if (dirs.length === 0) return {
1583
+ snapshot: empty,
1584
+ id: null
1585
+ };
1586
+ const latest = dirs[dirs.length - 1];
1587
+ const file = path.join(migrationsDir, latest, "snapshot.json");
1588
+ return {
1589
+ snapshot: JSON.parse(await readFile(file, "utf8")),
1590
+ id: latest
1591
+ };
1592
+ }
1593
+ function formatId(date, name) {
1594
+ const pad = (n) => n.toString().padStart(2, "0");
1595
+ 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()}`;
1596
+ }
1597
+ //#endregion
1598
+ //#region src/dsl/columns/builders.ts
1599
+ /**
1600
+ * Type-level brand stamps. Runtime is identity; the cast attaches the
1601
+ * relevant brand so `SchemaToTypes<S>` reads them per column.
1602
+ */
1603
+ function brandGenerated(col) {
1604
+ return col;
1605
+ }
1606
+ function brandNotNull(col) {
1607
+ return col;
1608
+ }
1609
+ function formatNumeric(base, precision, scale) {
1610
+ if (precision === void 0) return base;
1611
+ if (scale === void 0) return `${base}(${precision})`;
1612
+ return `${base}(${precision}, ${scale})`;
1613
+ }
1614
+ function serial() {
1615
+ return brandNotNull(brandGenerated(new ColumnBuilder("serial", { nullable: false })));
1616
+ }
1617
+ function bigSerial() {
1618
+ return brandNotNull(brandGenerated(new ColumnBuilder("bigserial", { nullable: false })));
1619
+ }
1620
+ function smallSerial() {
1621
+ return brandNotNull(brandGenerated(new ColumnBuilder("smallserial", { nullable: false })));
1622
+ }
1623
+ function integer() {
1624
+ return new ColumnBuilder("integer");
1625
+ }
1626
+ function bigint() {
1627
+ return new ColumnBuilder("bigint");
1628
+ }
1629
+ function smallint() {
1630
+ return new ColumnBuilder("smallint");
1631
+ }
1632
+ function decimal(precision, scale) {
1633
+ return new ColumnBuilder(formatNumeric("decimal", precision, scale));
1634
+ }
1635
+ function numeric(precision, scale) {
1636
+ return new ColumnBuilder(formatNumeric("numeric", precision, scale));
1637
+ }
1638
+ function real() {
1639
+ return new ColumnBuilder("real");
1640
+ }
1641
+ function doublePrecision() {
1642
+ return new ColumnBuilder("double precision");
1643
+ }
1644
+ function varchar(length = 255) {
1645
+ return new ColumnBuilder(`varchar(${length})`);
1646
+ }
1647
+ function char(length = 1) {
1648
+ return new ColumnBuilder(`char(${length})`);
1649
+ }
1650
+ function text() {
1651
+ return new ColumnBuilder("text");
1652
+ }
1653
+ function boolean() {
1654
+ return new ColumnBuilder("boolean");
1655
+ }
1656
+ /**
1657
+ * Subtype builder so `defaultNow()` can mark the resulting column as
1658
+ * generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter
1659
+ * omits the column on insert. Returns `this & GeneratedBrand` so the
1660
+ * subclass identity is preserved through the chain.
1661
+ */
1662
+ var TimestampBuilder = class extends ColumnBuilder {
1663
+ constructor(typeName = "timestamp") {
1664
+ super(typeName);
1665
+ }
1666
+ defaultNow() {
1667
+ this.state.default = "CURRENT_TIMESTAMP";
1668
+ return brandGenerated(this);
1669
+ }
1670
+ };
1671
+ function timestamp() {
1672
+ return new TimestampBuilder("timestamp");
1673
+ }
1674
+ function timestamptz() {
1675
+ return new TimestampBuilder("timestamptz");
1676
+ }
1677
+ function date() {
1678
+ return new ColumnBuilder("date");
1679
+ }
1680
+ function time() {
1681
+ return new ColumnBuilder("time");
1682
+ }
1683
+ function interval() {
1684
+ return new ColumnBuilder("interval");
1685
+ }
1686
+ /**
1687
+ * Subtype builder so `defaultRandom()` can mark the resulting column as
1688
+ * generated — when the DB fills in `gen_random_uuid()` for omitted columns.
1689
+ * Returns `this & GeneratedBrand` so chaining works in either order:
1690
+ * uuid().defaultRandom().primaryKey()
1691
+ * uuid().primaryKey().defaultRandom() ← also works
1692
+ */
1693
+ var UuidBuilder = class extends ColumnBuilder {
1694
+ constructor() {
1695
+ super("uuid");
1696
+ }
1697
+ defaultRandom() {
1698
+ this.state.default = "gen_random_uuid()";
1699
+ return brandGenerated(this);
1700
+ }
1701
+ };
1702
+ function uuid() {
1703
+ return new UuidBuilder();
1704
+ }
1705
+ /**
1706
+ * The `T` generic exists so adopters can declare their JSON shape:
1707
+ *
1708
+ * meta: jsonb<{ tags: string[] }>()
1709
+ *
1710
+ * `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the
1711
+ * row type narrows to `{ tags: string[] } | null`.
1712
+ */
1713
+ function json() {
1714
+ return new ColumnBuilder("json");
1715
+ }
1716
+ function jsonb() {
1717
+ return new ColumnBuilder("jsonb");
1718
+ }
1719
+ function bytea() {
1720
+ return new ColumnBuilder("bytea");
1721
+ }
1722
+ //#endregion
1723
+ //#region src/dsl/table.ts
1724
+ /**
1725
+ * Declare a typed table. The `TName extends string` generic narrows to the
1726
+ * literal table name so `SchemaToTypes<S>` can index by it without losing
1727
+ * the constant — `table('users', …)` widens to `TableDecl<'users', …>`,
1728
+ * not `TableDecl<string, …>`.
1729
+ */
1730
+ function table(name, columns, constraints) {
1731
+ const decl = {
1732
+ __isTable: true,
1733
+ __name: name,
1734
+ __columns: columns,
1735
+ __indexes: []
1736
+ };
1737
+ const refs = {};
1738
+ for (const [key, builder] of Object.entries(columns)) refs[key] = {
1739
+ __tableName: name,
1740
+ __name: key,
1741
+ __builder: builder,
1742
+ __state: () => builder.__state()
1743
+ };
1744
+ if (constraints) {
1745
+ const declared = constraints(refs);
1746
+ decl.__indexes = Object.values(declared);
1747
+ }
1748
+ return Object.assign(decl, refs);
1749
+ }
1750
+ //#endregion
1751
+ //#region src/dsl/constraints.ts
1752
+ function index(name) {
1753
+ return { on(...cols) {
1754
+ return {
1755
+ name,
1756
+ columns: cols.map((c) => c.__name),
1757
+ unique: false
1758
+ };
1759
+ } };
1760
+ }
1761
+ function unique(name) {
1762
+ return { on(...cols) {
1763
+ return {
1764
+ name,
1765
+ columns: cols.map((c) => c.__name),
1766
+ unique: true
1767
+ };
1768
+ } };
1769
+ }
1770
+ //#endregion
1771
+ //#region src/dsl/relations.ts
1772
+ function relations(source, builder) {
1773
+ return {
1774
+ __isRelations: true,
1775
+ __sourceTable: source.__name,
1776
+ __relations: builder({
1777
+ one: (target, opts) => ({
1778
+ kind: "one",
1779
+ target,
1780
+ fields: opts.fields,
1781
+ references: opts.references
1782
+ }),
1783
+ many: (target) => ({
1784
+ kind: "many",
1785
+ target
1786
+ })
1787
+ })
1788
+ };
1789
+ }
1790
+ //#endregion
1791
+ 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 };
1792
+
1793
+ //# sourceMappingURL=index.mjs.map