@forinda/kickjs-db 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,786 @@
1
+
2
+ import { _ as TableSnapshot, a as GeneratedBrand, c as NotNullBrand, d as Dialect, f as EnumSnapshot, g as SchemaSnapshot, 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 } from "./types-D2FzsPow.mjs";
3
+ import * as _$_forinda_kickjs0 from "@forinda/kickjs";
4
+ import { InjectionToken } from "@forinda/kickjs";
5
+ import * as _$kysely from "kysely";
6
+ import { Dialect as Dialect$1, Generated, Kysely } from "kysely";
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 + reorderings can't round-trip without dropping
98
+ * dependent columns; the diff engine surfaces them as a NoOp + a
99
+ * comment inside emit so the adopter writes a manual migration.
100
+ */
101
+ interface AddEnumValue {
102
+ kind: 'addEnumValue';
103
+ enum: string;
104
+ value: string;
105
+ /** When set, emit `ALTER TYPE … ADD VALUE 'x' BEFORE 'y'`. */
106
+ before?: string;
107
+ }
108
+ type Change = CreateTable | DropTable | RenameTable | AddColumn | DropColumn | RenameColumn | AlterColumn | AddIndex | DropIndex | AddForeignKey | DropForeignKey | CreateEnum | DropEnum | AddEnumValue;
109
+ type ChangeSet = Change[];
110
+ //#endregion
111
+ //#region src/diff/engine.d.ts
112
+ declare function diff(prev: SchemaSnapshot, next: SchemaSnapshot): ChangeSet;
113
+ //#endregion
114
+ //#region src/diff/invert.d.ts
115
+ /**
116
+ * Reverse a forward ChangeSet so emitting it produces the SQL that undoes
117
+ * the forward migration.
118
+ *
119
+ * The reverse of an *unambiguous* change is exact (rename → rename swapped,
120
+ * add → drop, drop → add). The reverse of an *ambiguous* change (drop column,
121
+ * drop table, type widen, NOT NULL gain without default) is a defensible
122
+ * best-effort derived from the snapshot the forward change carried — the
123
+ * runner refuses to apply a non-reviewed migration in non-dev so the operator
124
+ * always sees the draft before it touches a DB.
125
+ *
126
+ * The order is reversed too: drop FK before drop index before drop table is
127
+ * the safe sequence for tearing down what create-FK / create-index / create-
128
+ * table built up.
129
+ */
130
+ declare function invertChanges(forward: ChangeSet): ChangeSet;
131
+ declare function hasAmbiguousReverse(forward: ChangeSet): boolean;
132
+ //#endregion
133
+ //#region src/errors.d.ts
134
+ declare class KickDbError extends Error {
135
+ readonly code: string;
136
+ constructor(code: string, message: string);
137
+ }
138
+ //#endregion
139
+ //#region src/migrate/errors.d.ts
140
+ declare class MigrationError extends KickDbError {}
141
+ declare class MigrationLockError extends MigrationError {
142
+ constructor(message: string);
143
+ }
144
+ interface SchemaDiffSummary {
145
+ added: string[];
146
+ removed: string[];
147
+ changed: string[];
148
+ }
149
+ declare class MigrationDriftError extends MigrationError {
150
+ readonly diff: SchemaDiffSummary;
151
+ constructor(message: string, diff: SchemaDiffSummary);
152
+ }
153
+ declare class MigrationHashError extends MigrationError {
154
+ readonly id: string;
155
+ readonly expected: string;
156
+ readonly actual: string;
157
+ constructor(id: string, expected: string, actual: string);
158
+ }
159
+ declare class UnreviewedMigrationError extends MigrationError {
160
+ readonly id: string;
161
+ constructor(id: string);
162
+ }
163
+ //#endregion
164
+ //#region src/migrate/journal.d.ts
165
+ interface JournalEntry {
166
+ id: string;
167
+ tag: string;
168
+ hash: string;
169
+ createdAt: string;
170
+ }
171
+ interface Journal {
172
+ version: 1;
173
+ dialect: Dialect;
174
+ entries: JournalEntry[];
175
+ }
176
+ declare function readJournal(migrationsDir: string, dialect: Dialect): Promise<Journal>;
177
+ declare function appendJournalEntry(migrationsDir: string, dialect: Dialect, entry: JournalEntry): Promise<void>;
178
+ declare function computeMigrationHash(migrationDir: string): Promise<string>;
179
+ declare function verifyMigrationHash(migrationDir: string, expected: string): Promise<boolean>;
180
+ //#endregion
181
+ //#region src/migrate/adapter.d.ts
182
+ interface MigrationRow {
183
+ id: string;
184
+ name: string;
185
+ hash: string;
186
+ batch: number;
187
+ appliedAt: string;
188
+ direction: 'up' | 'down';
189
+ }
190
+ /**
191
+ * Slim contract that connects the runner to a concrete database driver.
192
+ *
193
+ * Concrete impls: MemoryMigrationAdapter (this package, test-only) and
194
+ * pgAdapter from @forinda/kickjs-db-pg. Future db-sqlite / db-mysql adapter
195
+ * packages will satisfy this same shape so the runner stays driver-agnostic.
196
+ */
197
+ interface MigrationAdapter {
198
+ readonly dialect: Dialect;
199
+ /** Idempotent CREATE TABLE IF NOT EXISTS for kick_migrations + kick_migrations_lock. */
200
+ ensureMigrationTables(): Promise<void>;
201
+ /** Read all applied migrations ordered by appliedAt asc, then id asc. */
202
+ listApplied(): Promise<MigrationRow[]>;
203
+ /** Insert a new applied migration row; appliedAt is set by the DB. */
204
+ recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void>;
205
+ /** Delete an applied migration row (used by `migrate down`). */
206
+ removeApplied(id: string): Promise<void>;
207
+ /** Atomic lock acquire — true if we got it, false if held. Owner string is recorded for diagnostics. */
208
+ acquireLock(owner: string): Promise<boolean>;
209
+ /** Release the lock (no-op if not held). */
210
+ releaseLock(): Promise<void>;
211
+ /** Run arbitrary SQL inside a transaction. Used to apply up.sql / down.sql. */
212
+ applySqlInTx(sql: string): Promise<void>;
213
+ /** Apply SQL outside any transaction — for migrations with `meta.transaction: false` (CREATE INDEX CONCURRENTLY etc). */
214
+ applySqlNoTx(sql: string): Promise<void>;
215
+ /** Introspect the live schema; returns the canonical SchemaSnapshot. Used by drift detection and `kick db introspect`. */
216
+ introspect(): Promise<SchemaSnapshot>;
217
+ /** Close any underlying pool / connection. Caller-owned resources may keep the no-op. */
218
+ close(): Promise<void>;
219
+ }
220
+ //#endregion
221
+ //#region src/migrate/schema.d.ts
222
+ declare const KICK_MIGRATIONS_TABLE = "kick_migrations";
223
+ declare const KICK_LOCK_TABLE = "kick_migrations_lock";
224
+ declare function migrationsTableDdl(dialect: Dialect): string;
225
+ declare function lockTableDdl(dialect: Dialect): string;
226
+ //#endregion
227
+ //#region src/migrate/memory-adapter.d.ts
228
+ /**
229
+ * In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-
230
+ * holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as
231
+ * test-only stubs — the real DB-bound semantics are validated in db-pg's
232
+ * integration tests, not here.
233
+ */
234
+ declare class MemoryMigrationAdapter implements MigrationAdapter {
235
+ readonly dialect: Dialect;
236
+ private rows;
237
+ private locked;
238
+ private appliedSql;
239
+ private currentSchema;
240
+ ensureMigrationTables(): Promise<void>;
241
+ listApplied(): Promise<MigrationRow[]>;
242
+ recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void>;
243
+ removeApplied(id: string): Promise<void>;
244
+ acquireLock(owner: string): Promise<boolean>;
245
+ releaseLock(): Promise<void>;
246
+ applySqlInTx(sql: string): Promise<void>;
247
+ applySqlNoTx(sql: string): Promise<void>;
248
+ introspect(): Promise<SchemaSnapshot>;
249
+ close(): Promise<void>;
250
+ /** Test-only setter — let drift tests stage a "live" schema state. */
251
+ __setIntrospectedSchema(snap: SchemaSnapshot): void;
252
+ /** Test-only inspector — what SQL we received. */
253
+ __appliedSql(): readonly string[];
254
+ }
255
+ //#endregion
256
+ //#region src/migrate/introspect-types.d.ts
257
+ /**
258
+ * Driver-agnostic SQL runner. Both pg.Client and pg.Pool match this shape via
259
+ * structural typing. Lets introspectPg() stay portable across pg / pg-pool /
260
+ * @neondatabase/serverless without importing 'pg' from the core package.
261
+ */
262
+ interface PgQueryRunner {
263
+ query<R = unknown>(sql: string, params?: readonly unknown[]): Promise<{
264
+ rows: R[];
265
+ }>;
266
+ }
267
+ interface IntrospectPgOptions {
268
+ /** Default 'public'. */
269
+ schema?: string;
270
+ /** Migration tracking tables to skip. Default ['kick_migrations', 'kick_migrations_lock']. */
271
+ excludeTables?: readonly string[];
272
+ }
273
+ //#endregion
274
+ //#region src/migrate/introspect-pg.d.ts
275
+ declare function introspectPg(client: PgQueryRunner, opts?: IntrospectPgOptions): Promise<SchemaSnapshot>;
276
+ //#endregion
277
+ //#region src/migrate/drift.d.ts
278
+ type DriftBehavior = 'error' | 'warn' | 'ignore';
279
+ interface DriftLogger {
280
+ warn: (message: string) => void;
281
+ }
282
+ declare function checkDrift(liveSnapshot: SchemaSnapshot, expectedSnapshot: SchemaSnapshot, behavior: DriftBehavior, log?: DriftLogger): Promise<void>;
283
+ //#endregion
284
+ //#region src/adapter.d.ts
285
+ type MigrationsOnBoot = 'fail-if-pending' | 'apply' | 'ignore';
286
+ interface KickDbAdapterConfig {
287
+ /** The driver-bound MigrationAdapter — pgAdapter() in @forinda/kickjs-db-pg, etc. */
288
+ migrationAdapter: MigrationAdapter;
289
+ /** Directory containing the generated migrations + _journal.json. */
290
+ migrationsDir: string;
291
+ /** Boot policy. Default 'fail-if-pending' — mirror the operator-explicit philosophy. */
292
+ migrationsOnBoot?: MigrationsOnBoot;
293
+ /** Drift detection mode. Default 'error' outside dev. */
294
+ driftCheck?: DriftBehavior;
295
+ /** Default true outside dev. */
296
+ requireReviewed?: boolean;
297
+ /** Optional DI token to register the migrationAdapter under, for adopters who need direct access. */
298
+ token?: InjectionToken<MigrationAdapter>;
299
+ }
300
+ /**
301
+ * KickJS lifecycle adapter for kickjs-db. Three jobs:
302
+ *
303
+ * 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.
304
+ * - 'fail-if-pending' (default): throw if any pending exists. Operators
305
+ * run `kick db migrate latest` explicitly before deploys land. Avoids
306
+ * the prisma footgun where migrations silently apply on deploy.
307
+ * - 'apply': run migrateLatest() automatically. Useful for dev / preview
308
+ * environments where convenience matters more than safety.
309
+ * - 'ignore': boot regardless. Last-resort escape hatch.
310
+ * 2. On shutdown, close the migrationAdapter (drains the pool, etc).
311
+ * 3. Register the migrationAdapter under an optional DI token so adopters
312
+ * can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers
313
+ * separately under DB_PRIMARY.
314
+ */
315
+ declare const kickDbAdapter: _$_forinda_kickjs0.AdapterFactory<KickDbAdapterConfig, unknown>;
316
+ //#endregion
317
+ //#region src/extend/types.d.ts
318
+ /**
319
+ * Method bag keyed by table name. Methods receive `this` as the
320
+ * extended client (the runtime calls them with `Function.prototype.call`
321
+ * so the binding is correct). Adopter-side TS annotation:
322
+ * `this: typeof dbX` — fine for v1; full self-typed inference is a
323
+ * separate refactor.
324
+ */
325
+ type ModelExtensions<DB> = { [Table in keyof DB & string]?: Record<string, (...args: never[]) => unknown> };
326
+ /** Top-level shape passed to `db.$extends(...)`. */
327
+ interface ExtensionDefinition<DB> {
328
+ model?: ModelExtensions<DB>;
329
+ }
330
+ /**
331
+ * Result type of `db.$extends({ model })` — the original client
332
+ * intersected with a per-table method bag. Adopters who want the
333
+ * result type to flow elsewhere can `type DbX = ReturnType<typeof
334
+ * extend>`; the inference is structural so usage stays clean.
335
+ */
336
+ type ExtendedClient<DB, E extends ExtensionDefinition<DB>> = KickDbClient<DB> & { [T in keyof NonNullable<E['model']> & keyof DB & string]: NonNullable<NonNullable<E['model']>[T]> };
337
+ //#endregion
338
+ //#region src/client/register.d.ts
339
+ /**
340
+ * Module-augmentable registry for the typed KickJS-DB surface. Adopters
341
+ * declare:
342
+ *
343
+ * declare module '@forinda/kickjs-db' {
344
+ * interface KickDbRegister {
345
+ * db: typeof appDbClient
346
+ * }
347
+ * }
348
+ *
349
+ * Once the augmentation is in scope, `KickDbClient` (with no explicit
350
+ * generic) widens to the registered DB shape everywhere —
351
+ * `@Inject(DB_PRIMARY) private db!: KickDbClient` produces the typed
352
+ * client with no manual cast at the call site.
353
+ *
354
+ * `kick db typegen` (M2.B-T9) emits this declaration into
355
+ * `.kickjs/types/kick__db.d.ts` for adopters who opt into codegen. Adopters
356
+ * who prefer to declare it by hand do so once in any module that's reached
357
+ * by their tsconfig.
358
+ *
359
+ * Named `KickDbRegister` rather than a generic `Register` to avoid
360
+ * collisions with other libraries that augment a same-named interface.
361
+ */
362
+ interface KickDbRegister {}
363
+ /**
364
+ * Pull the registered DB shape out of the augmentable KickDbRegister.
365
+ * `unknown` when the adopter hasn't declared an augmentation — keeps the
366
+ * M1-permissive fallback intact.
367
+ */
368
+ type RegisteredDB = KickDbRegister extends {
369
+ db: {
370
+ qb: {
371
+ __DB__?: never;
372
+ };
373
+ };
374
+ } ? unknown : KickDbRegister extends {
375
+ db: infer D;
376
+ } ? D extends {
377
+ qb: _$kysely.Kysely<infer X>;
378
+ } ? X : unknown : unknown;
379
+ //#endregion
380
+ //#region src/client/types.d.ts
381
+ interface QueryEvent {
382
+ sql: string;
383
+ parameters: readonly unknown[];
384
+ durationMs: number;
385
+ }
386
+ interface QueryErrorEvent {
387
+ sql: string;
388
+ parameters: readonly unknown[];
389
+ error: unknown;
390
+ }
391
+ interface BeforeQueryEvent {
392
+ /** Mutable — listeners may rewrite sql / parameters before execution. */
393
+ sql: string;
394
+ parameters: unknown[];
395
+ }
396
+ interface TransactionEvent {
397
+ isolation?: 'serializable' | 'repeatable read' | 'read committed' | 'read uncommitted';
398
+ }
399
+ interface TransactionRollbackEvent extends TransactionEvent {
400
+ error: unknown;
401
+ }
402
+ /**
403
+ * Fired when a query exceeds `createDbClient({ slowQueryThresholdMs })`.
404
+ * The `query` event ALSO fires for the same query — `slowQuery` is a
405
+ * separate channel so listeners can subscribe to slow ones only
406
+ * without filtering every query themselves.
407
+ */
408
+ interface SlowQueryEvent extends QueryEvent {
409
+ /** The configured threshold the query exceeded. */
410
+ thresholdMs: number;
411
+ }
412
+ interface KickDbClientEvents {
413
+ beforeQuery: BeforeQueryEvent;
414
+ query: QueryEvent;
415
+ queryError: QueryErrorEvent;
416
+ slowQuery: SlowQueryEvent;
417
+ transactionStart: TransactionEvent;
418
+ transactionCommit: TransactionEvent;
419
+ transactionRollback: TransactionRollbackEvent;
420
+ }
421
+ /**
422
+ * KickDbClient wraps a Kysely instance with three additions:
423
+ *
424
+ * 1. Lifecycle events (`on('query', ...)` etc) for observability + RLS
425
+ * rewriting via `beforeQuery`.
426
+ * 2. transaction(fn) / transaction(opts, fn) — passes a fully-scoped child
427
+ * client whose mutations are isolated.
428
+ * 3. tx.savepoint(fn) — nested rollback boundary inside an outer transaction.
429
+ *
430
+ * The underlying query builder is exposed as `db.qb` for advanced cases
431
+ * that need APIs not surfaced through the wrapper. Adopters typically
432
+ * never reach for `qb` — `selectFrom` / `insertInto` / etc. cover the
433
+ * common query surface.
434
+ *
435
+ * NB: Rather than re-typing every query method on this surface, we
436
+ * directly expose `selectFrom`/`insertInto`/`updateTable`/`deleteFrom`
437
+ * as bound functions of the underlying builder — keeps us in sync with
438
+ * upstream type evolution without manual mirroring.
439
+ */
440
+ interface KickDbClient<DB = RegisteredDB> {
441
+ /** Underlying query builder — escape hatch for advanced cases. */
442
+ readonly qb: Kysely<DB>;
443
+ readonly dialect: 'postgres' | 'sqlite' | 'mysql';
444
+ selectFrom: Kysely<DB>['selectFrom'];
445
+ insertInto: Kysely<DB>['insertInto'];
446
+ updateTable: Kysely<DB>['updateTable'];
447
+ deleteFrom: Kysely<DB>['deleteFrom'];
448
+ on<E extends keyof KickDbClientEvents>(event: E, listener: (e: KickDbClientEvents[E]) => void | Promise<void>): this;
449
+ off<E extends keyof KickDbClientEvents>(event: E, listener: (e: KickDbClientEvents[E]) => void | Promise<void>): this;
450
+ transaction<T>(fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
451
+ transaction<T>(opts: TransactionEvent, fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
452
+ savepoint<T>(fn: (sp: KickDbClient<DB>) => Promise<T>): Promise<T>;
453
+ /**
454
+ * Returns a wrapped client carrying adopter-defined per-table
455
+ * methods. Inside each method, `this` is the extended client so
456
+ * call-chains stay clean:
457
+ *
458
+ * const dbX = db.$extends({
459
+ * model: {
460
+ * users: {
461
+ * findByEmail(this: typeof dbX, email: string) {
462
+ * return this.selectFrom('users')
463
+ * .where('email', '=', email)
464
+ * .executeTakeFirst()
465
+ * },
466
+ * },
467
+ * },
468
+ * })
469
+ *
470
+ * await dbX.users.findByEmail('a@b.com')
471
+ *
472
+ * Result extensions (`compute()` over selected rows) and the
473
+ * insert-side toDriver pass land as follow-ups; v1 ships model
474
+ * methods only.
475
+ */
476
+ $extends<E extends ExtensionDefinition<DB>>(ext: E): ExtendedClient<DB, E>;
477
+ destroy(): Promise<void>;
478
+ }
479
+ interface CreateDbClientOptions<TSchema, _DB = unknown> {
480
+ /** Schema record — only used for type inference (M2-S1 tightens). */
481
+ schema: TSchema;
482
+ /** A Kysely Dialect — typically PostgresDialect from db-pg. */
483
+ dialect: Dialect$1;
484
+ /**
485
+ * Enable lifecycle event emission for `query` / `queryError` /
486
+ * `slowQuery` / `transactionStart` / `transactionCommit` /
487
+ * `transactionRollback`. Default `false` — zero overhead path; the
488
+ * Kysely log callback isn't even installed.
489
+ */
490
+ events?: boolean;
491
+ /**
492
+ * Fire the `slowQuery` event for any query whose duration exceeds
493
+ * this threshold (milliseconds). Default `null` — no slow-query
494
+ * detection. Setting a value implies `events: true` so the listener
495
+ * surface is attached.
496
+ */
497
+ slowQueryThresholdMs?: number | null;
498
+ }
499
+ //#endregion
500
+ //#region src/tokens.d.ts
501
+ declare const DB_PRIMARY: InjectionToken<KickDbClient>;
502
+ declare const DB_REPLICA: InjectionToken<KickDbClient>;
503
+ /**
504
+ * Alias for the default DB. Adopters who only have one database can inject
505
+ * `DB_CLIENT` instead of remembering whether it's primary/replica.
506
+ */
507
+ declare const DB_CLIENT: InjectionToken<KickDbClient<unknown>>;
508
+ //#endregion
509
+ //#region src/dsl/constraints.d.ts
510
+ interface IndexDecl {
511
+ name: string;
512
+ columns: string[];
513
+ unique: boolean;
514
+ }
515
+ interface ColRef {
516
+ __name: string;
517
+ }
518
+ declare function index(name: string): {
519
+ on(...cols: ColRef[]): IndexDecl;
520
+ };
521
+ declare function unique(name: string): {
522
+ on(...cols: ColRef[]): IndexDecl;
523
+ };
524
+ //#endregion
525
+ //#region src/dsl/table.d.ts
526
+ interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>> {
527
+ __isTable: true;
528
+ __name: TName;
529
+ __columns: C;
530
+ __indexes: IndexDecl[];
531
+ }
532
+ type TableRefs<TName extends string, C extends Record<string, ColumnBuilder>> = TableDecl<TName, C> & { [K in keyof C]: ColumnRef };
533
+ type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: { [K in keyof C]: ColumnRef }) => Record<string, IndexDecl>;
534
+ /**
535
+ * Declare a typed table. The `TName extends string` generic narrows to the
536
+ * literal table name so `SchemaToTypes<S>` can index by it without losing
537
+ * the constant — `table('users', …)` widens to `TableDecl<'users', …>`,
538
+ * not `TableDecl<string, …>`.
539
+ */
540
+ declare function table<TName extends string, C extends Record<string, ColumnBuilder>>(name: TName, columns: C, constraints?: ConstraintBuilder<C>): TableRefs<TName, C>;
541
+ //#endregion
542
+ //#region src/client/schema-types.d.ts
543
+ /**
544
+ * Pull each column's TS type and nullability into the row shape Kysely
545
+ * consumes as its `Database` interface.
546
+ *
547
+ * - Columns carrying the `GeneratedBrand` (set by serial / bigSerial /
548
+ * `default(...)` / `defaultNow()` / `defaultRandom()`) wrap in
549
+ * Kysely's `Generated<T>` so adopters can omit them on insert.
550
+ * - `notNull()` / `primaryKey()` stamp `NotNullBrand`, which drops the
551
+ * `| null` from the row type for that column.
552
+ * - `jsonb<{...}>()` carries the user-declared shape through without
553
+ * widening to `unknown`.
554
+ *
555
+ * The `Generated<T> | null` form for nullable + default columns models the
556
+ * SQL semantics: omitted on insert, the DB returns the default; if `null`
557
+ * is explicitly inserted, the DB stores null.
558
+ */
559
+ type IsNullable<C> = C extends NotNullBrand ? false : true;
560
+ 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;
561
+ 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 };
562
+ //#endregion
563
+ //#region src/client/create.d.ts
564
+ declare function createDbClient<TSchema, DB = SchemaToTypes<TSchema>>(opts: CreateDbClientOptions<TSchema, DB>): KickDbClient<DB>;
565
+ //#endregion
566
+ //#region src/migrate/runner.d.ts
567
+ interface RunnerOptions {
568
+ adapter: MigrationAdapter;
569
+ migrationsDir: string;
570
+ /** When true, refuse to apply migrations whose meta.json.reviewed is false. Defaults to true outside dev. */
571
+ requireReviewed?: boolean;
572
+ /** Owner string written into the lock table for diagnostics. */
573
+ owner?: string;
574
+ /** Drift detection mode. Default 'error'. */
575
+ driftCheck?: DriftBehavior;
576
+ /** Logger surface for drift warnings. Defaults to console. */
577
+ log?: DriftLogger;
578
+ }
579
+ interface AppliedSummary {
580
+ applied: string[];
581
+ batch: number | null;
582
+ }
583
+ declare function migrateLatest(opts: RunnerOptions): Promise<AppliedSummary>;
584
+ declare function migrateUp(opts: RunnerOptions): Promise<AppliedSummary>;
585
+ interface ReversedSummary {
586
+ reversed: string | null;
587
+ }
588
+ declare function migrateDown(opts: RunnerOptions): Promise<ReversedSummary>;
589
+ interface RollbackSummary {
590
+ reversed: string[];
591
+ batch: number | null;
592
+ }
593
+ interface StatusEntry {
594
+ id: string;
595
+ tag: string;
596
+ hash: string;
597
+ state: 'applied' | 'pending';
598
+ batch: number | null;
599
+ appliedAt: string | null;
600
+ reviewed: boolean;
601
+ }
602
+ declare function migrateStatus(opts: Pick<RunnerOptions, 'adapter' | 'migrationsDir'>): Promise<StatusEntry[]>;
603
+ declare function migrateRollback(opts: RunnerOptions): Promise<RollbackSummary>;
604
+ //#endregion
605
+ //#region src/emit/pg.d.ts
606
+ declare function emitPg(changes: ChangeSet): string;
607
+ //#endregion
608
+ //#region src/cli/config.d.ts
609
+ type MigrationAdapterFactory = () => MigrationAdapter | Promise<MigrationAdapter>;
610
+ interface DbConfig {
611
+ schemaPath: string;
612
+ migrationsDir: string;
613
+ dialect: Dialect;
614
+ /**
615
+ * Postgres connection string for the built-in pgAdapter path. Read from
616
+ * `db.connectionString` in kick.config.ts, or falls back to the
617
+ * DATABASE_URL env var. The CLI uses this when no `adapter` factory is
618
+ * provided.
619
+ */
620
+ connectionString?: string;
621
+ /**
622
+ * Escape hatch: a factory returning a fully-constructed MigrationAdapter.
623
+ * Takes precedence over `connectionString` when both are set. Use this
624
+ * for non-default adapter wiring (custom pool, neon-serverless, etc).
625
+ */
626
+ adapter?: MigrationAdapterFactory;
627
+ }
628
+ declare function resolveDbConfig(opts: {
629
+ configPath: string;
630
+ }): Promise<DbConfig>;
631
+ //#endregion
632
+ //#region src/cli/generate.d.ts
633
+ interface GenerateOptions {
634
+ name: string;
635
+ config: DbConfig;
636
+ cwd: string;
637
+ now?: () => Date;
638
+ /**
639
+ * When true, skip the schema diff and emit an empty migration shell
640
+ * (up.sql / down.sql with just the REVIEWED header, snapshot.json copying
641
+ * the prior schema state). Used for data migrations, seed inserts, or any
642
+ * change the diff engine can't author. Matches knex's `migrate:make`.
643
+ */
644
+ empty?: boolean;
645
+ }
646
+ interface GenerateResult {
647
+ status: 'created' | 'no-changes';
648
+ migrationDir?: string;
649
+ changeCount: number;
650
+ empty?: boolean;
651
+ }
652
+ declare function generate(opts: GenerateOptions): Promise<GenerateResult>;
653
+ //#endregion
654
+ //#region src/dsl/columns/builders.d.ts
655
+ declare function serial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand;
656
+ declare function bigSerial(): ColumnBuilder<bigint> & GeneratedBrand & NotNullBrand;
657
+ declare function smallSerial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand;
658
+ declare function integer(): ColumnBuilder<number>;
659
+ declare function bigint(): ColumnBuilder<bigint>;
660
+ declare function smallint(): ColumnBuilder<number>;
661
+ declare function decimal(precision?: number, scale?: number): ColumnBuilder<string>;
662
+ declare function numeric(precision?: number, scale?: number): ColumnBuilder<string>;
663
+ declare function real(): ColumnBuilder<number>;
664
+ declare function doublePrecision(): ColumnBuilder<number>;
665
+ declare function varchar(length?: number): ColumnBuilder<string>;
666
+ declare function char(length?: number): ColumnBuilder<string>;
667
+ declare function text(): ColumnBuilder<string>;
668
+ declare function boolean(): ColumnBuilder<boolean>;
669
+ /**
670
+ * Subtype builder so `defaultNow()` can mark the resulting column as
671
+ * generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter
672
+ * omits the column on insert. Returns `this & GeneratedBrand` so the
673
+ * subclass identity is preserved through the chain.
674
+ */
675
+ declare class TimestampBuilder extends ColumnBuilder<Date> {
676
+ constructor(typeName?: string);
677
+ defaultNow(): this & GeneratedBrand;
678
+ }
679
+ declare function timestamp(): TimestampBuilder;
680
+ declare function timestamptz(): TimestampBuilder;
681
+ declare function date(): ColumnBuilder<Date>;
682
+ declare function time(): ColumnBuilder<string>;
683
+ declare function interval(): ColumnBuilder<string>;
684
+ /**
685
+ * Subtype builder so `defaultRandom()` can mark the resulting column as
686
+ * generated — when the DB fills in `gen_random_uuid()` for omitted columns.
687
+ * Returns `this & GeneratedBrand` so chaining works in either order:
688
+ * uuid().defaultRandom().primaryKey()
689
+ * uuid().primaryKey().defaultRandom() ← also works
690
+ */
691
+ declare class UuidBuilder extends ColumnBuilder<string> {
692
+ constructor();
693
+ defaultRandom(): this & GeneratedBrand;
694
+ }
695
+ declare function uuid(): UuidBuilder;
696
+ /**
697
+ * The `T` generic exists so adopters can declare their JSON shape:
698
+ *
699
+ * meta: jsonb<{ tags: string[] }>()
700
+ *
701
+ * `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the
702
+ * row type narrows to `{ tags: string[] } | null`.
703
+ */
704
+ declare function json<T = unknown>(): ColumnBuilder<T>;
705
+ declare function jsonb<T = unknown>(): ColumnBuilder<T>;
706
+ declare function bytea(): ColumnBuilder<Uint8Array>;
707
+ //#endregion
708
+ //#region src/dsl/relations.d.ts
709
+ interface RelationOne {
710
+ kind: 'one';
711
+ target: TableDecl<string, Record<string, ColumnBuilder>>;
712
+ fields: ColumnRef[];
713
+ references: ColumnRef[];
714
+ }
715
+ interface RelationMany {
716
+ kind: 'many';
717
+ target: TableDecl<string, Record<string, ColumnBuilder>>;
718
+ }
719
+ type Relation = RelationOne | RelationMany;
720
+ interface RelationsDecl {
721
+ __isRelations: true;
722
+ __sourceTable: string;
723
+ __relations: Record<string, Relation>;
724
+ }
725
+ interface Helpers {
726
+ one: (target: TableDecl<string, Record<string, ColumnBuilder>>, opts: {
727
+ fields: ColumnRef[];
728
+ references: ColumnRef[];
729
+ }) => RelationOne;
730
+ many: (target: TableDecl<string, Record<string, ColumnBuilder>>) => RelationMany;
731
+ }
732
+ declare function relations<T extends TableDecl<string, Record<string, ColumnBuilder>>>(source: T, builder: (h: Helpers) => Record<string, Relation>): RelationsDecl;
733
+ //#endregion
734
+ //#region src/custom-type.d.ts
735
+ interface CustomTypeOptions<TJs, TDriver = unknown> {
736
+ /**
737
+ * SQL data type as it would appear in `CREATE TABLE` — `'text'`,
738
+ * `'jsonb'`, `'citext'`, `'geometry(Point, 4326)'`, etc. Returned
739
+ * via a thunk so adopters can compute the type from runtime config
740
+ * (e.g. dialect-specific overrides).
741
+ */
742
+ dataType: () => string;
743
+ /** Optional encode hook applied at insert / update time. */
744
+ toDriver?: (value: TJs) => TDriver;
745
+ /** Optional decode hook applied to selected rows. */
746
+ fromDriver?: (driver: TDriver) => TJs;
747
+ }
748
+ /**
749
+ * ColumnBuilder subclass produced by `customType()`. Carries the
750
+ * driver codecs so the (future) hooks pipeline can wire them through
751
+ * a Kysely plugin without each consumer re-declaring its mapping.
752
+ *
753
+ * The phantom `T` flows through `SchemaToTypes<S>` exactly like any
754
+ * other ColumnBuilder<T>, so adopters get full row-shape inference
755
+ * for free.
756
+ */
757
+ declare class CustomColumnBuilder<TJs> extends ColumnBuilder<TJs> {
758
+ /** Encode hook — run on values heading into the database. */
759
+ readonly toDriver?: (value: TJs) => unknown;
760
+ /** Decode hook — run on row values coming out of the database. */
761
+ readonly fromDriver?: (driver: unknown) => TJs;
762
+ constructor(opts: CustomTypeOptions<TJs>);
763
+ }
764
+ /**
765
+ * Build a reusable column factory for a custom type. The returned
766
+ * function is what callers use inside `table('foo', { col: factory() })`
767
+ * — same shape as the built-in `varchar()`, `text()`, etc.
768
+ *
769
+ * @example
770
+ * ```ts
771
+ * const ulid = customType<string>({
772
+ * dataType: () => 'char(26)',
773
+ * toDriver: (s) => s,
774
+ * fromDriver: (raw) => String(raw),
775
+ * })
776
+ *
777
+ * const events = table('events', {
778
+ * id: ulid().primaryKey(),
779
+ * ts: timestamp().notNull().defaultNow(),
780
+ * })
781
+ * ```
782
+ */
783
+ declare function customType<TJs>(opts: CustomTypeOptions<TJs>): () => CustomColumnBuilder<TJs>;
784
+ //#endregion
785
+ export { AddColumn, AddEnumValue, AddForeignKey, AddIndex, AlterColumn, type AppliedSummary, type BeforeQueryEvent, Change, ChangeSet, type CheckSnapshot, ColumnBuilder, type ColumnRef, type ColumnSnapshot, ColumnState, type CreateDbClientOptions, CreateEnum, CreateTable, CustomColumnBuilder, type CustomTypeOptions, DB_CLIENT, DB_PRIMARY, DB_REPLICA, type DbConfig, type Dialect, type DriftBehavior, type DriftLogger, DropColumn, DropEnum, DropForeignKey, DropIndex, DropTable, type ExtendedClient, type ExtensionDefinition, type FkAction, FkSpec, type ForeignKeySnapshot, type GenerateOptions, type GenerateResult, 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, MemoryMigrationAdapter, type MigrationAdapter, MigrationDriftError, MigrationError, MigrationHashError, MigrationLockError, type MigrationRow, type MigrationsOnBoot, type ModelExtensions, NotNullBrand, type PgQueryRunner, type QueryErrorEvent, type QueryEvent, type RegisteredDB, Relation, RelationMany, RelationOne, RelationsDecl, RenameColumn, RenameTable, type ReversedSummary, type RollbackSummary, type RunnerOptions, type SchemaDiffSummary, type SchemaSnapshot, type SchemaToTypes, type StatusEntry, TableDecl, type TableSnapshot, TimestampBuilder, type TransactionEvent, type TransactionRollbackEvent, UnreviewedMigrationError, UuidBuilder, appendJournalEntry, bigSerial, bigint, boolean, bytea, char, checkDrift, computeMigrationHash, createDbClient, customType, date, decimal, diff, doublePrecision, emitPg, extractSnapshot, generate, hasAmbiguousReverse, index, integer, interval, introspectPg, invertChanges, json, jsonb, kickDbAdapter, lockTableDdl, migrateDown, migrateLatest, migrateRollback, migrateStatus, migrateUp, migrationsTableDdl, numeric, readJournal, real, relations, renderSchemaSource, resolveDbConfig, serial, smallSerial, smallint, table, text, time, timestamp, timestamptz, unique, uuid, varchar, verifyMigrationHash };
786
+ //# sourceMappingURL=index.d.mts.map