@prisma/client-engine-runtime 8.1.0-dev.11 → 8.1.0-dev.12

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.
@@ -565,7 +564,14 @@ export declare class TransactionManager {
565
564
  startTransaction(options?: TransactionOptions): Promise<TransactionInfo>;
566
565
  commitTransaction(transactionId: string): Promise<void>;
567
566
  rollbackTransaction(transactionId: string): Promise<void>;
568
- getTransaction(txInfo: TransactionInfo, operation: string): Promise<Transaction>;
567
+ /**
568
+ * Returns a handle for running statements in the transaction. The handle rejects every
569
+ * statement issued after the transaction has started to close, or after the nested transaction
570
+ * that is innermost now has started to roll back. A commit of that nested transaction never
571
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
572
+ * including one issued while the commit waits to release the savepoint.
573
+ */
574
+ getTransaction(txInfo: TransactionInfo, operation: string): Promise<SqlQueryable>;
569
575
  cancelAllTransactions(): Promise<void>;
570
576
  }
571
577
 
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.
@@ -565,7 +564,14 @@ export declare class TransactionManager {
565
564
  startTransaction(options?: TransactionOptions): Promise<TransactionInfo>;
566
565
  commitTransaction(transactionId: string): Promise<void>;
567
566
  rollbackTransaction(transactionId: string): Promise<void>;
568
- getTransaction(txInfo: TransactionInfo, operation: string): Promise<Transaction>;
567
+ /**
568
+ * Returns a handle for running statements in the transaction. The handle rejects every
569
+ * statement issued after the transaction has started to close, or after the nested transaction
570
+ * that is innermost now has started to roll back. A commit of that nested transaction never
571
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
572
+ * including one issued while the commit waits to release the savepoint.
573
+ */
574
+ getTransaction(txInfo: TransactionInfo, operation: string): Promise<SqlQueryable>;
569
575
  cancelAllTransactions(): Promise<void>;
570
576
  }
571
577
 
package/dist/index.js CHANGED
@@ -2817,6 +2817,13 @@ var TransactionRolledBackError = class extends TransactionManagerError {
2817
2817
  super(`Transaction already closed: A ${operation} cannot be executed on a transaction that was rolled back.`);
2818
2818
  }
2819
2819
  };
2820
+ var NestedTransactionRolledBackError = class extends TransactionManagerError {
2821
+ constructor(operation) {
2822
+ super(
2823
+ `Nested transaction already closed: A ${operation} cannot be executed on a nested transaction that was rolled back.`
2824
+ );
2825
+ }
2826
+ };
2820
2827
  var TransactionStartTimeoutError = class extends TransactionManagerError {
2821
2828
  constructor() {
2822
2829
  super("Unable to start a transaction in the given time.");
@@ -2843,7 +2850,23 @@ var InvalidTransactionIsolationLevelError = class extends TransactionManagerErro
2843
2850
 
2844
2851
  // src/transaction-manager/transaction-manager.ts
2845
2852
  var MAX_CLOSED_TRANSACTIONS = 100;
2846
- var CANCEL_ROLLBACK_GRACE_MS = 2e3;
2853
+ var ROLLBACK_GRACE_MS = 2e3;
2854
+ function createScope(savepoint) {
2855
+ return { savepoint, closingReason: void 0, runningStatements: /* @__PURE__ */ new Set() };
2856
+ }
2857
+ function isNested(scope) {
2858
+ return scope.savepoint !== void 0;
2859
+ }
2860
+ function currentScope(scope) {
2861
+ return scope.mergedInto ? currentScope(scope.mergedInto) : scope;
2862
+ }
2863
+ function createCommitInterruption() {
2864
+ let interruptCommit;
2865
+ const commitInterrupted = new Promise((resolve) => {
2866
+ interruptCommit = resolve;
2867
+ });
2868
+ return { commitInterrupted, interruptCommit };
2869
+ }
2847
2870
  function trackStartingTransaction() {
2848
2871
  let markSettled;
2849
2872
  const settled = new Promise((resolve) => {
@@ -2923,16 +2946,9 @@ var TransactionManager = class {
2923
2946
  `Transaction missing underlying driver transaction when starting a nested transaction.`
2924
2947
  );
2925
2948
  }
2926
- existing.depth += 1;
2927
2949
  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
- }
2950
+ await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
2951
+ existing.scopes.push(createScope(savepointName));
2936
2952
  return { id: existing.id };
2937
2953
  });
2938
2954
  }
