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.
@@ -830,7 +830,19 @@ function buildHavingScalarClauses(qi, field, value, params, groupKeys) {
830
830
  const HAVING_COMPARISONS = { equals: '=', not: '!=', ...filters_js_1.JSON_RANGE_OPERATORS };
831
831
  const HAVING_OPERATORS = new Set([...Object.keys(HAVING_COMPARISONS), 'in', 'notIn']);
832
832
  function buildHavingNumericClauses(qi, expr, filter, params, operandType) {
833
- const bind = (value) => operandType === undefined ? value : whereMod.textComparedOperand(qi, operandType, value);
833
+ // A `_min` / `_max` operand is compared with a stored cell, so it binds as a
834
+ // where operand against that column does: a Date on a zone-less temporal
835
+ // column becomes the UTC-component literal (raw, node-postgres would render it
836
+ // in the PROCESS zone and the comparison would be hours off), and on MySQL a
837
+ // number against text binds as text.
838
+ const bind = (value) => {
839
+ if (operandType === undefined)
840
+ return value;
841
+ const temporal = value instanceof Date
842
+ ? (0, query_utils_js_1.coerceTemporalValue)(operandType, value, whereMod.utcDateTimeRewrite(qi, operandType))
843
+ : value;
844
+ return whereMod.textComparedOperand(qi, operandType, temporal);
845
+ };
834
846
  const bindList = (value) => operandType !== undefined && Array.isArray(value) ? value.map(bind) : value;
835
847
  if (filter === null) {
836
848
  throw new errors_js_1.ValidationError(`Invalid having filter on "${expr}" for table "${qi.table}": expected a value or operator object.`);
@@ -1413,9 +1413,19 @@ export interface ConnectOrCreateOp<T, TR extends object = {}> {
1413
1413
  where: Partial<T>;
1414
1414
  create: CreateDataInput<T, TR>;
1415
1415
  }
1416
+ /**
1417
+ * Nested `createMany` op (one-to-many relations): rows inserted in one batch,
1418
+ * each without nested relation writes of its own, optionally skipping rows that
1419
+ * collide with a unique key.
1420
+ */
1421
+ export interface NestedCreateManyOp<T> {
1422
+ data: OptionalInput<T> | OptionalInput<T>[];
1423
+ skipDuplicates?: boolean | undefined;
1424
+ }
1416
1425
  /** Nested write ops valid inside `create()` data for a relation field. */
1417
1426
  export interface NestedCreateOp<T, TR extends object = {}> {
1418
1427
  create?: CreateDataInput<T, TR> | CreateDataInput<T, TR>[] | undefined;
1428
+ createMany?: NestedCreateManyOp<T> | undefined;
1419
1429
  connect?: Partial<T> | Partial<T>[] | undefined;
1420
1430
  connectOrCreate?: ConnectOrCreateOp<T, TR> | ConnectOrCreateOp<T, TR>[] | undefined;
1421
1431
  }
@@ -1453,11 +1463,15 @@ export interface NestedToOneUpdateOp<T, TR extends object = {}> extends NestedTo
1453
1463
  update?: {
1454
1464
  data: UpdateDataInput<T, TR>;
1455
1465
  } | undefined;
1456
- upsert?: NestedUpsertOpItem<T, TR> | undefined;
1466
+ /** `where` is optional: without it the row is the one this record points at. */
1467
+ upsert?: (Omit<NestedUpsertOpItem<T, TR>, 'where'> & {
1468
+ where?: Partial<T> | undefined;
1469
+ }) | undefined;
1457
1470
  }
1458
1471
  /** Nested write ops valid inside `update()` data for a relation field. */
1459
1472
  export interface NestedUpdateOp<T, TR extends object = {}> {
1460
1473
  create?: CreateDataInput<T, TR> | CreateDataInput<T, TR>[] | undefined;
1474
+ createMany?: NestedCreateManyOp<T> | undefined;
1461
1475
  connect?: Partial<T> | Partial<T>[] | undefined;
1462
1476
  connectOrCreate?: ConnectOrCreateOp<T, TR> | ConnectOrCreateOp<T, TR>[] | undefined;
1463
1477
  disconnect?: Partial<T> | Partial<T>[] | undefined;
@@ -429,13 +429,14 @@ export interface PrismaModelMap {
429
429
  compoundUniques: Record<string, string[]>;
430
430
  /**
431
431
  * Prisma CLIENT-side default per Prisma field name. Prisma's
432
- * `@default(uuid())` / `@default(cuid())` / `@updatedAt` (and `@default(now())`
433
- * when the migration left no database default) are filled by the Prisma
434
- * client, not the database, so the columns commonly have NO db default and a
435
- * Prisma call site omits them. The compat adapter fills these on create
436
- * (`uuid` / `cuid` / `now`) and touches `updatedAt` fields on
437
- * update/updateMany/upsert, exactly like Prisma. Emitted by
438
- * `migrate-from-prisma` only for columns the database does not default.
432
+ * `@default(uuid())` / `@default(cuid())` / `@default(now())` / `@updatedAt`
433
+ * are filled by the Prisma client, not the database, so the columns commonly
434
+ * have NO db default and a Prisma call site omits them. The compat adapter
435
+ * fills these on create (`uuid` / `cuid` / `now`), at every depth of a nested
436
+ * write, and touches `updatedAt` fields on update/updateMany/upsert, exactly
437
+ * like Prisma. `migrate-from-prisma` emits `uuid` / `cuid` only for columns the
438
+ * database does not default, and `now` / `updatedAt` always: Prisma stamps
439
+ * them with the app's clock even when the column has a database default.
439
440
  */
440
441
  clientDefaults?: Record<string, 'uuid' | 'cuid' | 'now' | 'updatedAt'>;
441
442
  }
@@ -109,8 +109,10 @@ export declare class TransactionState {
109
109
  private readonly root;
110
110
  /** Frames whose SAVEPOINT is set and not yet released or rolled back, outermost first. */
111
111
  private readonly openFrames;
112
- /** Statements sent on the connection that have not answered yet. */
112
+ /** Statements sent on the connection (or queued to be) that have not answered yet. */
113
113
  private onWire;
114
+ /** Settles when the last statement handed to {@link send} has answered; it never rejects. */
115
+ private wireTail;
114
116
  /** A cancellable statement owns admission until its listener and delivery settle. */
115
117
  private exclusive;
116
118
  /** Statements and savepoint blocks started through the transaction that have not settled. */
@@ -219,6 +221,17 @@ export declare class TransactionState {
219
221
  screenRaw(sql: unknown): boolean;
220
222
  private assertAvailable;
221
223
  /** Put one statement on the wire, counted for {@link whenIdle} and recorded on failure. */
224
+ /**
225
+ * Send one statement, after every statement sent before it has answered.
226
+ *
227
+ * A transaction owns ONE connection, and `Promise.all([tx.a(), tx.b()])` (or a
228
+ * batched relation load, whose sibling loads start together) handed both to
229
+ * the driver at once. pg queues the second on the client itself, which it
230
+ * reports as deprecated and pg 9 removes; other drivers do not queue at all.
231
+ * The order is kept here instead, in call order, unless the driver pipelines.
232
+ * `recheck` runs after the wait and before sending, so a statement queued
233
+ * behind one that aborted or ended the transaction is refused rather than sent.
234
+ */
222
235
  private send;
223
236
  private settled;
224
237
  /** Record `err` as the first failure, unless one is already recorded. */
@@ -84,8 +84,10 @@ class TransactionState {
84
84
  root;
85
85
  /** Frames whose SAVEPOINT is set and not yet released or rolled back, outermost first. */
86
86
  openFrames = [];
87
- /** Statements sent on the connection that have not answered yet. */
87
+ /** Statements sent on the connection (or queued to be) that have not answered yet. */
88
88
  onWire = 0;
89
+ /** Settles when the last statement handed to {@link send} has answered; it never rejects. */
90
+ wireTail = Promise.resolve();
89
91
  /** A cancellable statement owns admission until its listener and delivery settle. */
90
92
  exclusive = false;
91
93
  /** Statements and savepoint blocks started through the transaction that have not settled. */
@@ -239,7 +241,13 @@ class TransactionState {
239
241
  this.settled();
240
242
  });
241
243
  }
242
- const result = await this.send(statement);
244
+ const result = await this.send(statement, () => {
245
+ // Re-read after waiting for the statements queued ahead of this one: one
246
+ // of them may have ended or aborted the transaction meanwhile.
247
+ this.assertOpen();
248
+ if (!recovery)
249
+ this.assertNotAborted();
250
+ });
243
251
  if (recovery)
244
252
  this.clearAbort();
245
253
  return result;
@@ -290,18 +298,52 @@ class TransactionState {
290
298
  throw new errors_js_1.ValidationError('A cancellable cursor requires an otherwise idle transaction connection.');
291
299
  }
292
300
  /** Put one statement on the wire, counted for {@link whenIdle} and recorded on failure. */
293
- async send(statement) {
301
+ /**
302
+ * Send one statement, after every statement sent before it has answered.
303
+ *
304
+ * A transaction owns ONE connection, and `Promise.all([tx.a(), tx.b()])` (or a
305
+ * batched relation load, whose sibling loads start together) handed both to
306
+ * the driver at once. pg queues the second on the client itself, which it
307
+ * reports as deprecated and pg 9 removes; other drivers do not queue at all.
308
+ * The order is kept here instead, in call order, unless the driver pipelines.
309
+ * `recheck` runs after the wait and before sending, so a statement queued
310
+ * behind one that aborted or ended the transaction is refused rather than sent.
311
+ */
312
+ async send(statement, recheck, inOrder = true) {
313
+ // A driver that pipelines (`supportsPipelining`) takes concurrent
314
+ // statements by design and answers them in order; the batch
315
+ // `$transaction([...])` path relies on dispatching them all at once there.
316
+ const ordered = inOrder && this.client.supportsPipelining !== true;
317
+ // Nothing ahead: send now, with no extra turn of the event loop.
318
+ const queued = ordered && this.onWire > 0;
294
319
  this.onWire++;
320
+ const previous = this.wireTail;
321
+ let done = () => { };
322
+ if (ordered) {
323
+ this.wireTail = new Promise((resolve) => {
324
+ done = resolve;
325
+ });
326
+ }
327
+ let sent = false;
295
328
  try {
329
+ if (queued) {
330
+ await previous;
331
+ recheck?.();
332
+ }
333
+ sent = true;
296
334
  return await statement();
297
335
  }
298
336
  catch (err) {
337
+ // A refusal by `recheck` is not a statement failure: nothing was sent.
338
+ if (!sent)
339
+ throw err;
299
340
  this.noteFailure(err);
300
341
  if (this.abortsOnError && reportedByServer(err))
301
342
  this.noteDead(err);
302
343
  throw err;
303
344
  }
304
345
  finally {
346
+ done();
305
347
  this.settled();
306
348
  }
307
349
  }
@@ -456,7 +498,9 @@ class TransactionState {
456
498
  }
457
499
  this.assertNotAborted();
458
500
  const name = `sp_${++this.savepointCount}`;
459
- await this.control(this.dialect.savepointStatement(name));
501
+ // In order: a statement issued before this block and still queued
502
+ // behind one on the wire belongs outside the savepoint.
503
+ await this.control(this.dialect.savepointStatement(name), true);
460
504
  const opened = {
461
505
  state: this,
462
506
  parent,
@@ -560,10 +604,21 @@ class TransactionState {
560
604
  * Typed INSIDE the statement, so the failure the state records is the Turbine
561
605
  * error and not the driver's.
562
606
  */
563
- async control(sql) {
607
+ async control(sql, inOrder = false) {
564
608
  this.assertOpen();
565
609
  this.assertAvailable();
566
- await this.send(() => sendControl(this.client, sql));
610
+ // RELEASE and ROLLBACK TO are not ordered behind statements still on the
611
+ // wire: a ROLLBACK TO after a statement cut short by its deadline is how
612
+ // that statement's outcome is settled, and it must not wait for the
613
+ // statement to end. A SAVEPOINT is (`inOrder`): sent past a statement
614
+ // queued before it, it would open the block around that statement, and
615
+ // the block's rollback would undo a statement that reported success.
616
+ await this.send(() => sendControl(this.client, sql), inOrder
617
+ ? () => {
618
+ this.assertOpen();
619
+ this.assertNotAborted();
620
+ }
621
+ : undefined, inOrder);
567
622
  }
568
623
  }
569
624
  exports.TransactionState = TransactionState;
@@ -300,11 +300,14 @@ function relationFkColumns(model, field) {
300
300
  * Prisma CLIENT-side defaults for a resolved model: `@default(uuid())` /
301
301
  * `@default(cuid())` / `@updatedAt` are filled by the Prisma client (the
302
302
  * database column typically has NO default), so migrated call sites omit those
303
- * fields and a plain insert violates NOT NULL. `@default(now())` is normally a
304
- * database default, so it is carried only when the introspected column has no
305
- * default. `@updatedAt` is always carried (Prisma touches it on every update
306
- * regardless of any database default). Returns undefined when the model has
307
- * none, keeping the emitted map byte-identical for unaffected schemas.
303
+ * fields and a plain insert violates NOT NULL. `uuid()` / `cuid()` are carried
304
+ * only when the column has no database default (either one is an opaque random
305
+ * id). `@default(now())` and `@updatedAt` are ALWAYS carried: Prisma sends its
306
+ * own clock's time even when the migration also wrote `DEFAULT
307
+ * CURRENT_TIMESTAMP`, and the two clocks differ, so leaving `now()` to the
308
+ * database made a row stamped "now" compare as later than the app's
309
+ * `new Date()` taken right after the insert. Returns undefined when the model
310
+ * has none, keeping the emitted map byte-identical for unaffected schemas.
308
311
  */
309
312
  function collectClientDefaults(model, resolvedFields, tableMeta) {
310
313
  if (!tableMeta)
@@ -319,16 +322,18 @@ function collectClientDefaults(model, resolvedFields, tableMeta) {
319
322
  out[field.name] = 'updatedAt';
320
323
  continue;
321
324
  }
322
- if (col?.hasDefault)
323
- continue; // the database fills it; nothing to emulate
324
325
  const def = field.attrs.find((a) => a.name === 'default');
325
326
  const raw = def?.args.find((a) => a.key === undefined && a.kind === 'raw')?.value ?? '';
327
+ if (/^now\s*\(\s*\)$/.test(raw)) {
328
+ out[field.name] = 'now';
329
+ continue;
330
+ }
331
+ if (col?.hasDefault)
332
+ continue; // the database fills it; nothing to emulate
326
333
  if (/^uuid\s*\(/.test(raw))
327
334
  out[field.name] = 'uuid';
328
335
  else if (/^cuid\s*\(/.test(raw))
329
336
  out[field.name] = 'cuid';
330
- else if (/^now\s*\(\s*\)$/.test(raw))
331
- out[field.name] = 'now';
332
337
  }
333
338
  return Object.keys(out).length > 0 ? out : undefined;
334
339
  }
package/dist/client.js CHANGED
@@ -24,7 +24,7 @@
24
24
  import pg from '#pg';
25
25
  import { openCheckout, typeCheckoutTimeouts } from './checkout.js';
26
26
  import { absorbCheckedOutErrors, settleLongIdleCheckouts, watchCheckouts, } from './connection-guard.js';
27
- import { detectPoolerTarget, fillTargetFromEnvironment, parseConnectionTarget, statementTimeoutSetting, withStartupSetting, } from './connection-url.js';
27
+ import { detectPooler, detectPoolerTarget, fillTargetFromEnvironment, parseConnectionTarget, readPrismaUrlParameters, statementTimeoutSetting, withSearchPathOption, withStartupSetting, } from './connection-url.js';
28
28
  import { resolveDiagnostics } from './diagnostics.js';
29
29
  import { assertDialectCapabilities, postgresDialect } from './dialect.js';
30
30
  import { ConnectionError, errorMessageModesDiverged, PipelineError, registerClientErrorMessageMode, runWithErrorMessageMode, setErrorMessageMode, TransactionOutcomeUnknownError, UnsupportedFeatureError, ValidationError, wrapPgError, } from './errors.js';
@@ -386,6 +386,32 @@ function pgEnv(name) {
386
386
  return (typeof process !== 'undefined' ? process.env?.[name] : undefined) || undefined;
387
387
  }
388
388
  /** Whether any explicit connection field suppresses the environment URL fallback. */
389
+ /**
390
+ * {@link readPrismaUrlParameters} for a connection string this client will
391
+ * open, with the refusals raised: an invalid value, and a non-public `schema`
392
+ * that cannot be pinned safely. A `search_path` rides the connection's startup
393
+ * `options`, which a transaction pooler drops or refuses, and the alternative
394
+ * (a session `SET`) leaks to the next client of a pooled backend; querying the
395
+ * wrong schema is the outcome this exists to prevent, so both are E003.
396
+ */
397
+ function readPrismaUrlParametersFor(connectionString, label) {
398
+ const params = readPrismaUrlParameters(connectionString);
399
+ if (!params)
400
+ return null;
401
+ if (params.invalid)
402
+ throw new ValidationError(`${label}: ${params.invalid}.`);
403
+ if (params.schema !== undefined && params.schema !== 'public') {
404
+ if (detectPooler(connectionString).pooled) {
405
+ throw new ValidationError(`${label} names schema "${params.schema}" on what looks like a transaction pooler. A pooler cannot ` +
406
+ 'carry a per-connection search_path; point the client at the direct endpoint, or use the public schema.');
407
+ }
408
+ if (withSearchPathOption(params.connectionString, params.schema, [], { quotedNames: true }) === null) {
409
+ throw new ValidationError(`${label}: schema "${params.schema}" cannot be set as the connection's search_path (it may not contain ` +
410
+ 'whitespace, a double quote or a backslash).');
411
+ }
412
+ }
413
+ return params;
414
+ }
389
415
  function hasExplicitConnectionTarget(config) {
390
416
  return (config.connectionString != null ||
391
417
  config.host != null ||
@@ -1097,9 +1123,11 @@ export class TurbineClient {
1097
1123
  // `connectionString: process.env.DATABASE_URL ?? ''` must keep constructing,
1098
1124
  // and it still suppresses the DATABASE_URL fallback because
1099
1125
  // `hasExplicitConnection` tests `!= null`, not truthiness.
1126
+ let prismaUrl = null;
1100
1127
  if (!config.pool) {
1101
1128
  if (config.connectionString) {
1102
1129
  assertUsableConnectionString(config.connectionString, 'connectionString');
1130
+ prismaUrl = readPrismaUrlParametersFor(config.connectionString, 'connectionString');
1103
1131
  }
1104
1132
  else if (config.connectionString == null &&
1105
1133
  config.host == null &&
@@ -1109,6 +1137,7 @@ export class TurbineClient {
1109
1137
  config.password == null &&
1110
1138
  process.env.DATABASE_URL) {
1111
1139
  assertUsableConnectionString(process.env.DATABASE_URL, 'DATABASE_URL environment variable');
1140
+ prismaUrl = readPrismaUrlParametersFor(process.env.DATABASE_URL, 'DATABASE_URL environment variable');
1112
1141
  }
1113
1142
  }
1114
1143
  for (const [i, replica] of (config.replicas ?? []).entries()) {
@@ -1314,6 +1343,26 @@ export class TurbineClient {
1314
1343
  if (config.ssl !== undefined) {
1315
1344
  poolConfig.ssl = config.ssl;
1316
1345
  }
1346
+ // Prisma's `schema` / `connection_limit` / `pool_timeout` (read and
1347
+ // validated above): stripped from what pg sees, and honoured. An explicit
1348
+ // client option wins over the URL's.
1349
+ if (prismaUrl && poolConfig.connectionString) {
1350
+ poolConfig.connectionString = prismaUrl.connectionString;
1351
+ if (prismaUrl.connectionLimit !== undefined && config.poolSize == null && config.max == null) {
1352
+ poolConfig.max = prismaUrl.connectionLimit;
1353
+ }
1354
+ if (prismaUrl.poolTimeoutMs !== undefined &&
1355
+ config.connectionTimeoutMs == null &&
1356
+ config.connectionTimeoutMillis == null) {
1357
+ poolConfig.connectionTimeoutMillis = prismaUrl.poolTimeoutMs;
1358
+ }
1359
+ if (prismaUrl.schema !== undefined && prismaUrl.schema !== 'public') {
1360
+ // Checked non-null when it was read.
1361
+ poolConfig.connectionString =
1362
+ withSearchPathOption(poolConfig.connectionString, prismaUrl.schema, [], { quotedNames: true }) ??
1363
+ poolConfig.connectionString;
1364
+ }
1365
+ }
1317
1366
  // Held as a `pg.Pool` for the length of this block: `PgCompatPool.on` is
1318
1367
  // optional (HTTP drivers have no pool events), and this branch owns a
1319
1368
  // 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[]): string | null;
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;
@@ -333,6 +333,18 @@ export const SEARCH_PATH_SCHEMA_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
333
333
  export function isPlainSchemaIdentifier(schema) {
334
334
  return SEARCH_PATH_SCHEMA_PATTERN.test(schema);
335
335
  }
336
+ /**
337
+ * Whether `schema` is in the wider set of names {@link withSearchPathOption} emits with
338
+ * `quotedNames: true`: anything but whitespace, a double quote, a backslash or a
339
+ * NUL. The name is always written double-quoted, so these four are exactly the
340
+ * characters that could end the quoted name or split the `options` string into a
341
+ * second `-c`; every other character (a hyphen, a dot, non-ASCII letters) is part
342
+ * of the identifier. Used for Prisma's `?schema=`, where names such as
343
+ * `tenant-a` are ordinary.
344
+ */
345
+ export function isQuotableSchemaName(schema) {
346
+ return schema.length > 0 && !/[\s"\\]/.test(schema) && !schema.includes('\u0000');
347
+ }
336
348
  /**
337
349
  * The one name outside {@link SEARCH_PATH_SCHEMA_PATTERN} that is still safe to
338
350
  * emit into the `options=-c` literal, and worth keeping.
@@ -479,8 +491,8 @@ function searchPathListValue(schema, alsoResolveIn) {
479
491
  * `null` as a refusal: the unpinned string means "into whichever schema the
480
492
  * role defaults to", the exact outcome this exists to prevent.
481
493
  */
482
- export function withSearchPathOption(connectionString, schema, alsoResolveIn = []) {
483
- if (!isPlainSchemaIdentifier(schema))
494
+ export function withSearchPathOption(connectionString, schema, alsoResolveIn = [], options = {}) {
495
+ if (!(options.quotedNames ? isQuotableSchemaName(schema) : isPlainSchemaIdentifier(schema)))
484
496
  return null;
485
497
  const setting = `-c search_path=${searchPathListValue(schema, alsoResolveIn)}`;
486
498
  const merged = mergeConnectionStringOptions(connectionString, setting);
@@ -496,3 +508,44 @@ export function withSearchPathOption(connectionString, schema, alsoResolveIn = [
496
508
  const head = q === -1 ? connectionString : connectionString.slice(0, q);
497
509
  return `${head}?${params.toString()}`;
498
510
  }
511
+ const PRISMA_URL_PARAMETERS = ['schema', 'connection_limit', 'pool_timeout'];
512
+ /**
513
+ * Read (and strip) Prisma's `schema` / `connection_limit` / `pool_timeout`.
514
+ * `null` when the string carries none of them, which is every Turbine-native
515
+ * connection string, so those pass through byte-for-byte. Only the query string
516
+ * is rewritten, never the userinfo or host (see
517
+ * {@link mergeConnectionStringOptions} for why).
518
+ */
519
+ export function readPrismaUrlParameters(connectionString) {
520
+ const q = connectionString.indexOf('?');
521
+ if (q === -1)
522
+ return null;
523
+ const params = new URLSearchParams(connectionString.slice(q + 1));
524
+ if (!PRISMA_URL_PARAMETERS.some((name) => params.has(name)))
525
+ return null;
526
+ const schema = params.get('schema') ?? '';
527
+ const limit = params.get('connection_limit');
528
+ const timeout = params.get('pool_timeout');
529
+ for (const name of PRISMA_URL_PARAMETERS)
530
+ params.delete(name);
531
+ const rest = params.toString();
532
+ const stripped = connectionString.slice(0, rest ? q + 1 : q) + rest;
533
+ const out = { connectionString: stripped };
534
+ if (schema !== '')
535
+ out.schema = schema;
536
+ if (limit !== null && limit !== '') {
537
+ const n = Number(limit);
538
+ if (!Number.isSafeInteger(n) || n < 1)
539
+ out.invalid = 'connection_limit must be a positive integer';
540
+ else
541
+ out.connectionLimit = n;
542
+ }
543
+ if (timeout !== null && timeout !== '') {
544
+ const n = Number(timeout);
545
+ if (!Number.isSafeInteger(n) || n < 0)
546
+ out.invalid = 'pool_timeout must be a non-negative whole number of seconds';
547
+ else
548
+ out.poolTimeoutMs = n * 1000;
549
+ }
550
+ return out;
551
+ }