@forinda/kickjs-db 7.4.0 → 8.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.
Files changed (61) hide show
  1. package/README.md +16 -45
  2. package/dist/cli.d.mts +16 -2
  3. package/dist/cli.d.mts.map +1 -1
  4. package/dist/cli.mjs +4 -3
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/create-CwuC1odW.mjs +29 -0
  7. package/dist/create-CwuC1odW.mjs.map +1 -0
  8. package/dist/custom-type-DeGuRFuz.mjs +12 -0
  9. package/dist/custom-type-DeGuRFuz.mjs.map +1 -0
  10. package/dist/devtools-events.d.mts +1 -1
  11. package/dist/devtools-events.mjs +1 -1
  12. package/dist/{index-DF69HndC.d.mts → index-2fEnHqpn.d.mts} +814 -156
  13. package/dist/index-2fEnHqpn.d.mts.map +1 -0
  14. package/dist/index.d.mts +6 -4
  15. package/dist/index.mjs +2 -2
  16. package/dist/mysql.d.mts +41 -37
  17. package/dist/mysql.d.mts.map +1 -1
  18. package/dist/mysql.mjs +8 -8
  19. package/dist/mysql.mjs.map +1 -1
  20. package/dist/pg-CsmRByEZ.mjs +12 -0
  21. package/dist/pg-CsmRByEZ.mjs.map +1 -0
  22. package/dist/pg.d.mts +74 -8
  23. package/dist/pg.d.mts.map +1 -1
  24. package/dist/pg.mjs +8 -7
  25. package/dist/pg.mjs.map +1 -1
  26. package/dist/schema-BjGAg-s1.d.mts +95 -0
  27. package/dist/schema-BjGAg-s1.d.mts.map +1 -0
  28. package/dist/schema-types-DH-d43Pf.d.mts +51 -0
  29. package/dist/schema-types-DH-d43Pf.d.mts.map +1 -0
  30. package/dist/schema.d.mts +2 -87
  31. package/dist/schema.mjs +2 -2
  32. package/dist/schema.mjs.map +1 -1
  33. package/dist/split-statements-BPCw9cII.mjs +14 -0
  34. package/dist/split-statements-BPCw9cII.mjs.map +1 -0
  35. package/dist/sqlite.d.mts +86 -6
  36. package/dist/sqlite.d.mts.map +1 -1
  37. package/dist/sqlite.mjs +13 -7
  38. package/dist/sqlite.mjs.map +1 -1
  39. package/dist/src-DUtVGG2c.mjs +199 -0
  40. package/dist/src-DUtVGG2c.mjs.map +1 -0
  41. package/dist/table-CGPsm5i7.d.mts +221 -0
  42. package/dist/table-CGPsm5i7.d.mts.map +1 -0
  43. package/dist/testing.d.mts +53 -0
  44. package/dist/testing.d.mts.map +1 -0
  45. package/dist/testing.mjs +12 -0
  46. package/dist/testing.mjs.map +1 -0
  47. package/dist/{types-DtvYnaXL.d.mts → types-BZoTujcR.d.mts} +346 -9
  48. package/dist/types-BZoTujcR.d.mts.map +1 -0
  49. package/dist/{table-Bl5SbKRg.d.mts → types-DNAKmwPO.d.mts} +186 -64
  50. package/dist/types-DNAKmwPO.d.mts.map +1 -0
  51. package/package.json +14 -4
  52. package/dist/custom-type-j8k__3sL.mjs +0 -12
  53. package/dist/custom-type-j8k__3sL.mjs.map +0 -1
  54. package/dist/index-DF69HndC.d.mts.map +0 -1
  55. package/dist/pg-BJmYKLhI.mjs +0 -12
  56. package/dist/pg-BJmYKLhI.mjs.map +0 -1
  57. package/dist/schema.d.mts.map +0 -1
  58. package/dist/src-BnHTLx5l.mjs +0 -166
  59. package/dist/src-BnHTLx5l.mjs.map +0 -1
  60. package/dist/table-Bl5SbKRg.d.mts.map +0 -1
  61. package/dist/types-DtvYnaXL.d.mts.map +0 -1
