@forinda/kickjs-db 8.0.0 → 8.2.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 (60) 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-BaiUxRiE.mjs +29 -0
  7. package/dist/create-BaiUxRiE.mjs.map +1 -0
  8. package/dist/custom-type-DoPt91ZM.mjs +12 -0
  9. package/dist/custom-type-DoPt91ZM.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-BQQWKybR.d.mts → index-BJYFXCB4.d.mts} +702 -167
  13. package/dist/index-BJYFXCB4.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-CuKSRK4C.mjs +12 -0
  21. package/dist/pg-CuKSRK4C.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 +1 -1
  31. package/dist/schema.mjs +2 -2
  32. package/dist/schema.mjs.map +1 -1
  33. package/dist/split-statements-DFaB7cus.mjs +14 -0
  34. package/dist/split-statements-DFaB7cus.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-CXdCpvjp.mjs +199 -0
  40. package/dist/src-CXdCpvjp.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-BnYMhgYq.d.mts} +352 -9
  48. package/dist/types-BnYMhgYq.d.mts.map +1 -0
  49. package/dist/{schema-DDMkteEP.d.mts → types-DNAKmwPO.d.mts} +174 -159
  50. package/dist/types-DNAKmwPO.d.mts.map +1 -0
  51. package/package.json +16 -6
  52. package/dist/custom-type-CZdUgkPT.mjs +0 -12
  53. package/dist/custom-type-CZdUgkPT.mjs.map +0 -1
  54. package/dist/index-BQQWKybR.d.mts.map +0 -1
  55. package/dist/pg-CwNv938J.mjs +0 -12
  56. package/dist/pg-CwNv938J.mjs.map +0 -1
  57. package/dist/schema-DDMkteEP.d.mts.map +0 -1
  58. package/dist/src-BEJ33yHI.mjs +0 -166
  59. package/dist/src-BEJ33yHI.mjs.map +0 -1
  60. package/dist/types-DtvYnaXL.d.mts.map +0 -1
@@ -1,5 +1,42 @@
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
+ /** The keys `where` always has — an optional one may be missing. */
28
+ type PresentKeys<W> = { [K in keyof W]-?: {} extends Pick<W, K> ? never : K; }[keyof W];
29
+ /** What `create` adds to `where`: every required column `where` may leave out. */
30
+ type CreateRest<DB, T extends keyof DB, W> = Omit<Insertable<DB[T]>, PresentKeys<W>> & Partial<Insertable<DB[T]>>;
31
+ type FindOrCreateOptions<DB, T extends keyof DB & string, W extends Partial<Selectable<DB[T]>> = Partial<Selectable<DB[T]>>> = {
32
+ /** Identifies the row — columns of a unique key. Also part of what's created. */
33
+ where: W & Record<Exclude<keyof W, keyof Selectable<DB[T]>>, never>;
34
+ } & ({} extends CreateRest<DB, T, W> ? {
35
+ create?: CreateRest<DB, T, W>;
36
+ } : {
37
+ create: CreateRest<DB, T, W>;
38
+ });
39
+ //#endregion
3
40
  //#region src/extend/types.d.ts
4
41
  /**
5
42
  * Method bag keyed by table name. Methods receive `this` as the
@@ -58,6 +95,136 @@ type ComputedFields<Bag> = Bag extends Record<string, {
58
95
  */
59
96
  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
97
  //#endregion
