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.
- package/README.md +2 -2
- package/dist/cjs/cli/prisma-resolve.js +14 -9
- package/dist/cjs/client.js +49 -0
- package/dist/cjs/connection-url.d.ts +44 -1
- package/dist/cjs/connection-url.js +57 -2
- package/dist/cjs/nested-write.js +79 -17
- package/dist/cjs/prisma-compat.d.ts +107 -15
- package/dist/cjs/prisma-compat.js +654 -113
- package/dist/cjs/query/aggregates.js +13 -1
- package/dist/cjs/query/types.d.ts +15 -1
- package/dist/cjs/schema.d.ts +8 -7
- package/dist/cjs/transaction-state.d.ts +14 -1
- package/dist/cjs/transaction-state.js +61 -6
- package/dist/cli/prisma-resolve.js +14 -9
- package/dist/client.js +50 -1
- package/dist/connection-url.d.ts +44 -1
- package/dist/connection-url.js +55 -2
- package/dist/nested-write.js +79 -17
- package/dist/prisma-compat.d.ts +107 -15
- package/dist/prisma-compat.js +652 -113
- package/dist/query/aggregates.js +14 -2
- package/dist/query/types.d.ts +15 -1
- package/dist/schema.d.ts +8 -7
- package/dist/transaction-state.d.ts +14 -1
- package/dist/transaction-state.js +61 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -276,7 +276,7 @@ Going deep on one database means the parts other ORMs push to raw SQL are typed
|
|
|
276
276
|
|
|
277
277
|
## Serverless and edge
|
|
278
278
|
|
|
279
|
-
The core is driver-agnostic: hand any pg-compatible pool to `turbineHttp()` and Turbine runs on Vercel Edge, Cloudflare Workers, Deno Deploy, or anywhere else without TCP. For Neon, `turbine-orm/neon-ws` and `turbine-orm/neon-http` bind its WebSocket `Pool` and its `neon()` HTTP function with their own session rules ([WebSocket](docs/neon-websocket.md), [HTTP](docs/neon-http.md)); both are Experimental. The main entry's import graph is held under **156 kB brotli** (edge entry under **
|
|
279
|
+
The core is driver-agnostic: hand any pg-compatible pool to `turbineHttp()` and Turbine runs on Vercel Edge, Cloudflare Workers, Deno Deploy, or anywhere else without TCP. For Neon, `turbine-orm/neon-ws` and `turbine-orm/neon-http` bind its WebSocket `Pool` and its `neon()` HTTP function with their own session rules ([WebSocket](docs/neon-websocket.md), [HTTP](docs/neon-http.md)); both are Experimental. The main entry's import graph is held under **156 kB brotli** (edge entry under **121 kB**) with `pg` external, enforced by `size-limit` in CI at those exact numbers; run `npm run size` for the current figure. MySQL generation emits exact column-local ENUM labels as literal unions and falls back to `string` when catalog labels may be damaged; see [typed ENUM generation](docs/mysql-enum-generation.md) for its boundaries and measured footprint.
|
|
280
280
|
|
|
281
281
|
```typescript
|
|
282
282
|
import { Pool } from '@neondatabase/serverless';
|
|
@@ -388,7 +388,7 @@ It is also built to be extended rather than wrapped. All SQL generation routes t
|
|
|
388
388
|
| **Studio** | Read-only by default | Full CRUD, cloud-hosted | Full CRUD; [Gateway](https://gateway.drizzle.team/) self-hosted, free | None | AdminJS integration guide (CRUD panel) |
|
|
389
389
|
| **Error PII safety** | Keys only by default | Values in messages | Raw pg errors | Raw pg errors | |
|
|
390
390
|
| **Migrations** | SQL-first, SHA-256 checksums | DSL-generated, shadow DB | SQL or Drizzle Kit | None | Generated by diffing entities against a snapshot or the database; TS/JS classes |
|
|
391
|
-
| **Edge runtime** | One import swap, under
|
|
391
|
+
| **Edge runtime** | One import swap, under 121 kB brotli (CI-enforced) | Driver adapter + WASM compiler | Native | Native | Cloudflare Workers and Deno (v7) |
|
|
392
392
|
| **Pipeline batching** | Parse/Bind/Execute protocol | Sequential in txn | Sequential | Manual | `flush()` runs queued changes in one transaction |
|
|
393
393
|
| **Typed errors** | `isRetryable` discriminant | Error codes only | None | None | `DriverException` subclasses (`UniqueConstraintViolationException`, ...) |
|
|
394
394
|
| **Nested relations** | 1 query, deep type inference | 1 query per relation by default; single-query `relationJoins` is Preview | 1 query, `relations()` re-declaration | Manual (`jsonArrayFrom`) | `populate`; default `balanced`: joins to-one, one query per to-many relation |
|
|
@@ -305,11 +305,14 @@ function relationFkColumns(model, field) {
|
|
|
305
305
|
* Prisma CLIENT-side defaults for a resolved model: `@default(uuid())` /
|
|
306
306
|
* `@default(cuid())` / `@updatedAt` are filled by the Prisma client (the
|
|
307
307
|
* database column typically has NO default), so migrated call sites omit those
|
|
308
|
-
* fields and a plain insert violates NOT NULL.
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
308
|
+
* fields and a plain insert violates NOT NULL. `uuid()` / `cuid()` are carried
|
|
309
|
+
* only when the column has no database default (either one is an opaque random
|
|
310
|
+
* id). `@default(now())` and `@updatedAt` are ALWAYS carried: Prisma sends its
|
|
311
|
+
* own clock's time even when the migration also wrote `DEFAULT
|
|
312
|
+
* CURRENT_TIMESTAMP`, and the two clocks differ, so leaving `now()` to the
|
|
313
|
+
* database made a row stamped "now" compare as later than the app's
|
|
314
|
+
* `new Date()` taken right after the insert. Returns undefined when the model
|
|
315
|
+
* has none, keeping the emitted map byte-identical for unaffected schemas.
|
|
313
316
|
*/
|
|
314
317
|
function collectClientDefaults(model, resolvedFields, tableMeta) {
|
|
315
318
|
if (!tableMeta)
|
|
@@ -324,16 +327,18 @@ function collectClientDefaults(model, resolvedFields, tableMeta) {
|
|
|
324
327
|
out[field.name] = 'updatedAt';
|
|
325
328
|
continue;
|
|
326
329
|
}
|
|
327
|
-
if (col?.hasDefault)
|
|
328
|
-
continue; // the database fills it; nothing to emulate
|
|
329
330
|
const def = field.attrs.find((a) => a.name === 'default');
|
|
330
331
|
const raw = def?.args.find((a) => a.key === undefined && a.kind === 'raw')?.value ?? '';
|
|
332
|
+
if (/^now\s*\(\s*\)$/.test(raw)) {
|
|
333
|
+
out[field.name] = 'now';
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (col?.hasDefault)
|
|
337
|
+
continue; // the database fills it; nothing to emulate
|
|
331
338
|
if (/^uuid\s*\(/.test(raw))
|
|
332
339
|
out[field.name] = 'uuid';
|
|
333
340
|
else if (/^cuid\s*\(/.test(raw))
|
|
334
341
|
out[field.name] = 'cuid';
|
|
335
|
-
else if (/^now\s*\(\s*\)$/.test(raw))
|
|
336
|
-
out[field.name] = 'now';
|
|
337
342
|
}
|
|
338
343
|
return Object.keys(out).length > 0 ? out : undefined;
|
|
339
344
|
}
|
package/dist/cjs/client.js
CHANGED
|
@@ -393,6 +393,32 @@ function pgEnv(name) {
|
|
|
393
393
|
return (typeof process !== 'undefined' ? process.env?.[name] : undefined) || undefined;
|
|
394
394
|
}
|
|
395
395
|
/** Whether any explicit connection field suppresses the environment URL fallback. */
|
|
396
|
+
/**
|
|
397
|
+
* {@link readPrismaUrlParameters} for a connection string this client will
|
|
398
|
+
* open, with the refusals raised: an invalid value, and a non-public `schema`
|
|
399
|
+
* that cannot be pinned safely. A `search_path` rides the connection's startup
|
|
400
|
+
* `options`, which a transaction pooler drops or refuses, and the alternative
|
|
401
|
+
* (a session `SET`) leaks to the next client of a pooled backend; querying the
|
|
402
|
+
* wrong schema is the outcome this exists to prevent, so both are E003.
|
|
403
|
+
*/
|
|
404
|
+
function readPrismaUrlParametersFor(connectionString, label) {
|
|
405
|
+
const params = (0, connection_url_js_1.readPrismaUrlParameters)(connectionString);
|
|
406
|
+
if (!params)
|
|
407
|
+
return null;
|
|
408
|
+
if (params.invalid)
|
|
409
|
+
throw new errors_js_1.ValidationError(`${label}: ${params.invalid}.`);
|
|
410
|
+
if (params.schema !== undefined && params.schema !== 'public') {
|
|
411
|
+
if ((0, connection_url_js_1.detectPooler)(connectionString).pooled) {
|
|
412
|
+
throw new errors_js_1.ValidationError(`${label} names schema "${params.schema}" on what looks like a transaction pooler. A pooler cannot ` +
|
|
413
|
+
'carry a per-connection search_path; point the client at the direct endpoint, or use the public schema.');
|
|
414
|
+
}
|
|
415
|
+
if ((0, connection_url_js_1.withSearchPathOption)(params.connectionString, params.schema, [], { quotedNames: true }) === null) {
|
|
416
|
+
throw new errors_js_1.ValidationError(`${label}: schema "${params.schema}" cannot be set as the connection's search_path (it may not contain ` +
|
|
417
|
+
'whitespace, a double quote or a backslash).');
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return params;
|
|
421
|
+
}
|
|
396
422
|
function hasExplicitConnectionTarget(config) {
|
|
397
423
|
return (config.connectionString != null ||
|
|
398
424
|
config.host != null ||
|
|
@@ -1105,9 +1131,11 @@ class TurbineClient {
|
|
|
1105
1131
|
// `connectionString: process.env.DATABASE_URL ?? ''` must keep constructing,
|
|
1106
1132
|
// and it still suppresses the DATABASE_URL fallback because
|
|
1107
1133
|
// `hasExplicitConnection` tests `!= null`, not truthiness.
|
|
1134
|
+
let prismaUrl = null;
|
|
1108
1135
|
if (!config.pool) {
|
|
1109
1136
|
if (config.connectionString) {
|
|
1110
1137
|
assertUsableConnectionString(config.connectionString, 'connectionString');
|
|
1138
|
+
prismaUrl = readPrismaUrlParametersFor(config.connectionString, 'connectionString');
|
|
1111
1139
|
}
|
|
1112
1140
|
else if (config.connectionString == null &&
|
|
1113
1141
|
config.host == null &&
|
|
@@ -1117,6 +1145,7 @@ class TurbineClient {
|
|
|
1117
1145
|
config.password == null &&
|
|
1118
1146
|
process.env.DATABASE_URL) {
|
|
1119
1147
|
assertUsableConnectionString(process.env.DATABASE_URL, 'DATABASE_URL environment variable');
|
|
1148
|
+
prismaUrl = readPrismaUrlParametersFor(process.env.DATABASE_URL, 'DATABASE_URL environment variable');
|
|
1120
1149
|
}
|
|
1121
1150
|
}
|
|
1122
1151
|
for (const [i, replica] of (config.replicas ?? []).entries()) {
|
|
@@ -1322,6 +1351,26 @@ class TurbineClient {
|
|
|
1322
1351
|
if (config.ssl !== undefined) {
|
|
1323
1352
|
poolConfig.ssl = config.ssl;
|
|
1324
1353
|
}
|
|
1354
|
+
// Prisma's `schema` / `connection_limit` / `pool_timeout` (read and
|
|
1355
|
+
// validated above): stripped from what pg sees, and honoured. An explicit
|
|
1356
|
+
// client option wins over the URL's.
|
|
1357
|
+
if (prismaUrl && poolConfig.connectionString) {
|
|
1358
|
+
poolConfig.connectionString = prismaUrl.connectionString;
|
|
1359
|
+
if (prismaUrl.connectionLimit !== undefined && config.poolSize == null && config.max == null) {
|
|
1360
|
+
poolConfig.max = prismaUrl.connectionLimit;
|
|
1361
|
+
}
|
|
1362
|
+
if (prismaUrl.poolTimeoutMs !== undefined &&
|
|
1363
|
+
config.connectionTimeoutMs == null &&
|
|
1364
|
+
config.connectionTimeoutMillis == null) {
|
|
1365
|
+
poolConfig.connectionTimeoutMillis = prismaUrl.poolTimeoutMs;
|
|
1366
|
+
}
|
|
1367
|
+
if (prismaUrl.schema !== undefined && prismaUrl.schema !== 'public') {
|
|
1368
|
+
// Checked non-null when it was read.
|
|
1369
|
+
poolConfig.connectionString =
|
|
1370
|
+
(0, connection_url_js_1.withSearchPathOption)(poolConfig.connectionString, prismaUrl.schema, [], { quotedNames: true }) ??
|
|
1371
|
+
poolConfig.connectionString;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1325
1374
|
// Held as a `pg.Pool` for the length of this block: `PgCompatPool.on` is
|
|
1326
1375
|
// optional (HTTP drivers have no pool events), and this branch owns a
|
|
1327
1376
|
// real pg pool that has one. Same shape as the replica loop below.
|
|
@@ -238,6 +238,16 @@ export declare function mergeConnectionStringOptions(connectionString: string, s
|
|
|
238
238
|
export declare const SEARCH_PATH_SCHEMA_PATTERN: RegExp;
|
|
239
239
|
/** Whether `schema` is a name {@link withSearchPathOption} will emit. */
|
|
240
240
|
export declare function isPlainSchemaIdentifier(schema: string): boolean;
|
|
241
|
+
/**
|
|
242
|
+
* Whether `schema` is in the wider set of names {@link withSearchPathOption} emits with
|
|
243
|
+
* `quotedNames: true`: anything but whitespace, a double quote, a backslash or a
|
|
244
|
+
* NUL. The name is always written double-quoted, so these four are exactly the
|
|
245
|
+
* characters that could end the quoted name or split the `options` string into a
|
|
246
|
+
* second `-c`; every other character (a hyphen, a dot, non-ASCII letters) is part
|
|
247
|
+
* of the identifier. Used for Prisma's `?schema=`, where names such as
|
|
248
|
+
* `tenant-a` are ordinary.
|
|
249
|
+
*/
|
|
250
|
+
export declare function isQuotableSchemaName(schema: string): boolean;
|
|
241
251
|
/**
|
|
242
252
|
* The schema names in a `SHOW search_path` value, unquoted.
|
|
243
253
|
*
|
|
@@ -304,4 +314,37 @@ export declare function parseSearchPathValue(shown: string): string[];
|
|
|
304
314
|
* `null` as a refusal: the unpinned string means "into whichever schema the
|
|
305
315
|
* role defaults to", the exact outcome this exists to prevent.
|
|
306
316
|
*/
|
|
307
|
-
export declare function withSearchPathOption(connectionString: string, schema: string, alsoResolveIn?: readonly string[]
|
|
317
|
+
export declare function withSearchPathOption(connectionString: string, schema: string, alsoResolveIn?: readonly string[], options?: {
|
|
318
|
+
quotedNames?: boolean;
|
|
319
|
+
}): string | null;
|
|
320
|
+
/**
|
|
321
|
+
* What a Prisma-style connection string asks for through the query parameters
|
|
322
|
+
* only Prisma's engine reads, with those parameters removed.
|
|
323
|
+
*
|
|
324
|
+
* node-postgres ignores `schema`, `connection_limit` and `pool_timeout`
|
|
325
|
+
* without a word, so a `DATABASE_URL` carried over from Prisma with
|
|
326
|
+
* `?schema=tenant_a` queried `public`: the most consequential silent drop a
|
|
327
|
+
* connection string can make. The client honours all three (see `TurbineClient`):
|
|
328
|
+
* `schema` becomes a connection-time `search_path`, `connection_limit` the pool
|
|
329
|
+
* size, and `pool_timeout` (seconds, `0` = wait forever) the checkout timeout.
|
|
330
|
+
*/
|
|
331
|
+
export interface PrismaUrlParameters {
|
|
332
|
+
/** The connection string without the three parameters, for the driver. */
|
|
333
|
+
readonly connectionString: string;
|
|
334
|
+
/** `schema`, when present and not empty. */
|
|
335
|
+
readonly schema?: string;
|
|
336
|
+
/** `connection_limit`, a positive integer. */
|
|
337
|
+
readonly connectionLimit?: number;
|
|
338
|
+
/** `pool_timeout` in milliseconds (`0` = no timeout). */
|
|
339
|
+
readonly poolTimeoutMs?: number;
|
|
340
|
+
/** Why a parameter cannot be honoured, for the caller's E003; the parameter is named, the URL never is. */
|
|
341
|
+
readonly invalid?: string;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Read (and strip) Prisma's `schema` / `connection_limit` / `pool_timeout`.
|
|
345
|
+
* `null` when the string carries none of them, which is every Turbine-native
|
|
346
|
+
* connection string, so those pass through byte-for-byte. Only the query string
|
|
347
|
+
* is rewritten, never the userinfo or host (see
|
|
348
|
+
* {@link mergeConnectionStringOptions} for why).
|
|
349
|
+
*/
|
|
350
|
+
export declare function readPrismaUrlParameters(connectionString: string): PrismaUrlParameters | null;
|
|
@@ -45,8 +45,10 @@ exports.statementTimeoutSetting = statementTimeoutSetting;
|
|
|
45
45
|
exports.withStartupSetting = withStartupSetting;
|
|
46
46
|
exports.mergeConnectionStringOptions = mergeConnectionStringOptions;
|
|
47
47
|
exports.isPlainSchemaIdentifier = isPlainSchemaIdentifier;
|
|
48
|
+
exports.isQuotableSchemaName = isQuotableSchemaName;
|
|
48
49
|
exports.parseSearchPathValue = parseSearchPathValue;
|
|
49
50
|
exports.withSearchPathOption = withSearchPathOption;
|
|
51
|
+
exports.readPrismaUrlParameters = readPrismaUrlParameters;
|
|
50
52
|
/**
|
|
51
53
|
* Host and port from a connection string, in either shape libpq accepts.
|
|
52
54
|
*
|
|
@@ -348,6 +350,18 @@ exports.SEARCH_PATH_SCHEMA_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
|
|
348
350
|
function isPlainSchemaIdentifier(schema) {
|
|
349
351
|
return exports.SEARCH_PATH_SCHEMA_PATTERN.test(schema);
|
|
350
352
|
}
|
|
353
|
+
/**
|
|
354
|
+
* Whether `schema` is in the wider set of names {@link withSearchPathOption} emits with
|
|
355
|
+
* `quotedNames: true`: anything but whitespace, a double quote, a backslash or a
|
|
356
|
+
* NUL. The name is always written double-quoted, so these four are exactly the
|
|
357
|
+
* characters that could end the quoted name or split the `options` string into a
|
|
358
|
+
* second `-c`; every other character (a hyphen, a dot, non-ASCII letters) is part
|
|
359
|
+
* of the identifier. Used for Prisma's `?schema=`, where names such as
|
|
360
|
+
* `tenant-a` are ordinary.
|
|
361
|
+
*/
|
|
362
|
+
function isQuotableSchemaName(schema) {
|
|
363
|
+
return schema.length > 0 && !/[\s"\\]/.test(schema) && !schema.includes('\u0000');
|
|
364
|
+
}
|
|
351
365
|
/**
|
|
352
366
|
* The one name outside {@link SEARCH_PATH_SCHEMA_PATTERN} that is still safe to
|
|
353
367
|
* emit into the `options=-c` literal, and worth keeping.
|
|
@@ -494,8 +508,8 @@ function searchPathListValue(schema, alsoResolveIn) {
|
|
|
494
508
|
* `null` as a refusal: the unpinned string means "into whichever schema the
|
|
495
509
|
* role defaults to", the exact outcome this exists to prevent.
|
|
496
510
|
*/
|
|
497
|
-
function withSearchPathOption(connectionString, schema, alsoResolveIn = []) {
|
|
498
|
-
if (!isPlainSchemaIdentifier(schema))
|
|
511
|
+
function withSearchPathOption(connectionString, schema, alsoResolveIn = [], options = {}) {
|
|
512
|
+
if (!(options.quotedNames ? isQuotableSchemaName(schema) : isPlainSchemaIdentifier(schema)))
|
|
499
513
|
return null;
|
|
500
514
|
const setting = `-c search_path=${searchPathListValue(schema, alsoResolveIn)}`;
|
|
501
515
|
const merged = mergeConnectionStringOptions(connectionString, setting);
|
|
@@ -511,3 +525,44 @@ function withSearchPathOption(connectionString, schema, alsoResolveIn = []) {
|
|
|
511
525
|
const head = q === -1 ? connectionString : connectionString.slice(0, q);
|
|
512
526
|
return `${head}?${params.toString()}`;
|
|
513
527
|
}
|
|
528
|
+
const PRISMA_URL_PARAMETERS = ['schema', 'connection_limit', 'pool_timeout'];
|
|
529
|
+
/**
|
|
530
|
+
* Read (and strip) Prisma's `schema` / `connection_limit` / `pool_timeout`.
|
|
531
|
+
* `null` when the string carries none of them, which is every Turbine-native
|
|
532
|
+
* connection string, so those pass through byte-for-byte. Only the query string
|
|
533
|
+
* is rewritten, never the userinfo or host (see
|
|
534
|
+
* {@link mergeConnectionStringOptions} for why).
|
|
535
|
+
*/
|
|
536
|
+
function readPrismaUrlParameters(connectionString) {
|
|
537
|
+
const q = connectionString.indexOf('?');
|
|
538
|
+
if (q === -1)
|
|
539
|
+
return null;
|
|
540
|
+
const params = new URLSearchParams(connectionString.slice(q + 1));
|
|
541
|
+
if (!PRISMA_URL_PARAMETERS.some((name) => params.has(name)))
|
|
542
|
+
return null;
|
|
543
|
+
const schema = params.get('schema') ?? '';
|
|
544
|
+
const limit = params.get('connection_limit');
|
|
545
|
+
const timeout = params.get('pool_timeout');
|
|
546
|
+
for (const name of PRISMA_URL_PARAMETERS)
|
|
547
|
+
params.delete(name);
|
|
548
|
+
const rest = params.toString();
|
|
549
|
+
const stripped = connectionString.slice(0, rest ? q + 1 : q) + rest;
|
|
550
|
+
const out = { connectionString: stripped };
|
|
551
|
+
if (schema !== '')
|
|
552
|
+
out.schema = schema;
|
|
553
|
+
if (limit !== null && limit !== '') {
|
|
554
|
+
const n = Number(limit);
|
|
555
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
556
|
+
out.invalid = 'connection_limit must be a positive integer';
|
|
557
|
+
else
|
|
558
|
+
out.connectionLimit = n;
|
|
559
|
+
}
|
|
560
|
+
if (timeout !== null && timeout !== '') {
|
|
561
|
+
const n = Number(timeout);
|
|
562
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
563
|
+
out.invalid = 'pool_timeout must be a non-negative whole number of seconds';
|
|
564
|
+
else
|
|
565
|
+
out.poolTimeoutMs = n * 1000;
|
|
566
|
+
}
|
|
567
|
+
return out;
|
|
568
|
+
}
|
package/dist/cjs/nested-write.js
CHANGED
|
@@ -28,7 +28,7 @@ const writes_js_1 = require("./query/writes.js");
|
|
|
28
28
|
const query_utils_js_1 = require("./query-utils.js");
|
|
29
29
|
const schema_js_1 = require("./schema.js");
|
|
30
30
|
const MAX_DEPTH = 10;
|
|
31
|
-
const CREATE_ONLY_OPS = new Set(['create', 'connect', 'connectOrCreate']);
|
|
31
|
+
const CREATE_ONLY_OPS = new Set(['create', 'createMany', 'connect', 'connectOrCreate']);
|
|
32
32
|
const UPDATE_ONLY_OPS = new Set(['disconnect', 'set', 'delete', 'update', 'upsert']);
|
|
33
33
|
// ---------------------------------------------------------------------------
|
|
34
34
|
// Pure helpers (exported for testing)
|
|
@@ -144,6 +144,7 @@ function isRelationEntry(meta, key, value) {
|
|
|
144
144
|
*/
|
|
145
145
|
const PAYLOAD_ROWS = [
|
|
146
146
|
['create', null],
|
|
147
|
+
['createMany', ['data']],
|
|
147
148
|
['connectOrCreate', ['create']],
|
|
148
149
|
['update', ['data']],
|
|
149
150
|
['updateMany', ['data']],
|
|
@@ -309,10 +310,14 @@ function validateOps(relationName, ops, isUpdate, rel) {
|
|
|
309
310
|
? ', disconnect, delete, update, upsert'
|
|
310
311
|
: ', disconnect, set, delete, update, upsert';
|
|
311
312
|
throw new errors_js_1.ValidationError(`Unknown nested write operation "${opName}" on relation "${relationName}". ` +
|
|
312
|
-
`Valid operations: create, connect, connectOrCreate${isUpdate ? updateOps : ''}.`);
|
|
313
|
+
`Valid operations: create, createMany, connect, connectOrCreate${isUpdate ? updateOps : ''}.`);
|
|
313
314
|
}
|
|
314
315
|
if (absent)
|
|
315
316
|
continue;
|
|
317
|
+
if (opName === 'createMany' && rel && rel.type !== 'hasMany') {
|
|
318
|
+
throw new errors_js_1.ValidationError(`Nested createMany on "${relationName}" is only valid on a one-to-many relation; "${relationName}" is ` +
|
|
319
|
+
`${rel.type}. Use create instead.`);
|
|
320
|
+
}
|
|
316
321
|
if (!isUpdate && UPDATE_ONLY_OPS.has(opName)) {
|
|
317
322
|
throw new errors_js_1.ValidationError(`Operation "${opName}" on relation "${relationName}" is only valid inside update(), not create().`);
|
|
318
323
|
}
|
|
@@ -350,7 +355,7 @@ function singleToOneItem(value, op, relName, rel) {
|
|
|
350
355
|
* that finds its row writes none; the levels requested for its `create` then
|
|
351
356
|
* return that existing row's related rows, as any relation read does.
|
|
352
357
|
*/
|
|
353
|
-
const READ_BACK_OPS = new Set(['create', 'connectOrCreate', 'update', 'upsert']);
|
|
358
|
+
const READ_BACK_OPS = new Set(['create', 'createMany', 'connectOrCreate', 'update', 'upsert']);
|
|
354
359
|
/**
|
|
355
360
|
* The `with` clause that reads back the tree a nested write just wrote.
|
|
356
361
|
*
|
|
@@ -1178,6 +1183,17 @@ async function processHasManyCreate(ctx, rel, ops, parentRow, depth, path, relNa
|
|
|
1178
1183
|
}
|
|
1179
1184
|
}
|
|
1180
1185
|
}
|
|
1186
|
+
// createMany: `{ data: row | row[], skipDuplicates? }`, rows without nested
|
|
1187
|
+
// relation writes (as in Prisma), inserted in the caller's order.
|
|
1188
|
+
if (ops.createMany !== undefined) {
|
|
1189
|
+
const { rows, skipDuplicates } = nestedCreateManyRows(ops.createMany, relName, ctx.schema.tables[rel.to]);
|
|
1190
|
+
if (rows.length > 0) {
|
|
1191
|
+
const injected = rows.map((row) => injectForeignKey(row, rel, parentRow, ctx.schema));
|
|
1192
|
+
for (const run of createManyShapeRuns(injected)) {
|
|
1193
|
+
await ctx.tx.table(rel.to).createMany({ data: run, ...(skipDuplicates ? { skipDuplicates: true } : {}) });
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1181
1197
|
// connect
|
|
1182
1198
|
if (ops.connect !== undefined) {
|
|
1183
1199
|
const items = toArray(ops.connect);
|
|
@@ -1480,6 +1496,40 @@ async function processSet(ctx, rel, setItems, parentRow) {
|
|
|
1480
1496
|
await ctx.tx.table(rel.to).update({ where: target, data: updateData });
|
|
1481
1497
|
}
|
|
1482
1498
|
}
|
|
1499
|
+
/**
|
|
1500
|
+
* The rows of a nested `createMany` payload. Prisma's shape is
|
|
1501
|
+
* `{ data: row | row[], skipDuplicates?: boolean }`, and its rows may not carry
|
|
1502
|
+
* nested relation writes of their own (a `createMany` is one INSERT). Anything
|
|
1503
|
+
* else is refused rather than read as zero rows.
|
|
1504
|
+
*/
|
|
1505
|
+
function nestedCreateManyRows(payload, relName, childMeta) {
|
|
1506
|
+
if (!(0, filters_js_1.isPlainRecord)(payload)) {
|
|
1507
|
+
throw new errors_js_1.ValidationError(`Nested createMany on "${relName}" takes { data: [...], skipDuplicates?: boolean }.`);
|
|
1508
|
+
}
|
|
1509
|
+
for (const key of Object.keys(payload)) {
|
|
1510
|
+
if (key !== 'data' && key !== 'skipDuplicates' && payload[key] !== undefined) {
|
|
1511
|
+
throw new errors_js_1.ValidationError(`Nested createMany on "${relName}": unknown key "${key}". Valid keys: data, skipDuplicates.`);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
const data = payload.data;
|
|
1515
|
+
const rows = Array.isArray(data) ? data : (0, filters_js_1.isPlainRecord)(data) ? [data] : undefined;
|
|
1516
|
+
if (!rows || rows.some((row) => !(0, filters_js_1.isPlainRecord)(row))) {
|
|
1517
|
+
throw new errors_js_1.ValidationError(`Nested createMany on "${relName}" requires \`data\`, a row object or an array of them.`);
|
|
1518
|
+
}
|
|
1519
|
+
if (payload.skipDuplicates !== undefined && typeof payload.skipDuplicates !== 'boolean') {
|
|
1520
|
+
throw new errors_js_1.ValidationError(`Nested createMany on "${relName}": skipDuplicates must be a boolean.`);
|
|
1521
|
+
}
|
|
1522
|
+
if (childMeta) {
|
|
1523
|
+
for (const row of rows) {
|
|
1524
|
+
const nested = Object.keys(extractRelationFields(row, childMeta).relations);
|
|
1525
|
+
if (nested.length > 0) {
|
|
1526
|
+
throw new errors_js_1.ValidationError(`Nested createMany on "${relName}" cannot write relations of its rows (${nested.join(', ')}). ` +
|
|
1527
|
+
'Use create for rows with nested writes.');
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
return { rows: rows, skipDuplicates: payload.skipDuplicates === true };
|
|
1532
|
+
}
|
|
1483
1533
|
// ---------------------------------------------------------------------------
|
|
1484
1534
|
// update / upsert operations (update-context only)
|
|
1485
1535
|
// ---------------------------------------------------------------------------
|
|
@@ -1489,17 +1539,21 @@ async function processNestedUpdate(ctx, rel, updateArg, relName, parentRow) {
|
|
|
1489
1539
|
return;
|
|
1490
1540
|
const correlation = parentCorrelationWhere(ctx, rel, parentRow);
|
|
1491
1541
|
for (const item of items) {
|
|
1492
|
-
|
|
1493
|
-
|
|
1542
|
+
// A to-one update may leave out `where`: the row is the one pointing at
|
|
1543
|
+
// this parent, as in Prisma.
|
|
1544
|
+
const toOne = rel.type === 'hasOne';
|
|
1545
|
+
if ((!item.where && !toOne) || !item.data) {
|
|
1546
|
+
throw new errors_js_1.ValidationError(`Nested update on "${rel.name}" requires ${toOne ? 'a "data" field' : 'both "where" and "data" fields'}.`);
|
|
1494
1547
|
}
|
|
1495
|
-
|
|
1548
|
+
const target = item.where ?? true;
|
|
1549
|
+
assertTargetSelectsSomething(target, 'update', relName, rel);
|
|
1496
1550
|
if (!correlation)
|
|
1497
|
-
throw notRelatedToParent('update', relName, rel,
|
|
1551
|
+
throw notRelatedToParent('update', relName, rel, target);
|
|
1498
1552
|
try {
|
|
1499
|
-
await ctx.tx.table(rel.to).update({ where: scopeWhereToParent(
|
|
1553
|
+
await ctx.tx.table(rel.to).update({ where: scopeWhereToParent(target, correlation), data: item.data });
|
|
1500
1554
|
}
|
|
1501
1555
|
catch (err) {
|
|
1502
|
-
rethrowAsNotRelated(err, 'update', relName, rel,
|
|
1556
|
+
rethrowAsNotRelated(err, 'update', relName, rel, target);
|
|
1503
1557
|
}
|
|
1504
1558
|
}
|
|
1505
1559
|
}
|
|
@@ -1513,19 +1567,24 @@ async function processNestedUpsert(ctx, rel, upsertArg, parentRow, relName) {
|
|
|
1513
1567
|
// surfaced to the caller rather than silently rewriting a stranger's row).
|
|
1514
1568
|
const correlation = parentCorrelationWhere(ctx, rel, parentRow);
|
|
1515
1569
|
for (const item of items) {
|
|
1516
|
-
|
|
1517
|
-
|
|
1570
|
+
// A to-one upsert may leave out `where`, as in Prisma: the row it means is
|
|
1571
|
+
// the one pointing at this parent (`true`, the to-one "the related row"
|
|
1572
|
+
// selector). A to-many one must name its row.
|
|
1573
|
+
const toOne = rel.type === 'hasOne';
|
|
1574
|
+
if ((!item.where && !toOne) || !item.create || !item.update) {
|
|
1575
|
+
throw new errors_js_1.ValidationError(`Nested upsert on "${rel.name}" requires ${toOne ? '' : '"where", '}"create", and "update" fields.`);
|
|
1518
1576
|
}
|
|
1519
|
-
|
|
1577
|
+
const target = item.where ?? true;
|
|
1578
|
+
assertTargetSelectsSomething(target, 'upsert', relName, rel);
|
|
1520
1579
|
const update = upsertUpdateData(ctx, rel, item);
|
|
1521
|
-
const scoped = correlation ? scopeWhereToParent(
|
|
1580
|
+
const scoped = correlation ? scopeWhereToParent(target, correlation) : null;
|
|
1522
1581
|
const existing = scoped ? await ctx.tx.table(rel.to).findUnique({ where: scoped }) : null;
|
|
1523
1582
|
if (existing && scoped) {
|
|
1524
1583
|
try {
|
|
1525
1584
|
await ctx.tx.table(rel.to).update({ where: scoped, data: update });
|
|
1526
1585
|
}
|
|
1527
1586
|
catch (err) {
|
|
1528
|
-
rethrowAsNotRelated(err, 'upsert', relName, rel,
|
|
1587
|
+
rethrowAsNotRelated(err, 'upsert', relName, rel, target);
|
|
1529
1588
|
}
|
|
1530
1589
|
}
|
|
1531
1590
|
else {
|
|
@@ -1575,9 +1634,12 @@ async function processBelongsToUpdate(ctx, rel, updateArg, parentRow, parentTabl
|
|
|
1575
1634
|
}
|
|
1576
1635
|
async function processBelongsToUpsert(ctx, rel, upsertArg, parentRow, parentTable) {
|
|
1577
1636
|
const item = upsertArg;
|
|
1578
|
-
|
|
1579
|
-
|
|
1637
|
+
// `where` is optional, as in Prisma: without it the row is the one this
|
|
1638
|
+
// parent points at.
|
|
1639
|
+
if (!item.create || !item.update) {
|
|
1640
|
+
throw new errors_js_1.ValidationError(`Nested upsert on belongsTo "${rel.name}" requires "create" and "update" fields.`);
|
|
1580
1641
|
}
|
|
1642
|
+
const target = item.where ?? true;
|
|
1581
1643
|
// Scope the lookup to the row this parent actually points at. Without the
|
|
1582
1644
|
// correlation, a `where` naming any other row would update a record with no
|
|
1583
1645
|
// relationship to the parent being written. A miss falls through to the
|
|
@@ -1593,7 +1655,7 @@ async function processBelongsToUpsert(ctx, rel, upsertArg, parentRow, parentTabl
|
|
|
1593
1655
|
// row can come back.
|
|
1594
1656
|
const existing = correlation
|
|
1595
1657
|
? ((await ctx.tx.table(rel.to).findMany({
|
|
1596
|
-
where: scopeWhereToParent(
|
|
1658
|
+
where: scopeWhereToParent(target, correlation),
|
|
1597
1659
|
// Internal engine read (see the connect path): no unlimited-findMany warning.
|
|
1598
1660
|
warnOnUnlimited: false,
|
|
1599
1661
|
}))[0] ?? null)
|