@@ -1,5 +1,36 @@
1
1
 
2
- import { Dialect, Expression, ExpressionBuilder, Kysely, KyselyPlugin } from "kysely";
2
+ import { l as NotNullBrand, o as GeneratedBrand, t as ColumnBuilder } from "./types-DNAKmwPO.mjs";
3
+ import { CommonTableExpression, Dialect, Expression, ExpressionBuilder, Insertable, Kysely, KyselyPlugin, SelectQueryBuilder, Selectable, SqlBool, UpdateObject } from "kysely";
4
+ //#region src/client/upsert.d.ts
5
+ interface UpsertOptions<DB, T extends keyof DB & string> {
6
+ /** The row — or rows — to insert. */
7
+ values: Insertable<DB[T]> | ReadonlyArray<Insertable<DB[T]>>;
8
+ /**
9
+ * The unique key (or primary key) whose conflict turns the insert into an
10
+ * update. On MySQL, any unique key conflicts — MySQL has no target; this is
11
+ * still used to read the rows back.
12
+ */
13
+ target: ReadonlyArray<keyof DB[T] & string>;
14
+ /**
15
+ * What to update on a conflict: column names take the incoming row's value
16
+ * (the default is every inserted column outside `target`); an object sets
17
+ * values or expressions — ``{ views: sql`page_views.views + 1` }``.
18
+ */
19
+ update?: ReadonlyArray<keyof DB[T] & string> | UpdateObject<DB, T>;
20
+ /**
21
+ * The predicate of a partial unique index `target` refers to (Postgres,
22
+ * SQLite). Write it as the index does, with literals — ``() => sql`active = 1` ``:
23
+ * the database matches it against the index, and a bound parameter can't be.
24
+ */
25
+ where?: (eb: ExpressionBuilder<DB, T>) => Expression<SqlBool>;
26
+ }
27
+ interface FindOrCreateOptions<DB, T extends keyof DB & string> {
28
+ /** Identifies the row — columns of a unique key. Also part of what's created. */
29
+ where: Partial<Selectable<DB[T]>>;
30
+ /** The rest of the row to create when none matches `where`. */
31
+ create?: Partial<Insertable<DB[T]>>;
32
+ }
33
+ //#endregion
3
34
  //#region src/extend/types.d.ts
4
35
  /**
5
36
  * Method bag keyed by table name. Methods receive `this` as the
@@ -58,6 +89,136 @@ type ComputedFields<Bag> = Bag extends Record<string, {
58
89
  */
59
90
  type ExtendedClient<DB, E extends ExtensionDefinition<DB>> = KickDbClient<E['result'] extends ResultExtensions<DB> ? DBWithResults<DB, NonNullable<E['result']>> : DB> & { [T in keyof NonNullable<E['model']> & keyof DB & string]: NonNullable<NonNullable<E['model']>[T]>; };
60
91
  //#endregion