98
+ //#region src/tenancy.d.ts
99
+ /**
100
+ * How tenants' rows are kept apart:
101
+ *
102
+ * - `'column'` — shared tables, a tenant column; kick/db adds the tenant to
103
+ * every query on a tenanted table and fills it on insert.
104
+ * - `'rls'` — shared tables, a tenant column, and a Postgres policy per
105
+ * tenanted table; kick/db hands each connection the current tenant, so
106
+ * the database filters.
107
+ * - `'schema'` — a Postgres schema per tenant; kick/db points each query at
108
+ * the tenant's schema.
109
+ * - `'database'` — a database per tenant (any dialect: a Postgres database,
110
+ * a SQLite / libsql / D1 file per tenant); kick/db sends each query to the
111
+ * tenant's database. `bypass()` uses the client's own `dialect` — the
112
+ * central database.
113
+ */
114
+ type TenancyStrategy = 'column' | 'rls' | 'schema' | 'database';
115
+ interface TenancyOptions {
116
+ strategy: TenancyStrategy;
117
+ /**
118
+ * The current tenant's id outside `run()`. Default: the request's `tenant`
119
+ * value (what a `LoadTenant` context contributor sets) — its `id`, or the
120
+ * value itself when it's a string. `undefined` means no tenant.
121
+ */
122
+ current?: () => string | undefined;
123
+ /** `'rls'`: the setting the policy reads. Default `app.tenant_id`. */
124
+ setting?: string;
125
+ /** `'schema'`: the schema for a tenant. Default `tenant_<id>`. */
126
+ schemaFor?: (tenantId: string) => string;
127
+ /**
128
+ * `'database'`: the dialect for a tenant's database. Called when the
129
+ * tenant's connections open — again after they were closed for being idle
130
+ * (`tenantIdleMs`) or to make room (`maxOpenTenants`).
131
+ */
132
+ dialectFor?: (tenantId: string) => Dialect;
133
+ /**
134
+ * `'database'`: close a tenant's connections after this long unused.
135
+ * Default 10 minutes; `0` keeps them for the client's life.
136
+ */
137
+ tenantIdleMs?: number;
138
+ /**
139
+ * `'database'`: at most this many tenants' connections open at once — the
140
+ * least recently used idle one is closed to make room. A soft cap: tenants
141
+ * with a query in flight are never closed. Default unlimited.
142
+ */
143
+ maxOpenTenants?: number;
144
+ /**
145
+ * `'rls'`: how a connection gets the tenant.
146
+ *
147
+ * - `'transaction'` (default) — `set_config(…, true)`, local to a
148
+ * transaction: a query outside one runs in its own short transaction.
149
+ * Safe behind a transaction-mode pooler (PgBouncer, Supavisor, Neon's
150
+ * pooler), which hands a server connection to another client between
151
+ * transactions.
152
+ * - `'connection'` — `set_config(…, false)` on the connection when it's
153
+ * handed out, only when the tenant changes: fewer round trips, but only
154
+ * for a pool that owns its connections (node-postgres' `Pool`, a direct
155
+ * connection). Behind a transaction-mode pooler the setting would leak to
156
+ * whoever gets the connection next.
157
+ */
158
+ binding?: 'transaction' | 'connection';
159
+ /**
160
+ * `'rls'`: a dialect connecting as a role that bypasses row-level security
161
+ * (`BYPASSRLS`, e.g. the migration role) — what `bypass()` runs on. Without
162
+ * it, `bypass()` throws under `'rls'`: there's no safe way for the app's own
163
+ * role to switch policies off (a flag any SQL can set is one injection away).
164
+ */
165
+ bypassDialect?: Dialect;
166
+ /** Called on every `bypass()`, for an audit log. */
167
+ onBypass?: (info: BypassInfo) => void;
168
+ /**
169
+ * `'rls'`: what to do when the app's role would skip the policies anyway —
170
+ * a superuser or `BYPASSRLS` role. Checked on the first connection.
171
+ * Default `'error'`.
172
+ */
173
+ roleCheck?: 'error' | 'warn' | 'off';
174
+ }
175
+ interface BypassInfo {
176
+ reason: string;
177
+ strategy: TenancyStrategy;
178
+ /** Where `bypass()` was called. */
179
+ stack: string | undefined;
180
+ }
181
+ interface BypassOptions {
182
+ /** Why — passed to `onBypass`, for the audit log. */
183
+ reason: string;
184
+ /** Allow it inside an HTTP request (refused there by default). */
185
+ allowInRequest?: boolean;
186
+ }
187
+ interface Tenancy extends Readonly<Required<Pick<TenancyOptions, 'strategy' | 'setting' | 'schemaFor' | 'binding' | 'roleCheck'>>> {
188
+ readonly bypassDialect?: Dialect;
189
+ readonly dialectFor?: (tenantId: string) => Dialect;
190
+ readonly tenantIdleMs: number;
191
+ readonly maxOpenTenants: number;
192
+ readonly __isTenancy: true;
193
+ /** Run `fn` as `tenantId` — jobs, cron, scripts, tests. Nested runs switch tenant. */
194
+ run<T>(tenantId: string, fn: () => T): T;
195
+ /**
196
+ * Run `fn` across every tenant — admin work, cross-tenant reports: no tenant
197
+ * filter (`'column'`), no schema switch (`'schema'`), the `bypassDialect`'s
198
+ * connections (`'rls'`). Needs a reason, reported to `onBypass`, and is
199
+ * refused inside an HTTP request unless `allowInRequest`.
200
+ */
201
+ bypass<T>(fn: () => T, options: BypassOptions): T;
202
+ /** The tenant in effect: an id, `null` inside `bypass()`, or `undefined` for none. */
203
+ current(): string | null | undefined;
204
+ }
205
+ /** Thrown when a tenanted table is queried with no tenant in effect. */
206
+ declare class TenantRequiredError extends Error {
207
+ constructor(table: string);
208
+ }
209
+ declare function defineTenancy(options: TenancyOptions): Tenancy;
210
+ /**
211
+ * The tenant column of a tenanted table — what marks it tenanted. Filled
212
+ * from the current tenant on insert, so it's optional there.
213
+ *
214
+ * ```ts
215
+ * export const notes = table('notes', {
216
+ * id: serial().primaryKey(),
217
+ * tenantId: tenantKey(tenancy),
218
+ * body: text().notNull(),
219
+ * })
220
+ * ```
221
+ *
222
+ * With `'rls'` the table also gets row-level security, forced (the app
223
+ * usually connects as the owner), and a policy matching the column to the
224
+ * setting. Pass another column to change its type: `tenantKey(tenancy, uuid())`.
225
+ */
226
+ declare function tenantKey<T = string>(tenancy: Tenancy, column?: ColumnBuilder<T>): ColumnBuilder<T> & NotNullBrand & GeneratedBrand;
227
+ //#endregion
61
228
  //#region src/client/register.d.ts