@@ -2949,9 +2965,9 @@ var TransactionManager = class {
2949
2965
  startedAt: Date.now(),
2950
2966
  transaction: void 0,
2951
2967
  operationQueue: Promise.resolve(),
2952
- depth: 1,
2953
- savepoints: [],
2954
- savepointCounter: 0
2968
+ savepointCounter: 0,
2969
+ scopes: [createScope(void 0)],
2970
+ ...createCommitInterruption()
2955
2971
  };
2956
2972
  if (abortController.signal.aborted) {
2957
2973
  throw new TransactionStartTimeoutError();
@@ -3026,43 +3042,38 @@ var TransactionManager = class {
3026
3042
  async commitTransaction(transactionId) {
3027
3043
  return await this.tracingHelper.runInChildSpan("commit_transaction", async () => {
3028
3044
  await this.#withActiveTransactionLock(transactionId, "commit", async (txw) => {
3029
- if (txw.depth > 1) {
3045
+ const scope = innermostScope(txw);
3046
+ if (isNested(scope)) {
3030
3047
  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
- );
3048
+ const outcome2 = await statementsSettledOrCommitInterrupted(txw, [...scope.runningStatements]);
3049
+ if (outcome2 !== "committed") {
3050
+ await this.#closeTransaction(txw, outcome2);
3051
+ throw closedTransactionError(txw, outcome2, "commit");
3036
3052
  }
3037
3053
  try {
3038
- await this.#releaseSavepoint(txw.transaction, savepointName);
3054
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
3039
3055
  } finally {
3040
- txw.savepoints.pop();
3041
- txw.depth -= 1;
3056
+ mergeInnermostScope(txw);
3042
3057
  }
3043
3058
  return;
3044
3059
  }
3045
- await this.#closeTransaction(txw, "committed");
3060
+ const outcome = await this.#closeTransaction(txw, "committed");
3061
+ if (outcome !== "committed") throw closedTransactionError(txw, outcome, "commit");
3046
3062
  });
3047
3063
  });
3048
3064
  }
3049
3065
  async rollbackTransaction(transactionId) {
3050
3066
  return await this.tracingHelper.runInChildSpan("rollback_transaction", async () => {
3051
3067
  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
- }
3068
+ const scope = innermostScope(txw);
3069
+ if (isNested(scope)) {
3060
3070
  try {
3061
- await this.#requiredRollbackToSavepoint(txw.transaction)(savepointName);
3062
- await this.#releaseSavepoint(txw.transaction, savepointName);
3071
+ await this.#closeScopes(txw, [scope], "nested_rolled_back");
3072
+ if (!txw.transaction) throw new TransactionNotFoundError();
3073
+ await this.#requiredRollbackToSavepoint(txw.transaction)(scope.savepoint);
3074
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
3063
3075
  } finally {
3064
- txw.savepoints.pop();
3065
- txw.depth -= 1;
3076
+ popRolledBackScope(txw);
3066
3077
  }
3067
3078
  return;
3068
3079
  }
@@ -3070,14 +3081,68 @@ var TransactionManager = class {
3070
3081
  });
3071
3082
  });
3072
3083
  }
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
- }
3084
+ /**
3085
+ * Returns a handle for running statements in the transaction. The handle rejects every
3086
+ * statement issued after the transaction has started to close, or after the nested transaction
3087
+ * that is innermost now has started to roll back. A commit of that nested transaction never
3088
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
3089
+ * including one issued while the commit waits to release the savepoint.
3090
+ */
3091
+ getTransaction(txInfo, operation) {
3092
+ return new Promise((resolve) => resolve(this.#issueHandle(txInfo, operation)));
3093
+ }
3094
+ #issueHandle(txInfo, operation) {
3095
+ const tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3096
+ const scope = innermostScope(tx);
3097
+ if (scope.closingReason !== void 0) throw closedTransactionError(tx, scope.closingReason, operation);
3079
3098
  if (!tx.transaction) throw new TransactionNotFoundError();
3080
- return tx.transaction;
3099
+ return this.#guardedQueryable(tx, tx.transaction, scope, operation);
3100
+ }
3101
+ #guardedQueryable(tx, transaction, scope, operation) {
3102
+ return {
3103
+ provider: transaction.provider,
3104
+ adapterName: transaction.adapterName,
3105
+ queryRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.queryRaw(query)),
3106
+ executeRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.executeRaw(query))
3107
+ };
3108
+ }
3109
+ async #runStatement(tx, issuedIn, operation, execute) {
3110
+ const scope = currentScope(issuedIn);
3111
+ if (scope.closingReason !== void 0) {
3112
+ throw closedTransactionError(tx, scope.closingReason, operation);
3113
+ }
3114
+ let markSettled;
3115
+ const settled = new Promise((resolve) => {
3116
+ markSettled = resolve;
3117
+ });
3118
+ scope.runningStatements.add(settled);
3119
+ try {
3120
+ return await execute();
3121
+ } finally {
3122
+ currentScope(issuedIn).runningStatements.delete(settled);
3123
+ markSettled();
3124
+ }
3125
+ }
3126
+ /**
3127
+ * Stops `scopes` from accepting statements, then waits for the ones already running. A commit
3128
+ * waits until they settle or the timeout or a disconnect interrupts it, and then becomes a
3129
+ * rollback. A rollback waits at most {@link ROLLBACK_GRACE_MS}. Resolves with how the
3130
+ * transaction is to be closed.
3131
+ */
3132
+ async #closeScopes(tx, scopes, reason) {
3133
+ markClosing(scopes, reason);
3134
+ const running = scopes.flatMap((scope) => [...scope.runningStatements]);
3135
+ if (running.length === 0) return reason;
3136
+ let outcome = reason;
3137
+ if (reason === "committed") {
3138
+ outcome = await statementsSettledOrCommitInterrupted(tx, running);
3139
+ if (outcome === "committed") return outcome;
3140
+ markClosing(scopes, outcome);
3141
+ }
3142
+ const allSettled = Promise.all(running).then(() => {
3143
+ });
3144
+ await settleWithin(allSettled, ROLLBACK_GRACE_MS);
3145
+ return outcome;
3081
3146
  }
