@forinda/kickjs-db 6.0.0 → 6.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.
@@ -0,0 +1,1320 @@
1
+
2
+ import { h as RelationMapEntry, n as CreateDbClientOptions, r as KickDbClient } from "./types-BZGFAXPN.mjs";
3
+ import { InjectionToken } from "@forinda/kickjs";
4
+ import { Generated, KyselyPlugin } from "kysely";
5
+ import { ReadonlyKysely } from "kysely/readonly";
6
+
7
+ //#region src/snapshot/types.d.ts
8
+ type Dialect$1 = 'postgres' | 'sqlite' | 'mysql';
9
+ type FkAction = 'cascade' | 'restrict' | 'set_null' | 'set_default' | 'no_action';
10
+ interface ColumnSnapshot {
11
+ name: string;
12
+ type: string;
13
+ nullable: boolean;
14
+ default: string | null;
15
+ primaryKey: boolean;
16
+ }
17
+ interface IndexSnapshot {
18
+ name: string;
19
+ columns: string[];
20
+ unique: boolean;
21
+ }
22
+ interface ForeignKeySnapshot {
23
+ name: string;
24
+ columns: string[];
25
+ refTable: string;
26
+ refColumns: string[];
27
+ onDelete: FkAction;
28
+ onUpdate: FkAction;
29
+ }
30
+ interface CheckSnapshot {
31
+ name: string;
32
+ expression: string;
33
+ }
34
+ interface TableSnapshot {
35
+ name: string;
36
+ columns: Record<string, ColumnSnapshot>;
37
+ indexes: IndexSnapshot[];
38
+ foreignKeys: ForeignKeySnapshot[];
39
+ checks: CheckSnapshot[];
40
+ }
41
+ /**
42
+ * PostgreSQL ENUM type declaration. Currently PG-only; the field is
43
+ * optional on `SchemaSnapshot` so other dialects don't have to carry
44
+ * a phantom `enums: {}`.
45
+ */
46
+ interface EnumSnapshot {
47
+ name: string;
48
+ /** Allowed values, in declaration order. PG preserves the order. */
49
+ values: readonly string[];
50
+ }
51
+ /**
52
+ * Resolved relation graph attached as a sidecar on the snapshot.
53
+ * Lives on `SchemaSnapshot.relations` (optional). Keyed
54
+ * sourceTable → relationName → resolved entry. Consumed by the
55
+ * relational-query compiler in `packages/db/src/query/`. The
56
+ * migration pipeline does not read this field — relations are
57
+ * query-time sugar, not DDL.
58
+ *
59
+ * Shaped this way (rather than re-using the runtime `RelationsDecl`)
60
+ * so the snapshot stays JSON-serializable: no function thunks, no
61
+ * back-references to table objects.
62
+ */
63
+ interface RelationSnapshot {
64
+ kind: 'one' | 'many';
65
+ /** Target table name. */
66
+ target: string;
67
+ /** Columns on the source table that participate in the join. */
68
+ sourceColumns: readonly string[];
69
+ /** Columns on the target table that participate in the join. */
70
+ targetColumns: readonly string[];
71
+ /**
72
+ * Optional pairing tag from `relationName: 'foo'` on both sides of
73
+ * the relation. Disambiguates multi-FK schemas. See
74
+ * docs/db/spec-relation-name.md (M4.B).
75
+ */
76
+ relationName?: string;
77
+ }
78
+ interface SchemaSnapshot {
79
+ version: 1;
80
+ dialect: Dialect$1;
81
+ tables: Record<string, TableSnapshot>;
82
+ /** ENUM types declared via `pgEnum()`. PG-only; absent on other dialects. */
83
+ enums?: Record<string, EnumSnapshot>;
84
+ /**
85
+ * Optional relation sidecar populated when the schema includes
86
+ * `relations()` declarations. Absent when no relations are
87
+ * declared so M0/M1 callers see the same snapshot shape they
88
+ * always did.
89
+ */
90
+ relations?: Record<string, Record<string, RelationSnapshot>>;
91
+ }
92
+ //#endregion
93
+ //#region src/snapshot/extract.d.ts
94
+ declare function extractSnapshot(schema: Record<string, unknown>, dialect: Dialect$1): SchemaSnapshot;
95
+ //#endregion
96
+ //#region src/snapshot/render.d.ts
97
+ /**
98
+ * Render a SchemaSnapshot to TypeScript source matching the kickjs-db DSL.
99
+ * Inverse of extractSnapshot().
100
+ *
101
+ * Naming: tables become exported `const`s with the same name. Constants
102
+ * starting with digits get an underscore prefix to stay JS-valid.
103
+ *
104
+ * Limits (M1 — refined in M2/M3):
105
+ * - No relations() emission. Adopter adds them manually post-introspect.
106
+ * - No checks (M1 doesn't model CHECK constraints in the snapshot).
107
+ * - Default values pass through as-is. The DSL accepts string defaults,
108
+ * so 'true' / 'CURRENT_TIMESTAMP' / "'foo'" all round-trip.
109
+ * - Auto-derived constraint names (`<table>_<col>_unique`, `<table>_<col>_fk`)
110
+ * are detected and rendered as the chained .unique() / .references() form.
111
+ * Custom-named constraints fall back to the third-arg callback / FK helper.
112
+ */
113
+ declare function renderSchemaSource(snapshot: SchemaSnapshot): string;
114
+ //#endregion
115
+ //#region src/diff/types.d.ts
116
+ interface CreateTable {
117
+ kind: 'createTable';
118
+ table: TableSnapshot;
119
+ }
120
+ interface DropTable {
121
+ kind: 'dropTable';
122
+ table: TableSnapshot;
123
+ }
124
+ interface RenameTable {
125
+ kind: 'renameTable';
126
+ from: string;
127
+ to: string;
128
+ }
129
+ interface AddColumn {
130
+ kind: 'addColumn';
131
+ table: string;
132
+ column: ColumnSnapshot;
133
+ }
134
+ interface DropColumn {
135
+ kind: 'dropColumn';
136
+ table: string;
137
+ column: ColumnSnapshot;
138
+ }
139
+ interface RenameColumn {
140
+ kind: 'renameColumn';
141
+ table: string;
142
+ from: string;
143
+ to: string;
144
+ }
145
+ interface AlterColumn {
146
+ kind: 'alterColumn';
147
+ table: string;
148
+ column: string;
149
+ before: ColumnSnapshot;
150
+ after: ColumnSnapshot;
151
+ }
152
+ interface AddIndex {
153
+ kind: 'addIndex';
154
+ table: string;
155
+ index: IndexSnapshot;
156
+ }
157
+ interface DropIndex {
158
+ kind: 'dropIndex';
159
+ table: string;
160
+ index: IndexSnapshot;
161
+ }
162
+ interface AddForeignKey {
163
+ kind: 'addForeignKey';
164
+ table: string;
165
+ fk: ForeignKeySnapshot;
166
+ }
167
+ interface DropForeignKey {
168
+ kind: 'dropForeignKey';
169
+ table: string;
170
+ fk: ForeignKeySnapshot;
171
+ }
172
+ interface CreateEnum {
173
+ kind: 'createEnum';
174
+ enum: EnumSnapshot;
175
+ }
176
+ interface DropEnum {
177
+ kind: 'dropEnum';
178
+ enum: EnumSnapshot;
179
+ }
180
+ /**
181
+ * PG ALTER TYPE … ADD VALUE — non-destructive value addition.
182
+ * Removed values can't round-trip without dropping dependent columns;
183
+ * the diff engine surfaces them via the separate `RemoveEnumValue`
184
+ * advisory below. Pure reorderings (same value set, different order)
185
+ * currently produce no diff at all — PG honours the canonical sort
186
+ * order at storage time, so user-visible behaviour is unchanged.
187
+ */
188
+ interface AddEnumValue {
189
+ kind: 'addEnumValue';
190
+ enum: string;
191
+ value: string;
192
+ /** When set, emit `ALTER TYPE … ADD VALUE 'x' BEFORE 'y'`. */
193
+ before?: string;
194
+ }
195
+ /**
196
+ * Change raised when an enum keeps the same name but loses one or
197
+ * more values across the diff. PostgreSQL has no `ALTER TYPE … DROP
198
+ * VALUE`, so the emitter renders a rename-recreate dance behind a
199
+ * `-- KICK ENUM REMOVE` header. The runner refuses to apply such a
200
+ * migration without `confirmEnumDrop: true` on `RunnerOptions` (or
201
+ * `--confirm-enum-drop` from the CLI).
202
+ *
203
+ * Spec: docs/db/spec-enum-value-removal.md.
204
+ */
205
+ interface RemoveEnumValue {
206
+ kind: 'removeEnumValue';
207
+ /** Enum type name. */
208
+ enum: string;
209
+ /** Values present in the previous snapshot but not in the next. */
210
+ removed: readonly string[];
211
+ /**
212
+ * Full value list AFTER the removal. Carried on the change so the
213
+ * emitter can render `CREATE TYPE … AS ENUM (…)` without needing
214
+ * the next-snapshot reference.
215
+ */
216
+ values: readonly string[];
217
+ /**
218
+ * Columns in the next snapshot whose declared type is this enum.
219
+ * Each gets one `ALTER TABLE … ALTER COLUMN … TYPE foo USING
220
+ * column::text::foo` clause inside the rename-recreate block.
221
+ *
222
+ * `default` carries the column's literal SQL default expression as
223
+ * declared on the prior snapshot, or `null` when the column has no
224
+ * default. The emitter wraps the type swap in
225
+ * `DROP DEFAULT` / `SET DEFAULT … ::"<enum>"` brackets only when
226
+ * this is non-null. Spec: docs/db/spec-default-preservation.md.
227
+ */
228
+ affectedColumns: readonly {
229
+ table: string;
230
+ column: string;
231
+ default: string | null;
232
+ }[];
233
+ }
234
+ type Change = CreateTable | DropTable | RenameTable | AddColumn | DropColumn | RenameColumn | AlterColumn | AddIndex | DropIndex | AddForeignKey | DropForeignKey | CreateEnum | DropEnum | AddEnumValue | RemoveEnumValue;
235
+ type ChangeSet = Change[];
236
+ //#endregion
237
+ //#region src/diff/engine.d.ts
238
+ declare function diff(prev: SchemaSnapshot, next: SchemaSnapshot): ChangeSet;
239
+ //#endregion
240
+ //#region src/diff/invert.d.ts
241
+ /**
242
+ * Reverse a forward ChangeSet so emitting it produces the SQL that undoes
243
+ * the forward migration.
244
+ *
245
+ * The reverse of an *unambiguous* change is exact (rename → rename swapped,
246
+ * add → drop, drop → add). The reverse of an *ambiguous* change (drop column,
247
+ * drop table, type widen, NOT NULL gain without default) is a defensible
248
+ * best-effort derived from the snapshot the forward change carried — the
249
+ * runner refuses to apply a non-reviewed migration in non-dev so the operator
250
+ * always sees the draft before it touches a DB.
251
+ *
252
+ * The order is reversed too: drop FK before drop index before drop table is
253
+ * the safe sequence for tearing down what create-FK / create-index / create-
254
+ * table built up.
255
+ */
256
+ declare function invertChanges(forward: ChangeSet): ChangeSet;
257
+ declare function hasAmbiguousReverse(forward: ChangeSet): boolean;
258
+ //#endregion
259
+ //#region src/errors.d.ts
260
+ declare class KickDbError extends Error {
261
+ readonly code: string;
262
+ constructor(code: string, message: string);
263
+ }
264
+ /**
265
+ * Thrown by `kick db generate` when the diff would emit a
266
+ * `removeEnumValue` change against a column whose default is one of
267
+ * the values being removed. The rename-recreate dance preserves
268
+ * column DEFAULTs through the type swap (M5.A.1), but it can't
269
+ * preserve a default that's no longer in the enum's value list — the
270
+ * `SET DEFAULT 'X'::"foo"` step would fail at apply time.
271
+ *
272
+ * The operator's options: change the column's default in the schema
273
+ * to a value that survives the removal, or drop the default entirely.
274
+ *
275
+ * Spec: docs/db/spec-default-preservation.md.
276
+ */
277
+ declare class RemovedValueAsDefaultError extends KickDbError {
278
+ readonly enum: string;
279
+ readonly table: string;
280
+ readonly column: string;
281
+ readonly value: string;
282
+ constructor(enumName: string, table: string, column: string, value: string);
283
+ }
284
+ //#endregion
285
+ //#region src/diff/composite-detect.d.ts
286
+ /**
287
+ * One composite-type field that holds the target enum. The composite
288
+ * may itself be referenced by table columns; that second level is not
289
+ * surfaced — the goal here is to refuse the rename-recreate, not to
290
+ * map the full dependency graph.
291
+ */
292
+ interface CompositeRef {
293
+ /** Schema-qualified composite type name, e.g. `"public.address_t"`. */
294
+ composite: string;
295
+ /** Attribute (field) within the composite that holds the enum. */
296
+ attribute: string;
297
+ /** Schema-qualified enum type name. */
298
+ enum: string;
299
+ }
300
+ /**
301
+ * Slim contract for a pg-protocol-compatible query function. Both
302
+ * `pg.Pool` and `@neondatabase/serverless`'s Pool match this shape, as
303
+ * does the `query` method on a pooled client.
304
+ */
305
+ interface CompositeQueryRunner {
306
+ query<R = unknown>(sql: string, params?: readonly unknown[]): Promise<{
307
+ rows: R[];
308
+ }>;
309
+ }
310
+ /**
311
+ * Find every PG composite type whose attribute(s) hold the given enum
312
+ * type. `enumName` may be unqualified (treated as `public.<name>`) or
313
+ * schema-qualified (`schema.name`).
314
+ *
315
+ * Returns an empty array when:
316
+ * - the enum doesn't exist in the live DB (the diff engine raised it
317
+ * against a snapshot, but the DB hasn't applied the prior migration
318
+ * yet — generate-time refusal would be a false alarm), or
319
+ * - no composite references the enum (the M3.B path is safe).
320
+ */
321
+ declare function detectCompositeReferences(runner: CompositeQueryRunner, enumName: string): Promise<CompositeRef[]>;
322
+ /**
323
+ * Thrown by `kick db generate` when the diff would emit one or more
324
+ * `removeEnumValue` changes against an enum that is referenced by a
325
+ * PG composite type. The rename-recreate dance can't reach into
326
+ * composite fields, so the generator refuses to write the migration
327
+ * rather than letting it fail at apply time.
328
+ *
329
+ * The operator's options: drop the composite, restructure it not to
330
+ * use the enum, or keep the value and ship the change later.
331
+ */
332
+ declare class CompositeEnumReferenceError extends KickDbError {
333
+ readonly refs: readonly CompositeRef[];
334
+ constructor(refs: readonly CompositeRef[]);
335
+ }
336
+ //#endregion
337
+ //#region src/migrate/errors.d.ts
338
+ declare class MigrationError extends KickDbError {}
339
+ declare class MigrationLockError extends MigrationError {
340
+ constructor(message: string);
341
+ }
342
+ interface SchemaDiffSummary {
343
+ added: string[];
344
+ removed: string[];
345
+ changed: string[];
346
+ }
347
+ declare class MigrationDriftError extends MigrationError {
348
+ readonly diff: SchemaDiffSummary;
349
+ constructor(message: string, diff: SchemaDiffSummary);
350
+ }
351
+ declare class MigrationHashError extends MigrationError {
352
+ readonly id: string;
353
+ readonly expected: string;
354
+ readonly actual: string;
355
+ constructor(id: string, expected: string, actual: string);
356
+ }
357
+ declare class UnreviewedMigrationError extends MigrationError {
358
+ readonly id: string;
359
+ constructor(id: string);
360
+ }
361
+ /**
362
+ * Thrown by the runner when a migration carries the `-- KICK ENUM
363
+ * REMOVE` header and the operator hasn't passed `confirmEnumDrop:
364
+ * true` (CLI: `--confirm-enum-drop`). Spec:
365
+ * docs/db/spec-enum-value-removal.md §4.
366
+ */
367
+ declare class MigrationEnumDropError extends MigrationError {
368
+ readonly id: string;
369
+ readonly enums: readonly string[];
370
+ readonly removed: readonly string[];
371
+ readonly columns: readonly string[];
372
+ constructor(id: string, enums: readonly string[], removed: readonly string[], columns: readonly string[]);
373
+ }
374
+ //#endregion
375
+ //#region src/migrate/enum-drop-gate.d.ts
376
+ /**
377
+ * Runner gate for the `-- KICK ENUM REMOVE` header.
378
+ *
379
+ * Pure parser + decision function — no I/O, no adapter, no DB. The
380
+ * runner reads up.sql, hands it to `parseEnumDropHeader`, and
381
+ * passes the result to `enforceEnumDropGate` which throws
382
+ * `MigrationEnumDropError` when the header is present and
383
+ * `confirmEnumDrop` is falsy.
384
+ *
385
+ * Spec: docs/db/spec-enum-value-removal.md §4.
386
+ */
387
+ /**
388
+ * Parsed payload from the header block. Empty arrays for keys not
389
+ * present (resilient to operators editing the migration by hand).
390
+ */
391
+ interface EnumDropHeader {
392
+ enums: string[];
393
+ removed: string[];
394
+ columns: string[];
395
+ }
396
+ /**
397
+ * Scan the first 64 lines of an up.sql for one or more enum-drop
398
+ * header blocks. Returns null when no header is present.
399
+ */
400
+ declare function parseEnumDropHeader(sql: string): EnumDropHeader | null;
401
+ /**
402
+ * Throws `MigrationEnumDropError` when the migration has an
403
+ * enum-drop header and `confirmEnumDrop` is not set. Returns
404
+ * silently otherwise.
405
+ */
406
+ declare function enforceEnumDropGate(id: string, sql: string, confirmEnumDrop: boolean): EnumDropHeader | null;
407
+ //#endregion
408
+ //#region src/migrate/journal.d.ts
409
+ interface JournalEntry {
410
+ id: string;
411
+ tag: string;
412
+ hash: string;
413
+ createdAt: string;
414
+ }
415
+ interface Journal {
416
+ version: 1;
417
+ dialect: Dialect$1;
418
+ entries: JournalEntry[];
419
+ }
420
+ declare function readJournal(migrationsDir: string, dialect: Dialect$1): Promise<Journal>;
421
+ declare function appendJournalEntry(migrationsDir: string, dialect: Dialect$1, entry: JournalEntry): Promise<void>;
422
+ declare function computeMigrationHash(migrationDir: string): Promise<string>;
423
+ declare function verifyMigrationHash(migrationDir: string, expected: string): Promise<boolean>;
424
+ //#endregion
425
+ //#region src/migrate/adapter.d.ts
426
+ interface MigrationRow {
427
+ id: string;
428
+ name: string;
429
+ hash: string;
430
+ batch: number;
431
+ appliedAt: string;
432
+ direction: 'up' | 'down';
433
+ }
434
+ /**
435
+ * Slim contract that connects the runner to a concrete database driver.
436
+ *
437
+ * Concrete impls: MemoryMigrationAdapter (this package, test-only) and
438
+ * pgAdapter from @forinda/kickjs-db/pg. Future db-sqlite / db-mysql adapter
439
+ * packages will satisfy this same shape so the runner stays driver-agnostic.
440
+ */
441
+ interface MigrationAdapter {
442
+ readonly dialect: Dialect$1;
443
+ /** Idempotent CREATE TABLE IF NOT EXISTS for kick_migrations + kick_migrations_lock. */
444
+ ensureMigrationTables(): Promise<void>;
445
+ /** Read all applied migrations ordered by appliedAt asc, then id asc. */
446
+ listApplied(): Promise<MigrationRow[]>;
447
+ /** Insert a new applied migration row; appliedAt is set by the DB. */
448
+ recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void>;
449
+ /** Delete an applied migration row (used by `migrate down`). */
450
+ removeApplied(id: string): Promise<void>;
451
+ /** Atomic lock acquire — true if we got it, false if held. Owner string is recorded for diagnostics. */
452
+ acquireLock(owner: string): Promise<boolean>;
453
+ /** Release the lock (no-op if not held). */
454
+ releaseLock(): Promise<void>;
455
+ /** Run arbitrary SQL inside a transaction. Used to apply up.sql / down.sql. */
456
+ applySqlInTx(sql: string): Promise<void>;
457
+ /** Apply SQL outside any transaction — for migrations with `meta.transaction: false` (CREATE INDEX CONCURRENTLY etc). */
458
+ applySqlNoTx(sql: string): Promise<void>;
459
+ /** Introspect the live schema; returns the canonical SchemaSnapshot. Used by drift detection and `kick db introspect`. */
460
+ introspect(): Promise<SchemaSnapshot>;
461
+ /** Close any underlying pool / connection. Caller-owned resources may keep the no-op. */
462
+ close(): Promise<void>;
463
+ }
464
+ //#endregion
465
+ //#region src/migrate/schema.d.ts
466
+ declare const KICK_MIGRATIONS_TABLE = "kick_migrations";
467
+ declare const KICK_LOCK_TABLE = "kick_migrations_lock";
468
+ declare function migrationsTableDdl(dialect: Dialect$1): string;
469
+ declare function lockTableDdl(dialect: Dialect$1): string;
470
+ //#endregion
471
+ //#region src/migrate/memory-adapter.d.ts
472
+ /**
473
+ * In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-
474
+ * holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as
475
+ * test-only stubs — the real DB-bound semantics are validated in db-pg's
476
+ * integration tests, not here.
477
+ */
478
+ declare class MemoryMigrationAdapter implements MigrationAdapter {
479
+ readonly dialect: Dialect$1;
480
+ private rows;
481
+ private locked;
482
+ private appliedSql;
483
+ private currentSchema;
484
+ ensureMigrationTables(): Promise<void>;
485
+ listApplied(): Promise<MigrationRow[]>;
486
+ recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void>;
487
+ removeApplied(id: string): Promise<void>;
488
+ acquireLock(owner: string): Promise<boolean>;
489
+ releaseLock(): Promise<void>;
490
+ applySqlInTx(sql: string): Promise<void>;
491
+ applySqlNoTx(sql: string): Promise<void>;
492
+ introspect(): Promise<SchemaSnapshot>;
493
+ close(): Promise<void>;
494
+ /** Test-only setter — let drift tests stage a "live" schema state. */
495
+ __setIntrospectedSchema(snap: SchemaSnapshot): void;
496
+ /** Test-only inspector — what SQL we received. */
497
+ __appliedSql(): readonly string[];
498
+ }
499
+ //#endregion
500
+ //#region src/migrate/introspect-types.d.ts
501
+ /**
502
+ * Driver-agnostic SQL runner. Both pg.Client and pg.Pool match this shape via
503
+ * structural typing. Lets introspectPg() stay portable across pg / pg-pool /
504
+ * @neondatabase/serverless without importing 'pg' from the core package.
505
+ */
506
+ interface PgQueryRunner {
507
+ query<R = unknown>(sql: string, params?: readonly unknown[]): Promise<{
508
+ rows: R[];
509
+ }>;
510
+ }
511
+ interface IntrospectPgOptions {
512
+ /** Default 'public'. */
513
+ schema?: string;
514
+ /** Migration tracking tables to skip. Default ['kick_migrations', 'kick_migrations_lock']. */
515
+ excludeTables?: readonly string[];
516
+ }
517
+ //#endregion
518
+ //#region src/migrate/introspect-pg.d.ts
519
+ declare function introspectPg(client: PgQueryRunner, opts?: IntrospectPgOptions): Promise<SchemaSnapshot>;
520
+ //#endregion
521
+ //#region src/migrate/introspect-sqlite.d.ts
522
+ /** Minimal better-sqlite3 surface introspection needs (sync `.all()`). */
523
+ interface SqliteIntrospectDb {
524
+ prepare(sql: string): {
525
+ all<R = unknown>(...params: unknown[]): R[];
526
+ };
527
+ }
528
+ interface IntrospectSqliteOptions {
529
+ excludeTables?: string[];
530
+ }
531
+ /**
532
+ * Read a live SQLite database into a {@link SchemaSnapshot} via
533
+ * `sqlite_master` + `PRAGMA` walks. Type strings come back as the
534
+ * column's *declared* affinity (`TEXT`, `INTEGER`, …) lowercased — SQLite
535
+ * doesn't preserve the original DSL type (a `uuid()` column reads back as
536
+ * `text`), so this is primarily for `kick db introspect` (reverse-engineer
537
+ * a schema), not byte-exact drift against a code-first snapshot.
538
+ */
539
+ declare function introspectSqlite(db: SqliteIntrospectDb, opts?: IntrospectSqliteOptions): SchemaSnapshot;
540
+ //#endregion
541
+ //#region src/migrate/introspect-mysql.d.ts
542
+ /** Minimal mysql2 surface introspection needs. Returns `[rows, fields]`. */
543
+ interface MysqlIntrospectDb {
544
+ query<R = unknown>(sql: string, params?: readonly unknown[]): Promise<[R, unknown]>;
545
+ }
546
+ interface IntrospectMysqlOptions {
547
+ excludeTables?: string[];
548
+ }
549
+ /**
550
+ * Read the current MySQL database into a {@link SchemaSnapshot} via
551
+ * `information_schema`. Types come back as the column's declared
552
+ * `COLUMN_TYPE` (`varchar(200)`, `tinyint(1)`, …) lowercased — MySQL
553
+ * doesn't preserve the original DSL type, so this powers `kick db
554
+ * introspect` rather than byte-exact drift against a code-first snapshot.
555
+ */
556
+ declare function introspectMysql(db: MysqlIntrospectDb, opts?: IntrospectMysqlOptions): Promise<SchemaSnapshot>;
557
+ //#endregion
558
+ //#region src/migrate/drift.d.ts
559
+ type DriftBehavior = 'error' | 'warn' | 'ignore';
560
+ interface DriftLogger {
561
+ warn: (message: string) => void;
562
+ }
563
+ declare function checkDrift(liveSnapshot: SchemaSnapshot, expectedSnapshot: SchemaSnapshot, behavior: DriftBehavior, log?: DriftLogger): Promise<void>;
564
+ //#endregion
565
+ //#region src/adapter.d.ts
566
+ type MigrationsOnBoot = 'fail-if-pending' | 'apply' | 'ignore';
567
+ interface KickDbAdapterConfig {
568
+ /** The driver-bound MigrationAdapter — pgAdapter() in @forinda/kickjs-db/pg, etc. */
569
+ migrationAdapter: MigrationAdapter;
570
+ /** Directory containing the generated migrations + _journal.json. */
571
+ migrationsDir: string;
572
+ /** Boot policy. Default 'fail-if-pending' — mirror the operator-explicit philosophy. */
573
+ migrationsOnBoot?: MigrationsOnBoot;
574
+ /** Drift detection mode. Default 'error' outside dev. */
575
+ driftCheck?: DriftBehavior;
576
+ /** Default true outside dev. */
577
+ requireReviewed?: boolean;
578
+ /** Optional DI token to register the migrationAdapter under, for adopters who need direct access. */
579
+ token?: InjectionToken<MigrationAdapter>;
580
+ /**
581
+ * Optional KickEventBus the adapter publishes migration events to.
582
+ * When set, `db:migration-applied` fires after a successful
583
+ * `migrateLatest()` on boot (apply policy only). Pair with
584
+ * `DEVTOOLS_BUS` so the events surface in the DevTools panel:
585
+ *
586
+ * import { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'
587
+ * // Resolve only when devtools is actually wired — adopters who
588
+ * // skip @forinda/kickjs-devtools never register the token, and
589
+ * // resolve() throws on missing tokens.
590
+ * const adapter = kickDbAdapter({
591
+ * ...,
592
+ * bus: container.has(DEVTOOLS_BUS) ? container.resolve(DEVTOOLS_BUS) : undefined,
593
+ * })
594
+ *
595
+ * Type imported via `import type` so kickjs-db keeps devtools-kit
596
+ * as an optional peer.
597
+ */
598
+ bus?: import('@forinda/kickjs-devtools-kit/bus').KickEventBus;
599
+ }
600
+ /**
601
+ * KickJS lifecycle adapter for kickjs-db. Three jobs:
602
+ *
603
+ * 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.
604
+ * - 'fail-if-pending' (default): throw if any pending exists. Operators
605
+ * run `kick db migrate latest` explicitly before deploys land. Avoids
606
+ * the prisma footgun where migrations silently apply on deploy.
607
+ * - 'apply': run migrateLatest() automatically. Useful for dev / preview
608
+ * environments where convenience matters more than safety.
609
+ * - 'ignore': boot regardless. Last-resort escape hatch.
610
+ * 2. On shutdown, close the migrationAdapter (drains the pool, etc).
611
+ * 3. Register the migrationAdapter under an optional DI token so adopters
612
+ * can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers
613
+ * separately under DB_PRIMARY.
614
+ */
615
+ declare const kickDbAdapter: import("@forinda/kickjs").AdapterFactory<KickDbAdapterConfig, unknown>;
616
+ //#endregion
617
+ //#region src/tokens.d.ts
618
+ declare const DB_PRIMARY: InjectionToken<KickDbClient>;
619
+ declare const DB_REPLICA: InjectionToken<KickDbClient>;
620
+ /**
621
+ * Alias for the default DB. Adopters who only have one database can inject
622
+ * `DB_CLIENT` instead of remembering whether it's primary/replica.
623
+ */
624
+ declare const DB_CLIENT: InjectionToken<KickDbClient<unknown>>;
625
+ //#endregion
626
+ //#region src/dsl/columns/types.d.ts
627
+ /**
628
+ * Runtime + type representation of a column reference (e.g. `users.id`).
629
+ * Carries the parent table name, the column's own name, plus runtime
630
+ * accessors used by FK thunks and constraint builders.
631
+ *
632
+ * Exported so adopters can annotate self-referencing thunks without
633
+ * spelling the shape inline:
634
+ *
635
+ * parentId: uuid().references((): ColumnRef => categories.id)
636
+ *
637
+ * Without the annotation the initializer of a self-referencing const
638
+ * trips TS7022 — TS needs to infer the const while the initializer
639
+ * already references it.
640
+ */
641
+ interface ColumnRef {
642
+ __tableName: string;
643
+ __name: string;
644
+ __builder: ColumnBuilder;
645
+ __state: () => ReturnType<ColumnBuilder['__state']>;
646
+ }
647
+ /**
648
+ * Resolved FK spec — `table` / `column` are pulled by invoking `thunk()`
649
+ * lazily. The thunk pattern lets self-referencing tables work:
650
+ *
651
+ * const categories = table('categories', {
652
+ * id: uuid().primaryKey().defaultRandom(),
653
+ * parentId: uuid().references((): ColumnRef => categories.id),
654
+ * })
655
+ *
656
+ * If we resolved at `.references()` call time, `categories` would TDZ-fail
657
+ * inside its own initializer. Storing the thunk and resolving on read
658
+ * (extract / render / emit) defers until after the const binding lands.
659
+ */
660
+ interface FkSpec {
661
+ thunk: () => ColumnRef;
662
+ onDelete: FkAction;
663
+ onUpdate: FkAction;
664
+ }
665
+ interface ColumnState {
666
+ type: string;
667
+ nullable: boolean;
668
+ default: string | null;
669
+ primaryKey: boolean;
670
+ unique: boolean;
671
+ references: FkSpec | null;
672
+ }
673
+ /**
674
+ * Type-only brand attached to a column when it's auto-assigned by the
675
+ * database (serial / bigserial / smallserial), has a runtime default
676
+ * (`.default(...)`), or carries an expression default
677
+ * (`uuid().defaultRandom()`, `timestamp().defaultNow()`). `SchemaToTypes<S>`
678
+ * reads this marker and wraps the column type in Kysely's `Generated<T>` so
679
+ * adopters can omit the column on insert.
680
+ *
681
+ * Runtime is a no-op — the symbol never reaches a value.
682
+ */
683
+ declare const KICK_GENERATED: unique symbol;
684
+ type GeneratedBrand = {
685
+ readonly [KICK_GENERATED]?: true;
686
+ };
687
+ /**
688
+ * Type-only brand attached to a column when `.notNull()` or `.primaryKey()`
689
+ * is called. `SchemaToTypes<S>` reads this brand to decide whether the
690
+ * column type is `T` (NOT NULL) or `T | null` (default nullable).
691
+ *
692
+ * Why a brand instead of a class generic: chained methods (notNull,
693
+ * primaryKey) can return `this & NotNullBrand` to narrow nullability while
694
+ * preserving the subclass identity — so `uuid().primaryKey().defaultRandom()`
695
+ * still resolves `defaultRandom()` on `UuidBuilder`. A class generic
696
+ * `<TNullable>` would collapse the subclass back to the parent.
697
+ */
698
+ declare const KICK_NOT_NULL: unique symbol;
699
+ type NotNullBrand = {
700
+ readonly [KICK_NOT_NULL]?: true;
701
+ };
702
+ /**
703
+ * Phantom-typed column builder. The `T` generic carries the column's TS
704
+ * value type (number / string / Date / etc.); nullability is tracked via
705
+ * the `NotNullBrand` intersection rather than a class generic so chain
706
+ * methods preserve subclass identity.
707
+ *
708
+ * Both `T` and the brand are erased at runtime; they exist purely so
709
+ * `SchemaToTypes<S>` can pull them out per column.
710
+ */
711
+ declare class ColumnBuilder<T = unknown> {
712
+ readonly __t?: T;
713
+ protected state: ColumnState;
714
+ constructor(type: string, defaults?: Partial<ColumnState>);
715
+ notNull(): this & NotNullBrand;
716
+ primaryKey(): this & NotNullBrand;
717
+ unique(): this;
718
+ array(): ColumnBuilder<T[]>;
719
+ references(target: () => ColumnRef, opts?: {
720
+ onDelete?: FkAction;
721
+ onUpdate?: FkAction;
722
+ }): this;
723
+ /**
724
+ * Mark the column as having a runtime / DB-assigned default. The
725
+ * `GeneratedBrand` flows into `SchemaToTypes<S>` so the column wraps
726
+ * in `Generated<T>` — adopters can `INSERT` without specifying it.
727
+ *
728
+ * Accepts the natural literal for the column type — `boolean().default(false)`,
729
+ * `integer().default(0)`, `varchar().default('active')`. Non-string
730
+ * literals are normalised to their SQL-literal text so the snapshot
731
+ * (`ColumnSnapshot.default: string | null`) and migration emitter stay
732
+ * string-only. For a quoted string default the text is the value
733
+ * itself (`'active'`); booleans/numbers emit bare (`false`, `0`).
734
+ */
735
+ default(value: string | number | boolean): this & GeneratedBrand;
736
+ toJSON(name: string): ColumnSnapshot;
737
+ __state(): Readonly<ColumnState>;
738
+ }
739
+ //#endregion
740
+ //#region src/dsl/constraints.d.ts
741
+ interface IndexDecl {
742
+ name: string;
743
+ columns: string[];
744
+ unique: boolean;
745
+ }
746
+ interface ColRef {
747
+ __name: string;
748
+ }
749
+ declare function index(name: string): {
750
+ on(...cols: ColRef[]): IndexDecl;
751
+ };
752
+ declare function unique(name: string): {
753
+ on(...cols: ColRef[]): IndexDecl;
754
+ };
755
+ //#endregion
756
+ //#region src/dsl/table.d.ts
757
+ interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>> {
758
+ __isTable: true;
759
+ __name: TName;
760
+ __columns: C;
761
+ __indexes: IndexDecl[];
762
+ }
763
+ type TableRefs<TName extends string, C extends Record<string, ColumnBuilder>> = TableDecl<TName, C> & { [K in keyof C]: ColumnRef };
764
+ type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: { [K in keyof C]: ColumnRef }) => Record<string, IndexDecl>;
765
+ /**
766
+ * Declare a typed table. The `TName extends string` generic narrows to the
767
+ * literal table name so `SchemaToTypes<S>` can index by it without losing
768
+ * the constant — `table('users', …)` widens to `TableDecl<'users', …>`,
769
+ * not `TableDecl<string, …>`.
770
+ */
771
+ declare function table<TName extends string, C extends Record<string, ColumnBuilder>>(name: TName, columns: C, constraints?: ConstraintBuilder<C>): TableRefs<TName, C>;
772
+ //#endregion
773
+ //#region src/client/schema-types.d.ts
774
+ /**
775
+ * Pull each column's TS type and nullability into the row shape Kysely
776
+ * consumes as its `Database` interface.
777
+ *
778
+ * - Columns carrying the `GeneratedBrand` (set by serial / bigSerial /
779
+ * `default(...)` / `defaultNow()` / `defaultRandom()`) wrap in
780
+ * Kysely's `Generated<T>` so adopters can omit them on insert.
781
+ * - `notNull()` / `primaryKey()` stamp `NotNullBrand`, which drops the
782
+ * `| null` from the row type for that column.
783
+ * - `jsonb<{...}>()` carries the user-declared shape through without
784
+ * widening to `unknown`.
785
+ *
786
+ * The `Generated<T> | null` form for nullable + default columns models the
787
+ * SQL semantics: omitted on insert, the DB returns the default; if `null`
788
+ * is explicitly inserted, the DB stores null.
789
+ */
790
+ type IsNullable<C> = C extends NotNullBrand ? false : true;
791
+ type ColumnTSType<C> = C extends ColumnBuilder<infer T> ? IsNullable<C> extends true ? C extends GeneratedBrand ? Generated<T> | null : T | null : C extends GeneratedBrand ? Generated<T> : T : never;
792
+ type SchemaToTypes<S> = { [K in keyof S as S[K] extends TableDecl<string, Record<string, ColumnBuilder>> ? S[K]['__name'] : never]: S[K] extends TableDecl<string, infer C> ? { [Col in keyof C]: ColumnTSType<C[Col]> } : never };
793
+ //#endregion
794
+ //#region src/client/create.d.ts
795
+ declare function createDbClient<TSchema, DB = SchemaToTypes<TSchema>>(opts: CreateDbClientOptions<TSchema, DB>): KickDbClient<DB>;
796
+ //#endregion
797
+ //#region src/client/plugins.d.ts
798
+ /**
799
+ * Pass this to `createDbClient({ plugins: [...] })` so
800
+ * `eb('col', '=', null)` (plus `!=` / `<>`) compiles to `IS NULL` /
801
+ * `IS NOT NULL` instead of the silently-false `= NULL` default.
802
+ *
803
+ * Without the plugin, Kysely passes `null` through as a bound
804
+ * parameter — the resulting `col = $1` evaluates to UNKNOWN under
805
+ * three-valued logic, which filters out every row including the
806
+ * ones the adopter intended to match. The plugin rewrites the AST
807
+ * before compilation so the operator becomes `IS` / `IS NOT` and
808
+ * the null literal flows inline (no `$N` parameter binding).
809
+ *
810
+ * ```ts
811
+ * import { createDbClient, safeNullComparison } from '@forinda/kickjs-db'
812
+ *
813
+ * const db = createDbClient({
814
+ * schema,
815
+ * dialect: pgDialect({ pool }),
816
+ * plugins: [safeNullComparison()],
817
+ * })
818
+ *
819
+ * await db.selectFrom('users').where('deletedAt', '=', null).selectAll().execute()
820
+ * // → SQL: select * from "users" where "deletedAt" is null
821
+ * ```
822
+ *
823
+ * Opt-in; default `createDbClient` chains stay byte-identical so
824
+ * existing repos that work around the gotcha manually don't see a
825
+ * behaviour change.
826
+ *
827
+ * **Why a kickjs-side helper rather than re-exporting Kysely's?**
828
+ * Kysely 0.29's own `SafeNullComparisonPlugin` ships broken on PG —
829
+ * it rewrites the operator but keeps the null operand parameterised,
830
+ * producing `WHERE "col" IS $1` with `$1=null`, which PG rejects
831
+ * with `syntax error at or near "$1"`. The kickjs version emits the
832
+ * literal `null` keyword inline so PG accepts it. Tracked upstream
833
+ * at <https://github.com/forinda/kick-js/issues/220>.
834
+ */
835
+ declare function safeNullComparison(): KyselyPlugin;
836
+ //#endregion
837
+ //#region src/migrate/runner.d.ts
838
+ interface RunnerOptions {
839
+ adapter: MigrationAdapter;
840
+ migrationsDir: string;
841
+ /** When true, refuse to apply migrations whose meta.json.reviewed is false. Defaults to true outside dev. */
842
+ requireReviewed?: boolean;
843
+ /** Owner string written into the lock table for diagnostics. */
844
+ owner?: string;
845
+ /** Drift detection mode. Default 'error'. */
846
+ driftCheck?: DriftBehavior;
847
+ /** Logger surface for drift warnings. Defaults to console. */
848
+ log?: DriftLogger;
849
+ /**
850
+ * Allow migrations carrying the `-- KICK ENUM REMOVE` header to
851
+ * apply. Default `false`. CLI exposes via `--confirm-enum-drop`.
852
+ * Spec: docs/db/spec-enum-value-removal.md.
853
+ */
854
+ confirmEnumDrop?: boolean;
855
+ }
856
+ interface AppliedSummary {
857
+ applied: string[];
858
+ batch: number | null;
859
+ }
860
+ declare function migrateLatest(opts: RunnerOptions): Promise<AppliedSummary>;
861
+ declare function migrateUp(opts: RunnerOptions): Promise<AppliedSummary>;
862
+ interface ReversedSummary {
863
+ reversed: string | null;
864
+ }
865
+ declare function migrateDown(opts: RunnerOptions): Promise<ReversedSummary>;
866
+ interface RollbackSummary {
867
+ reversed: string[];
868
+ batch: number | null;
869
+ }
870
+ interface StatusEntry {
871
+ id: string;
872
+ tag: string;
873
+ hash: string;
874
+ state: 'applied' | 'pending';
875
+ batch: number | null;
876
+ appliedAt: string | null;
877
+ reviewed: boolean;
878
+ }
879
+ declare function migrateStatus(opts: Pick<RunnerOptions, 'adapter' | 'migrationsDir'>): Promise<StatusEntry[]>;
880
+ declare function migrateRollback(opts: RunnerOptions): Promise<RollbackSummary>;
881
+ //#endregion
882
+ //#region src/migrate/review.d.ts
883
+ interface ReviewResult {
884
+ id: string;
885
+ /** True when the migration was already reviewed (no-op). */
886
+ alreadyReviewed: boolean;
887
+ }
888
+ /**
889
+ * Mark a migration as reviewed: flip `meta.json.reviewed` to `true`,
890
+ * swap the `-- REVIEWED: false` markers in `up.sql` / `down.sql` to
891
+ * `true`, and recompute the migration's journal hash (the marker swap
892
+ * changes the file bytes, so the stored hash must follow or the runner's
893
+ * integrity check would fail).
894
+ *
895
+ * This is the single source of truth for "reviewing" — adopters should
896
+ * never hand-edit `meta.json`, because that leaves the `-- REVIEWED`
897
+ * markers and the journal hash out of sync.
898
+ */
899
+ declare function reviewMigration(migrationsDir: string, id: string): Promise<ReviewResult>;
900
+ //#endregion
901
+ //#region src/emit/pg.d.ts
902
+ declare function emitPg(changes: ChangeSet): string;
903
+ //#endregion
904
+ //#region src/emit/sqlite.d.ts
905
+ /**
906
+ * Raised when a change set needs a SQLite table rebuild but the emitter
907
+ * wasn't given the resolved snapshots to build it from (it only has the
908
+ * per-change diff). `generate()` always passes the snapshots, so this only
909
+ * surfaces if `emitSqlite` is called bare with a rebuild-requiring change.
910
+ */
911
+ declare class SqliteRebuildRequiredError extends Error {
912
+ constructor(detail: string);
913
+ }
914
+ /**
915
+ * Resolved before/after schema snapshots, threaded in by `generate()` so
916
+ * the emitter can build the 12-step table-rebuild for changes SQLite's
917
+ * `ALTER TABLE` can't express (column type/null/default changes, FK
918
+ * add/drop on an existing table). `to` is the schema *after* the changes
919
+ * apply; `from` is before — their column intersection drives the
920
+ * `INSERT ... SELECT` data copy.
921
+ */
922
+ interface SqliteEmitContext {
923
+ from?: SchemaSnapshot;
924
+ to?: SchemaSnapshot;
925
+ }
926
+ /**
927
+ * Emit SQLite DDL for a change set.
928
+ *
929
+ * Most operations map to a direct statement (CREATE/DROP/RENAME TABLE,
930
+ * ADD/DROP/RENAME COLUMN, CREATE/DROP INDEX). The ones SQLite can't `ALTER`
931
+ * directly — `alterColumn`, and foreign-key add/drop on an existing table —
932
+ * are handled by a **table rebuild**: create a new table with the desired
933
+ * shape, copy rows, drop the old, rename, recreate indexes. Foreign keys
934
+ * are folded into `CREATE TABLE` (SQLite has no `ADD CONSTRAINT`).
935
+ */
936
+ declare function emitSqlite(changes: ChangeSet, ctx?: SqliteEmitContext): string;
937
+ //#endregion
938
+ //#region src/emit/mysql.d.ts
939
+ /**
940
+ * Emit MySQL DDL for a change set.
941
+ *
942
+ * MySQL has full `ALTER TABLE` support (unlike SQLite), so this mirrors
943
+ * the Postgres emitter's structure — column/FK/index changes map to direct
944
+ * ALTERs. The MySQL-specific bits:
945
+ * - backtick identifiers + PG→MySQL type mapping;
946
+ * - a single integer PK is emitted inline as `... AUTO_INCREMENT PRIMARY
947
+ * KEY` (MySQL requires an auto-increment column to be a key);
948
+ * - `alterColumn` uses `MODIFY COLUMN` (MySQL restates the whole column
949
+ * definition at once, rather than PG's separate SET TYPE / SET DEFAULT
950
+ * / SET NOT NULL clauses);
951
+ * - `dropForeignKey` uses `DROP FOREIGN KEY` (not `DROP CONSTRAINT`).
952
+ * - PG `ENUM` type changes are PG-only and throw (MySQL enums are inline
953
+ * column types, not standalone objects).
954
+ */
955
+ declare function emitMysql(changes: ChangeSet): string;
956
+ //#endregion
957
+ //#region src/cli/config.d.ts
958
+ type MigrationAdapterFactory = () => MigrationAdapter | Promise<MigrationAdapter>;
959
+ interface DbConfig {
960
+ schemaPath: string;
961
+ migrationsDir: string;
962
+ dialect: Dialect$1;
963
+ /**
964
+ * How `kick db migrate` reacts when the live DB has schema not recorded
965
+ * in the migrations (someone ran DDL out of band): `'error'` (default —
966
+ * refuse), `'warn'` (log + continue), `'ignore'` (skip the check). The
967
+ * check is dialect-normalised, so SQLite/MySQL's lossy introspection
968
+ * doesn't false-positive.
969
+ */
970
+ driftCheck?: DriftBehavior;
971
+ /**
972
+ * Postgres connection string for the built-in pgAdapter path. Read from
973
+ * `db.connectionString` in kick.config.ts, or falls back to the
974
+ * DATABASE_URL env var. The CLI uses this when no `adapter` factory is
975
+ * provided.
976
+ */
977
+ connectionString?: string;
978
+ /**
979
+ * Escape hatch: a factory returning a fully-constructed MigrationAdapter.
980
+ * Takes precedence over `connectionString` when both are set. Use this
981
+ * for non-default adapter wiring (custom pool, neon-serverless, etc).
982
+ */
983
+ adapter?: MigrationAdapterFactory;
984
+ }
985
+ declare function resolveDbConfig(opts: {
986
+ configPath: string;
987
+ }): Promise<DbConfig>;
988
+ //#endregion
989
+ //#region src/cli/generate.d.ts
990
+ interface GenerateOptions {
991
+ name: string;
992
+ config: DbConfig;
993
+ cwd: string;
994
+ now?: () => Date;
995
+ /**
996
+ * When true, skip the schema diff and emit an empty migration shell
997
+ * (up.sql / down.sql with just the REVIEWED header, snapshot.json copying
998
+ * the prior schema state). Used for data migrations, seed inserts, or any
999
+ * change the diff engine can't author. Matches knex's `migrate:make`.
1000
+ */
1001
+ empty?: boolean;
1002
+ /**
1003
+ * M4.C — generate-time gate for `removeEnumValue` changes. When the
1004
+ * diff produces one or more, this callback is invoked once per
1005
+ * affected enum to surface PG composite-type references. A non-empty
1006
+ * result aborts generate with `CompositeEnumReferenceError` (the
1007
+ * rename-recreate USING-cast can't reach into composite fields).
1008
+ *
1009
+ * Optional: when omitted, generate skips the check (no DB connection
1010
+ * required). The CLI wires this for `dialect=postgres` workflows.
1011
+ */
1012
+ detectCompositeRefs?: (enumName: string) => Promise<readonly CompositeRef[]>;
1013
+ }
1014
+ interface GenerateResult {
1015
+ status: 'created' | 'no-changes';
1016
+ migrationDir?: string;
1017
+ changeCount: number;
1018
+ empty?: boolean;
1019
+ }
1020
+ declare function generate(opts: GenerateOptions): Promise<GenerateResult>;
1021
+ //#endregion
1022
+ //#region src/dsl/columns/builders.d.ts
1023
+ declare function serial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand;
1024
+ declare function bigSerial(): ColumnBuilder<bigint> & GeneratedBrand & NotNullBrand;
1025
+ declare function smallSerial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand;
1026
+ declare function integer(): ColumnBuilder<number>;
1027
+ declare function bigint(): ColumnBuilder<bigint>;
1028
+ declare function smallint(): ColumnBuilder<number>;
1029
+ declare function decimal(precision?: number, scale?: number): ColumnBuilder<string>;
1030
+ declare function numeric(precision?: number, scale?: number): ColumnBuilder<string>;
1031
+ declare function real(): ColumnBuilder<number>;
1032
+ declare function doublePrecision(): ColumnBuilder<number>;
1033
+ declare function varchar(length?: number): ColumnBuilder<string>;
1034
+ declare function char(length?: number): ColumnBuilder<string>;
1035
+ declare function text(): ColumnBuilder<string>;
1036
+ declare function boolean(): ColumnBuilder<boolean>;
1037
+ /**
1038
+ * Subtype builder so `defaultNow()` can mark the resulting column as
1039
+ * generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter
1040
+ * omits the column on insert. Returns `this & GeneratedBrand` so the
1041
+ * subclass identity is preserved through the chain.
1042
+ */
1043
+ declare class TimestampBuilder extends ColumnBuilder<Date> {
1044
+ constructor(typeName?: string);
1045
+ defaultNow(): this & GeneratedBrand;
1046
+ }
1047
+ declare function timestamp(): TimestampBuilder;
1048
+ declare function timestamptz(): TimestampBuilder;
1049
+ declare function date(): ColumnBuilder<Date>;
1050
+ declare function time(): ColumnBuilder<string>;
1051
+ declare function interval(): ColumnBuilder<string>;
1052
+ /**
1053
+ * Subtype builder so `defaultRandom()` can mark the resulting column as
1054
+ * generated — when the DB fills in `gen_random_uuid()` for omitted columns.
1055
+ * Returns `this & GeneratedBrand` so chaining works in either order:
1056
+ * uuid().defaultRandom().primaryKey()
1057
+ * uuid().primaryKey().defaultRandom() ← also works
1058
+ */
1059
+ declare class UuidBuilder extends ColumnBuilder<string> {
1060
+ constructor();
1061
+ defaultRandom(): this & GeneratedBrand;
1062
+ }
1063
+ declare function uuid(): UuidBuilder;
1064
+ /**
1065
+ * The `T` generic exists so adopters can declare their JSON shape:
1066
+ *
1067
+ * meta: jsonb<{ tags: string[] }>()
1068
+ *
1069
+ * `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the
1070
+ * row type narrows to `{ tags: string[] } | null`.
1071
+ */
1072
+ declare function json<T = unknown>(): ColumnBuilder<T>;
1073
+ declare function jsonb<T = unknown>(): ColumnBuilder<T>;
1074
+ declare function bytea(): ColumnBuilder<Uint8Array>;
1075
+ //#endregion
1076
+ //#region src/dsl/relations.d.ts
1077
+ /**
1078
+ * Generic over the target table so the typegen plugin can pull
1079
+ * `target['__name']` without losing the literal string at the type
1080
+ * level. Existing callers that only read `kind` / `fields` /
1081
+ * `references` see the same surface.
1082
+ */
1083
+ interface RelationOne<TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<string, Record<string, ColumnBuilder>>> {
1084
+ kind: 'one';
1085
+ target: TTarget;
1086
+ fields: ColumnRef[];
1087
+ references: ColumnRef[];
1088
+ /**
1089
+ * Disambiguates this relation from sibling `one` relations on the
1090
+ * same source table that point at the same target. Pair with the
1091
+ * matching `relationName` on the inverse `many` side. See
1092
+ * docs/db/spec-relation-name.md.
1093
+ */
1094
+ relationName?: string;
1095
+ }
1096
+ interface RelationMany<TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<string, Record<string, ColumnBuilder>>> {
1097
+ kind: 'many';
1098
+ target: TTarget;
1099
+ /**
1100
+ * Pairs with the matching `relationName` on the inverse `one`
1101
+ * declaration. Required when the source table has multiple FKs
1102
+ * to the same target; resolver throws
1103
+ * `RelationalQueryMissingInverseError` otherwise.
1104
+ */
1105
+ relationName?: string;
1106
+ }
1107
+ type Relation = RelationOne | RelationMany;
1108
+ /**
1109
+ * Generic so the typegen plugin can read the source table name and
1110
+ * the per-relation kind/target via `RelationsDecl['__sourceTable']`
1111
+ * and `RelationsDecl['__relations']`. The runtime shape is
1112
+ * unchanged; the generic parameters narrow the type at call sites.
1113
+ */
1114
+ interface RelationsDecl<TSource extends string = string, TRelations extends Record<string, Relation> = Record<string, Relation>> {
1115
+ __isRelations: true;
1116
+ __sourceTable: TSource;
1117
+ __relations: TRelations;
1118
+ }
1119
+ interface Helpers {
1120
+ one: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T, opts: {
1121
+ fields: ColumnRef[];
1122
+ references: ColumnRef[];
1123
+ relationName?: string;
1124
+ }) => RelationOne<T>;
1125
+ many: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(target: T, opts?: {
1126
+ relationName?: string;
1127
+ }) => RelationMany<T>;
1128
+ }
1129
+ /**
1130
+ * Declare a typed relation set for `source`. The return type
1131
+ * preserves `source.__name` and the literal `kind`/`target` of every
1132
+ * helper-built entry so `SchemaToRelationsRegister<S>` (re-exported
1133
+ * from `@forinda/kickjs-db`) can walk the schema barrel and emit a
1134
+ * matching `KickDbRelationsRegister` augmentation at typegen time.
1135
+ */
1136
+ declare function relations<T extends TableDecl<string, Record<string, ColumnBuilder>>, R extends Record<string, Relation>>(source: T, builder: (h: Helpers) => R): RelationsDecl<T['__name'], R>;
1137
+ //#endregion
1138
+ //#region src/custom-type.d.ts
1139
+ interface CustomTypeOptions<TJs, TDriver = unknown> {
1140
+ /**
1141
+ * SQL data type as it would appear in `CREATE TABLE` — `'text'`,
1142
+ * `'jsonb'`, `'citext'`, `'geometry(Point, 4326)'`, etc. Returned
1143
+ * via a thunk so adopters can compute the type from runtime config
1144
+ * (e.g. dialect-specific overrides).
1145
+ */
1146
+ dataType: () => string;
1147
+ /** Optional encode hook applied at insert / update time. */
1148
+ toDriver?: (value: TJs) => TDriver;
1149
+ /** Optional decode hook applied to selected rows. */
1150
+ fromDriver?: (driver: TDriver) => TJs;
1151
+ }
1152
+ /**
1153
+ * ColumnBuilder subclass produced by `customType()`. Carries the
1154
+ * driver codecs so the (future) hooks pipeline can wire them through
1155
+ * a Kysely plugin without each consumer re-declaring its mapping.
1156
+ *
1157
+ * The phantom `T` flows through `SchemaToTypes<S>` exactly like any
1158
+ * other ColumnBuilder<T>, so adopters get full row-shape inference
1159
+ * for free.
1160
+ */
1161
+ declare class CustomColumnBuilder<TJs> extends ColumnBuilder<TJs> {
1162
+ /** Encode hook — run on values heading into the database. */
1163
+ readonly toDriver?: (value: TJs) => unknown;
1164
+ /** Decode hook — run on row values coming out of the database. */
1165
+ readonly fromDriver?: (driver: unknown) => TJs;
1166
+ constructor(opts: CustomTypeOptions<TJs>);
1167
+ }
1168
+ /**
1169
+ * Build a reusable column factory for a custom type. The returned
1170
+ * function is what callers use inside `table('foo', { col: factory() })`
1171
+ * — same shape as the built-in `varchar()`, `text()`, etc.
1172
+ *
1173
+ * @example
1174
+ * ```ts
1175
+ * const ulid = customType<string>({
1176
+ * dataType: () => 'char(26)',
1177
+ * toDriver: (s) => s,
1178
+ * fromDriver: (raw) => String(raw),
1179
+ * })
1180
+ *
1181
+ * const events = table('events', {
1182
+ * id: ulid().primaryKey(),
1183
+ * ts: timestamp().notNull().defaultNow(),
1184
+ * })
1185
+ * ```
1186
+ */
1187
+ declare function customType<TJs>(opts: CustomTypeOptions<TJs>): () => CustomColumnBuilder<TJs>;
1188
+ //#endregion
1189
+ //#region src/query/relations.d.ts
1190
+ type ResolvedRelation = RelationSnapshot;
1191
+ /**
1192
+ * Sidecar map: source table → relation name → resolved entry. Lives
1193
+ * on `SchemaSnapshot.relations` and is populated by
1194
+ * `extractRelations()` (`query/extract-relations.ts`).
1195
+ */
1196
+ type ResolvedRelations = Record<string, Record<string, ResolvedRelation>>;
1197
+ //#endregion
1198
+ //#region src/query/schema-relations-types.d.ts
1199
+ /**
1200
+ * Distribute over `S` (the schema record), keeping only the entries
1201
+ * that are `RelationsDecl<...>`. Each entry contributes one row to
1202
+ * the output object — keyed by the source table's `__name` and
1203
+ * carrying the per-relation `{ kind, target }` map.
1204
+ *
1205
+ * `Record<string, Record<string, RelationMapEntry>>` is the
1206
+ * structural shape consumed by `KickDbRelationsRegister`; this type
1207
+ * narrows it to the literal table names present in the schema.
1208
+ */
1209
+ type SchemaToRelationsRegister<S> = MergeBySource<{ [K in keyof S]: S[K] extends RelationsDecl<infer Source, infer R> ? Source extends string ? R extends Record<string, Relation> ? {
1210
+ source: Source;
1211
+ relations: ResolveRelations<R>;
1212
+ } : never : never : never }[keyof S]>;
1213
+ /**
1214
+ * Pull `{ kind, target }` for each relation entry. `target` shrinks
1215
+ * to the literal table name so the registry stays declarative
1216
+ * (matches the `RelationMapEntry` shape — see `query/types.ts`).
1217
+ */
1218
+ type ResolveRelations<R extends Record<string, Relation>> = { [K in keyof R]: {
1219
+ kind: R[K]['kind'];
1220
+ target: R[K]['target'] extends TableDecl<infer N, Record<string, ColumnBuilder>> ? N extends string ? N : string : string;
1221
+ } };
1222
+ /**
1223
+ * Fold a union of `{ source, relations }` records into a single
1224
+ * object keyed by `source`. TypeScript distributes the conditional
1225
+ * across the union and the mapped type collects every member.
1226
+ */
1227
+ type MergeBySource<U extends {
1228
+ source: string;
1229
+ relations: Record<string, RelationMapEntry>;
1230
+ }> = { [Source in U['source']]: Extract<U, {
1231
+ source: Source;
1232
+ }>['relations'] };
1233
+ //#endregion
1234
+ //#region src/query/errors.d.ts
1235
+ /**
1236
+ * Thrown at compile time when a `with` key references a relation
1237
+ * that the source table doesn't declare.
1238
+ */
1239
+ declare class RelationalQueryUnknownRelationError extends KickDbError {
1240
+ readonly sourceTable: string;
1241
+ readonly relationKey: string;
1242
+ constructor(sourceTable: string, relationKey: string);
1243
+ }
1244
+ /**
1245
+ * Thrown at compile time when a `with` clause nests deeper than
1246
+ * `maxDepth` (spec §7 R-3, default 5). Catches infinite specs on
1247
+ * self-referencing tables before any SQL is built.
1248
+ */
1249
+ declare class RelationalQueryDepthError extends KickDbError {
1250
+ readonly maxDepth: number;
1251
+ readonly trace: readonly string[];
1252
+ constructor(maxDepth: number, trace: readonly string[]);
1253
+ }
1254
+ /**
1255
+ * Thrown at compile time when a relation name collides with a
1256
+ * literal column on the same table (spec §7 R-5). Forces the schema
1257
+ * author to rename one of them so the LATERAL alias stays
1258
+ * unambiguous.
1259
+ */
1260
+ declare class RelationalQueryAliasCollisionError extends KickDbError {
1261
+ readonly sourceTable: string;
1262
+ readonly conflictingName: string;
1263
+ constructor(sourceTable: string, conflictingName: string);
1264
+ }
1265
+ /**
1266
+ * Thrown by `db.query.X.find{Many,First,Unique}` when an
1267
+ * `AbortSignal` passed via options fires (or is already aborted at
1268
+ * call time). Wraps the underlying cause — typically a DOMException
1269
+ * with `name === 'AbortError'`, or whatever the caller passed to
1270
+ * `AbortController.abort(reason)` — on the `cause` field for adopter
1271
+ * inspection (e.g. distinguishing HTTP timeout from explicit
1272
+ * cancellation from user-disconnect).
1273
+ *
1274
+ * Spec: docs/db/spec-abortsignal-threading.md.
1275
+ */
1276
+ declare class RelationalQueryCancelledError extends KickDbError {
1277
+ readonly cause?: unknown;
1278
+ constructor(cause?: unknown);
1279
+ }
1280
+ /**
1281
+ * Thrown by SQLite + MySQL compiler stubs in v1. The interface ships
1282
+ * with PG only; the other dialects fill in during M4 without an API
1283
+ * change at the call site.
1284
+ */
1285
+ declare class RelationalQueryNotSupportedError extends KickDbError {
1286
+ readonly dialect: string;
1287
+ constructor(dialect: string);
1288
+ }
1289
+ /**
1290
+ * Thrown at extract time when more than one inverse `one` declared
1291
+ * on the **target** table shares the same `relationName` AND points
1292
+ * back at the same source — the actual ambiguity case for resolver
1293
+ * step 1. Scope is per `(sourceTable, targetTable, relationName)`:
1294
+ * the same tag can be reused across unrelated table pairs. Spec:
1295
+ * docs/db/spec-relation-name.md §7 R-2.
1296
+ */
1297
+ declare class RelationalQueryAmbiguousRelationNameError extends KickDbError {
1298
+ readonly sourceTable: string;
1299
+ readonly targetTable: string;
1300
+ readonly relationName: string;
1301
+ /** Relation keys on the target table whose inverse `one` shares the tag. */
1302
+ readonly conflicting: readonly string[];
1303
+ constructor(sourceTable: string, targetTable: string, relationName: string, conflicting: readonly string[]);
1304
+ }
1305
+ /**
1306
+ * Thrown at extract time when a `many` relation has no inverse
1307
+ * `one` declared on the target table. The compiler needs the FK
1308
+ * column pair to build the join predicate; without an inverse we
1309
+ * have no way to discover it. Adopters fix by declaring the inverse
1310
+ * `one` on the target side (drizzle-style symmetric declarations).
1311
+ */
1312
+ declare class RelationalQueryMissingInverseError extends KickDbError {
1313
+ readonly sourceTable: string;
1314
+ readonly relationName: string;
1315
+ readonly targetTable: string;
1316
+ constructor(sourceTable: string, relationName: string, targetTable: string);
1317
+ }
1318
+ //#endregion
1319
+ export { emitSqlite as $, TableSnapshot as $n, MigrationRow as $t, integer as A, Change as An, DB_PRIMARY as At, time as B, RenameColumn as Bn, introspectMysql as Bt, bigint as C, invertChanges as Cn, ColumnState as Ct, date as D, AddForeignKey as Dn, KICK_NOT_NULL as Dt, char as E, AddEnumValue as En, KICK_GENERATED as Et, real as F, DropEnum as Fn, DriftBehavior as Ft, GenerateOptions as G, ColumnSnapshot as Gn, IntrospectPgOptions as Gt, timestamptz as H, renderSchemaSource as Hn, SqliteIntrospectDb as Ht, serial as I, DropForeignKey as In, DriftLogger as It, DbConfig as J, FkAction as Jn, KICK_LOCK_TABLE as Jt, GenerateResult as K, Dialect$1 as Kn, PgQueryRunner as Kt, smallSerial as L, DropIndex as Ln, checkDrift as Lt, json as M, CreateEnum as Mn, KickDbAdapterConfig as Mt, jsonb as N, CreateTable as Nn, MigrationsOnBoot as Nt, decimal as O, AddIndex as On, NotNullBrand as Ot, numeric as P, DropColumn as Pn, kickDbAdapter as Pt, SqliteRebuildRequiredError as Q, SchemaSnapshot as Qn, MigrationAdapter as Qt, smallint as R, DropTable as Rn, IntrospectMysqlOptions as Rt, bigSerial as S, hasAmbiguousReverse as Sn, ColumnRef as St, bytea as T, AddColumn as Tn, GeneratedBrand as Tt, uuid as U, extractSnapshot as Un, introspectSqlite as Ut, timestamp as V, RenameTable as Vn, IntrospectSqliteOptions as Vt, varchar as W, CheckSnapshot as Wn, introspectPg as Wt, resolveDbConfig as X, IndexSnapshot as Xn, lockTableDdl as Xt, MigrationAdapterFactory as Y, ForeignKeySnapshot as Yn, KICK_MIGRATIONS_TABLE as Yt, emitMysql as Z, RelationSnapshot as Zn, migrationsTableDdl as Zt, RelationOne as _, CompositeQueryRunner as _n, table as _t, RelationalQueryDepthError as a, verifyMigrationHash as an, RollbackSummary as at, TimestampBuilder as b, KickDbError as bn, unique as bt, RelationalQueryUnknownRelationError as c, parseEnumDropHeader as cn, migrateDown as ct, ResolvedRelations as d, MigrationError as dn, migrateStatus as dt, Journal as en, emitPg as et, CustomColumnBuilder as f, MigrationHashError as fn, migrateUp as ft, RelationMany as g, CompositeEnumReferenceError as gn, TableDecl as gt, Relation as h, UnreviewedMigrationError as hn, SchemaToTypes as ht, RelationalQueryCancelledError as i, readJournal as in, ReversedSummary as it, interval as j, ChangeSet as jn, DB_REPLICA as jt, doublePrecision as k, AlterColumn as kn, DB_CLIENT as kt, SchemaToRelationsRegister as l, MigrationDriftError as ln, migrateLatest as lt, customType as m, SchemaDiffSummary as mn, createDbClient as mt, RelationalQueryAliasCollisionError as n, appendJournalEntry as nn, reviewMigration as nt, RelationalQueryMissingInverseError as o, EnumDropHeader as on, RunnerOptions as ot, CustomTypeOptions as p, MigrationLockError as pn, safeNullComparison as pt, generate as q, EnumSnapshot as qn, MemoryMigrationAdapter as qt, RelationalQueryAmbiguousRelationNameError as r, computeMigrationHash as rn, AppliedSummary as rt, RelationalQueryNotSupportedError as s, enforceEnumDropGate as sn, StatusEntry as st, ReadonlyKysely as t, JournalEntry as tn, ReviewResult as tt, ResolvedRelation as u, MigrationEnumDropError as un, migrateRollback as ut, RelationsDecl as v, CompositeRef as vn, IndexDecl as vt, boolean as w, diff as wn, FkSpec as wt, UuidBuilder as x, RemovedValueAsDefaultError as xn, ColumnBuilder as xt, relations as y, detectCompositeReferences as yn, index as yt, text as z, RemoveEnumValue as zn, MysqlIntrospectDb as zt };
1320
+ //# sourceMappingURL=index-B1r7mcA1.d.mts.map