92
+ //#region src/tenancy.d.ts
93
+ /**
94
+ * How tenants' rows are kept apart:
95
+ *
96
+ * - `'column'` — shared tables, a tenant column; kick/db adds the tenant to
97
+ * every query on a tenanted table and fills it on insert.
98
+ * - `'rls'` — shared tables, a tenant column, and a Postgres policy per
99
+ * tenanted table; kick/db hands each connection the current tenant, so
100
+ * the database filters.
101
+ * - `'schema'` — a Postgres schema per tenant; kick/db points each query at
102
+ * the tenant's schema.
103
+ * - `'database'` — a database per tenant (any dialect: a Postgres database,
104
+ * a SQLite / libsql / D1 file per tenant); kick/db sends each query to the
105
+ * tenant's database. `bypass()` uses the client's own `dialect` — the
106
+ * central database.
107
+ */
108
+ type TenancyStrategy = 'column' | 'rls' | 'schema' | 'database';
109
+ interface TenancyOptions {
110
+ strategy: TenancyStrategy;
111
+ /**
112
+ * The current tenant's id outside `run()`. Default: the request's `tenant`
113
+ * value (what a `LoadTenant` context contributor sets) — its `id`, or the
114
+ * value itself when it's a string. `undefined` means no tenant.
115
+ */
116
+ current?: () => string | undefined;
117
+ /** `'rls'`: the setting the policy reads. Default `app.tenant_id`. */
118
+ setting?: string;
119
+ /** `'schema'`: the schema for a tenant. Default `tenant_<id>`. */
120
+ schemaFor?: (tenantId: string) => string;
121
+ /**
122
+ * `'database'`: the dialect for a tenant's database. Called when the
123
+ * tenant's connections open — again after they were closed for being idle
124
+ * (`tenantIdleMs`) or to make room (`maxOpenTenants`).
125
+ */
126
+ dialectFor?: (tenantId: string) => Dialect;
127
+ /**
128
+ * `'database'`: close a tenant's connections after this long unused.
129
+ * Default 10 minutes; `0` keeps them for the client's life.
130
+ */
131
+ tenantIdleMs?: number;
132
+ /**
133
+ * `'database'`: at most this many tenants' connections open at once — the
134
+ * least recently used idle one is closed to make room. A soft cap: tenants
135
+ * with a query in flight are never closed. Default unlimited.
136
+ */
137
+ maxOpenTenants?: number;
138
+ /**
139
+ * `'rls'`: how a connection gets the tenant.
140
+ *
141
+ * - `'transaction'` (default) — `set_config(…, true)`, local to a
142
+ * transaction: a query outside one runs in its own short transaction.
143
+ * Safe behind a transaction-mode pooler (PgBouncer, Supavisor, Neon's
144
+ * pooler), which hands a server connection to another client between
145
+ * transactions.
146
+ * - `'connection'` — `set_config(…, false)` on the connection when it's
147
+ * handed out, only when the tenant changes: fewer round trips, but only
148
+ * for a pool that owns its connections (node-postgres' `Pool`, a direct
149
+ * connection). Behind a transaction-mode pooler the setting would leak to
150
+ * whoever gets the connection next.
151
+ */
152
+ binding?: 'transaction' | 'connection';
153
+ /**
154
+ * `'rls'`: a dialect connecting as a role that bypasses row-level security
155
+ * (`BYPASSRLS`, e.g. the migration role) — what `bypass()` runs on. Without
156
+ * it, `bypass()` throws under `'rls'`: there's no safe way for the app's own
157
+ * role to switch policies off (a flag any SQL can set is one injection away).
158
+ */
159
+ bypassDialect?: Dialect;
160
+ /** Called on every `bypass()`, for an audit log. */
161
+ onBypass?: (info: BypassInfo) => void;
162
+ /**
163
+ * `'rls'`: what to do when the app's role would skip the policies anyway —
164
+ * a superuser or `BYPASSRLS` role. Checked on the first connection.
165
+ * Default `'error'`.
166
+ */
167
+ roleCheck?: 'error' | 'warn' | 'off';
168
+ }
169
+ interface BypassInfo {
170
+ reason: string;
171
+ strategy: TenancyStrategy;
172
+ /** Where `bypass()` was called. */
173
+ stack: string | undefined;
174
+ }
175
+ interface BypassOptions {
176
+ /** Why — passed to `onBypass`, for the audit log. */
177
+ reason: string;
178
+ /** Allow it inside an HTTP request (refused there by default). */
179
+ allowInRequest?: boolean;
180
+ }
181
+ interface Tenancy extends Readonly<Required<Pick<TenancyOptions, 'strategy' | 'setting' | 'schemaFor' | 'binding' | 'roleCheck'>>> {
182
+ readonly bypassDialect?: Dialect;
183
+ readonly dialectFor?: (tenantId: string) => Dialect;
184
+ readonly tenantIdleMs: number;
185
+ readonly maxOpenTenants: number;
186
+ readonly __isTenancy: true;
187
+ /** Run `fn` as `tenantId` — jobs, cron, scripts, tests. Nested runs switch tenant. */
188
+ run<T>(tenantId: string, fn: () => T): T;
189
+ /**
190
+ * Run `fn` across every tenant — admin work, cross-tenant reports: no tenant
191
+ * filter (`'column'`), no schema switch (`'schema'`), the `bypassDialect`'s
192
+ * connections (`'rls'`). Needs a reason, reported to `onBypass`, and is
193
+ * refused inside an HTTP request unless `allowInRequest`.
194
+ */
195
+ bypass<T>(fn: () => T, options: BypassOptions): T;
196
+ /** The tenant in effect: an id, `null` inside `bypass()`, or `undefined` for none. */
197
+ current(): string | null | undefined;
198
+ }
199
+ /** Thrown when a tenanted table is queried with no tenant in effect. */
200
+ declare class TenantRequiredError extends Error {
201
+ constructor(table: string);
202
+ }
203
+ declare function defineTenancy(options: TenancyOptions): Tenancy;
204
+ /**
205
+ * The tenant column of a tenanted table — what marks it tenanted. Filled
206
+ * from the current tenant on insert, so it's optional there.
207
+ *
208
+ * ```ts
209
+ * export const notes = table('notes', {
210
+ * id: serial().primaryKey(),
211
+ * tenantId: tenantKey(tenancy),
212
+ * body: text().notNull(),
213
+ * })
214
+ * ```
215
+ *
216
+ * With `'rls'` the table also gets row-level security, forced (the app
217
+ * usually connects as the owner), and a policy matching the column to the
218
+ * setting. Pass another column to change its type: `tenantKey(tenancy, uuid())`.
219
+ */
220
+ declare function tenantKey<T = string>(tenancy: Tenancy, column?: ColumnBuilder<T>): ColumnBuilder<T> & NotNullBrand & GeneratedBrand;
221
+ //#endregion
61
222
  //#region src/client/register.d.ts