3082
3147
  #getActiveOrClosingTransaction(transactionId, operation) {
3083
3148
  const transaction = this.transactions.get(transactionId);
@@ -3090,15 +3155,8 @@ var TransactionManager = class {
3090
3155
  case "waiting":
3091
3156
  case "running":
3092
3157
  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
- });
3158
+ default:
3159
+ throw closedTransactionError(closedTransaction, closedTransaction.status, operation);
3102
3160
  }
3103
3161
  } else {
3104
3162
  debug2(`Transaction not found.`, transactionId);
@@ -3115,6 +3173,9 @@ var TransactionManager = class {
3115
3173
  for (const { abortController } of starting) {
3116
3174
  abortController.abort();
3117
3175
  }
3176
+ for (const tx of this.transactions.values()) {
3177
+ tx.interruptCommit("rolled_back");
3178
+ }
3118
3179
  await Promise.allSettled([
3119
3180
  ...[...this.transactions.values()].map(
3120
3181
  (tx) => this.#runSerialized(tx, async () => {
@@ -3124,7 +3185,7 @@ var TransactionManager = class {
3124
3185
  }
3125
3186
  })
3126
3187
  ),
3127
- ...starting.map(({ settled }) => settleWithin(settled, CANCEL_ROLLBACK_GRACE_MS))
3188
+ ...starting.map(({ settled }) => settleWithin(settled, ROLLBACK_GRACE_MS))
3128
3189
  ]);
3129
3190
  }
3130
3191
  #nextSavepointName(transaction) {
@@ -3164,6 +3225,7 @@ var TransactionManager = class {
3164
3225
  this.#debugTransactionAlreadyClosedOnTimeout(transactionId);
3165
3226
  return;
3166
3227
  }
3228
+ tx.interruptCommit("timed_out");
3167
3229
  await this.#runSerialized(tx, async () => {
3168
3230
  const current = this.transactions.get(transactionId);
3169
3231
  if (current && ["running", "waiting"].includes(current.status)) {
@@ -3180,7 +3242,7 @@ var TransactionManager = class {
3180
3242
  return timer;
3181
3243
  }
3182
3244
  // 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.
3245
+ // status/scope checks and updates happen against a stable view of state.
3184
3246
  async #withActiveTransactionLock(transactionId, operation, callback) {
3185
3247
  const tx = this.#getActiveOrClosingTransaction(transactionId, operation);
3186
3248
  return await this.#runSerialized(tx, async () => {
@@ -3189,7 +3251,7 @@ var TransactionManager = class {
3189
3251
  });
3190
3252
  }
3191
3253
  // Serializes operations per transaction id to prevent interleaving across awaits.
3192
- // This avoids races where one operation mutates savepoint/depth state while another
3254
+ // This avoids races where one operation mutates scope state while another
3193
3255
  // operation is suspended, which could otherwise corrupt cleanup logic.
3194
3256
  async #runSerialized(tx, callback) {
3195
3257
  const previousOperation = tx.operationQueue;
@@ -3204,11 +3266,13 @@ var TransactionManager = class {
3204
3266
  releaseOperationLock();
3205
3267
  }
