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