62
223
  /**
63
224
  * Module-augmentable registry for the typed KickJS-DB surface. Adopters
@@ -158,9 +319,9 @@ type TableRelations<Table extends string> = Table extends keyof RegisteredRelati
158
319
  *
159
320
  * Helpers like `eb.and(...)`, `eb.or(...)`, `eb.ref('col')`,
160
321
  * `eb.fn.count(...)` are Kysely's standard surface. There is no
161
- * `eb.eq` — that's the callable form. There is no `eb.desc` —
162
- * order direction lands as a separate Kysely call (e.g. wrap the
163
- * ref expression in `sql\`... desc\``) when needed in v1.
322
+ * `eb.eq` — that's the callable form. For a sort direction wrap the
323
+ * ref in `desc()` / `asc()` from `@forinda/kickjs-db`:
324
+ * orderBy: (_u, eb) => [desc(eb.ref('createdAt')), asc(eb.ref('id'))]
164
325
  */
165
326
  type QueryOps<DB, Table extends keyof DB & string> = ExpressionBuilder<DB, Table>;
166
327
  /**
@@ -190,6 +351,21 @@ interface FindManyOptions<DB = RegisteredDB, Table extends keyof DB & string = k
190
351
  offset?: number;
191
352
  /** Override the spec's default depth guard (5). Throws `RelationalQueryDepthError` on excess. */
192
353
  maxDepth?: number;
354
+ /**
355
+ * Include rows a `softDelete()` column marks as deleted. Applies to this
356
+ * level only — set it inside a `with` entry for related rows.
357
+ */
358
+ withDeleted?: boolean;
359
+ /**
360
+ * Which columns to return. Name the ones you want (`{ id: true, email: true }`),
361
+ * or the ones you don't (`{ passwordHash: false }`); not both kinds at once.
362
+ */
363
+ columns?: { [K in keyof DB[Table]]?: boolean; };
364
+ /**
365
+ * Computed fields, each an SQL expression over the row:
366
+ * `{ commentCount: (_p, eb) => eb.selectFrom('comments')…select(eb.fn.countAll().as('n')) }`.
367
+ */
368
+ extras?: Record<string, (table: TableRefs<DB, Table>, ops: QueryOps<DB, Table>) => Expression<unknown>>;
193
369
  with?: WithClause<DB, TableRelations<Table>>;