62
229
  /**
63
230
  * Module-augmentable registry for the typed KickJS-DB surface. Adopters
@@ -158,9 +325,9 @@ type TableRelations<Table extends string> = Table extends keyof RegisteredRelati
158
325
  *
159
326
  * Helpers like `eb.and(...)`, `eb.or(...)`, `eb.ref('col')`,
160
327
  * `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.
328
+ * `eb.eq` — that's the callable form. For a sort direction wrap the
329
+ * ref in `desc()` / `asc()` from `@forinda/kickjs-db`:
330
+ * orderBy: (_u, eb) => [desc(eb.ref('createdAt')), asc(eb.ref('id'))]
164
331
  */
165
332
  type QueryOps<DB, Table extends keyof DB & string> = ExpressionBuilder<DB, Table>;
166
333
  /**
@@ -190,6 +357,21 @@ interface FindManyOptions<DB = RegisteredDB, Table extends keyof DB & string = k
190
357
  offset?: number;
191
358
  /** Override the spec's default depth guard (5). Throws `RelationalQueryDepthError` on excess. */
192
359
  maxDepth?: number;
360
+ /**
361
+ * Include rows a `softDelete()` column marks as deleted. Applies to this
362
+ * level only — set it inside a `with` entry for related rows.
363
+ */
364
+ withDeleted?: boolean;
365
+ /**
366
+ * Which columns to return. Name the ones you want (`{ id: true, email: true }`),
367
+ * or the ones you don't (`{ passwordHash: false }`); not both kinds at once.
368
+ */
369
+ columns?: { [K in keyof DB[Table]]?: boolean; };
370
+ /**
371
+ * Computed fields, each an SQL expression over the row:
372
+ * `{ commentCount: (_p, eb) => eb.selectFrom('comments')…select(eb.fn.countAll().as('n')) }`.
373
+ */
374
+ extras?: Record<string, (table: TableRefs<DB, Table>, ops: QueryOps<DB, Table>) => Expression<unknown>>;
193
375
  with?: WithClause<DB, TableRelations<Table>>;
194
376
  /**
195
377
  * Cancellation handle. When the signal aborts, the in-flight
@@ -217,7 +399,19 @@ type WithClause<DB, Rels extends Record<string, RelationMapEntry>> = { [K in key
217
399
  * Resolved row shape returned by `findMany`. Base table columns
218
400
  * intersected with the per-relation slot map produced by `with`.
219
401
  */