3206
3268
  }
3207
- async #closeTransaction(tx, status) {
3208
- const createClosingPromise = async () => {
3209
- debug2("Closing transaction.", { transactionId: tx.id, status });
3269
+ /** Resolves with how the transaction was closed, which differs from `requested` for an interrupted commit. */
3270
+ async #closeTransaction(tx, requested) {
3271
+ const createClosingPromise = async (scopesClosed2) => {
3272
+ debug2("Closing transaction.", { transactionId: tx.id, requested });
3273
+ const outcome = await scopesClosed2;
3210
3274
  try {
3211
- if (tx.transaction && status === "committed") {
3275
+ if (tx.transaction && outcome === "committed") {
3212
3276
  if (tx.transaction.options.usePhantomQuery) {
3213
3277
  await this.#withQuerySpanAndEvent(PHANTOM_COMMIT_QUERY(), tx.transaction, () => tx.transaction.commit());
3214
3278
  } else {
@@ -3238,7 +3302,7 @@ var TransactionManager = class {
3238
3302
  }
3239
3303
  }
3240
3304
  } finally {
3241
- tx.status = status;
3305
+ tx.status = outcome;
3242
3306
  clearTimeout(tx.timer);
3243
3307
  tx.timer = void 0;
3244
3308
  this.transactions.delete(tx.id);
@@ -3247,17 +3311,18 @@ var TransactionManager = class {
3247
3311
  this.closedTransactions.shift();
3248
3312
  }
3249
3313
  }
3314
+ return outcome;
3250
3315
  };
3251
3316
  if (tx.status === "closing") {
3252
3317
  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;
3318
+ this.#getActiveOrClosingTransaction(tx.id, requested === "committed" ? "commit" : "rollback");
3319
+ throw new TransactionInternalConsistencyError("Transaction still active after it was closed.");
3260
3320
  }
3321
+ const scopesClosed = this.#closeScopes(tx, tx.scopes, requested);
3322
+ return await Object.assign(tx, {
3323
+ status: "closing",
3324
+ closing: createClosingPromise(scopesClosed)
3325
+ }).closing;
3261
3326
  }
3262
3327
  #validateOptions(options) {
3263
3328
  if (!options.timeout) throw new TransactionManagerError("timeout is required");
@@ -3279,6 +3344,56 @@ var TransactionManager = class {
3279
3344
  });
3280
3345
  }
3281
3346
  };
3347
+ function innermostScope(tx) {
3348
+ return tx.scopes[tx.scopes.length - 1];
3349
+ }
3350
+ function popInnermostScope(tx) {
3351
+ const child = innermostScope(tx);
3352
+ tx.scopes.pop();
3353
+ const parent = innermostScope(tx);
3354
+ const moved = [...child.runningStatements];
3355
+ for (const statement of moved) {
3356
+ parent.runningStatements.add(statement);
3357
+ }
3358
+ child.runningStatements.clear();
3359
+ return { child, parent, moved };
3360
+ }
3361
+ function mergeInnermostScope(tx) {
3362
+ const { child, parent } = popInnermostScope(tx);
3363
+ child.mergedInto = parent;
3364
+ }
3365
+ function popRolledBackScope(tx) {
3366
+ const { parent, moved } = popInnermostScope(tx);
3367
+ for (const statement of moved) {
3368
+ void statement.then(() => currentScope(parent).runningStatements.delete(statement));
3369
+ }
3370
+ }
3371
+ function markClosing(scopes, reason) {
3372
+ for (const scope of scopes) {
3373
+ scope.closingReason = reason;
3374
+ }
3375
+ }
3376
+ async function statementsSettledOrCommitInterrupted(tx, running) {
3377
+ if (running.length === 0) return "committed";
3378
+ return await Promise.race([Promise.all(running).then(() => "committed"), tx.commitInterrupted]);
3379
+ }
3380
+ function closedTransactionError(tx, reason, operation) {
3381
+ switch (reason) {
3382
+ case "committed":
3383
+ return new TransactionClosedError(operation);
3384
+ case "rolled_back":
3385
+ return new TransactionRolledBackError(operation);
3386
+ case "nested_rolled_back":
3387
+ return new NestedTransactionRolledBackError(operation);
3388
+ case "timed_out":
3389
+ return new TransactionExecutionTimeoutError(operation, {
3390
+ timeout: tx.timeout,
3391
+ timeTaken: Date.now() - tx.startedAt
3392
+ });
3393
+ default:
3394
+ return assertNever(reason, "Unknown closing reason.");
3395
+ }
3396
+ }
3282
3397
  function createTimeoutIfDefined(cb, ms) {
3283
3398
  return ms !== void 0 ? setTimeout(cb, ms) : void 0;
3284
3399
  }