194
370
  /**
195
371
  * Cancellation handle. When the signal aborts, the in-flight
@@ -217,7 +393,19 @@ type WithClause<DB, Rels extends Record<string, RelationMapEntry>> = { [K in key
217
393
  * Resolved row shape returned by `findMany`. Base table columns
218
394
  * intersected with the per-relation slot map produced by `with`.
219
395
  */
220
- type FindManyRow<DB, Table extends keyof DB & string, Opts extends FindManyOptions<DB, Table>> = DB[Table] & WithSlots<DB, Table, Opts['with']>;
396
+ type FindManyRow<DB, Table extends keyof DB & string, Opts extends FindManyOptions<DB, Table>> = SelectedColumns<DB[Table], Opts['columns']> & ExtraFields<Opts['extras']> & WithSlots<DB, Table, Opts['with']>;
397
+ /**
398
+ * The row's columns narrowed by `columns`: only the `true` ones when any is
399
+ * `true`, otherwise all but the `false` ones.
400
+ */
401
+ type SelectedColumns<Row, C> = C extends Record<string, boolean | undefined> ? true extends C[keyof C] // Inclusion: a literal `true` is there; a `boolean` flag may be.
402
+ ? Pick<Row, { [K in keyof C & keyof Row]: C[K] extends true ? K : never; }[keyof C & keyof Row]> & Partial<Pick<Row, { [K in keyof C & keyof Row]: C[K] extends true ? never : true extends C[K] ? K : never; }[keyof C & keyof Row]>> : Omit<Row, { [K in keyof C & keyof Row]: C[K] extends false ? K : never; }[keyof C & keyof Row]> : Row;
403
+ /**
404
+ * Each extra's value type, read off the expression it returns. A scalar
405
+ * subquery (`eb.selectFrom(…).select(x.as('n'))`) is its one column's value,
406
+ * or null when it finds no row.
407
+ */
408
+ type ExtraFields<E> = E extends Record<string, (...args: never[]) => Expression<unknown>> ? { [K in keyof E]: ReturnType<E[K]> extends SelectQueryBuilder<any, any, infer O> ? O[keyof O] | null : ReturnType<E[K]> extends Expression<infer T> ? T : never; } : {};
221
409
  /**
222
410
  * Map each present `with` key to its resolved relation slot. Absent
223
411
  * keys do not appear in the result shape — adopters who omit `with`
@@ -238,6 +426,15 @@ interface TableQueryNamespace<DB, Table extends keyof DB & string> {
238
426
  findMany<O extends FindManyOptions<DB, Table>>(options?: O): Promise<Array<FindManyRow<DB, Table, O>>>;
239
427
  findFirst<O extends FindManyOptions<DB, Table>>(options?: O): Promise<FindManyRow<DB, Table, O> | null>;
240
428
  findUnique<O extends FindManyOptions<DB, Table>>(options: O): Promise<FindManyRow<DB, Table, O> | null>;
429
+ /**
430
+ * `findMany` plus the number of rows `where` matches before `limit` /
431
+ * `offset` — one page and the total, the `{ data, total }` shape `ctx.paginate` takes.
432
+ * Runs two queries.
433
+ */
434
+ findManyAndCount<O extends FindManyOptions<DB, Table>>(options?: O): Promise<{
435
+ data: Array<FindManyRow<DB, Table, O>>;
436
+ total: number;
437
+ }>;
241
438
  }