220
- type FindManyRow<DB, Table extends keyof DB & string, Opts extends FindManyOptions<DB, Table>> = DB[Table] & WithSlots<DB, Table, Opts['with']>;
402
+ 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']>;
403
+ /**
404
+ * The row's columns narrowed by `columns`: only the `true` ones when any is
405
+ * `true`, otherwise all but the `false` ones.
406
+ */
407
+ 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.
408
+ ? 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;
409
+ /**
410
+ * Each extra's value type, read off the expression it returns. A scalar
411
+ * subquery (`eb.selectFrom(…).select(x.as('n'))`) is its one column's value,
412
+ * or null when it finds no row.
413
+ */
414
+ 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
415
  /**
222
416
  * Map each present `with` key to its resolved relation slot. Absent
223
417
  * keys do not appear in the result shape — adopters who omit `with`
@@ -238,6 +432,15 @@ interface TableQueryNamespace<DB, Table extends keyof DB & string> {
238
432
  findMany<O extends FindManyOptions<DB, Table>>(options?: O): Promise<Array<FindManyRow<DB, Table, O>>>;
239
433
  findFirst<O extends FindManyOptions<DB, Table>>(options?: O): Promise<FindManyRow<DB, Table, O> | null>;
240
434
  findUnique<O extends FindManyOptions<DB, Table>>(options: O): Promise<FindManyRow<DB, Table, O> | null>;
435
+ /**
436
+ * `findMany` plus the number of rows `where` matches before `limit` /
437
+ * `offset` — one page and the total, the `{ data, total }` shape `ctx.paginate` takes.
438
+ * Runs two queries.
439
+ */
440
+ findManyAndCount<O extends FindManyOptions<DB, Table>>(options?: O): Promise<{
441
+ data: Array<FindManyRow<DB, Table, O>>;
442
+ total: number;
443
+ }>;
241
444
  }
