@prisma/query-plan-executor 7.10.1 → 7.11.0-dev.1

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/dist/index.d.ts CHANGED
@@ -2425,6 +2425,12 @@ declare type PureQueryPlanNode<Rest = never> = {
2425
2425
  * query plan purification. Never produced by the query compiler.
2426
2426
  */
2427
2427
  lastInsertId?: string;
2428
+ /**
2429
+ * Present when this node holds an already-evaluated runtime result (e.g. from
2430
+ * an evaluated impure query plan node) and does not need to be traversed and copied
2431
+ * by evaluateArg.
2432
+ */
2433
+ isEvaluated?: boolean;
2428
2434
  } | {
2429
2435
  type: 'seq';
2430
2436
  args: (PureQueryPlanNode<Rest> | Rest)[];
@@ -3275,6 +3281,12 @@ declare interface TracingHelper {
3275
3281
  runInChildSpan<R>(nameOrOptions: string | ExtendedSpanOptions, callback: SpanCallback<R>): R;
3276
3282
  }
3277
3283
 
3284
+ /**
3285
+ * A transaction on one connection. The caller calls either `commit()` or `rollback()`, once,
3286
+ * and sends nothing on the transaction afterwards. `commit()` is called only when no statement is
3287
+ * running. `rollback()`, `rollbackToSavepoint()`, `releaseSavepoint()` and a `ROLLBACK` sent through
3288
+ * `executeRaw` may be called while one is.
3289
+ */
3278
3290
  declare interface Transaction extends AdapterInfo, SqlQueryable {
3279
3291
  /**
3280
3292
  * Transaction options.
@@ -3329,7 +3341,14 @@ export declare class TransactionManager {
3329
3341
  startTransaction(options?: TransactionOptions_2): Promise<TransactionInfo>;
3330
3342
  commitTransaction(transactionId: string): Promise<void>;
3331
3343
  rollbackTransaction(transactionId: string): Promise<void>;
3332
- getTransaction(txInfo: TransactionInfo, operation: string): Promise<Transaction>;
3344
+ /**
3345
+ * Returns a handle for running statements in the transaction. The handle rejects every
3346
+ * statement issued after the transaction has started to close, or after the nested transaction
3347
+ * that is innermost now has started to roll back. A commit of that nested transaction never
3348
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
3349
+ * including one issued while the commit waits to release the savepoint.
3350
+ */
3351
+ getTransaction(txInfo: TransactionInfo, operation: string): Promise<SqlQueryable>;
3333
3352
  cancelAllTransactions(): Promise<void>;
3334
3353
  }
3335
3354
 
package/dist/index.js CHANGED
@@ -72089,7 +72089,7 @@ __export(index_exports, {
72089
72089
  module.exports = __toCommonJS(index_exports);
72090
72090
 
72091
72091
  // package.json
72092
- var version = "7.10.1";
72092
+ var version = "7.11.0-dev.1";
72093
72093
 
72094
72094
  // ../../node_modules/.pnpm/temporal-polyfill@0.3.0/node_modules/temporal-polyfill/chunks/internal.js
72095
72095
  function clampProp(e2, n2, t2, o2, r2) {
@@ -79950,13 +79950,14 @@ function debugCreate(namespace) {
79950
79950
  };
79951
79951
  const debugCall = (...args) => {
79952
79952
  const { enabled: enabled3, namespace: namespace2, color, log: log6 } = instanceProps;
79953
+ const isEnabled = topProps.enabled(namespace2) || enabled3;
79953
79954
  if (args.length !== 0) {
79954
- argsHistory.push([namespace2, ...args]);
79955
+ argsHistory.push([namespace2, ...isEnabled ? args : args.map(summarizeArg)]);
79955
79956
  }
79956
79957
  if (argsHistory.length > MAX_ARGS_HISTORY) {
79957
79958
  argsHistory.shift();
79958
79959
  }
79959
- if (topProps.enabled(namespace2) || enabled3) {
79960
+ if (isEnabled) {
79960
79961
  const stringArgs = args.map((arg) => {
79961
79962
  if (typeof arg === "string") {
79962
79963
  return arg;
@@ -79981,6 +79982,15 @@ var Debug = new Proxy(debugCreate, {
79981
79982
  get: (_3, prop) => topProps[prop],
79982
79983
  set: (_3, prop, value) => topProps[prop] = value
79983
79984
  });
79985
+ function summarizeArg(arg) {
79986
+ if (arg instanceof Error) {
79987
+ return `${arg.name}: ${arg.message}`;
79988
+ }
79989
+ if (typeof arg === "object" && arg !== null || typeof arg === "function") {
79990
+ return "[Object]";
79991
+ }
79992
+ return arg;
79993
+ }
79984
79994
  function safeStringify(value, indent = 2) {
79985
79995
  const cache = /* @__PURE__ */ new Set();
79986
79996
  return JSON.stringify(
@@ -83507,7 +83517,7 @@ var QueryInterpreter = class _QueryInterpreter {
83507
83517
  switch (node.type) {
83508
83518
  case "value": {
83509
83519
  return {
83510
- value: evaluateArg(node.args, context4.scope, context4.generators),
83520
+ value: node.isEvaluated ? node.args : evaluateArg(node.args, context4.scope, context4.generators),
83511
83521
  lastInsertId: node.lastInsertId
83512
83522
  };
83513
83523
  }
@@ -83587,7 +83597,7 @@ var QueryInterpreter = class _QueryInterpreter {
83587
83597
  }
83588
83598
  case "reverse": {
83589
83599
  const { value, lastInsertId } = await this.interpretNode(node.args, context4);
83590
- return { value: Array.isArray(value) ? value.reverse() : value, lastInsertId };
83600
+ return { value: Array.isArray(value) ? value.slice().reverse() : value, lastInsertId };
83591
83601
  }
83592
83602
  case "unique": {
83593
83603
  const { value, lastInsertId } = await this.interpretNode(node.args, context4);
@@ -83615,10 +83625,12 @@ var QueryInterpreter = class _QueryInterpreter {
83615
83625
  if (parent === null) {
83616
83626
  return { value: null, lastInsertId };
83617
83627
  }
83628
+ const parentRecords = (Array.isArray(parent) ? parent : [parent]).map(asRecord);
83618
83629
  const children = await Promise.all(
83619
83630
  node.args.children.map(async (joinExpr) => ({
83620
83631
  joinExpr,
83621
- childRecords: (await this.interpretNode(joinExpr.child, context4)).value
83632
+ // A child can only attach to a parent whose join keys are all non-null.
83633
+ childRecords: parentRecords.some((record2) => joinExpr.on.every(([key]) => record2[key] != null)) ? (await this.interpretNode(joinExpr.child, context4)).value : []
83622
83634
  }))
83623
83635
  );
83624
83636
  return { value: attachChildrenToParents(parent, children, node.args.canAssumeStrictEquality), lastInsertId };
@@ -83679,7 +83691,10 @@ var QueryInterpreter = class _QueryInterpreter {
83679
83691
  #interpretPureNode(node, scope, generators) {
83680
83692
  switch (node.type) {
83681
83693
  case "value": {
83682
- return { value: evaluateArg(node.args, scope, generators), lastInsertId: node.lastInsertId };
83694
+ return {
83695
+ value: node.isEvaluated ? node.args : evaluateArg(node.args, scope, generators),
83696
+ lastInsertId: node.lastInsertId
83697
+ };
83683
83698
  }
83684
83699
  case "seq": {
83685
83700
  let result;
@@ -83722,7 +83737,7 @@ var QueryInterpreter = class _QueryInterpreter {
83722
83737
  }
83723
83738
  case "reverse": {
83724
83739
  const { value, lastInsertId } = this.#interpretPureNode(node.args, scope, generators);
83725
- return { value: Array.isArray(value) ? value.reverse() : value, lastInsertId };
83740
+ return { value: Array.isArray(value) ? value.slice().reverse() : value, lastInsertId };
83726
83741
  }
83727
83742
  case "unique": {
83728
83743
  const { value, lastInsertId } = this.#interpretPureNode(node.args, scope, generators);
@@ -84033,7 +84048,8 @@ function purifyQueryPlan(node, evalNode) {
84033
84048
  const evaluated = {
84034
84049
  type: "value",
84035
84050
  args: result.value,
84036
- lastInsertId: result.lastInsertId
84051
+ lastInsertId: result.lastInsertId,
84052
+ isEvaluated: true
84037
84053
  };
84038
84054
  const purified = replaceImpureNode(node, impureNode, evaluated);
84039
84055
  if (!purified) {
@@ -84197,6 +84213,13 @@ var TransactionRolledBackError = class extends TransactionManagerError {
84197
84213
  super(`Transaction already closed: A ${operation} cannot be executed on a transaction that was rolled back.`);
84198
84214
  }
84199
84215
  };
84216
+ var NestedTransactionRolledBackError = class extends TransactionManagerError {
84217
+ constructor(operation) {
84218
+ super(
84219
+ `Nested transaction already closed: A ${operation} cannot be executed on a nested transaction that was rolled back.`
84220
+ );
84221
+ }
84222
+ };
84200
84223
  var TransactionStartTimeoutError = class extends TransactionManagerError {
84201
84224
  constructor() {
84202
84225
  super("Unable to start a transaction in the given time.");
@@ -84221,7 +84244,23 @@ var InvalidTransactionIsolationLevelError = class extends TransactionManagerErro
84221
84244
  }
84222
84245
  };
84223
84246
  var MAX_CLOSED_TRANSACTIONS = 100;
84224
- var CANCEL_ROLLBACK_GRACE_MS = 2e3;
84247
+ var ROLLBACK_GRACE_MS = 2e3;
84248
+ function createScope(savepoint) {
84249
+ return { savepoint, closingReason: void 0, runningStatements: /* @__PURE__ */ new Set() };
84250
+ }
84251
+ function isNested(scope) {
84252
+ return scope.savepoint !== void 0;
84253
+ }
84254
+ function currentScope(scope) {
84255
+ return scope.mergedInto ? currentScope(scope.mergedInto) : scope;
84256
+ }
84257
+ function createCommitInterruption() {
84258
+ let interruptCommit;
84259
+ const commitInterrupted = new Promise((resolve) => {
84260
+ interruptCommit = resolve;
84261
+ });
84262
+ return { commitInterrupted, interruptCommit };
84263
+ }
84225
84264
  function trackStartingTransaction() {
84226
84265
  let markSettled;
84227
84266
  const settled = new Promise((resolve) => {
@@ -84301,16 +84340,9 @@ var TransactionManager = class {
84301
84340
  `Transaction missing underlying driver transaction when starting a nested transaction.`
84302
84341
  );
84303
84342
  }
84304
- existing.depth += 1;
84305
84343
  const savepointName = this.#nextSavepointName(existing);
84306
- existing.savepoints.push(savepointName);
84307
- try {
84308
- await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
84309
- } catch (e2) {
84310
- existing.depth -= 1;
84311
- existing.savepoints.pop();
84312
- throw e2;
84313
- }
84344
+ await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
84345
+ existing.scopes.push(createScope(savepointName));
84314
84346
  return { id: existing.id };
84315
84347
  });
84316
84348
  }
@@ -84327,9 +84359,9 @@ var TransactionManager = class {
84327
84359
  startedAt: Date.now(),
84328
84360
  transaction: void 0,
84329
84361
  operationQueue: Promise.resolve(),
84330
- depth: 1,
84331
- savepoints: [],
84332
- savepointCounter: 0
84362
+ savepointCounter: 0,
84363
+ scopes: [createScope(void 0)],
84364
+ ...createCommitInterruption()
84333
84365
  };
84334
84366
  if (abortController.signal.aborted) {
84335
84367
  throw new TransactionStartTimeoutError();
@@ -84404,43 +84436,38 @@ var TransactionManager = class {
84404
84436
  async commitTransaction(transactionId) {
84405
84437
  return await this.tracingHelper.runInChildSpan("commit_transaction", async () => {
84406
84438
  await this.#withActiveTransactionLock(transactionId, "commit", async (txw) => {
84407
- if (txw.depth > 1) {
84439
+ const scope = innermostScope(txw);
84440
+ if (isNested(scope)) {
84408
84441
  if (!txw.transaction) throw new TransactionNotFoundError();
84409
- const savepointName = txw.savepoints.at(-1);
84410
- if (!savepointName) {
84411
- throw new TransactionInternalConsistencyError(
84412
- `Missing savepoint for nested commit. Depth: ${txw.depth}, transactionId: ${txw.id}`
84413
- );
84442
+ const outcome2 = await statementsSettledOrCommitInterrupted(txw, [...scope.runningStatements]);
84443
+ if (outcome2 !== "committed") {
84444
+ await this.#closeTransaction(txw, outcome2);
84445
+ throw closedTransactionError(txw, outcome2, "commit");
84414
84446
  }
84415
84447
  try {
84416
- await this.#releaseSavepoint(txw.transaction, savepointName);
84448
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
84417
84449
  } finally {
84418
- txw.savepoints.pop();
84419
- txw.depth -= 1;
84450
+ mergeInnermostScope(txw);
84420
84451
  }
84421
84452
  return;
84422
84453
  }
84423
- await this.#closeTransaction(txw, "committed");
84454
+ const outcome = await this.#closeTransaction(txw, "committed");
84455
+ if (outcome !== "committed") throw closedTransactionError(txw, outcome, "commit");
84424
84456
  });
84425
84457
  });
84426
84458
  }
84427
84459
  async rollbackTransaction(transactionId) {
84428
84460
  return await this.tracingHelper.runInChildSpan("rollback_transaction", async () => {
84429
84461
  await this.#withActiveTransactionLock(transactionId, "rollback", async (txw) => {
84430
- if (txw.depth > 1) {
84431
- if (!txw.transaction) throw new TransactionNotFoundError();
84432
- const savepointName = txw.savepoints.at(-1);
84433
- if (!savepointName) {
84434
- throw new TransactionInternalConsistencyError(
84435
- `Missing savepoint for nested rollback. Depth: ${txw.depth}, transactionId: ${txw.id}`
84436
- );
84437
- }
84462
+ const scope = innermostScope(txw);
84463
+ if (isNested(scope)) {
84438
84464
  try {
84439
- await this.#requiredRollbackToSavepoint(txw.transaction)(savepointName);
84440
- await this.#releaseSavepoint(txw.transaction, savepointName);
84465
+ await this.#closeScopes(txw, [scope], "nested_rolled_back");
84466
+ if (!txw.transaction) throw new TransactionNotFoundError();
84467
+ await this.#requiredRollbackToSavepoint(txw.transaction)(scope.savepoint);
84468
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
84441
84469
  } finally {
84442
- txw.savepoints.pop();
84443
- txw.depth -= 1;
84470
+ popRolledBackScope(txw);
84444
84471
  }
84445
84472
  return;
84446
84473
  }
@@ -84448,14 +84475,68 @@ var TransactionManager = class {
84448
84475
  });
84449
84476
  });
84450
84477
  }
84451
- async getTransaction(txInfo, operation) {
84452
- let tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
84453
- if (tx.status === "closing") {
84454
- await tx.closing;
84455
- tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
84456
- }
84478
+ /**
84479
+ * Returns a handle for running statements in the transaction. The handle rejects every
84480
+ * statement issued after the transaction has started to close, or after the nested transaction
84481
+ * that is innermost now has started to roll back. A commit of that nested transaction never
84482
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
84483
+ * including one issued while the commit waits to release the savepoint.
84484
+ */
84485
+ getTransaction(txInfo, operation) {
84486
+ return new Promise((resolve) => resolve(this.#issueHandle(txInfo, operation)));
84487
+ }
84488
+ #issueHandle(txInfo, operation) {
84489
+ const tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
84490
+ const scope = innermostScope(tx);
84491
+ if (scope.closingReason !== void 0) throw closedTransactionError(tx, scope.closingReason, operation);
84457
84492
  if (!tx.transaction) throw new TransactionNotFoundError();
84458
- return tx.transaction;
84493
+ return this.#guardedQueryable(tx, tx.transaction, scope, operation);
84494
+ }
84495
+ #guardedQueryable(tx, transaction, scope, operation) {
84496
+ return {
84497
+ provider: transaction.provider,
84498
+ adapterName: transaction.adapterName,
84499
+ queryRaw: (query2) => this.#runStatement(tx, scope, operation, () => transaction.queryRaw(query2)),
84500
+ executeRaw: (query2) => this.#runStatement(tx, scope, operation, () => transaction.executeRaw(query2))
84501
+ };
84502
+ }
84503
+ async #runStatement(tx, issuedIn, operation, execute) {
84504
+ const scope = currentScope(issuedIn);
84505
+ if (scope.closingReason !== void 0) {
84506
+ throw closedTransactionError(tx, scope.closingReason, operation);
84507
+ }
84508
+ let markSettled;
84509
+ const settled = new Promise((resolve) => {
84510
+ markSettled = resolve;
84511
+ });
84512
+ scope.runningStatements.add(settled);
84513
+ try {
84514
+ return await execute();
84515
+ } finally {
84516
+ currentScope(issuedIn).runningStatements.delete(settled);
84517
+ markSettled();
84518
+ }
84519
+ }
84520
+ /**
84521
+ * Stops `scopes` from accepting statements, then waits for the ones already running. A commit
84522
+ * waits until they settle or the timeout or a disconnect interrupts it, and then becomes a
84523
+ * rollback. A rollback waits at most {@link ROLLBACK_GRACE_MS}. Resolves with how the
84524
+ * transaction is to be closed.
84525
+ */
84526
+ async #closeScopes(tx, scopes, reason) {
84527
+ markClosing(scopes, reason);
84528
+ const running = scopes.flatMap((scope) => [...scope.runningStatements]);
84529
+ if (running.length === 0) return reason;
84530
+ let outcome = reason;
84531
+ if (reason === "committed") {
84532
+ outcome = await statementsSettledOrCommitInterrupted(tx, running);
84533
+ if (outcome === "committed") return outcome;
84534
+ markClosing(scopes, outcome);
84535
+ }
84536
+ const allSettled = Promise.all(running).then(() => {
84537
+ });
84538
+ await settleWithin(allSettled, ROLLBACK_GRACE_MS);
84539
+ return outcome;
84459
84540
  }
84460
84541
  #getActiveOrClosingTransaction(transactionId, operation) {
84461
84542
  const transaction = this.transactions.get(transactionId);
@@ -84468,15 +84549,8 @@ var TransactionManager = class {
84468
84549
  case "waiting":
84469
84550
  case "running":
84470
84551
  throw new TransactionInternalConsistencyError("Active transaction found in closed transactions list.");
84471
- case "committed":
84472
- throw new TransactionClosedError(operation);
84473
- case "rolled_back":
84474
- throw new TransactionRolledBackError(operation);
84475
- case "timed_out":
84476
- throw new TransactionExecutionTimeoutError(operation, {
84477
- timeout: closedTransaction.timeout,
84478
- timeTaken: Date.now() - closedTransaction.startedAt
84479
- });
84552
+ default:
84553
+ throw closedTransactionError(closedTransaction, closedTransaction.status, operation);
84480
84554
  }
84481
84555
  } else {
84482
84556
  debug22(`Transaction not found.`, transactionId);
@@ -84493,6 +84567,9 @@ var TransactionManager = class {
84493
84567
  for (const { abortController } of starting) {
84494
84568
  abortController.abort();
84495
84569
  }
84570
+ for (const tx of this.transactions.values()) {
84571
+ tx.interruptCommit("rolled_back");
84572
+ }
84496
84573
  await Promise.allSettled([
84497
84574
  ...[...this.transactions.values()].map(
84498
84575
  (tx) => this.#runSerialized(tx, async () => {
@@ -84502,7 +84579,7 @@ var TransactionManager = class {
84502
84579
  }
84503
84580
  })
84504
84581
  ),
84505
- ...starting.map(({ settled }) => settleWithin(settled, CANCEL_ROLLBACK_GRACE_MS))
84582
+ ...starting.map(({ settled }) => settleWithin(settled, ROLLBACK_GRACE_MS))
84506
84583
  ]);
84507
84584
  }
84508
84585
  #nextSavepointName(transaction) {
@@ -84542,6 +84619,7 @@ var TransactionManager = class {
84542
84619
  this.#debugTransactionAlreadyClosedOnTimeout(transactionId);
84543
84620
  return;
84544
84621
  }
84622
+ tx.interruptCommit("timed_out");
84545
84623
  await this.#runSerialized(tx, async () => {
84546
84624
  const current = this.transactions.get(transactionId);
84547
84625
  if (current && ["running", "waiting"].includes(current.status)) {
@@ -84558,7 +84636,7 @@ var TransactionManager = class {
84558
84636
  return timer;
84559
84637
  }
84560
84638
  // Any operation that mutates or closes a transaction must run through this lock so
84561
- // status/savepoint/depth checks and updates happen against a stable view of state.
84639
+ // status/scope checks and updates happen against a stable view of state.
84562
84640
  async #withActiveTransactionLock(transactionId, operation, callback) {
84563
84641
  const tx = this.#getActiveOrClosingTransaction(transactionId, operation);
84564
84642
  return await this.#runSerialized(tx, async () => {
@@ -84567,7 +84645,7 @@ var TransactionManager = class {
84567
84645
  });
84568
84646
  }
84569
84647
  // Serializes operations per transaction id to prevent interleaving across awaits.
84570
- // This avoids races where one operation mutates savepoint/depth state while another
84648
+ // This avoids races where one operation mutates scope state while another
84571
84649
  // operation is suspended, which could otherwise corrupt cleanup logic.
84572
84650
  async #runSerialized(tx, callback) {
84573
84651
  const previousOperation = tx.operationQueue;
@@ -84582,11 +84660,13 @@ var TransactionManager = class {
84582
84660
  releaseOperationLock();
84583
84661
  }
84584
84662
  }
84585
- async #closeTransaction(tx, status) {
84586
- const createClosingPromise = async () => {
84587
- debug22("Closing transaction.", { transactionId: tx.id, status });
84663
+ /** Resolves with how the transaction was closed, which differs from `requested` for an interrupted commit. */
84664
+ async #closeTransaction(tx, requested) {
84665
+ const createClosingPromise = async (scopesClosed2) => {
84666
+ debug22("Closing transaction.", { transactionId: tx.id, requested });
84667
+ const outcome = await scopesClosed2;
84588
84668
  try {
84589
- if (tx.transaction && status === "committed") {
84669
+ if (tx.transaction && outcome === "committed") {
84590
84670
  if (tx.transaction.options.usePhantomQuery) {
84591
84671
  await this.#withQuerySpanAndEvent(PHANTOM_COMMIT_QUERY(), tx.transaction, () => tx.transaction.commit());
84592
84672
  } else {
@@ -84616,7 +84696,7 @@ var TransactionManager = class {
84616
84696
  }
84617
84697
  }
84618
84698
  } finally {
84619
- tx.status = status;
84699
+ tx.status = outcome;
84620
84700
  clearTimeout(tx.timer);
84621
84701
  tx.timer = void 0;
84622
84702
  this.transactions.delete(tx.id);
@@ -84625,17 +84705,18 @@ var TransactionManager = class {
84625
84705
  this.closedTransactions.shift();
84626
84706
  }
84627
84707
  }
84708
+ return outcome;
84628
84709
  };
84629
84710
  if (tx.status === "closing") {
84630
84711
  await tx.closing;
84631
- this.#getActiveOrClosingTransaction(tx.id, status === "committed" ? "commit" : "rollback");
84632
- } else {
84633
- await Object.assign(tx, {
84634
- status: "closing",
84635
- reason: status,
84636
- closing: createClosingPromise()
84637
- }).closing;
84712
+ this.#getActiveOrClosingTransaction(tx.id, requested === "committed" ? "commit" : "rollback");
84713
+ throw new TransactionInternalConsistencyError("Transaction still active after it was closed.");
84638
84714
  }
84715
+ const scopesClosed = this.#closeScopes(tx, tx.scopes, requested);
84716
+ return await Object.assign(tx, {
84717
+ status: "closing",
84718
+ closing: createClosingPromise(scopesClosed)
84719
+ }).closing;
84639
84720
  }
84640
84721
  #validateOptions(options) {
84641
84722
  if (!options.timeout) throw new TransactionManagerError("timeout is required");
@@ -84657,6 +84738,56 @@ var TransactionManager = class {
84657
84738
  });
84658
84739
  }
84659
84740
  };
84741
+ function innermostScope(tx) {
84742
+ return tx.scopes[tx.scopes.length - 1];
84743
+ }
84744
+ function popInnermostScope(tx) {
84745
+ const child = innermostScope(tx);
84746
+ tx.scopes.pop();
84747
+ const parent = innermostScope(tx);
84748
+ const moved = [...child.runningStatements];
84749
+ for (const statement of moved) {
84750
+ parent.runningStatements.add(statement);
84751
+ }
84752
+ child.runningStatements.clear();
84753
+ return { child, parent, moved };
84754
+ }
84755
+ function mergeInnermostScope(tx) {
84756
+ const { child, parent } = popInnermostScope(tx);
84757
+ child.mergedInto = parent;
84758
+ }
84759
+ function popRolledBackScope(tx) {
84760
+ const { parent, moved } = popInnermostScope(tx);
84761
+ for (const statement of moved) {
84762
+ void statement.then(() => currentScope(parent).runningStatements.delete(statement));
84763
+ }
84764
+ }
84765
+ function markClosing(scopes, reason) {
84766
+ for (const scope of scopes) {
84767
+ scope.closingReason = reason;
84768
+ }
84769
+ }
84770
+ async function statementsSettledOrCommitInterrupted(tx, running) {
84771
+ if (running.length === 0) return "committed";
84772
+ return await Promise.race([Promise.all(running).then(() => "committed"), tx.commitInterrupted]);
84773
+ }
84774
+ function closedTransactionError(tx, reason, operation) {
84775
+ switch (reason) {
84776
+ case "committed":
84777
+ return new TransactionClosedError(operation);
84778
+ case "rolled_back":
84779
+ return new TransactionRolledBackError(operation);
84780
+ case "nested_rolled_back":
84781
+ return new NestedTransactionRolledBackError(operation);
84782
+ case "timed_out":
84783
+ return new TransactionExecutionTimeoutError(operation, {
84784
+ timeout: tx.timeout,
84785
+ timeTaken: Date.now() - tx.startedAt
84786
+ });
84787
+ default:
84788
+ return assertNever(reason, "Unknown closing reason.");
84789
+ }
84790
+ }
84660
84791
  function createTimeoutIfDefined(cb, ms) {
84661
84792
  return ms !== void 0 ? setTimeout(cb, ms) : void 0;
84662
84793
  }
@@ -102423,7 +102554,7 @@ function mapColumnType(field) {
102423
102554
  case "TINY_BLOB":
102424
102555
  case "MEDIUM_BLOB":
102425
102556
  case "LONG_BLOB":
102426
- if (field["dataTypeFormat"] === "json") {
102557
+ if (field.isDataTypeFormatJson()) {
102427
102558
  return ColumnTypeEnum.Json;
102428
102559
  } else if (field.collation.index === BINARY_COLLATION_INDEX) {
102429
102560
  return ColumnTypeEnum.Bytes;
@@ -102701,36 +102832,62 @@ var MariaDbTransaction = class extends MariaDbQueryable {
102701
102832
  this.options = options;
102702
102833
  this.cleanup = cleanup;
102703
102834
  }
102835
+ /**
102836
+ * Set on entry to `commit()` or `rollback()`, before either sends SQL. Once the pool has lent the
102837
+ * connection to a new owner, a second close would send `COMMIT` or `ROLLBACK` into that owner's
102838
+ * session and release the connection twice, so the transaction closes at most once and sends
102839
+ * nothing afterwards.
102840
+ */
102841
+ closed = false;
102842
+ async performIO(query2) {
102843
+ this.assertOpen();
102844
+ return await super.performIO(query2);
102845
+ }
102704
102846
  async commit() {
102705
102847
  debug4(`[js::commit]`);
102706
- try {
102707
- await this.client.query({ sql: "COMMIT" });
102708
- } catch (err) {
102709
- this.onError(err);
102710
- } finally {
102711
- this.cleanup?.();
102712
- await releaseConnection(this.client);
102713
- }
102848
+ await this.close("COMMIT");
102714
102849
  }
102715
102850
  async rollback() {
102716
102851
  debug4(`[js::rollback]`);
102852
+ await this.close("ROLLBACK");
102853
+ }
102854
+ async createSavepoint(name22) {
102855
+ await this.sendTransactionControl(`SAVEPOINT ${name22}`);
102856
+ }
102857
+ async rollbackToSavepoint(name22) {
102858
+ await this.sendTransactionControl(`ROLLBACK TO ${name22}`);
102859
+ }
102860
+ async releaseSavepoint(name22) {
102861
+ await this.sendTransactionControl(`RELEASE SAVEPOINT ${name22}`);
102862
+ }
102863
+ async close(sql4) {
102864
+ if (this.closed) {
102865
+ return;
102866
+ }
102867
+ this.closed = true;
102717
102868
  try {
102718
- await this.client.query({ sql: "ROLLBACK" });
102869
+ await this.client.query({ sql: sql4 });
102719
102870
  } catch (err) {
102720
102871
  this.onError(err);
102721
102872
  } finally {
102722
- this.cleanup?.();
102723
- await releaseConnection(this.client);
102873
+ try {
102874
+ this.cleanup?.();
102875
+ } finally {
102876
+ await releaseConnection(this.client);
102877
+ }
102724
102878
  }
102725
102879
  }
102726
- async createSavepoint(name22) {
102727
- await this.client.query({ sql: `SAVEPOINT ${name22}` }).catch(this.onError.bind(this));
102728
- }
102729
- async rollbackToSavepoint(name22) {
102730
- await this.client.query({ sql: `ROLLBACK TO ${name22}` }).catch(this.onError.bind(this));
102880
+ async sendTransactionControl(sql4) {
102881
+ this.assertOpen();
102882
+ await this.client.query({ sql: sql4 }).catch(this.onError.bind(this));
102731
102883
  }
102732
- async releaseSavepoint(name22) {
102733
- await this.client.query({ sql: `RELEASE SAVEPOINT ${name22}` }).catch(this.onError.bind(this));
102884
+ assertOpen() {
102885
+ if (this.closed) {
102886
+ throw new DriverAdapterError({
102887
+ kind: "TransactionAlreadyClosed",
102888
+ cause: "The transaction has already been committed or rolled back"
102889
+ });
102890
+ }
102734
102891
  }
102735
102892
  };
102736
102893
  var PrismaMariaDbAdapter = class extends MariaDbQueryable {
@@ -103473,6 +103630,9 @@ function mapIsolationLevel(level) {
103473
103630
  });
103474
103631
  }
103475
103632
  }
103633
+ function isFloatArg(arg, argType) {
103634
+ return typeof arg === "number" && (argType.dbType === "FLOAT" || argType.dbType === "REAL");
103635
+ }
103476
103636
  function mapArg2(arg, argType) {
103477
103637
  if (arg === null) {
103478
103638
  return null;
@@ -103766,10 +103926,13 @@ var MssqlQueryable = class {
103766
103926
  req.arrayRowMode = true;
103767
103927
  for (let i2 = 0; i2 < query2.args.length; i2++) {
103768
103928
  const argType = query2.argTypes[i2];
103769
- if (query2.args[i2] === null && argType.scalarType === "bytes") {
103929
+ const arg = query2.args[i2];
103930
+ if (arg === null && argType.scalarType === "bytes") {
103770
103931
  req.input(`P${i2 + 1}`, import_mssql.default.VarBinary, null);
103932
+ } else if (isFloatArg(arg, argType)) {
103933
+ req.input(`P${i2 + 1}`, import_mssql.default.Float, arg);
103771
103934
  } else {
103772
- req.input(`P${i2 + 1}`, mapArg2(query2.args[i2], argType));
103935
+ req.input(`P${i2 + 1}`, mapArg2(arg, argType));
103773
103936
  }
103774
103937
  }
103775
103938
  const res = await req.query(query2.sql);
@@ -103947,6 +104110,7 @@ var ArrayColumnType = {
103947
104110
  TEXT_ARRAY: 1009,
103948
104111
  TIMESTAMP_ARRAY: 1115,
103949
104112
  TIMESTAMPTZ_ARRAY: 1185,
104113
+ TIMETZ_ARRAY: 1270,
103950
104114
  TIME_ARRAY: 1183,
103951
104115
  UUID_ARRAY: 2951,
103952
104116
  VARBIT_ARRAY: 1563,
@@ -104145,6 +104309,7 @@ function fieldToColumnType(fieldTypeId) {
104145
104309
  case ArrayColumnType.DATE_ARRAY:
104146
104310
  return ColumnTypeEnum.DateArray;
104147
104311
  case ArrayColumnType.TIME_ARRAY:
104312
+ case ArrayColumnType.TIMETZ_ARRAY:
104148
104313
  return ColumnTypeEnum.TimeArray;
104149
104314
  case ArrayColumnType.TIMESTAMP_ARRAY:
104150
104315
  return ColumnTypeEnum.DateTimeArray;
@@ -104186,10 +104351,22 @@ function normalize_time(time3) {
104186
104351
  return time3;
104187
104352
  }
104188
104353
  function normalize_timez(time3) {
104189
- return time3.replace(/[+-]\d{2}(:\d{2})?$/, "");
104354
+ const match2 = time3.match(/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?([+-])(\d{2})(?::(\d{2}))?(?::(\d{2}))?$/);
104355
+ if (!match2) return time3;
104356
+ const [, h2, m2, s2, fraction = "", sign2, oh, om = "0", os7 = "0"] = match2;
104357
+ const offset = (sign2 === "+" ? 1 : -1) * (Number(oh) * 3600 + Number(om) * 60 + Number(os7));
104358
+ if (offset === 0) return `${h2}:${m2}:${s2}${fraction}`;
104359
+ const seconds = ((Number(h2) * 3600 + Number(m2) * 60 + Number(s2) - offset) % 86400 + 86400) % 86400;
104360
+ const pad2 = (n2) => String(n2).padStart(2, "0");
104361
+ return `${pad2(Math.floor(seconds / 3600))}:${pad2(Math.floor(seconds / 60) % 60)}:${pad2(seconds % 60)}${fraction}`;
104190
104362
  }
104191
104363
  function normalize_money(money) {
104192
- return money.slice(1);
104364
+ if (!/^-?\$\d{1,3}(,\d{3})*\.\d{2}$/.test(money)) {
104365
+ throw new Error(
104366
+ `Unsupported money format "${money}": only the default lc_monetary format, such as -$1,234.50, is supported`
104367
+ );
104368
+ }
104369
+ return money.replace(/[^\d.-]/g, "");
104193
104370
  }
104194
104371
  function normalize_xml(xml) {
104195
104372
  return xml;
@@ -104211,6 +104388,7 @@ var customParsers = {
104211
104388
  [ScalarColumnType.TIME]: normalize_time,
104212
104389
  [ArrayColumnType.TIME_ARRAY]: normalize_array(normalize_time),
104213
104390
  [ScalarColumnType.TIMETZ]: normalize_timez,
104391
+ [ArrayColumnType.TIMETZ_ARRAY]: normalize_array(normalize_timez),
104214
104392
  [ScalarColumnType.DATE]: normalize_date,
104215
104393
  [ArrayColumnType.DATE_ARRAY]: normalize_array(normalize_date),
104216
104394
  [ScalarColumnType.TIMESTAMP]: normalize_timestamp,
@@ -104242,8 +104420,9 @@ function mapArg3(arg, argType) {
104242
104420
  if (arg instanceof Date) {
104243
104421
  switch (argType.dbType) {
104244
104422
  case "TIME":
104245
- case "TIMETZ":
104246
104423
  return formatTime3(arg);
104424
+ case "TIMETZ":
104425
+ return formatTime3(arg) + "+00";
104247
104426
  case "DATE":
104248
104427
  return formatDate3(arg);
104249
104428
  default:
@@ -104577,15 +104756,50 @@ var PgTransaction = class extends PgQueryable {
104577
104756
  this.pgOptions = pgOptions;
104578
104757
  this.cleanup = cleanup;
104579
104758
  }
104759
+ closed = false;
104760
+ runningStatements = 0;
104761
+ async performIO(query2) {
104762
+ if (this.closed) {
104763
+ throw new DriverAdapterError({
104764
+ kind: "TransactionAlreadyClosed",
104765
+ cause: "The transaction has already been committed or rolled back"
104766
+ });
104767
+ }
104768
+ this.runningStatements++;
104769
+ try {
104770
+ return await super.performIO(query2);
104771
+ } finally {
104772
+ this.runningStatements--;
104773
+ }
104774
+ }
104775
+ /**
104776
+ * Closes the transaction at most once. Once the pool has lent the client to
104777
+ * a new owner, a second `release()` would corrupt the pool's bookkeeping, so
104778
+ * it is skipped. A client with a statement still running is released with an
104779
+ * error so the pool destroys it instead of lending out a busy connection.
104780
+ */
104781
+ close() {
104782
+ if (this.closed) {
104783
+ return;
104784
+ }
104785
+ this.closed = true;
104786
+ try {
104787
+ this.cleanup?.();
104788
+ } finally {
104789
+ if (this.runningStatements > 0) {
104790
+ this.client.release(new Error("Transaction closed with a statement still running"));
104791
+ } else {
104792
+ this.client.release();
104793
+ }
104794
+ }
104795
+ }
104580
104796
  async commit() {
104581
104797
  debug6(`[js::commit]`);
104582
- this.cleanup?.();
104583
- this.client.release();
104798
+ this.close();
104584
104799
  }
104585
104800
  async rollback() {
104586
104801
  debug6(`[js::rollback]`);
104587
- this.cleanup?.();
104588
- this.client.release();
104802
+ this.close();
104589
104803
  }
104590
104804
  async createSavepoint(name22) {
104591
104805
  await this.executeRaw({ sql: `SAVEPOINT ${name22}`, args: [], argTypes: [] });
@@ -104677,7 +104891,12 @@ var PrismaPgAdapterFactory = class {
104677
104891
  config;
104678
104892
  externalPool;
104679
104893
  async connect() {
104680
- const client2 = this.externalPool ?? new esm_default.Pool(this.config);
104894
+ const client2 = this.externalPool ?? new esm_default.Pool(withSearchPath(this.config, this.options?.schema));
104895
+ if (this.externalPool !== null && this.options?.schema !== void 0) {
104896
+ debug6(
104897
+ `The search path is not set on externally provided pools, schema "${this.options.schema}" is only used for generated queries. Set the search path on the pool itself if raw queries need it.`
104898
+ );
104899
+ }
104681
104900
  const onIdleClientError = (err) => {
104682
104901
  debug6(`Error from idle pool client: ${err.message} %O`, err);
104683
104902
  this.options?.onPoolError?.(err);
@@ -104707,6 +104926,28 @@ var PrismaPgAdapterFactory = class {
104707
104926
  });
104708
104927
  }
104709
104928
  };
104929
+ function withSearchPath(config3, schema) {
104930
+ if (schema === void 0 || setsSearchPath(config3.options)) {
104931
+ return config3;
104932
+ }
104933
+ const searchPath = `-c search_path=${escapeOptionValue(quoteIdentifierIfNeeded(schema))},public`;
104934
+ return {
104935
+ ...config3,
104936
+ options: config3.options ? `${config3.options} ${searchPath}` : searchPath
104937
+ };
104938
+ }
104939
+ function setsSearchPath(options) {
104940
+ return options !== void 0 && /(?:^|\s)(?:-c\s*|--)search[_-]path=/i.test(options);
104941
+ }
104942
+ function quoteIdentifierIfNeeded(name22) {
104943
+ if (/^[a-z_][a-z0-9_$]*$/.test(name22)) {
104944
+ return name22;
104945
+ }
104946
+ return `"${name22.replaceAll('"', '""')}"`;
104947
+ }
104948
+ function escapeOptionValue(value) {
104949
+ return value.replace(/[\\\s]/g, (char) => `\\${char}`);
104950
+ }
104710
104951
 
104711
104952
  // src/logic/adapter.ts
104712
104953
  function createAdapter(url2, supportedFactories = defaultFactories) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/query-plan-executor",
3
- "version": "7.10.1",
3
+ "version": "7.11.0-dev.1",
4
4
  "description": "This package is intended for Prisma's internal use",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -19,11 +19,11 @@
19
19
  "hono": "^4.12.23",
20
20
  "temporal-polyfill": "0.3.0",
21
21
  "zod": "4.1.3",
22
- "@prisma/adapter-pg": "7.10.1",
23
- "@prisma/adapter-mssql": "7.10.1",
24
- "@prisma/client-engine-runtime": "7.10.1",
25
- "@prisma/adapter-mariadb": "7.10.1",
26
- "@prisma/driver-adapter-utils": "7.10.1"
22
+ "@prisma/adapter-pg": "7.11.0-dev.1",
23
+ "@prisma/adapter-mariadb": "7.11.0-dev.1",
24
+ "@prisma/adapter-mssql": "7.11.0-dev.1",
25
+ "@prisma/client-engine-runtime": "7.11.0-dev.1",
26
+ "@prisma/driver-adapter-utils": "7.11.0-dev.1"
27
27
  },
28
28
  "files": [
29
29
  "dist"
@@ -31,7 +31,6 @@
31
31
  "sideEffects": false,
32
32
  "scripts": {
33
33
  "dev": "DEV=true tsx helpers/build.ts",
34
- "build": "tsx helpers/build.ts",
35
- "test": "vitest run"
34
+ "build": "tsx helpers/build.ts"
36
35
  }
37
36
  }