package/dist/index.mjs CHANGED
@@ -2764,6 +2764,13 @@ var TransactionRolledBackError = class extends TransactionManagerError {
2764
2764
  super(`Transaction already closed: A ${operation} cannot be executed on a transaction that was rolled back.`);
2765
2765
  }
2766
2766
  };
2767
+ var NestedTransactionRolledBackError = class extends TransactionManagerError {
2768
+ constructor(operation) {
2769
+ super(
2770
+ `Nested transaction already closed: A ${operation} cannot be executed on a nested transaction that was rolled back.`
2771
+ );
2772
+ }
2773
+ };
2767
2774
  var TransactionStartTimeoutError = class extends TransactionManagerError {
2768
2775
  constructor() {
2769
2776
  super("Unable to start a transaction in the given time.");
@@ -2790,7 +2797,23 @@ var InvalidTransactionIsolationLevelError = class extends TransactionManagerErro
2790
2797
 
2791
2798
  // src/transaction-manager/transaction-manager.ts
2792
2799
  var MAX_CLOSED_TRANSACTIONS = 100;
2793
- var CANCEL_ROLLBACK_GRACE_MS = 2e3;
2800
+ var ROLLBACK_GRACE_MS = 2e3;
2801
+ function createScope(savepoint) {
2802
+ return { savepoint, closingReason: void 0, runningStatements: /* @__PURE__ */ new Set() };
2803
+ }
2804
+ function isNested(scope) {
2805
+ return scope.savepoint !== void 0;
2806
+ }
2807
+ function currentScope(scope) {
2808
+ return scope.mergedInto ? currentScope(scope.mergedInto) : scope;
2809
+ }
2810
+ function createCommitInterruption() {
2811
+ let interruptCommit;
2812
+ const commitInterrupted = new Promise((resolve) => {
2813
+ interruptCommit = resolve;
2814
+ });
2815
+ return { commitInterrupted, interruptCommit };
2816
+ }
2794
2817
  function trackStartingTransaction() {
2795
2818
  let markSettled;
2796
2819
  const settled = new Promise((resolve) => {
@@ -2870,16 +2893,9 @@ var TransactionManager = class {
2870
2893
  `Transaction missing underlying driver transaction when starting a nested transaction.`
2871
2894
  );
2872
2895
  }
2873
- existing.depth += 1;
2874
2896
  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
- }
2897
+ await this.#requiredCreateSavepoint(existing.transaction)(savepointName);
2898
+ existing.scopes.push(createScope(savepointName));
2883
2899
  return { id: existing.id };
2884
2900
  });
2885
2901
  }
@@ -2896,9 +2912,9 @@ var TransactionManager = class {
2896
2912
  startedAt: Date.now(),
2897
2913
  transaction: void 0,
2898
2914
  operationQueue: Promise.resolve(),
2899
- depth: 1,
2900
- savepoints: [],
2901
- savepointCounter: 0
2915
+ savepointCounter: 0,
2916
+ scopes: [createScope(void 0)],
2917
+ ...createCommitInterruption()
2902
2918
  };
2903
2919
  if (abortController.signal.aborted) {
2904
2920
  throw new TransactionStartTimeoutError();
@@ -2973,43 +2989,38 @@ var TransactionManager = class {
2973
2989
  async commitTransaction(transactionId) {
2974
2990
  return await this.tracingHelper.runInChildSpan("commit_transaction", async () => {
2975
2991
  await this.#withActiveTransactionLock(transactionId, "commit", async (txw) => {
2976
- if (txw.depth > 1) {
2992
+ const scope = innermostScope(txw);
2993
+ if (isNested(scope)) {
2977
2994
  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
- );
2995
+ const outcome2 = await statementsSettledOrCommitInterrupted(txw, [...scope.runningStatements]);
2996
+ if (outcome2 !== "committed") {
2997
+ await this.#closeTransaction(txw, outcome2);
2998
+ throw closedTransactionError(txw, outcome2, "commit");
2983
2999
  }
2984
3000
  try {
2985
- await this.#releaseSavepoint(txw.transaction, savepointName);
3001
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
2986
3002
  } finally {
2987
- txw.savepoints.pop();
2988
- txw.depth -= 1;
3003
+ mergeInnermostScope(txw);
2989
3004
  }
2990
3005
  return;
2991
3006
  }
2992
- await this.#closeTransaction(txw, "committed");
3007
+ const outcome = await this.#closeTransaction(txw, "committed");
3008
+ if (outcome !== "committed") throw closedTransactionError(txw, outcome, "commit");
2993
3009
  });
2994
3010
  });
2995
3011
  }