242
439
  /**
243
440
  * Top-level `db.query` namespace. One slot per table in `DB`. Defaults
@@ -269,6 +466,58 @@ interface TransactionEvent {
269
466
  interface TransactionRollbackEvent extends TransactionEvent {
270
467
  error: unknown;
271
468
  }
469
+ /** Fired before a transaction is run again after a retryable failure. */
470
+ interface TransactionRetryEvent extends TransactionEvent {
471
+ /** The attempt about to run — `2` is the first retry. */
472
+ attempt: number;
473
+ /** What failed the previous attempt (a serialization failure or deadlock). */
474
+ error: unknown;
475
+ delayMs: number;
476
+ }
477
+ /** Options for `transaction(opts, fn)`. */
478
+ interface TransactionOptions extends TransactionEvent {
479
+ /**
480
+ * What to do when a transaction is already open on this call chain:
481
+ *
482
+ * - `'reuse'` (default) — run inside it; the outer one commits or rolls back.
483
+ * - `'savepoint'` — run inside it behind a savepoint, so a throw undoes only this part.
484
+ * - `'separate'` — open an independent transaction on another connection.
485
+ *
486
+ * `isolation` and `retry` apply only when a transaction actually starts.
487
+ */
488
+ nested?: 'reuse' | 'savepoint' | 'separate';
489
+ /**
490
+ * Start the transaction read-only (Postgres, MySQL): a write inside it fails.
491
+ * For reports that must see one consistent view and must not change it.
492
+ * SQLite has no read-only transactions, so it's refused there.
493
+ */
494
+ readOnly?: boolean;
495
+ /**
496
+ * Run the transaction as this role (`SET LOCAL ROLE`, Postgres): row-level
497
+ * security policies `TO` that role apply. The connection's own role must be
498
+ * a member of it.
499
+ */
500
+ role?: string;
501
+ /**
502
+ * Settings for this transaction only (`set_config(key, value, true)`,
503
+ * Postgres), for policies to read with `current_setting('app.user_id')`.
504
+ * Keys need a dot (`app.user_id`). Values are bound, never spliced into SQL.
505
+ */
506
+ settings?: Record<string, string | number | boolean>;
507
+ /**
508
+ * Run the whole transaction again when it fails with a retryable error —
509
+ * a serialization failure or deadlock (`err.retryable`). `true` is three
510
+ * attempts; waits between them back off exponentially with jitter.
511
+ *
512
+ * The callback runs once per attempt, so keep side effects outside the
513
+ * database in `afterCommit`.
514
+ */
515
+ retry?: boolean | number | {
516
+ attempts: number;
517
+ baseDelayMs?: number;
518
+ maxDelayMs?: number;
519
+ };
520
+ }
272
521
  /**
273
522
  * Fired when a query exceeds `createDbClient({ slowQueryThresholdMs })`.
274
523
  * The `query` event ALSO fires for the same query — `slowQuery` is a
@@ -287,6 +536,7 @@ interface KickDbClientEvents {
287
536
  transactionStart: TransactionEvent;
288
537
  transactionCommit: TransactionEvent;
289
538
  transactionRollback: TransactionRollbackEvent;
539
+ transactionRetry: TransactionRetryEvent;
290
540
  }
291
541
  /**
292
542
  * KickDbClient wraps a Kysely instance with three additions:
@@ -312,6 +562,19 @@ interface KickDbClient<DB = RegisteredDB> {
312
562
  readonly qb: Kysely<DB>;
313
563
  readonly dialect: 'postgres' | 'sqlite' | 'mysql';
314
564
  selectFrom: Kysely<DB>['selectFrom'];
565
+ /**
566
+ * Start a query with a common table expression. Takes Kysely's
567
+ * `(name, query)`, or a CTE made once with `cte()` and spread in:
568
+ * `db.with(...recent).selectFrom('recent')`. Runs on the primary.
569
+ */
570
+ with: Kysely<DB>['with'];
571
+ withRecursive: Kysely<DB>['withRecursive'];
572
+ /**
573
+ * A named CTE to reuse across queries: `const recent = db.cte('recent', (q) =>
574
+ * q.selectFrom('posts').where(…))`, then `db.with(...recent)`. Typed from
575
+ * the query; works with any client of the same schema.
576
+ */
577
+ cte<N extends string, E extends CommonTableExpression<DB, N>>(name: N, query: E): readonly [N, E];
315
578
  insertInto: Kysely<DB>['insertInto'];
316
579
  updateTable: Kysely<DB>['updateTable'];
317
580
  deleteFrom: Kysely<DB>['deleteFrom'];
