turbine-orm 0.95.0 → 0.96.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.
@@ -19,7 +19,7 @@ import { assertArrayWrite } from './query/writes.js';
19
19
  import { markInternalCombinator, resolveColumnName } from './query-utils.js';
20
20
  import { normalizeKeyColumns } from './schema.js';
21
21
  const MAX_DEPTH = 10;
22
- const CREATE_ONLY_OPS = new Set(['create', 'connect', 'connectOrCreate']);
22
+ const CREATE_ONLY_OPS = new Set(['create', 'createMany', 'connect', 'connectOrCreate']);
23
23
  const UPDATE_ONLY_OPS = new Set(['disconnect', 'set', 'delete', 'update', 'upsert']);
24
24
  // ---------------------------------------------------------------------------
25
25
  // Pure helpers (exported for testing)
@@ -135,6 +135,7 @@ function isRelationEntry(meta, key, value) {
135
135
  */
136
136
  const PAYLOAD_ROWS = [
137
137
  ['create', null],
138
+ ['createMany', ['data']],
138
139
  ['connectOrCreate', ['create']],
139
140
  ['update', ['data']],
140
141
  ['updateMany', ['data']],
@@ -300,10 +301,14 @@ function validateOps(relationName, ops, isUpdate, rel) {
300
301
  ? ', disconnect, delete, update, upsert'
301
302
  : ', disconnect, set, delete, update, upsert';
302
303
  throw new ValidationError(`Unknown nested write operation "${opName}" on relation "${relationName}". ` +
303
- `Valid operations: create, connect, connectOrCreate${isUpdate ? updateOps : ''}.`);
304
+ `Valid operations: create, createMany, connect, connectOrCreate${isUpdate ? updateOps : ''}.`);
304
305
  }
305
306
  if (absent)
306
307
  continue;
308
+ if (opName === 'createMany' && rel && rel.type !== 'hasMany') {
309
+ throw new ValidationError(`Nested createMany on "${relationName}" is only valid on a one-to-many relation; "${relationName}" is ` +
310
+ `${rel.type}. Use create instead.`);
311
+ }
307
312
  if (!isUpdate && UPDATE_ONLY_OPS.has(opName)) {
308
313
  throw new ValidationError(`Operation "${opName}" on relation "${relationName}" is only valid inside update(), not create().`);
309
314
  }
@@ -341,7 +346,7 @@ function singleToOneItem(value, op, relName, rel) {
341
346
  * that finds its row writes none; the levels requested for its `create` then
342
347
  * return that existing row's related rows, as any relation read does.
343
348
  */
344
- const READ_BACK_OPS = new Set(['create', 'connectOrCreate', 'update', 'upsert']);
349
+ const READ_BACK_OPS = new Set(['create', 'createMany', 'connectOrCreate', 'update', 'upsert']);
345
350
  /**
346
351
  * The `with` clause that reads back the tree a nested write just wrote.
347
352
  *
@@ -1169,6 +1174,17 @@ async function processHasManyCreate(ctx, rel, ops, parentRow, depth, path, relNa
1169
1174
  }
1170
1175
  }
1171
1176
  }
1177
+ // createMany: `{ data: row | row[], skipDuplicates? }`, rows without nested
1178
+ // relation writes (as in Prisma), inserted in the caller's order.
1179
+ if (ops.createMany !== undefined) {
1180
+ const { rows, skipDuplicates } = nestedCreateManyRows(ops.createMany, relName, ctx.schema.tables[rel.to]);
1181
+ if (rows.length > 0) {
1182
+ const injected = rows.map((row) => injectForeignKey(row, rel, parentRow, ctx.schema));
1183
+ for (const run of createManyShapeRuns(injected)) {
1184
+ await ctx.tx.table(rel.to).createMany({ data: run, ...(skipDuplicates ? { skipDuplicates: true } : {}) });
1185
+ }
1186
+ }
1187
+ }
1172
1188
  // connect
1173
1189
  if (ops.connect !== undefined) {
1174
1190
  const items = toArray(ops.connect);
@@ -1471,6 +1487,40 @@ async function processSet(ctx, rel, setItems, parentRow) {
1471
1487
  await ctx.tx.table(rel.to).update({ where: target, data: updateData });
1472
1488
  }
1473
1489
  }
1490
+ /**
1491
+ * The rows of a nested `createMany` payload. Prisma's shape is
1492
+ * `{ data: row | row[], skipDuplicates?: boolean }`, and its rows may not carry
1493
+ * nested relation writes of their own (a `createMany` is one INSERT). Anything
1494
+ * else is refused rather than read as zero rows.
1495
+ */
1496
+ function nestedCreateManyRows(payload, relName, childMeta) {
1497
+ if (!isPlainRecord(payload)) {
1498
+ throw new ValidationError(`Nested createMany on "${relName}" takes { data: [...], skipDuplicates?: boolean }.`);
1499
+ }
1500
+ for (const key of Object.keys(payload)) {
1501
+ if (key !== 'data' && key !== 'skipDuplicates' && payload[key] !== undefined) {
1502
+ throw new ValidationError(`Nested createMany on "${relName}": unknown key "${key}". Valid keys: data, skipDuplicates.`);
1503
+ }
1504
+ }
1505
+ const data = payload.data;
1506
+ const rows = Array.isArray(data) ? data : isPlainRecord(data) ? [data] : undefined;
1507
+ if (!rows || rows.some((row) => !isPlainRecord(row))) {
1508
+ throw new ValidationError(`Nested createMany on "${relName}" requires \`data\`, a row object or an array of them.`);
1509
+ }
1510
+ if (payload.skipDuplicates !== undefined && typeof payload.skipDuplicates !== 'boolean') {
1511
+ throw new ValidationError(`Nested createMany on "${relName}": skipDuplicates must be a boolean.`);
1512
+ }
1513
+ if (childMeta) {
1514
+ for (const row of rows) {
1515
+ const nested = Object.keys(extractRelationFields(row, childMeta).relations);
1516
+ if (nested.length > 0) {
1517
+ throw new ValidationError(`Nested createMany on "${relName}" cannot write relations of its rows (${nested.join(', ')}). ` +
1518
+ 'Use create for rows with nested writes.');
1519
+ }
1520
+ }
1521
+ }
1522
+ return { rows: rows, skipDuplicates: payload.skipDuplicates === true };
1523
+ }
1474
1524
  // ---------------------------------------------------------------------------
1475
1525
  // update / upsert operations (update-context only)
1476
1526
  // ---------------------------------------------------------------------------
@@ -1480,17 +1530,21 @@ async function processNestedUpdate(ctx, rel, updateArg, relName, parentRow) {
1480
1530
  return;
1481
1531
  const correlation = parentCorrelationWhere(ctx, rel, parentRow);
1482
1532
  for (const item of items) {
1483
- if (!item.where || !item.data) {
1484
- throw new ValidationError(`Nested update on "${rel.name}" requires both "where" and "data" fields.`);
1533
+ // A to-one update may leave out `where`: the row is the one pointing at
1534
+ // this parent, as in Prisma.
1535
+ const toOne = rel.type === 'hasOne';
1536
+ if ((!item.where && !toOne) || !item.data) {
1537
+ throw new ValidationError(`Nested update on "${rel.name}" requires ${toOne ? 'a "data" field' : 'both "where" and "data" fields'}.`);
1485
1538
  }
1486
- assertTargetSelectsSomething(item.where, 'update', relName, rel);
1539
+ const target = item.where ?? true;
1540
+ assertTargetSelectsSomething(target, 'update', relName, rel);
1487
1541
  if (!correlation)
1488
- throw notRelatedToParent('update', relName, rel, item.where);
1542
+ throw notRelatedToParent('update', relName, rel, target);
1489
1543
  try {
1490
- await ctx.tx.table(rel.to).update({ where: scopeWhereToParent(item.where, correlation), data: item.data });
1544
+ await ctx.tx.table(rel.to).update({ where: scopeWhereToParent(target, correlation), data: item.data });
1491
1545
  }
1492
1546
  catch (err) {
1493
- rethrowAsNotRelated(err, 'update', relName, rel, item.where);
1547
+ rethrowAsNotRelated(err, 'update', relName, rel, target);
1494
1548
  }
1495
1549
  }
1496
1550
  }
@@ -1504,19 +1558,24 @@ async function processNestedUpsert(ctx, rel, upsertArg, parentRow, relName) {
1504
1558
  // surfaced to the caller rather than silently rewriting a stranger's row).
1505
1559
  const correlation = parentCorrelationWhere(ctx, rel, parentRow);
1506
1560
  for (const item of items) {
1507
- if (!item.where || !item.create || !item.update) {
1508
- throw new ValidationError(`Nested upsert on "${rel.name}" requires "where", "create", and "update" fields.`);
1561
+ // A to-one upsert may leave out `where`, as in Prisma: the row it means is
1562
+ // the one pointing at this parent (`true`, the to-one "the related row"
1563
+ // selector). A to-many one must name its row.
1564
+ const toOne = rel.type === 'hasOne';
1565
+ if ((!item.where && !toOne) || !item.create || !item.update) {
1566
+ throw new ValidationError(`Nested upsert on "${rel.name}" requires ${toOne ? '' : '"where", '}"create", and "update" fields.`);
1509
1567
  }
1510
- assertTargetSelectsSomething(item.where, 'upsert', relName, rel);
1568
+ const target = item.where ?? true;
1569
+ assertTargetSelectsSomething(target, 'upsert', relName, rel);
1511
1570
  const update = upsertUpdateData(ctx, rel, item);
1512
- const scoped = correlation ? scopeWhereToParent(item.where, correlation) : null;
1571
+ const scoped = correlation ? scopeWhereToParent(target, correlation) : null;
1513
1572
  const existing = scoped ? await ctx.tx.table(rel.to).findUnique({ where: scoped }) : null;
1514
1573
  if (existing && scoped) {
1515
1574
  try {
1516
1575
  await ctx.tx.table(rel.to).update({ where: scoped, data: update });
1517
1576
  }
1518
1577
  catch (err) {
1519
- rethrowAsNotRelated(err, 'upsert', relName, rel, item.where);
1578
+ rethrowAsNotRelated(err, 'upsert', relName, rel, target);
1520
1579
  }
1521
1580
  }
1522
1581
  else {
@@ -1566,9 +1625,12 @@ async function processBelongsToUpdate(ctx, rel, updateArg, parentRow, parentTabl
1566
1625
  }
1567
1626
  async function processBelongsToUpsert(ctx, rel, upsertArg, parentRow, parentTable) {
1568
1627
  const item = upsertArg;
1569
- if (!item.where || !item.create || !item.update) {
1570
- throw new ValidationError(`Nested upsert on belongsTo "${rel.name}" requires "where", "create", and "update" fields.`);
1628
+ // `where` is optional, as in Prisma: without it the row is the one this
1629
+ // parent points at.
1630
+ if (!item.create || !item.update) {
1631
+ throw new ValidationError(`Nested upsert on belongsTo "${rel.name}" requires "create" and "update" fields.`);
1571
1632
  }
1633
+ const target = item.where ?? true;
1572
1634
  // Scope the lookup to the row this parent actually points at. Without the
1573
1635
  // correlation, a `where` naming any other row would update a record with no
1574
1636
  // relationship to the parent being written. A miss falls through to the
@@ -1584,7 +1646,7 @@ async function processBelongsToUpsert(ctx, rel, upsertArg, parentRow, parentTabl
1584
1646
  // row can come back.
1585
1647
  const existing = correlation
1586
1648
  ? ((await ctx.tx.table(rel.to).findMany({
1587
- where: scopeWhereToParent(item.where, correlation),
1649
+ where: scopeWhereToParent(target, correlation),
1588
1650
  // Internal engine read (see the connect path): no unlimited-findMany warning.
1589
1651
  warnOnUnlimited: false,
1590
1652
  }))[0] ?? null)
@@ -63,21 +63,26 @@
63
63
  * - `instanceof PrismaClientKnownRequestError`, `.meta`/message byte parity
64
64
  * (opt into `prismaErrorCodes` for a `.code` like `P2002`, without pretending
65
65
  * `instanceof` identity).
66
- * - `Prisma.join` / `Prisma.raw` composition beyond plain fragment flattening.
66
+ * - Splicing another library's `Prisma.sql` fragments unless asked to: they are
67
+ * bound as values until the client is given that library's namespace
68
+ * ({@link PrismaCompatOptions.prismaNamespace}).
67
69
  * - Fluent relation chaining (`prisma.user.findUnique().posts()`).
68
70
  * - Accelerate / Pulse / driver-adapter preview features, the Mongo API, and the
69
71
  * `prisma migrate`/`db` CLI family (Turbine ships its own migrations).
70
72
  * - **Negative `take`** (take-from-end) throws: Turbine has no reverse-take.
71
73
  * A **`cursor` on a nested relation include** throws: `with` has no cursor
72
74
  * (`take` / `skip` there page each parent's rows, as in Prisma).
73
- * - **A filtered relation count** (`_count: { select: { posts: { where } } }`)
74
- * and **`distinct` on a nested include** throw `UnsupportedFeatureError`:
75
- * core counts and includes a relation whole, so honoring either would mean
76
- * returning a wrong number or duplicate rows. The message names the
77
- * alternative (a `count` / `findMany` on the related model).
75
+ * - **`distinct` on a nested include** throws `UnsupportedFeatureError`: core
76
+ * includes a relation whole, so honoring it would mean returning duplicate
77
+ * rows. The message names the alternative (a `findMany` on the related model).
78
+ * A filtered relation count (`_count: { select: { posts: { where } } }`) and a
79
+ * `_count` below the top level ARE supported: this layer runs one grouped
80
+ * count per counted relation after the read, in the same transaction (see
81
+ * {@link ReadPlan}). Those two forms count one-to-many relations only; a
82
+ * many-to-many one is refused by name.
78
83
  * - **Nothing is accepted and dropped.** Every option on an included relation
79
- * and every key under `_count` is translated, refused by name (the two
80
- * above, `cursor`), or refused as unknown (`ValidationError`, with a
84
+ * and every key under `_count` is translated, refused by name (`distinct`,
85
+ * `cursor`), or refused as unknown (`ValidationError`, with a
81
86
  * suggestion): a misspelled `wher`, a Turbine spelling like `limit`, a
82
87
  * relation `_count` does not know. The same holds for `$transaction` options
83
88
  * (`maxWait` is accepted, warned about once, and not applied: the pool's
@@ -89,10 +94,11 @@
89
94
  * - **Write projections**: `select` / `omit` on create/update/delete/upsert
90
95
  * narrow the RETURNED OBJECT (see {@link resolveWriteProjection}); they do
91
96
  * NOT narrow the statement's `RETURNING` list, so the column still crosses
92
- * the wire, and `pii: true` remains the SQL-level control. A relation key in
93
- * either (or any `include` on a write) THROWS, since a write returns its own
94
- * row only. `omit` on READS is translated to core's own `omit`, see
95
- * {@link translateOmit}.
97
+ * the wire, and `pii: true` remains the SQL-level control. A write whose
98
+ * `include` / `select` names a relation or `_count` runs as the write followed
99
+ * by a read of the written row by primary key, in one transaction (a delete
100
+ * reads first), so it returns what Prisma returns. `omit` on READS is
101
+ * translated to core's own `omit`, see {@link translateOmit}.
96
102
  * - **`take` / `skip` / `cursor` on `count` and `aggregate`** throw: Prisma
97
103
  * computes those over one page of rows and Turbine has no paged count. An
98
104
  * `orderBy` alone changes nothing there and is accepted. `count({ select })`
@@ -126,7 +132,7 @@
126
132
  * });
127
133
  * ```
128
134
  */
129
- import type { TurbineClient } from './client.js';
135
+ import type { TransactionClient, TurbineClient } from './client.js';
130
136
  import { type DeferredQuery } from './query/index.js';
131
137
  import type { PrismaCompatMap, SchemaMetadata } from './schema.js';
132
138
  /** A build-only query object with the `build*` methods the adapter drives. */
@@ -191,6 +197,10 @@ export interface CompatTransactionClient {
191
197
  /** The minimal `TurbineClient` surface the adapter consumes. */
192
198
  export interface CompatTurbineClient extends CompatTransactionClient {
193
199
  readonly schema: SchemaMetadata;
200
+ /** Core `connect()`; absent on a test stub. */
201
+ connect?(): Promise<void>;
202
+ /** Core `disconnect()`; absent on a test stub. */
203
+ disconnect?(): Promise<unknown>;
194
204
  $transaction<R>(fn: (tx: CompatTransactionClient) => Promise<R>, options?: unknown): Promise<R>;
195
205
  $transaction(queries: readonly DeferredQuery<unknown>[], options?: unknown): Promise<unknown[]>;
196
206
  }
@@ -218,6 +228,16 @@ export interface Sql {
218
228
  readonly values: readonly unknown[];
219
229
  readonly [SQL_FRAGMENT]: true;
220
230
  }
231
+ /** The structural shape of a fragment: this module's {@link Sql}, or another library's. */
232
+ export interface SqlFragmentLike {
233
+ readonly strings: readonly string[];
234
+ readonly values: readonly unknown[];
235
+ }
236
+ /** The part of a client library's `Prisma` namespace {@link PrismaCompatOptions.prismaNamespace} reads. */
237
+ export interface PrismaNamespaceLike {
238
+ /** `Prisma.empty`: an instance of the library's fragment class. */
239
+ readonly empty: object;
240
+ }
221
241
  /**
222
242
  * `Prisma`-compatible raw-SQL helpers, a minimal local implementation so
223
243
  * migrated `Prisma.sql\`…\`` / `Prisma.join(...)` / `Prisma.raw(...)` calls keep
@@ -272,6 +292,27 @@ export interface PrismaCompatOptions {
272
292
  * `false` (Turbine's own `TURBINE_E0NN` codes are preserved untouched).
273
293
  */
274
294
  prismaErrorCodes?: boolean;
295
+ /**
296
+ * The `Prisma` namespace of the client library the call sites were written
297
+ * against (`import { Prisma } from '@prisma/client'`). With it, fragments that
298
+ * library builds (`Prisma.sql`, `Prisma.join`, `Prisma.raw`, `Prisma.empty`)
299
+ * compose in `$queryRaw` / `$executeRaw` exactly like this module's own: nested
300
+ * in a template, as the lone argument, and inside each other. Without it they
301
+ * are bound as `$N` values, which is the safe reading of an object nobody vouched
302
+ * for.
303
+ *
304
+ * Only instances of the namespace's own fragment class are spliced (recognized
305
+ * by prototype, never by shape), so an object parsed from a request body is a
306
+ * value whatever keys it carries.
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * import { Prisma } from '@prisma/client';
311
+ * const prisma = createPrismaCompatClient(db, PRISMA_MAP, { prismaNamespace: Prisma });
312
+ * await prisma.$queryRaw`SELECT * FROM "User" WHERE id IN (${Prisma.join(ids)})`;
313
+ * ```
314
+ */
315
+ prismaNamespace?: PrismaNamespaceLike;
275
316
  }
276
317
  /** The delegate operations this adapter exposes. */
277
318
  export type CompatOperation = 'findMany' | 'findFirst' | 'findFirstOrThrow' | 'findUnique' | 'findUniqueOrThrow' | 'create' | 'createMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany' | 'upsert' | 'count' | 'aggregate' | 'groupBy';
@@ -335,9 +376,11 @@ export interface PrismaModelDelegate<M extends PrismaModelTypes> {
335
376
  * the transaction's own connection.
336
377
  */
337
378
  export interface PrismaCompatRawSurface {
338
- $queryRaw<T = unknown>(strings: TemplateStringsArray, ...values: unknown[]): Promise<T[]>;
379
+ /** A tagged template, or one fragment (`$queryRaw(Prisma.sql\`...\`)`), as in Prisma. */
380
+ $queryRaw<T = unknown>(strings: TemplateStringsArray | SqlFragmentLike, ...values: unknown[]): Promise<T[]>;
339
381
  $queryRawUnsafe<T = unknown>(sql: string, ...params: unknown[]): Promise<T[]>;
340
- $executeRaw(strings: TemplateStringsArray, ...values: unknown[]): Promise<number>;
382
+ /** A tagged template, or one fragment (`$executeRaw(Prisma.sql\`...\`)`), as in Prisma. */
383
+ $executeRaw(strings: TemplateStringsArray | SqlFragmentLike, ...values: unknown[]): Promise<number>;
341
384
  $executeRawUnsafe(sql: string, ...params: unknown[]): Promise<number>;
342
385
  }
343
386
  /**
@@ -403,7 +446,13 @@ export interface PrismaCompatClientBase<S extends Record<string, PrismaModelType
403
446
  * extensions throw, see {@link PrismaCompatExtension}.
404
447
  */
405
448
  $extends<E extends PrismaCompatExtension>(extension: E): PrismaCompatExtendedClient<S, E>;
449
+ /** Open a connection now (core `connect()`: one `SELECT 1`), so a bad URL fails here rather than at the first query. */
406
450
  $connect(): Promise<void>;
451
+ /**
452
+ * Close the wrapped client's pool (core `disconnect()`), so a script can
453
+ * exit. Idempotent, and shared by every `$extends` of this client. Unlike
454
+ * Prisma the pool is not reopened by a later query: build a new client.
455
+ */
407
456
  $disconnect(): Promise<void>;
408
457
  }
409
458
  /** Options accepted by `$transaction`, in its callback and array forms. */
@@ -435,6 +484,49 @@ export type PrismaCompatClient<S extends Record<string, PrismaModelTypes> = Reco
435
484
  } & {
436
485
  [K in keyof S as Uncapitalize<K & string>]: PrismaModelDelegate<S[K]>;
437
486
  } & PrismaCompatClientBase<S>;
487
+ /**
488
+ * The Turbine client under a compat client: the `TurbineClient` it wraps for the
489
+ * client (or any `$extends` of it), and the core `TransactionClient` for the `tx`
490
+ * a `$transaction(async (tx) => ...)` callback receives (or one
491
+ * {@link bindTransaction} made). This is how code is moved off the compat surface
492
+ * one module at a time: a ported function takes the compat client, calls
493
+ * `turbineOf`, and uses Turbine's own API on the SAME connection, so inside a
494
+ * transaction it sees that transaction's uncommitted writes and is rolled back
495
+ * with it.
496
+ *
497
+ * Throws for anything this module did not build.
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * await prisma.$transaction(async (tx) => {
502
+ * await tx.user.update({ where: { id }, data: { name } });
503
+ * const user = await turbineOf(tx).table('users').findUnique({ where: { id } }); // same transaction
504
+ * });
505
+ * ```
506
+ */
507
+ export declare function turbineOf<S extends Record<string, PrismaModelTypes>>(compat: PrismaCompatClient<S>): TurbineClient;
508
+ export declare function turbineOf<S extends Record<string, PrismaModelTypes>>(tx: PrismaCompatTransactionClient<S>): TransactionClient;
509
+ export declare function turbineOf(compat: object): TurbineClient | TransactionClient;
510
+ /**
511
+ * A compat transaction client running inside a core transaction this layer did
512
+ * not open: the other direction of {@link turbineOf}. Code already on Turbine's API
513
+ * opens `db.$transaction(async (core) => ...)` and calls into a module still
514
+ * written against the Prisma surface with `bindTransaction(prisma, core)`; every
515
+ * delegate call and raw statement on the result runs on `core`'s connection and
516
+ * commits or rolls back with it. The result has the same members as the `tx` of
517
+ * a compat `$transaction` callback (delegates, extension `model` members, the
518
+ * raw surface), and no `$transaction` of its own, as in Prisma.
519
+ *
520
+ * @example
521
+ * ```ts
522
+ * await db.$transaction(async (core) => {
523
+ * await core.table('users').update({ where: { id }, data: { name } });
524
+ * await legacyAudit(bindTransaction(prisma, core)); // still prisma.auditLog.create(...)
525
+ * });
526
+ * ```
527
+ */
528
+ export declare function bindTransaction<S extends Record<string, PrismaModelTypes>>(compat: PrismaCompatClient<S>, tx: TransactionClient): PrismaCompatTransactionClient<S>;
529
+ export declare function bindTransaction(compat: object, tx: TransactionClient): PrismaCompatTransactionClient;
438
530
  /** @internal Names on a compat client that are NOT model delegates. */
439
531
  export declare const CLIENT_RESERVED_KEYS: ReadonlySet<string>;
440
532
  /**