2996
3012
  async rollbackTransaction(transactionId) {
2997
3013
  return await this.tracingHelper.runInChildSpan("rollback_transaction", async () => {
2998
3014
  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
- }
3015
+ const scope = innermostScope(txw);
3016
+ if (isNested(scope)) {
3007
3017
  try {
3008
- await this.#requiredRollbackToSavepoint(txw.transaction)(savepointName);
3009
- await this.#releaseSavepoint(txw.transaction, savepointName);
3018
+ await this.#closeScopes(txw, [scope], "nested_rolled_back");
3019
+ if (!txw.transaction) throw new TransactionNotFoundError();
3020
+ await this.#requiredRollbackToSavepoint(txw.transaction)(scope.savepoint);
3021
+ await this.#releaseSavepoint(txw.transaction, scope.savepoint);
3010
3022
  } finally {
3011
- txw.savepoints.pop();
3012
- txw.depth -= 1;
3023
+ popRolledBackScope(txw);
3013
3024
  }
3014
3025
  return;
3015
3026
  }
@@ -3017,14 +3028,68 @@ var TransactionManager = class {
3017
3028
  });
3018
3029
  });
3019
3030
  }
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
- }
3031
+ /**
3032
+ * Returns a handle for running statements in the transaction. The handle rejects every
3033
+ * statement issued after the transaction has started to close, or after the nested transaction
3034
+ * that is innermost now has started to roll back. A commit of that nested transaction never
3035
+ * closes the handle: it runs its statements in the enclosing transaction from then on,
3036
+ * including one issued while the commit waits to release the savepoint.
3037
+ */
3038
+ getTransaction(txInfo, operation) {
3039
+ return new Promise((resolve) => resolve(this.#issueHandle(txInfo, operation)));
3040
+ }
3041
+ #issueHandle(txInfo, operation) {
3042
+ const tx = this.#getActiveOrClosingTransaction(txInfo.id, operation);
3043
+ const scope = innermostScope(tx);
3044
+ if (scope.closingReason !== void 0) throw closedTransactionError(tx, scope.closingReason, operation);
3026
3045
  if (!tx.transaction) throw new TransactionNotFoundError();
3027
- return tx.transaction;
3046
+ return this.#guardedQueryable(tx, tx.transaction, scope, operation);
3047
+ }
3048
+ #guardedQueryable(tx, transaction, scope, operation) {
3049
+ return {
3050
+ provider: transaction.provider,
3051
+ adapterName: transaction.adapterName,
3052
+ queryRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.queryRaw(query)),
3053
+ executeRaw: (query) => this.#runStatement(tx, scope, operation, () => transaction.executeRaw(query))
3054
+ };
3055
+ }
3056
+ async #runStatement(tx, issuedIn, operation, execute) {
3057
+ const scope = currentScope(issuedIn);
3058
+ if (scope.closingReason !== void 0) {
3059
+ throw closedTransactionError(tx, scope.closingReason, operation);
3060
+ }
3061
+ let markSettled;
3062
+ const settled = new Promise((resolve) => {
3063
+ markSettled = resolve;
3064
+ });
3065
+ scope.runningStatements.add(settled);
3066
+ try {
3067
+ return await execute();
3068
+ } finally {
3069
+ currentScope(issuedIn).runningStatements.delete(settled);
3070
+ markSettled();
3071
+ }
3072
+ }
3073
+ /**
3074
+ * Stops `scopes` from accepting statements, then waits for the ones already running. A commit
3075
+ * waits until they settle or the timeout or a disconnect interrupts it, and then becomes a
3076
+ * rollback. A rollback waits at most {@link ROLLBACK_GRACE_MS}. Resolves with how the
3077
+ * transaction is to be closed.
3078
+ */
3079
+ async #closeScopes(tx, scopes, reason) {
3080
+ markClosing(scopes, reason);
3081
+ const running = scopes.flatMap((scope) => [...scope.runningStatements]);
3082
+ if (running.length === 0) return reason;
3083
+ let outcome = reason;
3084
+ if (reason === "committed") {
3085
+ outcome = await statementsSettledOrCommitInterrupted(tx, running);
3086
+ if (outcome === "committed") return outcome;
3087
+ markClosing(scopes, outcome);
3088
+ }
3089
+ const allSettled = Promise.all(running).then(() => {
3090
+ });
3091
+ await settleWithin(allSettled, ROLLBACK_GRACE_MS);
3092
+ return outcome;
3028
3093
  }