242
445
  /**
243
446
  * Top-level `db.query` namespace. One slot per table in `DB`. Defaults
@@ -269,6 +472,58 @@ interface TransactionEvent {
269
472
  interface TransactionRollbackEvent extends TransactionEvent {
270
473
  error: unknown;
271
474
  }
475
+ /** Fired before a transaction is run again after a retryable failure. */
476
+ interface TransactionRetryEvent extends TransactionEvent {
477
+ /** The attempt about to run — `2` is the first retry. */
478
+ attempt: number;
479
+ /** What failed the previous attempt (a serialization failure or deadlock). */
480
+ error: unknown;
481
+ delayMs: number;
482
+ }
483
+ /** Options for `transaction(opts, fn)`. */
484
+ interface TransactionOptions extends TransactionEvent {
485
+ /**
486
+ * What to do when a transaction is already open on this call chain:
487
+ *
488
+ * - `'reuse'` (default) — run inside it; the outer one commits or rolls back.
489
+ * - `'savepoint'` — run inside it behind a savepoint, so a throw undoes only this part.
490
+ * - `'separate'` — open an independent transaction on another connection.
491
+ *
492
+ * `isolation` and `retry` apply only when a transaction actually starts.
493
+ */
494
+ nested?: 'reuse' | 'savepoint' | 'separate';
495
+ /**
496
+ * Start the transaction read-only (Postgres, MySQL): a write inside it fails.
497
+ * For reports that must see one consistent view and must not change it.
498
+ * SQLite has no read-only transactions, so it's refused there.
499
+ */
500
+ readOnly?: boolean;
501
+ /**
502
+ * Run the transaction as this role (`SET LOCAL ROLE`, Postgres): row-level
503
+ * security policies `TO` that role apply. The connection's own role must be
504
+ * a member of it.
505
+ */
506
+ role?: string;
507
+ /**
508
+ * Settings for this transaction only (`set_config(key, value, true)`,
509
+ * Postgres), for policies to read with `current_setting('app.user_id')`.
510
+ * Keys need a dot (`app.user_id`). Values are bound, never spliced into SQL.
511
+ */
512
+ settings?: Record<string, string | number | boolean>;
513
+ /**
514
+ * Run the whole transaction again when it fails with a retryable error —
515
+ * a serialization failure or deadlock (`err.retryable`). `true` is three
516
+ * attempts; waits between them back off exponentially with jitter.
517
+ *
518
+ * The callback runs once per attempt, so keep side effects outside the
519
+ * database in `afterCommit`.
520
+ */
521
+ retry?: boolean | number | {
522
+ attempts: number;
523
+ baseDelayMs?: number;
524
+ maxDelayMs?: number;
525
+ };
526
+ }
272
527
  /**
273
528
  * Fired when a query exceeds `createDbClient({ slowQueryThresholdMs })`.
274
529
  * The `query` event ALSO fires for the same query — `slowQuery` is a
@@ -287,6 +542,7 @@ interface KickDbClientEvents {
287
542
  transactionStart: TransactionEvent;
288
543
  transactionCommit: TransactionEvent;
289
544
  transactionRollback: TransactionRollbackEvent;
545
+ transactionRetry: TransactionRetryEvent;
290
546
  }
291
547
  /**
292
548
  * KickDbClient wraps a Kysely instance with three additions:
@@ -312,6 +568,19 @@ interface KickDbClient<DB = RegisteredDB> {
312
568
  readonly qb: Kysely<DB>;
313
569
  readonly dialect: 'postgres' | 'sqlite' | 'mysql';
314
570
  selectFrom: Kysely<DB>['selectFrom'];
571
+ /**
572
+ * Start a query with a common table expression. Takes Kysely's
573
+ * `(name, query)`, or a CTE made once with `cte()` and spread in:
574
+ * `db.with(...recent).selectFrom('recent')`. Runs on the primary.
575
+ */
576
+ with: Kysely<DB>['with'];
577
+ withRecursive: Kysely<DB>['withRecursive'];
578
+ /**
579
+ * A named CTE to reuse across queries: `const recent = db.cte('recent', (q) =>
580
+ * q.selectFrom('posts').where(…))`, then `db.with(...recent)`. Typed from
581
+ * the query; works with any client of the same schema.
582
+ */
583
+ cte<N extends string, E extends CommonTableExpression<DB, N>>(name: N, query: E): readonly [N, E];
315
584
  insertInto: Kysely<DB>['insertInto'];
316
585
  updateTable: Kysely<DB>['updateTable'];
317
586
  deleteFrom: Kysely<DB>['deleteFrom'];
