@prisma/client-engine-runtime 7.10.1 → 7.11.0-dev.2

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.mts CHANGED
@@ -15,7 +15,6 @@ import type { SqlCommenterQueryInfo } from '@prisma/sqlcommenter';
15
15
  import { SqlDriverAdapter } from '@prisma/driver-adapter-utils';
16
16
  import { SqlQueryable } from '@prisma/driver-adapter-utils';
17
17
  import { SqlResultSet } from '@prisma/driver-adapter-utils';
18
- import { Transaction } from '@prisma/driver-adapter-utils';
19
18
 
20
19
  /**
21
20
  * Applies SQL commenter plugins and returns the merged key-value pairs.
@@ -318,6 +317,12 @@ export declare type PureQueryPlanNode<Rest = never> = {
318
317
  * query plan purification. Never produced by the query compiler.
319
318
  */
320
319
  lastInsertId?: string;
320
+ /**
321
+ * Present when this node holds an already-evaluated runtime result (e.g. from
322
+ * an evaluated impure query plan node) and does not need to be traversed and copied
323
+ * by evaluateArg.
324
+ */
325
+ isEvaluated?: boolean;
321
326
  } | {
322
327
  type: 'seq';
323
328
  args: (PureQueryPlanNode<Rest> | Rest)[];
@@ -565,7 +570,14 @@ export declare class TransactionManager {
565
570
  startTransaction(options?: TransactionOptions): Promise<TransactionInfo>;
566
571
  commitTransaction(transactionId: string): Promise<void>;
567
572
  rollbackTransaction(transactionId: string): Promise<void>;
568
- getTransaction(txInfo: TransactionInfo, operation: string): Promise<Transaction>;
573
+ /**
574
+ * Returns a handle for running statements in the transaction. The handle rejects every
575
+ * statement issued after the transaction has started to close, or after the nested transaction
576
+ * that is innermost now has started to roll back. A commit of that nested transaction never
577
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
578
+ * including one issued while the commit waits to release the savepoint.
579
+ */
580
+ getTransaction(txInfo: TransactionInfo, operation: string): Promise<SqlQueryable>;
569
581
  cancelAllTransactions(): Promise<void>;
570
582
  }
571
583
 
package/dist/index.d.ts CHANGED
@@ -15,7 +15,6 @@ import type { SqlCommenterQueryInfo } from '@prisma/sqlcommenter';
15
15
  import { SqlDriverAdapter } from '@prisma/driver-adapter-utils';
16
16
  import { SqlQueryable } from '@prisma/driver-adapter-utils';
17
17
  import { SqlResultSet } from '@prisma/driver-adapter-utils';
18
- import { Transaction } from '@prisma/driver-adapter-utils';
19
18
 
20
19
  /**
21
20
  * Applies SQL commenter plugins and returns the merged key-value pairs.
@@ -318,6 +317,12 @@ export declare type PureQueryPlanNode<Rest = never> = {
318
317
  * query plan purification. Never produced by the query compiler.
319
318
  */
320
319
  lastInsertId?: string;
320
+ /**
321
+ * Present when this node holds an already-evaluated runtime result (e.g. from
322
+ * an evaluated impure query plan node) and does not need to be traversed and copied
323
+ * by evaluateArg.
324
+ */
325
+ isEvaluated?: boolean;
321
326
  } | {
322
327
  type: 'seq';
323
328
  args: (PureQueryPlanNode<Rest> | Rest)[];
@@ -565,7 +570,14 @@ export declare class TransactionManager {
565
570
  startTransaction(options?: TransactionOptions): Promise<TransactionInfo>;
566
571
  commitTransaction(transactionId: string): Promise<void>;
567
572
  rollbackTransaction(transactionId: string): Promise<void>;
568
- getTransaction(txInfo: TransactionInfo, operation: string): Promise<Transaction>;
573
+ /**
574
+ * Returns a handle for running statements in the transaction. The handle rejects every
575
+ * statement issued after the transaction has started to close, or after the nested transaction
576
+ * that is innermost now has started to roll back. A commit of that nested transaction never
577
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
578
+ * including one issued while the commit waits to release the savepoint.
579
+ */
580
+ getTransaction(txInfo: TransactionInfo, operation: string): Promise<SqlQueryable>;
569
581
  cancelAllTransactions(): Promise<void>;
570
582
  }
571
583
 
package/dist/index.js CHANGED
@@ -1654,7 +1654,7 @@ var QueryInterpreter = class _QueryInterpreter {
1654
1654
  switch (node.type) {
1655
1655
  case "value": {
1656
1656
  return {
1657
- value: evaluateArg(node.args, context.scope, context.generators),
1657
+ value: node.isEvaluated ? node.args : evaluateArg(node.args, context.scope, context.generators),
1658
1658
  lastInsertId: node.lastInsertId
1659
1659
  };
1660
1660
  }
@@ -1734,7 +1734,7 @@ var QueryInterpreter = class _QueryInterpreter {
1734
1734
  }
1735
1735
  case "reverse": {
1736
1736
  const { value, lastInsertId } = await this.interpretNode(node.args, context);
1737
- return { value: Array.isArray(value) ? value.reverse() : value, lastInsertId };
1737
+ return { value: Array.isArray(value) ? value.slice().reverse() : value, lastInsertId };
1738
1738
  }
1739
1739
  case "unique": {
1740
1740
  const { value, lastInsertId } = await this.interpretNode(node.args, context);
@@ -1762,10 +1762,12 @@ var QueryInterpreter = class _QueryInterpreter {
1762
1762
  if (parent === null) {
1763
1763
  return { value: null, lastInsertId };
1764
1764
  }
1765
+ const parentRecords = (Array.isArray(parent) ? parent : [parent]).map(asRecord);
1765
1766
  const children = await Promise.all(
1766
1767
  node.args.children.map(async (joinExpr) => ({
1767
1768
  joinExpr,
1768
- childRecords: (await this.interpretNode(joinExpr.child, context)).value
1769
+ // A child can only attach to a parent whose join keys are all non-null.
1770
+ childRecords: parentRecords.some((record) => joinExpr.on.every(([key]) => record[key] != null)) ? (await this.interpretNode(joinExpr.child, context)).value : []
1769
1771
  }))
1770
1772
  );
1771
1773
  return { value: attachChildrenToParents(parent, children, node.args.canAssumeStrictEquality), lastInsertId };
@@ -1826,7 +1828,10 @@ var QueryInterpreter = class _QueryInterpreter {
1826
1828
  #interpretPureNode(node, scope, generators) {
1827
1829
  switch (node.type) {
1828
1830
  case "value": {
1829
- return { value: evaluateArg(node.args, scope, generators), lastInsertId: node.lastInsertId };
1831
+ return {
1832
+ value: node.isEvaluated ? node.args : evaluateArg(node.args, scope, generators),
1833
+ lastInsertId: node.lastInsertId
1834
+ };
1830
1835
  }
1831
1836
  case "seq": {
1832
1837
  let result;
@@ -1869,7 +1874,7 @@ var QueryInterpreter = class _QueryInterpreter {
1869
1874
  }
1870
1875
  case "reverse": {
1871
1876
  const { value, lastInsertId } = this.#interpretPureNode(node.args, scope, generators);
1872
- return { value: Array.isArray(value) ? value.reverse() : value, lastInsertId };
1877
+ return { value: Array.isArray(value) ? value.slice().reverse() : value, lastInsertId };
1873
1878
  }
1874
1879
  case "unique": {
1875
1880
  const { value, lastInsertId } = this.#interpretPureNode(node.args, scope, generators);
@@ -2180,7 +2185,8 @@ function purifyQueryPlan(node, evalNode) {
2180
2185
  const evaluated = {
2181
2186
  type: "value",
2182
2187
  args: result.value,
2183
- lastInsertId: result.lastInsertId
2188
+ lastInsertId: result.lastInsertId,
2189
+ isEvaluated: true
2184
2190
  };
2185
2191
  const purified = replaceImpureNode(node, impureNode, evaluated);
2186
2192
  if (!purified) {
@@ -2439,7 +2445,7 @@ var Parameterizer = class {
2439
2445
  for (const [key, value] of Object.entries(obj)) {
2440
2446
  const edge = this.#view.inputEdge(node, key);
2441
2447
  if (edge) {
2442
- result[key] = this.#parameterizeValue(value, edge);
2448
+ result[key] = this.#parameterizeValue(value, edge, key);
2443
2449
  } else {
2444
2450
  result[key] = value;
2445
2451
  }
@@ -2449,7 +2455,7 @@ var Parameterizer = class {
2449
2455
  /**
2450
2456
  * Core parameterization logic for a single value.
2451
2457
  */
2452
- #parameterizeValue(value, edge) {
2458
+ #parameterizeValue(value, edge, key) {
2453
2459
  const classified = classifyValue(value);
2454
2460
  switch (classified.kind) {
2455
2461
  case "null":
@@ -2457,7 +2463,7 @@ var Parameterizer = class {
2457
2463
  case "structural":
2458
2464
  return value;
2459
2465
  case "primitive":
2460
- return this.#handlePrimitive(classified.value, edge);
2466
+ return this.#handlePrimitive(classified.value, edge, key);
2461
2467
  case "taggedScalar":
2462
2468
  return this.#handleTaggedScalar(value, classified.tag, edge);
2463
2469
  case "array":
@@ -2471,7 +2477,7 @@ var Parameterizer = class {
2471
2477
  /**
2472
2478
  * Handles parameterization of primitive values (string, number, boolean).
2473
2479
  */
2474
- #handlePrimitive(value, edge) {
2480
+ #handlePrimitive(value, edge, key) {
2475
2481
  if ((0, import_param_graph.hasFlag)(edge, import_param_graph.EdgeFlag.ParamEnum) && edge.enumNameIndex !== void 0 && typeof value === "string") {
2476
2482
  const enumValues = this.#view.enumValues(edge);
2477
2483
  if (enumValues && Object.hasOwn(enumValues, value)) {
@@ -2486,13 +2492,18 @@ var Parameterizer = class {
2486
2492
  if (mask === 0) {
2487
2493
  return value;
2488
2494
  }
2489
- const type = getPrimitivePlaceholderType(value);
2495
+ if (mask & import_param_graph.ScalarMask.Json) {
2496
+ if (JSON_COMPARISON_FILTERS.has(key)) {
2497
+ return value;
2498
+ }
2499
+ const jsonValue = JSON.stringify(value);
2500
+ const type2 = { type: "Json" };
2501
+ return this.#getOrCreatePlaceholder(jsonValue, type2);
2502
+ }
2503
+ const type = getPrimitivePlaceholderType(value, mask);
2490
2504
  if (!matchesPrimitiveMask(type, mask)) {
2491
2505
  return value;
2492
2506
  }
2493
- if (mask & import_param_graph.ScalarMask.Json) {
2494
- value = JSON.stringify(value);
2495
- }
2496
2507
  return this.#getOrCreatePlaceholder(value, type);
2497
2508
  }
2498
2509
  /**
@@ -2530,7 +2541,7 @@ var Parameterizer = class {
2530
2541
  const allValid = items.every((item) => validateListElement(item, edge));
2531
2542
  if (allValid && items.length > 0) {
2532
2543
  const decodedItems = items.map((item) => decodeIfTagged(item));
2533
- const innerType = inferListElementType(items);
2544
+ const innerType = inferListElementType(items, (0, import_param_graph.getScalarMask)(edge));
2534
2545
  const type = { type: "List", inner: innerType };
2535
2546
  return this.#getOrCreatePlaceholder(decodedItems, type);
2536
2547
  }
@@ -2619,9 +2630,10 @@ function createValueKey(value, type) {
2619
2630
  const valueKey = serializeValue(value);
2620
2631
  return `${typeKey}:${valueKey}`;
2621
2632
  }
2633
+ var JSON_COMPARISON_FILTERS = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
2622
2634
  var MAX_INT = 2 ** 31 - 1;
2623
2635
  var MIN_INT = -(2 ** 31);
2624
- function getPrimitivePlaceholderType(value) {
2636
+ function getPrimitivePlaceholderType(value, mask) {
2625
2637
  switch (typeof value) {
2626
2638
  case "boolean":
2627
2639
  return { type: "Boolean" };
@@ -2632,6 +2644,9 @@ function getPrimitivePlaceholderType(value) {
2632
2644
  if (MIN_INT <= value && value <= MAX_INT) {
2633
2645
  return { type: "Int" };
2634
2646
  }
2647
+ if (!(mask & import_param_graph.ScalarMask.BigInt) && mask & import_param_graph.ScalarMask.Float) {
2648
+ return { type: "Float" };
2649
+ }
2635
2650
  return { type: "BigInt" };
2636
2651
  case "string":
2637
2652
  return { type: "String" };
@@ -2668,14 +2683,14 @@ function getTaggedPlaceholderType(tag) {
2668
2683
  return void 0;
2669
2684
  }
2670
2685
  }
2671
- function inferListElementType(items) {
2686
+ function inferListElementType(items, mask) {
2672
2687
  let widest = { type: "Any" };
2673
2688
  for (const item of items) {
2674
2689
  const classified = classifyValue(item);
2675
2690
  let itemType;
2676
2691
  switch (classified.kind) {
2677
2692
  case "primitive":
2678
- itemType = getPrimitivePlaceholderType(classified.value);
2693
+ itemType = getPrimitivePlaceholderType(classified.value, mask);
2679
2694
  break;
2680
2695
  case "taggedScalar":
2681
2696
  itemType = getTaggedPlaceholderType(classified.tag) ?? { type: "Any" };
@@ -2723,8 +2738,8 @@ function validateListElement(item, edge) {
2723
2738
  case "null":
2724
2739
  return false;
2725
2740
  case "primitive": {
2726
- const type = getPrimitivePlaceholderType(classified.value);
2727
2741
  const mask = (0, import_param_graph.getScalarMask)(edge);
2742
+ const type = getPrimitivePlaceholderType(classified.value, mask);
2728
2743
  return mask !== 0 && matchesPrimitiveMask(type, mask);
2729
2744
  }
2730
2745
  case "taggedScalar": {
@@ -2817,6 +2832,13 @@ var TransactionRolledBackError = class extends TransactionManagerError {
2817
2832
  super(`Transaction already closed: A ${operation} cannot be executed on a transaction that was rolled back.`);
2818
2833
  }
2819
2834
  };
2835
+ var NestedTransactionRolledBackError = class extends TransactionManagerError {
2836
+ constructor(operation) {
2837
+ super(
2838
+ `Nested transaction already closed: A ${operation} cannot be executed on a nested transaction that was rolled back.`
2839
+ );
2840
+ }
2841
+ };
2820
2842
  var TransactionStartTimeoutError = class extends TransactionManagerError {
2821
2843
  constructor() {
2822
2844
  super("Unable to start a transaction in the given time.");
@@ -2843,7 +2865,23 @@ var InvalidTransactionIsolationLevelError = class extends TransactionManagerErro
2843
2865
 
2844
2866
  // src/transaction-manager/transaction-manager.ts
2845
2867
  var MAX_CLOSED_TRANSACTIONS = 100;
2846
- var CANCEL_ROLLBACK_GRACE_MS = 2e3;
2868
+ var ROLLBACK_GRACE_MS = 2e3;
2869
+ function createScope(savepoint) {
2870
+ return { savepoint, closingReason: void 0, runningStatements: /* @__PURE__ */ new Set() };
2871
+ }
2872
+ function isNested(scope) {
2873
+ return scope.savepoint !== void 0;
2874
+ }
2875
+ function currentScope(scope) {
2876
+ return scope.mergedInto ? currentScope(scope.mergedInto) : scope;
2877
+ }
2878
+ function createCommitInterruption() {
2879
+ let interruptCommit;
2880
+ const commitInterrupted = new Promise((resolve) => {
2881
+ interruptCommit = resolve;
2882
+ });
2883
+ return { commitInterrupted, interruptCommit };
2884
+ }
2847
2885
  function trackStartingTransaction() {
2848
2886
  let markSettled;
2849
2887
  const settled = new Promise((resolve) => {
@@ -2923,16 +2961,9 @@ var TransactionManager = class {
2923
2961
  `Transaction missing underlying driver transaction when starting a nested transaction.`
2924
2962
  );
2925
2963
  }
2926
- existing.depth += 1;
2927
2964
  const savepointName = this.#nextSavepointName(existing);
2928
- existing.savepoints.push(savepointName);
2929
- try {
2930
- await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
2931
- } catch (e) {
2932
- existing.depth -= 1;
2933
- existing.savepoints.pop();
2934
- throw e;
2935
- }
2965
+ await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
2966
+ existing.scopes.push(createScope(savepointName));
2936
2967
  return { id: existing.id };
2937
2968
  });
2938
2969
  }
@@ -2949,9 +2980,9 @@ var TransactionManager = class {
2949
2980
  startedAt: Date.now(),
2950
2981
  transaction: void 0,
2951
2982
  operationQueue: Promise.resolve(),
2952
- depth: 1,
2953
- savepoints: [],
2954
- savepointCounter: 0
2983
+ savepointCounter: 0,
2984
+ scopes: [createScope(void 0)],
2985
+ ...createCommitInterruption()
2955
2986
  };
2956
2987
  if (abortController.signal.aborted) {
2957
2988
  throw new TransactionStartTimeoutError();
@@ -3026,43 +3057,38 @@ var TransactionManager = class {
3026
3057
  async commitTransaction(transactionId) {
3027
3058
  return await this.tracingHelper.runInChildSpan("commit_transaction", async () => {
3028
3059
  await this.#withActiveTransactionLock(transactionId, "commit", async (txw) => {
3029
- if (txw.depth > 1) {
3060
+ const scope = innermostScope(txw);
3061
+ if (isNested(scope)) {
3030
3062
  if (!txw.transaction) throw new TransactionNotFoundError();
3031
- const savepointName = txw.savepoints.at(-1);
3032
- if (!savepointName) {
3033
- throw new TransactionInternalConsistencyError(
3034
- `Missing savepoint for nested commit. Depth: ${txw.depth}, transactionId: ${txw.id}`
3035
- );
3063
+ const outcome2 = await statementsSettledOrCommitInterrupted(txw, [...scope.runningStatements]);
3064
+ if (outcome2 !== "committed") {
3065
+ await this.#closeTransaction(txw, outcome2);
3066
+ throw closedTransactionError(txw, outcome2, "commit");
3036
3067
  }
3037
3068
  try {
3038
- await this.#releaseSavepoint(txw.transaction, savepointName);
3069
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
3039
3070
  } finally {
3040
- txw.savepoints.pop();
3041
- txw.depth -= 1;
3071
+ mergeInnermostScope(txw);
3042
3072
  }
3043
3073
  return;
3044
3074
  }
3045
- await this.#closeTransaction(txw, "committed");
3075
+ const outcome = await this.#closeTransaction(txw, "committed");
3076
+ if (outcome !== "committed") throw closedTransactionError(txw, outcome, "commit");
3046
3077
  });
3047
3078
  });
3048
3079
  }
3049
3080
  async rollbackTransaction(transactionId) {
3050
3081
  return await this.tracingHelper.runInChildSpan("rollback_transaction", async () => {
3051
3082
  await this.#withActiveTransactionLock(transactionId, "rollback", async (txw) => {
3052
- if (txw.depth > 1) {
3053
- if (!txw.transaction) throw new TransactionNotFoundError();
3054
- const savepointName = txw.savepoints.at(-1);
3055
- if (!savepointName) {
3056
- throw new TransactionInternalConsistencyError(
3057
- `Missing savepoint for nested rollback. Depth: ${txw.depth}, transactionId: ${txw.id}`
3058
- );
3059
- }
3083
+ const scope = innermostScope(txw);
3084
+ if (isNested(scope)) {
3060
3085
  try {
3061
- await this.#requiredRollbackToSavepoint(txw.transaction)(savepointName);
3062
- await this.#releaseSavepoint(txw.transaction, savepointName);
3086
+ await this.#closeScopes(txw, [scope], "nested_rolled_back");
3087
+ if (!txw.transaction) throw new TransactionNotFoundError();
3088
+ await this.#requiredRollbackToSavepoint(txw.transaction)(scope.savepoint);
3089
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
3063
3090
  } finally {
3064
- txw.savepoints.pop();
3065
- txw.depth -= 1;
3091
+ popRolledBackScope(txw);
3066
3092
  }
3067
3093
  return;
3068
3094
  }
@@ -3070,14 +3096,68 @@ var TransactionManager = class {
3070
3096
  });
3071
3097
  });
3072
3098
  }
3073
- async getTransaction(txInfo, operation) {
3074
- let tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3075
- if (tx.status === "closing") {
3076
- await tx.closing;
3077
- tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3078
- }
3099
+ /**
3100
+ * Returns a handle for running statements in the transaction. The handle rejects every
3101
+ * statement issued after the transaction has started to close, or after the nested transaction
3102
+ * that is innermost now has started to roll back. A commit of that nested transaction never
3103
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
3104
+ * including one issued while the commit waits to release the savepoint.
3105
+ */
3106
+ getTransaction(txInfo, operation) {
3107
+ return new Promise((resolve) => resolve(this.#issueHandle(txInfo, operation)));
3108
+ }
3109
+ #issueHandle(txInfo, operation) {
3110
+ const tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3111
+ const scope = innermostScope(tx);
3112
+ if (scope.closingReason !== void 0) throw closedTransactionError(tx, scope.closingReason, operation);
3079
3113
  if (!tx.transaction) throw new TransactionNotFoundError();
3080
- return tx.transaction;
3114
+ return this.#guardedQueryable(tx, tx.transaction, scope, operation);
3115
+ }
3116
+ #guardedQueryable(tx, transaction, scope, operation) {
3117
+ return {
3118
+ provider: transaction.provider,
3119
+ adapterName: transaction.adapterName,
3120
+ queryRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.queryRaw(query)),
3121
+ executeRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.executeRaw(query))
3122
+ };
3123
+ }
3124
+ async #runStatement(tx, issuedIn, operation, execute) {
3125
+ const scope = currentScope(issuedIn);
3126
+ if (scope.closingReason !== void 0) {
3127
+ throw closedTransactionError(tx, scope.closingReason, operation);
3128
+ }
3129
+ let markSettled;
3130
+ const settled = new Promise((resolve) => {
3131
+ markSettled = resolve;
3132
+ });
3133
+ scope.runningStatements.add(settled);
3134
+ try {
3135
+ return await execute();
3136
+ } finally {
3137
+ currentScope(issuedIn).runningStatements.delete(settled);
3138
+ markSettled();
3139
+ }
3140
+ }
3141
+ /**
3142
+ * Stops `scopes` from accepting statements, then waits for the ones already running. A commit
3143
+ * waits until they settle or the timeout or a disconnect interrupts it, and then becomes a
3144
+ * rollback. A rollback waits at most {@link ROLLBACK_GRACE_MS}. Resolves with how the
3145
+ * transaction is to be closed.
3146
+ */
3147
+ async #closeScopes(tx, scopes, reason) {
3148
+ markClosing(scopes, reason);
3149
+ const running = scopes.flatMap((scope) => [...scope.runningStatements]);
3150
+ if (running.length === 0) return reason;
3151
+ let outcome = reason;
3152
+ if (reason === "committed") {
3153
+ outcome = await statementsSettledOrCommitInterrupted(tx, running);
3154
+ if (outcome === "committed") return outcome;
3155
+ markClosing(scopes, outcome);
3156
+ }
3157
+ const allSettled = Promise.all(running).then(() => {
3158
+ });
3159
+ await settleWithin(allSettled, ROLLBACK_GRACE_MS);
3160
+ return outcome;
3081
3161
  }
3082
3162
  #getActiveOrClosingTransaction(transactionId, operation) {
3083
3163
  const transaction = this.transactions.get(transactionId);
@@ -3090,15 +3170,8 @@ var TransactionManager = class {
3090
3170
  case "waiting":
3091
3171
  case "running":
3092
3172
  throw new TransactionInternalConsistencyError("Active transaction found in closed transactions list.");
3093
- case "committed":
3094
- throw new TransactionClosedError(operation);
3095
- case "rolled_back":
3096
- throw new TransactionRolledBackError(operation);
3097
- case "timed_out":
3098
- throw new TransactionExecutionTimeoutError(operation, {
3099
- timeout: closedTransaction.timeout,
3100
- timeTaken: Date.now() - closedTransaction.startedAt
3101
- });
3173
+ default:
3174
+ throw closedTransactionError(closedTransaction, closedTransaction.status, operation);
3102
3175
  }
3103
3176
  } else {
3104
3177
  debug2(`Transaction not found.`, transactionId);
@@ -3115,6 +3188,9 @@ var TransactionManager = class {
3115
3188
  for (const { abortController } of starting) {
3116
3189
  abortController.abort();
3117
3190
  }
3191
+ for (const tx of this.transactions.values()) {
3192
+ tx.interruptCommit("rolled_back");
3193
+ }
3118
3194
  await Promise.allSettled([
3119
3195
  ...[...this.transactions.values()].map(
3120
3196
  (tx) => this.#runSerialized(tx, async () => {
@@ -3124,7 +3200,7 @@ var TransactionManager = class {
3124
3200
  }
3125
3201
  })
3126
3202
  ),
3127
- ...starting.map(({ settled }) => settleWithin(settled, CANCEL_ROLLBACK_GRACE_MS))
3203
+ ...starting.map(({ settled }) => settleWithin(settled, ROLLBACK_GRACE_MS))
3128
3204
  ]);
3129
3205
  }
3130
3206
  #nextSavepointName(transaction) {
@@ -3164,6 +3240,7 @@ var TransactionManager = class {
3164
3240
  this.#debugTransactionAlreadyClosedOnTimeout(transactionId);
3165
3241
  return;
3166
3242
  }
3243
+ tx.interruptCommit("timed_out");
3167
3244
  await this.#runSerialized(tx, async () => {
3168
3245
  const current = this.transactions.get(transactionId);
3169
3246
  if (current && ["running", "waiting"].includes(current.status)) {
@@ -3180,7 +3257,7 @@ var TransactionManager = class {
3180
3257
  return timer;
3181
3258
  }
3182
3259
  // Any operation that mutates or closes a transaction must run through this lock so
3183
- // status/savepoint/depth checks and updates happen against a stable view of state.
3260
+ // status/scope checks and updates happen against a stable view of state.
3184
3261
  async #withActiveTransactionLock(transactionId, operation, callback) {
3185
3262
  const tx = this.#getActiveOrClosingTransaction(transactionId, operation);
3186
3263
  return await this.#runSerialized(tx, async () => {
@@ -3189,7 +3266,7 @@ var TransactionManager = class {
3189
3266
  });
3190
3267
  }
3191
3268
  // Serializes operations per transaction id to prevent interleaving across awaits.
3192
- // This avoids races where one operation mutates savepoint/depth state while another
3269
+ // This avoids races where one operation mutates scope state while another
3193
3270
  // operation is suspended, which could otherwise corrupt cleanup logic.
3194
3271
  async #runSerialized(tx, callback) {
3195
3272
  const previousOperation = tx.operationQueue;
@@ -3204,11 +3281,13 @@ var TransactionManager = class {
3204
3281
  releaseOperationLock();
3205
3282
  }
3206
3283
  }
3207
- async #closeTransaction(tx, status) {
3208
- const createClosingPromise = async () => {
3209
- debug2("Closing transaction.", { transactionId: tx.id, status });
3284
+ /** Resolves with how the transaction was closed, which differs from `requested` for an interrupted commit. */
3285
+ async #closeTransaction(tx, requested) {
3286
+ const createClosingPromise = async (scopesClosed2) => {
3287
+ debug2("Closing transaction.", { transactionId: tx.id, requested });
3288
+ const outcome = await scopesClosed2;
3210
3289
  try {
3211
- if (tx.transaction && status === "committed") {
3290
+ if (tx.transaction && outcome === "committed") {
3212
3291
  if (tx.transaction.options.usePhantomQuery) {
3213
3292
  await this.#withQuerySpanAndEvent(PHANTOM_COMMIT_QUERY(), tx.transaction, () => tx.transaction.commit());
3214
3293
  } else {
@@ -3238,7 +3317,7 @@ var TransactionManager = class {
3238
3317
  }
3239
3318
  }
3240
3319
  } finally {
3241
- tx.status = status;
3320
+ tx.status = outcome;
3242
3321
  clearTimeout(tx.timer);
3243
3322
  tx.timer = void 0;
3244
3323
  this.transactions.delete(tx.id);
@@ -3247,17 +3326,18 @@ var TransactionManager = class {
3247
3326
  this.closedTransactions.shift();
3248
3327
  }
3249
3328
  }
3329
+ return outcome;
3250
3330
  };
3251
3331
  if (tx.status === "closing") {
3252
3332
  await tx.closing;
3253
- this.#getActiveOrClosingTransaction(tx.id, status === "committed" ? "commit" : "rollback");
3254
- } else {
3255
- await Object.assign(tx, {
3256
- status: "closing",
3257
- reason: status,
3258
- closing: createClosingPromise()
3259
- }).closing;
3333
+ this.#getActiveOrClosingTransaction(tx.id, requested === "committed" ? "commit" : "rollback");
3334
+ throw new TransactionInternalConsistencyError("Transaction still active after it was closed.");
3260
3335
  }
3336
+ const scopesClosed = this.#closeScopes(tx, tx.scopes, requested);
3337
+ return await Object.assign(tx, {
3338
+ status: "closing",
3339
+ closing: createClosingPromise(scopesClosed)
3340
+ }).closing;
3261
3341
  }
3262
3342
  #validateOptions(options) {
3263
3343
  if (!options.timeout) throw new TransactionManagerError("timeout is required");
@@ -3279,6 +3359,56 @@ var TransactionManager = class {
3279
3359
  });
3280
3360
  }
3281
3361
  };
3362
+ function innermostScope(tx) {
3363
+ return tx.scopes[tx.scopes.length - 1];
3364
+ }
3365
+ function popInnermostScope(tx) {
3366
+ const child = innermostScope(tx);
3367
+ tx.scopes.pop();
3368
+ const parent = innermostScope(tx);
3369
+ const moved = [...child.runningStatements];
3370
+ for (const statement of moved) {
3371
+ parent.runningStatements.add(statement);
3372
+ }
3373
+ child.runningStatements.clear();
3374
+ return { child, parent, moved };
3375
+ }
3376
+ function mergeInnermostScope(tx) {
3377
+ const { child, parent } = popInnermostScope(tx);
3378
+ child.mergedInto = parent;
3379
+ }
3380
+ function popRolledBackScope(tx) {
3381
+ const { parent, moved } = popInnermostScope(tx);
3382
+ for (const statement of moved) {
3383
+ void statement.then(() => currentScope(parent).runningStatements.delete(statement));
3384
+ }
3385
+ }
3386
+ function markClosing(scopes, reason) {
3387
+ for (const scope of scopes) {
3388
+ scope.closingReason = reason;
3389
+ }
3390
+ }
3391
+ async function statementsSettledOrCommitInterrupted(tx, running) {
3392
+ if (running.length === 0) return "committed";
3393
+ return await Promise.race([Promise.all(running).then(() => "committed"), tx.commitInterrupted]);
3394
+ }
3395
+ function closedTransactionError(tx, reason, operation) {
3396
+ switch (reason) {
3397
+ case "committed":
3398
+ return new TransactionClosedError(operation);
3399
+ case "rolled_back":
3400
+ return new TransactionRolledBackError(operation);
3401
+ case "nested_rolled_back":
3402
+ return new NestedTransactionRolledBackError(operation);
3403
+ case "timed_out":
3404
+ return new TransactionExecutionTimeoutError(operation, {
3405
+ timeout: tx.timeout,
3406
+ timeTaken: Date.now() - tx.startedAt
3407
+ });
3408
+ default:
3409
+ return assertNever(reason, "Unknown closing reason.");
3410
+ }
3411
+ }
3282
3412
  function createTimeoutIfDefined(cb, ms) {
3283
3413
  return ms !== void 0 ? setTimeout(cb, ms) : void 0;
3284
3414
  }
package/dist/index.mjs CHANGED
@@ -1601,7 +1601,7 @@ var QueryInterpreter = class _QueryInterpreter {
1601
1601
  switch (node.type) {
1602
1602
  case "value": {
1603
1603
  return {
1604
- value: evaluateArg(node.args, context.scope, context.generators),
1604
+ value: node.isEvaluated ? node.args : evaluateArg(node.args, context.scope, context.generators),
1605
1605
  lastInsertId: node.lastInsertId
1606
1606
  };
1607
1607
  }
@@ -1681,7 +1681,7 @@ var QueryInterpreter = class _QueryInterpreter {
1681
1681
  }
1682
1682
  case "reverse": {
1683
1683
  const { value, lastInsertId } = await this.interpretNode(node.args, context);
1684
- return { value: Array.isArray(value) ? value.reverse() : value, lastInsertId };
1684
+ return { value: Array.isArray(value) ? value.slice().reverse() : value, lastInsertId };
1685
1685
  }
1686
1686
  case "unique": {
1687
1687
  const { value, lastInsertId } = await this.interpretNode(node.args, context);
@@ -1709,10 +1709,12 @@ var QueryInterpreter = class _QueryInterpreter {
1709
1709
  if (parent === null) {
1710
1710
  return { value: null, lastInsertId };
1711
1711
  }
1712
+ const parentRecords = (Array.isArray(parent) ? parent : [parent]).map(asRecord);
1712
1713
  const children = await Promise.all(
1713
1714
  node.args.children.map(async (joinExpr) => ({
1714
1715
  joinExpr,
1715
- childRecords: (await this.interpretNode(joinExpr.child, context)).value
1716
+ // A child can only attach to a parent whose join keys are all non-null.
1717
+ childRecords: parentRecords.some((record) => joinExpr.on.every(([key]) => record[key] != null)) ? (await this.interpretNode(joinExpr.child, context)).value : []
1716
1718
  }))
1717
1719
  );
1718
1720
  return { value: attachChildrenToParents(parent, children, node.args.canAssumeStrictEquality), lastInsertId };
@@ -1773,7 +1775,10 @@ var QueryInterpreter = class _QueryInterpreter {
1773
1775
  #interpretPureNode(node, scope, generators) {
1774
1776
  switch (node.type) {
1775
1777
  case "value": {
1776
- return { value: evaluateArg(node.args, scope, generators), lastInsertId: node.lastInsertId };
1778
+ return {
1779
+ value: node.isEvaluated ? node.args : evaluateArg(node.args, scope, generators),
1780
+ lastInsertId: node.lastInsertId
1781
+ };
1777
1782
  }
1778
1783
  case "seq": {
1779
1784
  let result;
@@ -1816,7 +1821,7 @@ var QueryInterpreter = class _QueryInterpreter {
1816
1821
  }
1817
1822
  case "reverse": {
1818
1823
  const { value, lastInsertId } = this.#interpretPureNode(node.args, scope, generators);
1819
- return { value: Array.isArray(value) ? value.reverse() : value, lastInsertId };
1824
+ return { value: Array.isArray(value) ? value.slice().reverse() : value, lastInsertId };
1820
1825
  }
1821
1826
  case "unique": {
1822
1827
  const { value, lastInsertId } = this.#interpretPureNode(node.args, scope, generators);
@@ -2127,7 +2132,8 @@ function purifyQueryPlan(node, evalNode) {
2127
2132
  const evaluated = {
2128
2133
  type: "value",
2129
2134
  args: result.value,
2130
- lastInsertId: result.lastInsertId
2135
+ lastInsertId: result.lastInsertId,
2136
+ isEvaluated: true
2131
2137
  };
2132
2138
  const purified = replaceImpureNode(node, impureNode, evaluated);
2133
2139
  if (!purified) {
@@ -2386,7 +2392,7 @@ var Parameterizer = class {
2386
2392
  for (const [key, value] of Object.entries(obj)) {
2387
2393
  const edge = this.#view.inputEdge(node, key);
2388
2394
  if (edge) {
2389
- result[key] = this.#parameterizeValue(value, edge);
2395
+ result[key] = this.#parameterizeValue(value, edge, key);
2390
2396
  } else {
2391
2397
  result[key] = value;
2392
2398
  }
@@ -2396,7 +2402,7 @@ var Parameterizer = class {
2396
2402
  /**
2397
2403
  * Core parameterization logic for a single value.
2398
2404
  */
2399
- #parameterizeValue(value, edge) {
2405
+ #parameterizeValue(value, edge, key) {
2400
2406
  const classified = classifyValue(value);
2401
2407
  switch (classified.kind) {
2402
2408
  case "null":
@@ -2404,7 +2410,7 @@ var Parameterizer = class {
2404
2410
  case "structural":
2405
2411
  return value;
2406
2412
  case "primitive":
2407
- return this.#handlePrimitive(classified.value, edge);
2413
+ return this.#handlePrimitive(classified.value, edge, key);
2408
2414
  case "taggedScalar":
2409
2415
  return this.#handleTaggedScalar(value, classified.tag, edge);
2410
2416
  case "array":
@@ -2418,7 +2424,7 @@ var Parameterizer = class {
2418
2424
  /**
2419
2425
  * Handles parameterization of primitive values (string, number, boolean).
2420
2426
  */
2421
- #handlePrimitive(value, edge) {
2427
+ #handlePrimitive(value, edge, key) {
2422
2428
  if (hasFlag(edge, EdgeFlag.ParamEnum) && edge.enumNameIndex !== void 0 && typeof value === "string") {
2423
2429
  const enumValues = this.#view.enumValues(edge);
2424
2430
  if (enumValues && Object.hasOwn(enumValues, value)) {
@@ -2433,13 +2439,18 @@ var Parameterizer = class {
2433
2439
  if (mask === 0) {
2434
2440
  return value;
2435
2441
  }
2436
- const type = getPrimitivePlaceholderType(value);
2442
+ if (mask & ScalarMask.Json) {
2443
+ if (JSON_COMPARISON_FILTERS.has(key)) {
2444
+ return value;
2445
+ }
2446
+ const jsonValue = JSON.stringify(value);
2447
+ const type2 = { type: "Json" };
2448
+ return this.#getOrCreatePlaceholder(jsonValue, type2);
2449
+ }
2450
+ const type = getPrimitivePlaceholderType(value, mask);
2437
2451
  if (!matchesPrimitiveMask(type, mask)) {
2438
2452
  return value;
2439
2453
  }
2440
- if (mask & ScalarMask.Json) {
2441
- value = JSON.stringify(value);
2442
- }
2443
2454
  return this.#getOrCreatePlaceholder(value, type);
2444
2455
  }
2445
2456
  /**
@@ -2477,7 +2488,7 @@ var Parameterizer = class {
2477
2488
  const allValid = items.every((item) => validateListElement(item, edge));
2478
2489
  if (allValid && items.length > 0) {
2479
2490
  const decodedItems = items.map((item) => decodeIfTagged(item));
2480
- const innerType = inferListElementType(items);
2491
+ const innerType = inferListElementType(items, getScalarMask(edge));
2481
2492
  const type = { type: "List", inner: innerType };
2482
2493
  return this.#getOrCreatePlaceholder(decodedItems, type);
2483
2494
  }
@@ -2566,9 +2577,10 @@ function createValueKey(value, type) {
2566
2577
  const valueKey = serializeValue(value);
2567
2578
  return `${typeKey}:${valueKey}`;
2568
2579
  }
2580
+ var JSON_COMPARISON_FILTERS = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
2569
2581
  var MAX_INT = 2 ** 31 - 1;
2570
2582
  var MIN_INT = -(2 ** 31);
2571
- function getPrimitivePlaceholderType(value) {
2583
+ function getPrimitivePlaceholderType(value, mask) {
2572
2584
  switch (typeof value) {
2573
2585
  case "boolean":
2574
2586
  return { type: "Boolean" };
@@ -2579,6 +2591,9 @@ function getPrimitivePlaceholderType(value) {
2579
2591
  if (MIN_INT <= value && value <= MAX_INT) {
2580
2592
  return { type: "Int" };
2581
2593
  }
2594
+ if (!(mask & ScalarMask.BigInt) && mask & ScalarMask.Float) {
2595
+ return { type: "Float" };
2596
+ }
2582
2597
  return { type: "BigInt" };
2583
2598
  case "string":
2584
2599
  return { type: "String" };
@@ -2615,14 +2630,14 @@ function getTaggedPlaceholderType(tag) {
2615
2630
  return void 0;
2616
2631
  }
2617
2632
  }
2618
- function inferListElementType(items) {
2633
+ function inferListElementType(items, mask) {
2619
2634
  let widest = { type: "Any" };
2620
2635
  for (const item of items) {
2621
2636
  const classified = classifyValue(item);
2622
2637
  let itemType;
2623
2638
  switch (classified.kind) {
2624
2639
  case "primitive":
2625
- itemType = getPrimitivePlaceholderType(classified.value);
2640
+ itemType = getPrimitivePlaceholderType(classified.value, mask);
2626
2641
  break;
2627
2642
  case "taggedScalar":
2628
2643
  itemType = getTaggedPlaceholderType(classified.tag) ?? { type: "Any" };
@@ -2670,8 +2685,8 @@ function validateListElement(item, edge) {
2670
2685
  case "null":
2671
2686
  return false;
2672
2687
  case "primitive": {
2673
- const type = getPrimitivePlaceholderType(classified.value);
2674
2688
  const mask = getScalarMask(edge);
2689
+ const type = getPrimitivePlaceholderType(classified.value, mask);
2675
2690
  return mask !== 0 && matchesPrimitiveMask(type, mask);
2676
2691
  }
2677
2692
  case "taggedScalar": {
@@ -2764,6 +2779,13 @@ var TransactionRolledBackError = class extends TransactionManagerError {
2764
2779
  super(`Transaction already closed: A ${operation} cannot be executed on a transaction that was rolled back.`);
2765
2780
  }
2766
2781
  };
2782
+ var NestedTransactionRolledBackError = class extends TransactionManagerError {
2783
+ constructor(operation) {
2784
+ super(
2785
+ `Nested transaction already closed: A ${operation} cannot be executed on a nested transaction that was rolled back.`
2786
+ );
2787
+ }
2788
+ };
2767
2789
  var TransactionStartTimeoutError = class extends TransactionManagerError {
2768
2790
  constructor() {
2769
2791
  super("Unable to start a transaction in the given time.");
@@ -2790,7 +2812,23 @@ var InvalidTransactionIsolationLevelError = class extends TransactionManagerErro
2790
2812
 
2791
2813
  // src/transaction-manager/transaction-manager.ts
2792
2814
  var MAX_CLOSED_TRANSACTIONS = 100;
2793
- var CANCEL_ROLLBACK_GRACE_MS = 2e3;
2815
+ var ROLLBACK_GRACE_MS = 2e3;
2816
+ function createScope(savepoint) {
2817
+ return { savepoint, closingReason: void 0, runningStatements: /* @__PURE__ */ new Set() };
2818
+ }
2819
+ function isNested(scope) {
2820
+ return scope.savepoint !== void 0;
2821
+ }
2822
+ function currentScope(scope) {
2823
+ return scope.mergedInto ? currentScope(scope.mergedInto) : scope;
2824
+ }
2825
+ function createCommitInterruption() {
2826
+ let interruptCommit;
2827
+ const commitInterrupted = new Promise((resolve) => {
2828
+ interruptCommit = resolve;
2829
+ });
2830
+ return { commitInterrupted, interruptCommit };
2831
+ }
2794
2832
  function trackStartingTransaction() {
2795
2833
  let markSettled;
2796
2834
  const settled = new Promise((resolve) => {
@@ -2870,16 +2908,9 @@ var TransactionManager = class {
2870
2908
  `Transaction missing underlying driver transaction when starting a nested transaction.`
2871
2909
  );
2872
2910
  }
2873
- existing.depth += 1;
2874
2911
  const savepointName = this.#nextSavepointName(existing);
2875
- existing.savepoints.push(savepointName);
2876
- try {
2877
- await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
2878
- } catch (e) {
2879
- existing.depth -= 1;
2880
- existing.savepoints.pop();
2881
- throw e;
2882
- }
2912
+ await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
2913
+ existing.scopes.push(createScope(savepointName));
2883
2914
  return { id: existing.id };
2884
2915
  });
2885
2916
  }
@@ -2896,9 +2927,9 @@ var TransactionManager = class {
2896
2927
  startedAt: Date.now(),
2897
2928
  transaction: void 0,
2898
2929
  operationQueue: Promise.resolve(),
2899
- depth: 1,
2900
- savepoints: [],
2901
- savepointCounter: 0
2930
+ savepointCounter: 0,
2931
+ scopes: [createScope(void 0)],
2932
+ ...createCommitInterruption()
2902
2933
  };
2903
2934
  if (abortController.signal.aborted) {
2904
2935
  throw new TransactionStartTimeoutError();
@@ -2973,43 +3004,38 @@ var TransactionManager = class {
2973
3004
  async commitTransaction(transactionId) {
2974
3005
  return await this.tracingHelper.runInChildSpan("commit_transaction", async () => {
2975
3006
  await this.#withActiveTransactionLock(transactionId, "commit", async (txw) => {
2976
- if (txw.depth > 1) {
3007
+ const scope = innermostScope(txw);
3008
+ if (isNested(scope)) {
2977
3009
  if (!txw.transaction) throw new TransactionNotFoundError();
2978
- const savepointName = txw.savepoints.at(-1);
2979
- if (!savepointName) {
2980
- throw new TransactionInternalConsistencyError(
2981
- `Missing savepoint for nested commit. Depth: ${txw.depth}, transactionId: ${txw.id}`
2982
- );
3010
+ const outcome2 = await statementsSettledOrCommitInterrupted(txw, [...scope.runningStatements]);
3011
+ if (outcome2 !== "committed") {
3012
+ await this.#closeTransaction(txw, outcome2);
3013
+ throw closedTransactionError(txw, outcome2, "commit");
2983
3014
  }
2984
3015
  try {
2985
- await this.#releaseSavepoint(txw.transaction, savepointName);
3016
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
2986
3017
  } finally {
2987
- txw.savepoints.pop();
2988
- txw.depth -= 1;
3018
+ mergeInnermostScope(txw);
2989
3019
  }
2990
3020
  return;
2991
3021
  }
2992
- await this.#closeTransaction(txw, "committed");
3022
+ const outcome = await this.#closeTransaction(txw, "committed");
3023
+ if (outcome !== "committed") throw closedTransactionError(txw, outcome, "commit");
2993
3024
  });
2994
3025
  });
2995
3026
  }
2996
3027
  async rollbackTransaction(transactionId) {
2997
3028
  return await this.tracingHelper.runInChildSpan("rollback_transaction", async () => {
2998
3029
  await this.#withActiveTransactionLock(transactionId, "rollback", async (txw) => {
2999
- if (txw.depth > 1) {
3000
- if (!txw.transaction) throw new TransactionNotFoundError();
3001
- const savepointName = txw.savepoints.at(-1);
3002
- if (!savepointName) {
3003
- throw new TransactionInternalConsistencyError(
3004
- `Missing savepoint for nested rollback. Depth: ${txw.depth}, transactionId: ${txw.id}`
3005
- );
3006
- }
3030
+ const scope = innermostScope(txw);
3031
+ if (isNested(scope)) {
3007
3032
  try {
3008
- await this.#requiredRollbackToSavepoint(txw.transaction)(savepointName);
3009
- await this.#releaseSavepoint(txw.transaction, savepointName);
3033
+ await this.#closeScopes(txw, [scope], "nested_rolled_back");
3034
+ if (!txw.transaction) throw new TransactionNotFoundError();
3035
+ await this.#requiredRollbackToSavepoint(txw.transaction)(scope.savepoint);
3036
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
3010
3037
  } finally {
3011
- txw.savepoints.pop();
3012
- txw.depth -= 1;
3038
+ popRolledBackScope(txw);
3013
3039
  }
3014
3040
  return;
3015
3041
  }
@@ -3017,14 +3043,68 @@ var TransactionManager = class {
3017
3043
  });
3018
3044
  });
3019
3045
  }
3020
- async getTransaction(txInfo, operation) {
3021
- let tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3022
- if (tx.status === "closing") {
3023
- await tx.closing;
3024
- tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3025
- }
3046
+ /**
3047
+ * Returns a handle for running statements in the transaction. The handle rejects every
3048
+ * statement issued after the transaction has started to close, or after the nested transaction
3049
+ * that is innermost now has started to roll back. A commit of that nested transaction never
3050
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
3051
+ * including one issued while the commit waits to release the savepoint.
3052
+ */
3053
+ getTransaction(txInfo, operation) {
3054
+ return new Promise((resolve) => resolve(this.#issueHandle(txInfo, operation)));
3055
+ }
3056
+ #issueHandle(txInfo, operation) {
3057
+ const tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3058
+ const scope = innermostScope(tx);
3059
+ if (scope.closingReason !== void 0) throw closedTransactionError(tx, scope.closingReason, operation);
3026
3060
  if (!tx.transaction) throw new TransactionNotFoundError();
3027
- return tx.transaction;
3061
+ return this.#guardedQueryable(tx, tx.transaction, scope, operation);
3062
+ }
3063
+ #guardedQueryable(tx, transaction, scope, operation) {
3064
+ return {
3065
+ provider: transaction.provider,
3066
+ adapterName: transaction.adapterName,
3067
+ queryRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.queryRaw(query)),
3068
+ executeRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.executeRaw(query))
3069
+ };
3070
+ }
3071
+ async #runStatement(tx, issuedIn, operation, execute) {
3072
+ const scope = currentScope(issuedIn);
3073
+ if (scope.closingReason !== void 0) {
3074
+ throw closedTransactionError(tx, scope.closingReason, operation);
3075
+ }
3076
+ let markSettled;
3077
+ const settled = new Promise((resolve) => {
3078
+ markSettled = resolve;
3079
+ });
3080
+ scope.runningStatements.add(settled);
3081
+ try {
3082
+ return await execute();
3083
+ } finally {
3084
+ currentScope(issuedIn).runningStatements.delete(settled);
3085
+ markSettled();
3086
+ }
3087
+ }
3088
+ /**
3089
+ * Stops `scopes` from accepting statements, then waits for the ones already running. A commit
3090
+ * waits until they settle or the timeout or a disconnect interrupts it, and then becomes a
3091
+ * rollback. A rollback waits at most {@link ROLLBACK_GRACE_MS}. Resolves with how the
3092
+ * transaction is to be closed.
3093
+ */
3094
+ async #closeScopes(tx, scopes, reason) {
3095
+ markClosing(scopes, reason);
3096
+ const running = scopes.flatMap((scope) => [...scope.runningStatements]);
3097
+ if (running.length === 0) return reason;
3098
+ let outcome = reason;
3099
+ if (reason === "committed") {
3100
+ outcome = await statementsSettledOrCommitInterrupted(tx, running);
3101
+ if (outcome === "committed") return outcome;
3102
+ markClosing(scopes, outcome);
3103
+ }
3104
+ const allSettled = Promise.all(running).then(() => {
3105
+ });
3106
+ await settleWithin(allSettled, ROLLBACK_GRACE_MS);
3107
+ return outcome;
3028
3108
  }
3029
3109
  #getActiveOrClosingTransaction(transactionId, operation) {
3030
3110
  const transaction = this.transactions.get(transactionId);
@@ -3037,15 +3117,8 @@ var TransactionManager = class {
3037
3117
  case "waiting":
3038
3118
  case "running":
3039
3119
  throw new TransactionInternalConsistencyError("Active transaction found in closed transactions list.");
3040
- case "committed":
3041
- throw new TransactionClosedError(operation);
3042
- case "rolled_back":
3043
- throw new TransactionRolledBackError(operation);
3044
- case "timed_out":
3045
- throw new TransactionExecutionTimeoutError(operation, {
3046
- timeout: closedTransaction.timeout,
3047
- timeTaken: Date.now() - closedTransaction.startedAt
3048
- });
3120
+ default:
3121
+ throw closedTransactionError(closedTransaction, closedTransaction.status, operation);
3049
3122
  }
3050
3123
  } else {
3051
3124
  debug2(`Transaction not found.`, transactionId);
@@ -3062,6 +3135,9 @@ var TransactionManager = class {
3062
3135
  for (const { abortController } of starting) {
3063
3136
  abortController.abort();
3064
3137
  }
3138
+ for (const tx of this.transactions.values()) {
3139
+ tx.interruptCommit("rolled_back");
3140
+ }
3065
3141
  await Promise.allSettled([
3066
3142
  ...[...this.transactions.values()].map(
3067
3143
  (tx) => this.#runSerialized(tx, async () => {
@@ -3071,7 +3147,7 @@ var TransactionManager = class {
3071
3147
  }
3072
3148
  })
3073
3149
  ),
3074
- ...starting.map(({ settled }) => settleWithin(settled, CANCEL_ROLLBACK_GRACE_MS))
3150
+ ...starting.map(({ settled }) => settleWithin(settled, ROLLBACK_GRACE_MS))
3075
3151
  ]);
3076
3152
  }
3077
3153
  #nextSavepointName(transaction) {
@@ -3111,6 +3187,7 @@ var TransactionManager = class {
3111
3187
  this.#debugTransactionAlreadyClosedOnTimeout(transactionId);
3112
3188
  return;
3113
3189
  }
3190
+ tx.interruptCommit("timed_out");
3114
3191
  await this.#runSerialized(tx, async () => {
3115
3192
  const current = this.transactions.get(transactionId);
3116
3193
  if (current && ["running", "waiting"].includes(current.status)) {
@@ -3127,7 +3204,7 @@ var TransactionManager = class {
3127
3204
  return timer;
3128
3205
  }
3129
3206
  // Any operation that mutates or closes a transaction must run through this lock so
3130
- // status/savepoint/depth checks and updates happen against a stable view of state.
3207
+ // status/scope checks and updates happen against a stable view of state.
3131
3208
  async #withActiveTransactionLock(transactionId, operation, callback) {
3132
3209
  const tx = this.#getActiveOrClosingTransaction(transactionId, operation);
3133
3210
  return await this.#runSerialized(tx, async () => {
@@ -3136,7 +3213,7 @@ var TransactionManager = class {
3136
3213
  });
3137
3214
  }
3138
3215
  // Serializes operations per transaction id to prevent interleaving across awaits.
3139
- // This avoids races where one operation mutates savepoint/depth state while another
3216
+ // This avoids races where one operation mutates scope state while another
3140
3217
  // operation is suspended, which could otherwise corrupt cleanup logic.
3141
3218
  async #runSerialized(tx, callback) {
3142
3219
  const previousOperation = tx.operationQueue;
@@ -3151,11 +3228,13 @@ var TransactionManager = class {
3151
3228
  releaseOperationLock();
3152
3229
  }
3153
3230
  }
3154
- async #closeTransaction(tx, status) {
3155
- const createClosingPromise = async () => {
3156
- debug2("Closing transaction.", { transactionId: tx.id, status });
3231
+ /** Resolves with how the transaction was closed, which differs from `requested` for an interrupted commit. */
3232
+ async #closeTransaction(tx, requested) {
3233
+ const createClosingPromise = async (scopesClosed2) => {
3234
+ debug2("Closing transaction.", { transactionId: tx.id, requested });
3235
+ const outcome = await scopesClosed2;
3157
3236
  try {
3158
- if (tx.transaction && status === "committed") {
3237
+ if (tx.transaction && outcome === "committed") {
3159
3238
  if (tx.transaction.options.usePhantomQuery) {
3160
3239
  await this.#withQuerySpanAndEvent(PHANTOM_COMMIT_QUERY(), tx.transaction, () => tx.transaction.commit());
3161
3240
  } else {
@@ -3185,7 +3264,7 @@ var TransactionManager = class {
3185
3264
  }
3186
3265
  }
3187
3266
  } finally {
3188
- tx.status = status;
3267
+ tx.status = outcome;
3189
3268
  clearTimeout(tx.timer);
3190
3269
  tx.timer = void 0;
3191
3270
  this.transactions.delete(tx.id);
@@ -3194,17 +3273,18 @@ var TransactionManager = class {
3194
3273
  this.closedTransactions.shift();
3195
3274
  }
3196
3275
  }
3276
+ return outcome;
3197
3277
  };
3198
3278
  if (tx.status === "closing") {
3199
3279
  await tx.closing;
3200
- this.#getActiveOrClosingTransaction(tx.id, status === "committed" ? "commit" : "rollback");
3201
- } else {
3202
- await Object.assign(tx, {
3203
- status: "closing",
3204
- reason: status,
3205
- closing: createClosingPromise()
3206
- }).closing;
3280
+ this.#getActiveOrClosingTransaction(tx.id, requested === "committed" ? "commit" : "rollback");
3281
+ throw new TransactionInternalConsistencyError("Transaction still active after it was closed.");
3207
3282
  }
3283
+ const scopesClosed = this.#closeScopes(tx, tx.scopes, requested);
3284
+ return await Object.assign(tx, {
3285
+ status: "closing",
3286
+ closing: createClosingPromise(scopesClosed)
3287
+ }).closing;
3208
3288
  }
3209
3289
  #validateOptions(options) {
3210
3290
  if (!options.timeout) throw new TransactionManagerError("timeout is required");
@@ -3226,6 +3306,56 @@ var TransactionManager = class {
3226
3306
  });
3227
3307
  }
3228
3308
  };
3309
+ function innermostScope(tx) {
3310
+ return tx.scopes[tx.scopes.length - 1];
3311
+ }
3312
+ function popInnermostScope(tx) {
3313
+ const child = innermostScope(tx);
3314
+ tx.scopes.pop();
3315
+ const parent = innermostScope(tx);
3316
+ const moved = [...child.runningStatements];
3317
+ for (const statement of moved) {
3318
+ parent.runningStatements.add(statement);
3319
+ }
3320
+ child.runningStatements.clear();
3321
+ return { child, parent, moved };
3322
+ }
3323
+ function mergeInnermostScope(tx) {
3324
+ const { child, parent } = popInnermostScope(tx);
3325
+ child.mergedInto = parent;
3326
+ }
3327
+ function popRolledBackScope(tx) {
3328
+ const { parent, moved } = popInnermostScope(tx);
3329
+ for (const statement of moved) {
3330
+ void statement.then(() => currentScope(parent).runningStatements.delete(statement));
3331
+ }
3332
+ }
3333
+ function markClosing(scopes, reason) {
3334
+ for (const scope of scopes) {
3335
+ scope.closingReason = reason;
3336
+ }
3337
+ }
3338
+ async function statementsSettledOrCommitInterrupted(tx, running) {
3339
+ if (running.length === 0) return "committed";
3340
+ return await Promise.race([Promise.all(running).then(() => "committed"), tx.commitInterrupted]);
3341
+ }
3342
+ function closedTransactionError(tx, reason, operation) {
3343
+ switch (reason) {
3344
+ case "committed":
3345
+ return new TransactionClosedError(operation);
3346
+ case "rolled_back":
3347
+ return new TransactionRolledBackError(operation);
3348
+ case "nested_rolled_back":
3349
+ return new NestedTransactionRolledBackError(operation);
3350
+ case "timed_out":
3351
+ return new TransactionExecutionTimeoutError(operation, {
3352
+ timeout: tx.timeout,
3353
+ timeTaken: Date.now() - tx.startedAt
3354
+ });
3355
+ default:
3356
+ return assertNever(reason, "Unknown closing reason.");
3357
+ }
3358
+ }
3229
3359
  function createTimeoutIfDefined(cb, ms) {
3230
3360
  return ms !== void 0 ? setTimeout(cb, ms) : void 0;
3231
3361
  }
@@ -91,6 +91,12 @@ export type PureQueryPlanNode<Rest = never> = {
91
91
  * query plan purification. Never produced by the query compiler.
92
92
  */
93
93
  lastInsertId?: string;
94
+ /**
95
+ * Present when this node holds an already-evaluated runtime result (e.g. from
96
+ * an evaluated impure query plan node) and does not need to be traversed and copied
97
+ * by evaluateArg.
98
+ */
99
+ isEvaluated?: boolean;
94
100
  } | {
95
101
  type: 'seq';
96
102
  args: (PureQueryPlanNode<Rest> | Rest)[];
@@ -0,0 +1,39 @@
1
+ import type { SqlDriverAdapter, SqlQuery, SqlResultSet, Transaction } from '@prisma/driver-adapter-utils';
2
+ import { type Mock } from 'vitest';
3
+ import { Options } from './transaction';
4
+ import { TransactionManager } from './transaction-manager';
5
+ export declare const START_TRANSACTION_TIME = 200;
6
+ export declare const TRANSACTION_EXECUTION_TIMEOUT = 500;
7
+ export declare const TRANSACTION_OPTIONS: Options;
8
+ export declare const EMPTY_RESULT_SET: SqlResultSet;
9
+ export declare class MockDriverAdapter implements SqlDriverAdapter {
10
+ adapterName: string;
11
+ provider: SqlDriverAdapter['provider'];
12
+ private readonly usePhantomQuery;
13
+ private readonly createSavepoint;
14
+ private readonly rollbackToSavepoint;
15
+ private readonly releaseSavepoint;
16
+ executeRawMock: Mock<(query: SqlQuery) => Promise<number>>;
17
+ queryRawMock: Mock<(query: SqlQuery) => Promise<SqlResultSet>>;
18
+ commitMock: Mock<() => Promise<void>>;
19
+ rollbackMock: Mock<() => Promise<void>>;
20
+ constructor(options?: {
21
+ provider?: SqlDriverAdapter['provider'];
22
+ usePhantomQuery?: boolean;
23
+ createSavepoint?: Transaction['createSavepoint'];
24
+ rollbackToSavepoint?: Transaction['rollbackToSavepoint'];
25
+ releaseSavepoint?: Transaction['releaseSavepoint'];
26
+ });
27
+ executeRaw(params: SqlQuery): Promise<number>;
28
+ queryRaw(_params: SqlQuery): Promise<SqlResultSet>;
29
+ executeScript(_script: string): Promise<void>;
30
+ dispose(): Promise<void>;
31
+ startTransaction(): Promise<Transaction>;
32
+ }
33
+ export declare function startTransaction(transactionManager: TransactionManager, options?: Partial<Options>): Promise<string>;
34
+ export type Deferred<T> = {
35
+ promise: Promise<T>;
36
+ resolve: (value: T) => void;
37
+ reject: (error: unknown) => void;
38
+ };
39
+ export declare function deferred<T>(): Deferred<T>;
@@ -12,6 +12,9 @@ export declare class TransactionClosedError extends TransactionManagerError {
12
12
  export declare class TransactionRolledBackError extends TransactionManagerError {
13
13
  constructor(operation: string);
14
14
  }
15
+ export declare class NestedTransactionRolledBackError extends TransactionManagerError {
16
+ constructor(operation: string);
17
+ }
15
18
  export declare class TransactionStartTimeoutError extends TransactionManagerError {
16
19
  constructor();
17
20
  }
@@ -1,4 +1,4 @@
1
- import { SqlDriverAdapter, Transaction } from '@prisma/driver-adapter-utils';
1
+ import { SqlDriverAdapter, SqlQueryable } from '@prisma/driver-adapter-utils';
2
2
  import { QueryEvent } from '../events';
3
3
  import type { SchemaProvider } from '../schema';
4
4
  import { TracingHelper } from '../tracing';
@@ -26,6 +26,13 @@ export declare class TransactionManager {
26
26
  startTransaction(options?: Options): Promise<TransactionInfo>;
27
27
  commitTransaction(transactionId: string): Promise<void>;
28
28
  rollbackTransaction(transactionId: string): Promise<void>;
29
- getTransaction(txInfo: TransactionInfo, operation: string): Promise<Transaction>;
29
+ /**
30
+ * Returns a handle for running statements in the transaction. The handle rejects every
31
+ * statement issued after the transaction has started to close, or after the nested transaction
32
+ * that is innermost now has started to roll back. A commit of that nested transaction never
33
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
34
+ * including one issued while the commit waits to release the savepoint.
35
+ */
36
+ getTransaction(txInfo: TransactionInfo, operation: string): Promise<SqlQueryable>;
30
37
  cancelAllTransactions(): Promise<void>;
31
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/client-engine-runtime",
3
- "version": "7.10.1",
3
+ "version": "7.11.0-dev.2",
4
4
  "description": "This package is intended for Prisma's internal use",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -31,20 +31,20 @@
31
31
  "nanoid": "5.1.16",
32
32
  "ulid": "3.0.0",
33
33
  "uuid": "14.0.0",
34
- "@prisma/client-runtime-utils": "7.10.1",
35
- "@prisma/debug": "7.10.1",
36
- "@prisma/driver-adapter-utils": "7.10.1",
37
- "@prisma/sqlcommenter": "7.10.1",
38
- "@prisma/param-graph": "7.10.1",
39
- "@prisma/json-protocol": "7.10.1"
34
+ "@prisma/client-runtime-utils": "7.11.0-dev.2",
35
+ "@prisma/sqlcommenter": "7.11.0-dev.2",
36
+ "@prisma/debug": "7.11.0-dev.2",
37
+ "@prisma/driver-adapter-utils": "7.11.0-dev.2",
38
+ "@prisma/param-graph": "7.11.0-dev.2",
39
+ "@prisma/json-protocol": "7.11.0-dev.2"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@codspeed/benchmark.js-plugin": "4.0.0",
43
43
  "@types/benchmark": "2.1.5",
44
44
  "@types/node": "~20.19.24",
45
45
  "benchmark": "2.1.4",
46
- "@prisma/get-dmmf": "7.10.1",
47
- "@prisma/param-graph-builder": "7.10.1"
46
+ "@prisma/param-graph-builder": "7.11.0-dev.2",
47
+ "@prisma/get-dmmf": "7.11.0-dev.2"
48
48
  },
49
49
  "files": [
50
50
  "dist"
@@ -52,7 +52,6 @@
52
52
  "sideEffects": false,
53
53
  "scripts": {
54
54
  "dev": "DEV=true tsx helpers/build.ts",
55
- "build": "tsx helpers/build.ts",
56
- "test": "vitest run"
55
+ "build": "tsx helpers/build.ts"
57
56
  }
58
57
  }