3029
3094
  #getActiveOrClosingTransaction(transactionId, operation) {
3030
3095
  const transaction = this.transactions.get(transactionId);
@@ -3037,15 +3102,8 @@ var TransactionManager = class {
3037
3102
  case "waiting":
3038
3103
  case "running":
3039
3104
  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
- });
3105
+ default:
3106
+ throw closedTransactionError(closedTransaction, closedTransaction.status, operation);
3049
3107
  }
3050
3108
  } else {
3051
3109
  debug2(`Transaction not found.`, transactionId);
@@ -3062,6 +3120,9 @@ var TransactionManager = class {
3062
3120
  for (const { abortController } of starting) {
3063
3121
  abortController.abort();
3064
3122
  }
3123
+ for (const tx of this.transactions.values()) {
3124
+ tx.interruptCommit("rolled_back");
3125
+ }
3065
3126
  await Promise.allSettled([
3066
3127
  ...[...this.transactions.values()].map(
3067
3128
  (tx) => this.#runSerialized(tx, async () => {
@@ -3071,7 +3132,7 @@ var TransactionManager = class {
3071
3132
  }
3072
3133
  })
3073
3134
  ),
3074
- ...starting.map(({ settled }) => settleWithin(settled, CANCEL_ROLLBACK_GRACE_MS))
3135
+ ...starting.map(({ settled }) => settleWithin(settled, ROLLBACK_GRACE_MS))
3075
3136
  ]);
3076
3137
  }
3077
3138
  #nextSavepointName(transaction) {
@@ -3111,6 +3172,7 @@ var TransactionManager = class {
3111
3172
  this.#debugTransactionAlreadyClosedOnTimeout(transactionId);
3112
3173
  return;
3113
3174
  }
3175
+ tx.interruptCommit("timed_out");
3114
3176
  await this.#runSerialized(tx, async () => {
3115
3177
  const current = this.transactions.get(transactionId);
3116
3178
  if (current && ["running", "waiting"].includes(current.status)) {
@@ -3127,7 +3189,7 @@ var TransactionManager = class {
3127
3189
  return timer;
3128
3190
  }
3129
3191
  // 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.
3192
+ // status/scope checks and updates happen against a stable view of state.
3131
3193
  async #withActiveTransactionLock(transactionId, operation, callback) {
3132
3194
  const tx = this.#getActiveOrClosingTransaction(transactionId, operation);
3133
3195
  return await this.#runSerialized(tx, async () => {
@@ -3136,7 +3198,7 @@ var TransactionManager = class {
3136
3198
  });
3137
3199
  }
3138
3200
  // Serializes operations per transaction id to prevent interleaving across awaits.
3139
- // This avoids races where one operation mutates savepoint/depth state while another
3201
+ // This avoids races where one operation mutates scope state while another
3140
3202
  // operation is suspended, which could otherwise corrupt cleanup logic.
3141
3203
  async #runSerialized(tx, callback) {
3142
3204
  const previousOperation = tx.operationQueue;
@@ -3151,11 +3213,13 @@ var TransactionManager = class {
3151
3213
  releaseOperationLock();
3152
3214
  }
3153
3215
  }
3154
- async #closeTransaction(tx, status) {
3155
- const createClosingPromise = async () => {
3156
- debug2("Closing transaction.", { transactionId: tx.id, status });
3216
+ /** Resolves with how the transaction was closed, which differs from `requested` for an interrupted commit. */
3217
+ async #closeTransaction(tx, requested) {
3218
+ const createClosingPromise = async (scopesClosed2) => {
3219
+ debug2("Closing transaction.", { transactionId: tx.id, requested });
3220
+ const outcome = await scopesClosed2;
3157
3221
  try {
3158
- if (tx.transaction && status === "committed") {
3222
+ if (tx.transaction && outcome === "committed") {
3159
3223
  if (tx.transaction.options.usePhantomQuery) {
3160
3224
  await this.#withQuerySpanAndEvent(PHANTOM_COMMIT_QUERY(), tx.transaction, () => tx.transaction.commit());
3161
3225
  } else {
@@ -3185,7 +3249,7 @@ var TransactionManager = class {
3185
3249
  }
3186
3250
  }
3187
3251
  } finally {
3188
- tx.status = status;
3252
+ tx.status = outcome;
3189
3253
  clearTimeout(tx.timer);
3190
3254
  tx.timer = void 0;
3191
3255
  this.transactions.delete(tx.id);
@@ -3194,17 +3258,18 @@ var TransactionManager = class {
3194
3258
  this.closedTransactions.shift();
3195
3259
  }
3196
3260
  }
3261
+ return outcome;
3197
3262
  };
3198
3263
  if (tx.status === "closing") {
3199
3264
  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;
3265
+ this.#getActiveOrClosingTransaction(tx.id, requested === "committed" ? "commit" : "rollback");
3266
+ throw new TransactionInternalConsistencyError("Transaction still active after it was closed.");
3207
3267
  }
3268
+ const scopesClosed = this.#closeScopes(tx, tx.scopes, requested);
3269
+ return await Object.assign(tx, {
3270
+ status: "closing",
3271
+ closing: createClosingPromise(scopesClosed)
3272
+ }).closing;
3208
3273
  }
3209
3274
  #validateOptions(options) {
3210
3275
  if (!options.timeout) throw new TransactionManagerError("timeout is required");
@@ -3226,6 +3291,56 @@ var TransactionManager = class {
3226
3291
  });
3227
3292
  }