@@ -330,9 +593,56 @@ interface KickDbClient<DB = RegisteredDB> {
330
593
  readonly query: QueryNamespace<DB>;
331
594
  on<E extends keyof KickDbClientEvents>(event: E, listener: (e: KickDbClientEvents[E]) => void | Promise<void>): this;
332
595
  off<E extends keyof KickDbClientEvents>(event: E, listener: (e: KickDbClientEvents[E]) => void | Promise<void>): this;
596
+ /**
597
+ * Insert, or update the rows whose `target` key already exists — one
598
+ * statement (`ON CONFLICT … DO UPDATE` / `ON DUPLICATE KEY UPDATE`).
599
+ * Returns the rows as stored.
600
+ *
601
+ * await db.upsert('users', { values: { email, name }, target: ['email'] })
602
+ */
603
+ upsert<T extends keyof DB & string>(table: T, opts: UpsertOptions<DB, T> & {
604
+ values: Insertable<DB[T]>;
605
+ }): Promise<Selectable<DB[T]>>;
606
+ upsert<T extends keyof DB & string>(table: T, opts: UpsertOptions<DB, T> & {
607
+ values: ReadonlyArray<Insertable<DB[T]>>;
608
+ }): Promise<Selectable<DB[T]>[]>;
609
+ /**
610
+ * The row matching `where`, or a new one from `where` + `create`;
611
+ * `created` says which. Race-safe across concurrent requests.
612
+ *
613
+ * const { row, created } = await db.findOrCreate('tags', { where: { name: 'urgent' } })
614
+ */
615
+ findOrCreate<T extends keyof DB & string>(table: T, opts: FindOrCreateOptions<DB, T>): Promise<{
616
+ row: Selectable<DB[T]>;
617
+ created: boolean;
618
+ }>;
619
+ /**
620
+ * Re-run a materialized view's query and store the new result (Postgres).
621
+ * `concurrently: true` keeps the view readable while it refreshes; it
622
+ * needs a unique index on the view, and can't run inside a transaction.
623
+ */
624
+ refreshMaterializedView(name: keyof DB & string, options?: {
625
+ concurrently?: boolean;
626
+ }): Promise<void>;
333
627
  transaction<T>(fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
334
- transaction<T>(opts: TransactionEvent, fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
628
+ transaction<T>(opts: TransactionOptions, fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
335
629
  savepoint<T>(fn: (sp: KickDbClient<DB>) => Promise<T>): Promise<T>;
630
+ /**
631
+ * Run `fn` once the current transaction commits — send the email, publish
632
+ * the event. Dropped if it rolls back (or the savepoint it was registered
633
+ * in does). Outside a transaction, runs right away.
634
+ *
635
+ * A hook that throws is reported to the error observers; the transaction
636
+ * stays committed.
637
+ */
638
+ afterCommit(fn: () => unknown): Promise<void>;
639
+ /** Whether this call chain is inside a transaction. */
640
+ readonly inTransaction: boolean;
641
+ /**
642
+ * This client with every read on the primary — for reading what you just
643
+ * wrote when replicas lag. The same client when there are no replicas.
644
+ */
645
+ readonly primary: KickDbClient<DB>;
336
646
  /**
337
647
  * Returns a wrapped client carrying adopter-defined per-table
338
648
  * methods. Inside each method, `this` is the extended client so
@@ -362,8 +672,29 @@ interface KickDbClient<DB = RegisteredDB> {
362
672
  interface CreateDbClientOptions<TSchema, _DB = unknown> {
363
673
  /** Schema record — only used for type inference (M2-S1 tightens). */
364
674
  schema: TSchema;
365
- /** A Kysely Dialect — typically PostgresDialect from db-pg. */
675
+ /**
676
+ * A Kysely dialect: `pgDialect` / `mysqlDialect` / `sqliteDialect`, or any
677
+ * Kysely dialect (Neon, D1, libsql, `bun:sqlite`, PlanetScale…).
678
+ */
366
679
  dialect: Dialect;
680
+ /**
681
+ * Which SQL `dialect` speaks, when it can't be told from the dialect:
682
+ * kick/db's own dialects say so, and others are recognised by their
683
+ * Kysely adapter. A dialect that's neither throws until this is set.
684
+ */
685
+ dialectTag?: 'postgres' | 'mysql' | 'sqlite';
686
+ /**
687
+ * Keep tenants apart: the same `defineTenancy()` the schema's
688
+ * `tenantKey()` columns use. See {@link import('../tenancy').defineTenancy}.
689
+ */
690
+ tenancy?: Tenancy;
691
+ /**
692
+ * Read replicas — a dialect, or several used in turn. Reads outside a
693
+ * transaction (`selectFrom`, `db.query`) go to a replica; writes, raw
694
+ * `db.qb`, and everything inside a transaction go to `dialect`. Read your
695
+ * own writes through `db.primary`.
696
+ */
697
+ replica?: Dialect | readonly Dialect[];
367
698
  /**
368
699
  * Enable lifecycle event emission for `query` / `queryError` /
369
700
  * `slowQuery` / `transactionStart` / `transactionCommit` /
@@ -440,7 +771,13 @@ interface CreateDbClientOptions<TSchema, _DB = unknown> {
440
771
  * inline. Tracked upstream at <https://github.com/forinda/kick-js/issues/220>.
441
772
  */
442
773
  plugins?: KyselyPlugin[];
774
+ /**
775
+ * `'snake_case'`: tables and columns are snake_case in the database and
776
+ * camelCase in TypeScript — `firstName` is the `first_name` column. Set the
777
+ * same `casing` in `kick.config.ts` so migrations use those names.
778
+ */
779
+ casing?: 'snake_case';
443
780
  }
444
781
  //#endregion
445
- export { ModelExtensions as C, ExtensionDefinition as S, TableRelations as _, QueryErrorEvent as a, RegisteredDB as b, TransactionEvent as c, FindManyRow as d, KickDbRelationsRegister as f, TableQueryNamespace as g, RelationMapEntry as h, KickDbClientEvents as i, TransactionRollbackEvent as l, RegisteredRelations as m, CreateDbClientOptions as n, QueryEvent as o, QueryNamespace as p, KickDbClient as r, SlowQueryEvent as s, BeforeQueryEvent as t, FindManyOptions as u, WithClause as v, ExtendedClient as x, KickDbRegister as y };
446
- //# sourceMappingURL=types-DtvYnaXL.d.mts.map
782
+ export { tenantKey as A, BypassInfo as C, TenancyStrategy as D, TenancyOptions as E, UpsertOptions as F, ExtensionDefinition as M, ModelExtensions as N, TenantRequiredError as O, FindOrCreateOptions as P, RegisteredDB as S, Tenancy as T, RelationMapEntry as _, QueryErrorEvent as a, WithClause as b, TransactionEvent as c, TransactionRollbackEvent as d, FindManyOptions as f, RegisteredRelations as g, QueryNamespace as h, KickDbClientEvents as i, ExtendedClient as j, defineTenancy as k, TransactionOptions as l, KickDbRelationsRegister as m, CreateDbClientOptions as n, QueryEvent as o, FindManyRow as p, KickDbClient as r, SlowQueryEvent as s, BeforeQueryEvent as t, TransactionRetryEvent as u, TableQueryNamespace as v, BypassOptions as w, KickDbRegister as x, TableRelations as y };
783
+ //# sourceMappingURL=types-BZoTujcR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BZoTujcR.d.mts","names":[],"sources":["../src/client/upsert.ts","../src/extend/types.ts","../src/tenancy.ts","../src/client/register.ts","../src/query/types.ts","../src/client/types.ts"],"mappings":";;;;UAkBiB,cAAc,IAAI,gBAAgB;;EAEjD,QAAQ,WAAW,GAAG,MAAM,cAAc,WAAW,GAAG;;;;;;EAMxD,QAAQ,oBAAoB,GAAG;;;;;;EAM/B,SAAS,oBAAoB,GAAG,eAAe,aAAa,IAAI;;;;;;EAMhE,SAAS,IAAI,kBAAkB,IAAI,OAAO,WAAW;;UAGtC,oBAAoB,IAAI,gBAAgB;;EAEvD,OAAO,QAAQ,WAAW,GAAG;;EAE7B,SAAS,QAAQ,WAAW,GAAG;;;;;;;;;;;KCFrB,gBAAgB,SACzB,eAAe,eAAe,mBAAmB;;;;;;;UASnC,gBAAgB;;EAE/B,OAAO,QAAQ,aAAa;;EAE5B,UAAU,KAA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