@@ -330,9 +599,56 @@ interface KickDbClient<DB = RegisteredDB> {
330
599
  readonly query: QueryNamespace<DB>;
331
600
  on<E extends keyof KickDbClientEvents>(event: E, listener: (e: KickDbClientEvents[E]) => void | Promise<void>): this;
332
601
  off<E extends keyof KickDbClientEvents>(event: E, listener: (e: KickDbClientEvents[E]) => void | Promise<void>): this;
602
+ /**
603
+ * Insert, or update the rows whose `target` key already exists — one
604
+ * statement (`ON CONFLICT … DO UPDATE` / `ON DUPLICATE KEY UPDATE`).
605
+ * Returns the rows as stored.
606
+ *
607
+ * await db.upsert('users', { values: { email, name }, target: ['email'] })
608
+ */
609
+ upsert<T extends keyof DB & string>(table: T, opts: UpsertOptions<DB, T> & {
610
+ values: Insertable<DB[T]>;
611
+ }): Promise<Selectable<DB[T]>>;
612
+ upsert<T extends keyof DB & string>(table: T, opts: UpsertOptions<DB, T> & {
613
+ values: ReadonlyArray<Insertable<DB[T]>>;
614
+ }): Promise<Selectable<DB[T]>[]>;
615
+ /**
616
+ * The row matching `where`, or a new one from `where` + `create`;
617
+ * `created` says which. Race-safe across concurrent requests.
618
+ *
619
+ * const { row, created } = await db.findOrCreate('tags', { where: { name: 'urgent' } })
620
+ */
621
+ findOrCreate<T extends keyof DB & string, W extends Partial<Selectable<DB[T]>>>(table: T, opts: FindOrCreateOptions<DB, T, W>): Promise<{
622
+ row: Selectable<DB[T]>;
623
+ created: boolean;
624
+ }>;
625
+ /**
626
+ * Re-run a materialized view's query and store the new result (Postgres).
627
+ * `concurrently: true` keeps the view readable while it refreshes; it
628
+ * needs a unique index on the view, and can't run inside a transaction.
629
+ */
630
+ refreshMaterializedView(name: keyof DB & string, options?: {
631
+ concurrently?: boolean;
632
+ }): Promise<void>;
333
633
  transaction<T>(fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
334
- transaction<T>(opts: TransactionEvent, fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
634
+ transaction<T>(opts: TransactionOptions, fn: (tx: KickDbClient<DB>) => Promise<T>): Promise<T>;
335
635
  savepoint<T>(fn: (sp: KickDbClient<DB>) => Promise<T>): Promise<T>;
636
+ /**
637
+ * Run `fn` once the current transaction commits — send the email, publish
638
+ * the event. Dropped if it rolls back (or the savepoint it was registered
639
+ * in does). Outside a transaction, runs right away.
640
+ *
641
+ * A hook that throws is reported to the error observers; the transaction
642
+ * stays committed.
643
+ */
644
+ afterCommit(fn: () => unknown): Promise<void>;
645
+ /** Whether this call chain is inside a transaction. */
646
+ readonly inTransaction: boolean;
647
+ /**
648
+ * This client with every read on the primary — for reading what you just
649
+ * wrote when replicas lag. The same client when there are no replicas.
650
+ */
651
+ readonly primary: KickDbClient<DB>;
336
652
  /**
337
653
  * Returns a wrapped client carrying adopter-defined per-table
338
654
  * methods. Inside each method, `this` is the extended client so
@@ -362,8 +678,29 @@ interface KickDbClient<DB = RegisteredDB> {
362
678
  interface CreateDbClientOptions<TSchema, _DB = unknown> {
363
679
  /** Schema record — only used for type inference (M2-S1 tightens). */
364
680
  schema: TSchema;
365
- /** A Kysely Dialect — typically PostgresDialect from db-pg. */
681
+ /**
682
+ * A Kysely dialect: `pgDialect` / `mysqlDialect` / `sqliteDialect`, or any
683
+ * Kysely dialect (Neon, D1, libsql, `bun:sqlite`, PlanetScale…).
684
+ */
366
685
  dialect: Dialect;
686
+ /**
687
+ * Which SQL `dialect` speaks, when it can't be told from the dialect:
688
+ * kick/db's own dialects say so, and others are recognised by their
689
+ * Kysely adapter. A dialect that's neither throws until this is set.
690
+ */
691
+ dialectTag?: 'postgres' | 'mysql' | 'sqlite';
692
+ /**
693
+ * Keep tenants apart: the same `defineTenancy()` the schema's
694
+ * `tenantKey()` columns use. See {@link import('../tenancy').defineTenancy}.
695
+ */
696
+ tenancy?: Tenancy;
697
+ /**
698
+ * Read replicas — a dialect, or several used in turn. Reads outside a
699
+ * transaction (`selectFrom`, `db.query`) go to a replica; writes, raw
700
+ * `db.qb`, and everything inside a transaction go to `dialect`. Read your
701
+ * own writes through `db.primary`.
702
+ */
703
+ replica?: Dialect | readonly Dialect[];
367
704
  /**
368
705
  * Enable lifecycle event emission for `query` / `queryError` /
369
706
  * `slowQuery` / `transactionStart` / `transactionCommit` /
@@ -440,7 +777,13 @@ interface CreateDbClientOptions<TSchema, _DB = unknown> {
440
777
  * inline. Tracked upstream at <https://github.com/forinda/kick-js/issues/220>.
441
778
  */
442
779
  plugins?: KyselyPlugin[];
780
+ /**
781
+ * `'snake_case'`: tables and columns are snake_case in the database and
782
+ * camelCase in TypeScript — `firstName` is the `first_name` column. Set the
783
+ * same `casing` in `kick.config.ts` so migrations use those names.
784
+ */
785
+ casing?: 'snake_case';
443
786
  }
444
787
  //#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
788
+ 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 };
789
+ //# sourceMappingURL=types-BnYMhgYq.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BnYMhgYq.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;;;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