3228
3293
  };
3294
+ function innermostScope(tx) {
3295
+ return tx.scopes[tx.scopes.length - 1];
3296
+ }
3297
+ function popInnermostScope(tx) {
3298
+ const child = innermostScope(tx);
3299
+ tx.scopes.pop();
3300
+ const parent = innermostScope(tx);
3301
+ const moved = [...child.runningStatements];
3302
+ for (const statement of moved) {
3303
+ parent.runningStatements.add(statement);
3304
+ }
3305
+ child.runningStatements.clear();
3306
+ return { child, parent, moved };
3307
+ }
3308
+ function mergeInnermostScope(tx) {
3309
+ const { child, parent } = popInnermostScope(tx);
3310
+ child.mergedInto = parent;
3311
+ }
3312
+ function popRolledBackScope(tx) {
3313
+ const { parent, moved } = popInnermostScope(tx);
3314
+ for (const statement of moved) {
3315
+ void statement.then(() => currentScope(parent).runningStatements.delete(statement));
3316
+ }
3317
+ }
3318
+ function markClosing(scopes, reason) {
3319
+ for (const scope of scopes) {
3320
+ scope.closingReason = reason;
3321
+ }
3322
+ }
3323
+ async function statementsSettledOrCommitInterrupted(tx, running) {
3324
+ if (running.length === 0) return "committed";
3325
+ return await Promise.race([Promise.all(running).then(() => "committed"), tx.commitInterrupted]);
3326
+ }
3327
+ function closedTransactionError(tx, reason, operation) {
3328
+ switch (reason) {
3329
+ case "committed":
3330
+ return new TransactionClosedError(operation);
3331
+ case "rolled_back":
3332
+ return new TransactionRolledBackError(operation);
3333
+ case "nested_rolled_back":
3334
+ return new NestedTransactionRolledBackError(operation);
3335
+ case "timed_out":
3336
+ return new TransactionExecutionTimeoutError(operation, {
3337
+ timeout: tx.timeout,
3338
+ timeTaken: Date.now() - tx.startedAt
3339
+ });
3340
+ default:
3341
+ return assertNever(reason, "Unknown closing reason.");
3342
+ }
3343
+ }
3229
3344
  function createTimeoutIfDefined(cb, ms) {
3230
3345
  return ms !== void 0 ? setTimeout(cb, ms) : void 0;
3231
3346
  }
@@ -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": "8.1.0-dev.11",
3
+ "version": "8.1.0-dev.12",
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/driver-adapter-utils": "8.1.0-dev.11",
35
- "@prisma/param-graph": "8.1.0-dev.11",
36
- "@prisma/json-protocol": "8.1.0-dev.11",
37
- "@prisma/client-runtime-utils": "8.1.0-dev.11",
38
- "@prisma/debug": "8.1.0-dev.11",
39
- "@prisma/sqlcommenter": "8.1.0-dev.11"
34
+ "@prisma/debug": "8.1.0-dev.12",
35
+ "@prisma/client-runtime-utils": "8.1.0-dev.12",
36
+ "@prisma/driver-adapter-utils": "8.1.0-dev.12",
37
+ "@prisma/sqlcommenter": "8.1.0-dev.12",
38
+ "@prisma/param-graph": "8.1.0-dev.12",
39
+ "@prisma/json-protocol": "8.1.0-dev.12"
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": "8.1.0-dev.11",
47
- "@prisma/param-graph-builder": "8.1.0-dev.11"
46
+ "@prisma/get-dmmf": "8.1.0-dev.12",
47
+ "@prisma/param-graph-builder": "8.1.0-dev.12"
48
48
  },
49
49
  "files": [
50
50
  "dist"