Skip to content

Suggestion: using AsyncLocalStorage for transactions #5729

Closed

Description

@vdeturckheim

Problem

First, a disclaimer: AsyncLocalStorage is not available in all supported versions of Node.js yet but this can either be discussed for the future or there are ways of having similar APIs in older version sof Node.js depending on the choices made.

Right now (if I understand the doc well), to build a transaction, one must keep a list of writes and commit all of them at once at the end. So let's imagine in a web server, when the user wants all the db writes linked with the HTTP requests to be in the same transaction, they would have to do something like attaching an array to a request object or something like that, add all the writes to it and commit before the response with prisma.$transaction(...).

Suggested solution

Using an API like AsyncLocalStorage can give the following UX:

prisma.$openTransaction()
...
write_1
...
write_n
prisma.$commitTransaction() <- all the writes are automatically linked with the current transaction

This has a few shortcomings:

Alternatives

N/A

Additional context

So I am mostly trying the water to see if there would be interest and what would be the feedback over here on such feature :)

Activity

  1. added
    kind/feature
    tech/typescript
    bug/2-confirmed
    and removed
    bug/2-confirmed
    on Feb 18, 2021
  2. psteinroe commented on Mar 9, 2021

    @psteinroe

    +1

    We are currently using TypeORM and really want to migrate to prisma, but are still looking for a lean solution to handle transactions such as https://github.com/odavid/typeorm-transactional-cls-hooked is providing for TypeORM.

  3. sorenbs commented on Jun 14, 2021

    @sorenbs
    Member

    @vdeturckheim - I don't think you would need AsyncLocalStorage for something like this. As Node is single-threaded, it is safe to create a singleton array per request and append db actions to it. You could then execute them all in a transaction when the request ends. Does that make sense?

    @steinroe - When Prisma introduces support for long-running transactions, it should be possible to create a third-party library like cls-hooked. I don't think it is likely that this functionality will be included directly in Prisma. Does that make sense?

  4. vdeturckheim commented on Jun 15, 2021

    @vdeturckheim
    Author

    @sorenbs this forces you to always have access to this singleton array, meaning you need to pass a context with all function calls. The point of AsyncLocalStorage is to be able not to do that and provide a UX where the code would be the same inside and outside transactions.

  5. BertholetDamien commented on Jul 19, 2021

    @BertholetDamien

    I agree with the proposition. Without that, it will be impossible for us to migrate or even used Prisma in any production application. It's an essential feature to manage transactions correctly without programmation overhead.

    Other than that, Prisma fixes a lot of ORMs commons problems. I'm in love with what you've built, it's just amazing.

    Let me know if I can help you to provide this feature, it is really essential for all large applications.
    And Prisma deserves to be used by large applications.

  6. Papooch commented on Nov 3, 2021

    @Papooch

    It would be awesome to have this feature, it wouldn't be actually so hard to implement. At the time being, you can use cls-hooked or pure AsyncLocalStorage to leverage async context with transactions (similarly how Sequelize does it) (if you use NestJS, you can use nestjs-cls to do the same)

    /* cls setup */
    import * as cls from 'cls-hooked'
    export const transactionContext = cls.createNamespace('transaction-namespace')
    /* some service that initiates the transaction */
        // ...
        await this.prisma.$transaction(async (prisma) => {
            // store the transaction prisma client inside the context
            transactionContext.set('prisma', prisma);
            const result = await serviceThatSouldUseTransaction.doTheThing('something');
           // ... more code
        })
    /* service that should use transaction */
       // ...
       doTheThing(input: string) {
           // either reuse prisma client from context or use the default one
           const prisma = transactionContext.get('prisma') ?? this.prisma;
           // if the prisma client was retrieved form the context, the call will be run within the transaction
           return prisma.thing.findMany({ where: { what: input } })
       }

    In real application, you could of course abstract it and make it more type safe, but this is the gist.

    P.S. You need to enable interactive transactions to be able to pass a callback function to $transaction.

  7. matthewmueller commented on Feb 4, 2022

    @matthewmueller
    Contributor

    Thanks for your suggestions everyone! We solved this issue a few months ago with Interactive Transactions, which is now in Preview.

    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["interactiveTransactions"]
    }

    You can now pass a function to prisma.$transaction:

    await prisma.$transaction(async (prisma) => {
      // 1. Decrement amount from the sender.
      const sender = await prisma.account.update({
        data: {
          balance: {
            decrement: amount,
          },
        },
        where: {
          email: from,
        },
      })
      // 2. Verify that the sender's balance didn't go below zero.
      if (sender.balance < 0) {
        throw new Error(`${from} doesn't have enough to send ${amount}`)
      }
      // 3. Increment the recipient's balance by amount
      const recipient = prisma.account.update({
        data: {
          balance: {
            increment: amount,
          },
        },
        where: {
          email: to,
        },
      })
      return recipient
    })

    Use it wisely 😉

    If you have any feedback on this feature, please let us know in this issue. Now's a good time to give it a go, since we're actively resolving issues in preparation for making it Generally Available.

  8. 13 remaining items

  9. fuvidani commented on Jan 4, 2024

    @fuvidani

    Hey @renatoaraujoc, I believe I have most of it working. I need to finish a few remaining details. Once those are done and rigorous testing validates the solution, I'll share what I can. 😉

  10. renatoaraujoc commented on Jan 4, 2024

    @renatoaraujoc

    Hey @fuvidani, looks awesome, can't wait!

  11. codechikbhoka commented on Jan 7, 2024

    @codechikbhoka

    Waiting for Spring like magical @transactional :)

  12. Papooch commented on Jan 22, 2024

    @Papooch

    In the meantime (if you use NestJS), I released a new version of nestjs-cls with support for plugins together with a Transactional plugin and a Prisma adapter for it.

    The important part is that it does not try to monkey-patch the internals of any library, but still makes propagating the Prisma transaction as easy as:

    @Injectable()
    class UserService {
        constructor(
            @InjectTransaction()
            private readonly prismaTx: Transaction<TransactionalAdapterPrisma>,
            private readonly accountService: AccountService,
        ) {}
    
        @Transactional()
        async createUser(name: string): Promise<User> {
            const user = await this.prismaTx.user.create({ data: { name } });
            await this.accountService.createAccountForUser(user.id);
            return user;
        }
    }
    @Injectable()
    class AccountService {
        constructor(
            @InjectTransaction()
            private readonly prismaTx: Transaction<TransactionalAdapterPrisma>,
        ) {}
    
        async createAccountForUser(id: number): Promise<Account> {
            // if called within a transaction, `prismaTx` will reference the same transactional client
            return this.prismaTx.user.create({
                data: { userId: id, number: Math.random() },
            });
        }
    }
  13. fuvidani commented on Jan 24, 2024

    @fuvidani

    Hi @renatoaraujoc, @codechikbhoka, @nitedani and everybody else! Let me share our current working version. If you find any issues, please leave a comment! 🙇‍♂️

    Summary

    We achieve seamless tx propagation by

    • monkey-patching Prisma's $transaction(). On the top-level, we wrap the execution into an ALS context. Otherwise, we keep reusing the tx client from the ALS
    • creating a Proxy around PrismaClient. This ensures that an arbitrary this.prisma.todo.findFirst() uses the active tx client if available

    The @Transactional decorator only needs to check if it's being executed in an already running transaction context. To open a new transaction, it defers this responsibility to the patched and proxied Prisma.

    The Prisma Patch

    We can create a function that receives a PrismaClient, patches it and returns it.

    import { Prisma, PrismaClient } from '@prisma/client';
    import { ClsService, ClsServiceManager } from 'nestjs-cls';
    
    export const TX_CLIENT_KEY = 'txClient';
    
    export function patchPrismaTx<T extends PrismaClient>(prisma: T) {
      const original$transaction = prisma.$transaction;
      prisma.$transaction = (...args: unknown[]) => {
        if (typeof args[0] === 'function') {
          const fn = args[0] as (
            txClient: Prisma.TransactionClient
          ) => Promise<unknown>;
          args[0] = async (txClient: Prisma.TransactionClient) => {
            const clsService = ClsServiceManager.getClsService();
    
            const maybeExistingTxClient = clsService.get<
              Prisma.TransactionClient | undefined
            >(TX_CLIENT_KEY);
    
            if (maybeExistingTxClient) {
              console.log(`Return txClient from ALS`);
              return fn(maybeExistingTxClient);
            }
    
            if (clsService.isActive()) {
              // covering this for completeness, should rarely happen
              console.warn(`Context active without txClient`);
              return executeInContext({
                context: clsService,
                txClient,
                fn,
              });
            }
    
            // this occurs on the top-level
            return clsService.run(async () =>
              executeInContext({
                context: clsService,
                txClient,
                fn,
              })
            );
          };
        }
    
        return original$transaction.apply(prisma, args as any) as any;
      };
    
      return prisma;
    }
    
    type ExecutionParams = {
      context: ClsService;
      txClient: Prisma.TransactionClient;
      fn: (txClient: Prisma.TransactionClient) => Promise<unknown>;
    };
    
    
    async function executeInContext({ context, txClient, fn }: ExecutionParams) {
      context.set(TX_CLIENT_KEY, txClient);
    
      console.log(`Top-level: open context, store txClient and propagate`);
      try {
        return await fn(txClient);
      } finally {
        context.set(TX_CLIENT_KEY, undefined);
        console.log(`Top-level: ALS context reset`);
      }
    }

    The Prisma Proxy

    We're essentially making sure that

    • this.prisma.todo.findFirst() uses the active tx client if available
    • no matter how deep you nest prisma.$transaction() calls, they all receive the same client.
    export function createPrismaProxy<T extends PrismaClient>(target: T) {
      return new Proxy(target, {
        get(_, prop, receiver) {
          // provide an undocumented escape hatch to access the root PrismaClient and start top-level transactions
          if (prop === '$root') {
            console.log(`[Proxy] Accessing root Prisma`);
            return target;
          }
    
          const maybeExistingTxClient = ClsServiceManager.getClsService().get<
            Prisma.TransactionClient | undefined
          >(TX_CLIENT_KEY);
    
          const prisma = maybeExistingTxClient ?? target;
    
          if (
            prop === '$transaction' &&
            maybeExistingTxClient &&
            typeof target[prop] === 'function'
          ) {
            console.log(
              `[Proxy] $transaction called on a txClient, continue nesting it`
            );
    
            return function (...args: unknown[]) {
              // grab the callback of the native "prisma.$transaction(callback, options)" invocation and invoke it with the txClient from the ALS
              if (typeof args[0] === 'function') {
                return args[0](maybeExistingTxClient);
              } else {
                throw new Error(
                  'prisma.$transaction called with a non-function argument'
                );
              }
            };
          }
    
          return Reflect.get(prisma, prop, receiver);
        },
        // following traps needed to make the Proxy work with jest.spyOn()
        set(_, prop, newValue, receiver) {
          if (prop === '$transaction') {
            console.log(`Please don't spy on $transaction.`);
            return false;
          }
    
          const maybeExistingTxClient = ClsServiceManager.getClsService().get<
            Prisma.TransactionClient | undefined
          >(TX_CLIENT_KEY);
    
          const prisma = maybeExistingTxClient ?? target;
          return Reflect.set(prisma, prop, newValue, receiver);
        },
        defineProperty(_, prop, attributes) {
          const maybeExistingTxClient = ClsServiceManager.getClsService().get<
            Prisma.TransactionClient | undefined
          >(TX_CLIENT_KEY);
    
          const prisma = maybeExistingTxClient ?? target;
          return Reflect.defineProperty(prisma, prop, attributes);
        },
      });
    }

    Putting it together

    All we need to do is make sure that the Prisma client we're using in our application is patched and proxied properly. In this example, I assume a Nest PrismaService that is used across the application an a singleton.

    @Injectable()
    export class PrismaService extends PrismaClient {
      constructor() {
        super();
    
        const patchedPrisma = patchPrismaTx(new PrismaClient());
    
        return createPrismaProxy(patchedPrisma);
      }
    }

    Transactional Decorator

    With the patched Prisma in place, the decorator's only responsibilities are to:

    • make sure PrismaService is available (Inject)
    • check if it's being executed in an active ALS context with a tx client
    • "request" a real transaction by accessing the $root Prisma. The patch will take care of setting up the ALS context
    export function Transactional(
      isolationLevel?: Prisma.TransactionIsolationLevel
    ): MethodDecorator {
      const injectPrisma = Inject(PrismaService);
    
      return (
        target: any,
        propertyKey: string | symbol,
        descriptor: PropertyDescriptor
      ) => {
        injectPrisma(target, 'prismaClient');
    
        const originalMethod = descriptor.value;
    
        descriptor.value = async function (...args: unknown[]) {
          const cls = ClsServiceManager.getClsService();
    
          if (cls.get(TX_CLIENT_KEY)) {
            // A transaction has already been started. Just call the function.
            // The top-level wrapper will take care of resetting the context.
            console.log('Already running in an active transaction');
            return originalMethod.apply(this, [...args]);
          }
    
          const prisma = (this as any).prismaClient as PrismaService;
    
          // defer the context setup to the patched prisma
          return (prisma['$root'] as PrismaClient).$transaction(
            async () => {
              return originalMethod.apply(this, [...args]);
            },
            {
              isolationLevel,
            }
          );
        };
      };
    }

    Limitations

    • No support for nested, isolated transactions. This version will either wrap everything or nothing. This should already cover the majority of cases. Nested, isolated transactions (preferably via CHECKPOINTs) are future work.
    • You might notice that the patch does not take the array-based $transaction([]) usage into account. This is a conscious design decision. It's practically a legacy way of serially executing statements, most of us use the interactive transactions (callbacks) anyway. If you still need to support it, you should implement the handling.
    • Spying on prisma.$transaction() is a no-go. The patch and the proxy are essential to make the propagation work. If you have tests where you change the behavior of $transaction() via Jest, it's going to break it. I'm going to leave it up to you to decide if it's a good practice to spy directly on a low-level operation like prisma.$transaction() on a day-to-day basis. Just be aware of the limitation.

    Please leave feedback if you notice anything. 🙇‍♂️ Have fun! 🥳

  14. Shahor commented on Jan 25, 2024

    @Shahor

    Wow :O

    I had plans to implement exactly that on my nestjs codebase so this comment is an actual godsend!

    @fuvidani Thank you so much for sharing with everyone, I'm sure it'll benefit the whole community!

  15. adamlamaa commented on Mar 7, 2024

    @adamlamaa

    @fuvidani Been looking for a solution to handle prisma transactions in a clean way in NestJS, and at the bottom of my rabithole I have found your solution. Thank you for sharing, really awesome of you 💙

    Bit new to NestJS still so appoligies if my follow up questions to your suggestion seem basic.

    1. Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
      (As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).

    2. I am unsure of how to use the decorator, would something like below be correct usage of it?

    export class UserService {
    
    	constructor(private prismaService: PrismaService){}
    
    	@Transactional()
    	public updateUser(data){
    		this.prismaService.user.update(...);
    		this.prismaService.log.create(...);
    	}
    }
    
    1. If I had a UserRepository would this be a correct usage?
    export class UserService {
    
    	constructor(
    		private userRepository: UserRepository, 
    		private logService: LogService
    	){}
    
    	@Transactional()
    	public updateUser(data){
    		this.userRepository.update(...);
    		this.logService.log(...);
    	}
    }
    
    export class UserRepository {
    
    	constructor(private prismaService: PrismaService){}
    
    	public update(data){
    		this.prismaService.user.update(...);
    	}
    }
    
  16. myfunc commented on Apr 6, 2024

    @myfunc

    @fuvidani
    Faced with the issue:
    When I trying access PrismaClient in debugger (VSCode) - debug server freezes.

    As "access". Even "get" reading in "VSCode/Variables" panel makes UI frozen.

    My guess, it happens when debugger tries get prisma, and createPrismaProxy returns something that node.js debugger doesn't expcect.

  17. myfunc commented on Apr 6, 2024

    @myfunc

    @fuvidani Faced with the issue: When I trying access PrismaClient in debugger (VSCode) - debug server freezes.

    As "access". Even "get" reading in "VSCode/Variables" panel makes UI frozen.

    My guess, it happens when debugger tries get prisma, and createPrismaProxy returns something that node.js debugger doesn't expcect.

    Added console.log and noticed that "Symbol()" is read just before freezing.
    image

  18. myfunc commented on Apr 6, 2024

    @myfunc

    PrismaClient has property with unknown for me Symbol key.
    When debugger tries to read that it falls to an infinity loop.
    I guess, the same happens when I tring to log value of the property.
    image

    After a 1-2 minutes console.log writes an extremely long stack trace.
    That part repeates many times:
    image

    Also related issue: #21615

  19. myfunc commented on Apr 6, 2024

    @myfunc

    Updating to "@prisma/client": "^5.12.1", fixed a problem

  20. fuvidani commented on Apr 23, 2024

    @fuvidani

    @fuvidani Been looking for a solution to handle prisma transactions in a clean way in NestJS, and at the bottom of my rabithole I have found your solution. Thank you for sharing, really awesome of you 💙

    Bit new to NestJS still so appoligies if my follow up questions to your suggestion seem basic.

    1. Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
      (As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).
    2. I am unsure of how to use the decorator, would something like below be correct usage of it?
    export class UserService {
    
    	constructor(private prismaService: PrismaService){}
    
    	@Transactional()
    	public updateUser(data){
    		this.prismaService.user.update(...);
    		this.prismaService.log.create(...);
    	}
    }
    
    1. If I had a UserRepository would this be a correct usage?
    export class UserService {
    
    	constructor(
    		private userRepository: UserRepository, 
    		private logService: LogService
    	){}
    
    	@Transactional()
    	public updateUser(data){
    		this.userRepository.update(...);
    		this.logService.log(...);
    	}
    }
    
    export class UserRepository {
    
    	constructor(private prismaService: PrismaService){}
    
    	public update(data){
    		this.prismaService.user.update(...);
    	}
    }
    

    Hi @adamlamaa! 👋 Apologies for the delayed response 😔

    1. Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
      (As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).

    Of course! The beauty of the decorator is that it can be freely nested/composed. If you check its implementation you'll see that if the decorator detects an active tx client in the call-chain, it simply executes the decorated method: any prisma command later on will automatically reuse the same tx client.

    About where to place the decorators: we have cases where we use it on a repository method. For instance you could have a model backed by 2 tables that are kept in sync: a read-optimized and an append-only one for historization. The double-table approach is abstracted by the repository, and the @Transactional decorator on writing methods ensure atomicity across the two tables.

    Nevertheless, you're right that most of the time the decorator finds its usage on the service layer because it is the layer responsible for fulfilling use-cases, orchestrating changes across different models (== tables).

    Warning: isolation levels

    In case you're familiar with isolation levels and apply them consciously, be aware that the automatic transaction propagation affects them too. If you compose multiple service methods that have the decorator on top but with different isolation levels, the top-level one will be applied, always. This is because in most databases you cannot change the isolation level of a transaction as soon as the first query statement is executed. Note: It can only become an issue if you have an inner method decorated with a stricter isolation level than the top-level one. Let me know if this is not clear and I can provide a deeper explanation. 🙇‍♂️

    1. I am unsure of how to use the decorator, would something like below be correct usage of it?

    Yes, perfect!

    1. If I had a UserRepository would this be a correct usage?

    Works too!

    Btw., you can test atomicity by calling several repository operations from your updateUser method, but before it returns, add throw new Error(). With a Jest test you can verify that the number of rows in the corresponding tables remained the same before and after the execution (i.e. the tx rolled back everything). 😉

  21. myfunc commented on May 12, 2024

    @myfunc

    I successfully used that approach with minor changes and fixes in the production project for a site with 2-5k online.
    But there are a problems.

    Warning: undesired transaction wrapping

    In a team of 2+ developers, code is being changed, and there is a case when another developer adds a new prisma query to the service's method that could be executed in the @transactional stack.

    For example, I have the method createGame (block 1), which is called by service (block 2).

    // GameService
      async createGame(game: CreateGameArgs) {
        const data = await this.prismaService.pvpGame.create({
          data: {
            ...game,
            state: GameState.IN_PROGRESS,
          },
        });
        // tslint:disable:no-floating-promises
        this.setCurrentGame(data);
        return data;
      }
    // UserGameService
      @Transactional()
      private async startNewGame(futureBlock?: number, user: User) {
        const currentBlock = await this.eosService.getCurrentBlock();
        if (!futureBlock || futureBlock <= currentBlock.block_num) {
          futureBlock = (await this.waitAnyNextBlock()).future_block_num;
        }
        const game = await this.gameService.createGame({ // Calling method from previous block
          secret: this.generateSecret(),
          futureBlock,
          userId: user.id
        });
    
        return game;
      }

    All seems to be good. But if another developer decides inside of GameService verify that the user isn't blacklisted (just an example).
    verifyUserOrThrow method can be implicitly executed inside of a transaction,
    That call may execute many queries to $transactions that can lead to deadlocks caused by attempts to read/update locked DB rows.

    // GameService
      async createGame(game: CreateGameArgs) {
        await this.userService.verifyUserOrThrow(game.user); // Dangerous code!!!. Can be executed inside of transaction.
        const data = await this.prismaService.pvpGame.create({
          data: {
            ...game,
            state: GameState.IN_PROGRESS,
          },
        });
        // tslint:disable:no-floating-promises
        this.setCurrentGame(data);
        return data;
      }

    I wondering how to use that decorator in a safe way.
    Currently, I am thinking about an eslint extension that will highlight prisma calls that are inside of possible transactions or another way to make nested queries forbidden with no special decorator or method's call.

  22. myfunc commented on Jun 10, 2024

    @myfunc

    I decided to publish my solution with "@PrismaTransactional" decorator that contains a code from the thread shared by @fuvidani.
    Thank you!

    That decorator is actively used on production with no issues, but I don't recomment to use it without understanding what happens under the good.

    Feel free to try, leave feedback or contribute.

    https://github.com/myfunc/prisma-transactional

  23. guipfernandes commented on Mar 31, 2025

    @guipfernandes

    Hey guys, putting my two cents in this topic, here is my current working implementation using NestJS. I used as a reference other implementations mentioned here and in other issues, thanks everyone!
    My solution involves

    • A decorator to create a transactional block
    • Allow running subtransactions nested or not (I only implemented two types of propagation, which are the ones I need right now)
    • The possibility to run a callback after the current transaction succeeds, useful for event dispatching.

    The interface

    export interface AtomicExecutor {
        runAtomically<R>(callback: () => Promise<R>, propagation?: Propagation): Promise<R>;
    
        /**
         * Run the given callback after the current atomic execution succeeds.
         */
        defer(callback: () => void): void;
    }
    
    export abstract class AtomicExecutor {}
    
    export enum Propagation {
        /**
         * If a transaction exists, it executes within that transaction. Otherwise, creates a new transaction.
         */
        REQUIRED,
        /**
         * If a transaction exists, it creates an inner independent transaction. Otherwise, creates a new transaction.
         */
        NESTED,
    }
    
    export function Transactional(propagation?: Propagation): MethodDecorator {
        const injectAtomicExecutor = Inject(AtomicExecutor);
    
        return (target: NonNullable<unknown>, _, descriptor: PropertyDescriptor) => {
            injectAtomicExecutor(target, 'atomicExecutor');
    
            const originalMethod = descriptor.value as (...args: unknown[]) => Promise<unknown>;
    
            // eslint-disable-next-line no-param-reassign -- Needed for the decorator
            descriptor.value = async function atomic(...args: unknown[]) {
                const {atomicExecutor} = this as {atomicExecutor: AtomicExecutor};
    
                return atomicExecutor.runAtomically(() => originalMethod.apply(this, args), propagation);
            };
        };
    }

    The implementation

    export type ProviderState = {
        transaction: PrismaService;
        rootPromise: Promise<unknown>;
    };
    
    @Injectable()
    export class PrismaProvider implements AtomicExecutor {
        constructor(
            private readonly prisma: PrismaService,
            private readonly contextStore: AsyncLocalStorage<ProviderState>
        ) {}
    
        get client(): PrismaService {
            return this.contextStore.getStore()?.transaction ?? this.prisma;
        }
    
        /**
         * Runs the callback within a transaction context.
         */
        async runAtomically<R>(callback: () => Promise<R>, propagation: Propagation = Propagation.REQUIRED): Promise<R> {
            const currentState = this.contextStore.getStore();
    
            if (currentState != null) {
                if (propagation === Propagation.NESTED) {
                    return runSubTransaction(currentState.transaction, callback);
                }
    
                return callback();
            }
    
            const promise: Promise<R> = this.prisma.$transaction(
                (transaction) =>
                    this.contextStore.run(
                        {
                            transaction: createTransactionProxy(transaction),
                            rootPromise: promise,
                        },
                        callback
                    )
            );
    
            return promise;
        }
    
        defer(callback: () => void): void {
            const state = this.contextStore.getStore();
    
            if (state === undefined) {
                callback();
    
                return;
            }
    
            state.rootPromise
                .then(() => this.contextStore.exit(callback))
                .catch(() => {
                    // Errors should be handled by the root promise or the callback itself
                });
        }
    }
    
    export function createTransactionProxy<T extends Prisma.TransactionClient>(transaction: T): PrismaService {
        return new Proxy(transaction, {
            get(_, prop, receiver) {
                if (prop === '$transaction') {
                    return async function $transaction(...args: unknown[]) {
                        if (typeof args[0] === 'function') {
                            const callback = args[0] as (transaction: Prisma.TransactionClient) => Promise<unknown>;
                            const options = args[1] as {propagation?: Propagation};
    
                            if (options?.propagation === Propagation.NESTED) {
                                return runSubTransaction(transaction, () => callback(transaction));
                            }
    
                            return callback(transaction);
                        }
    
                        if (Array.isArray(args[0])) {
                            const promises = args[0] as Array<Prisma.PrismaPromise<unknown>>;
                            const options = args[1] as {propagation?: Propagation};
    
                            if (options?.propagation === Propagation.NESTED) {
                                return runSubTransaction(transaction, () => Promise.all(promises));
                            }
    
                            return Promise.all(promises);
                        }
    
                        throw new Error('Unsupported $transaction call');
                    };
                }
    
                if (typeof prop === 'string' && !(prop in transaction)) {
                    throw new Error(`Method "${prop}" is not allowed within a transaction context`);
                }
    
                return Reflect.get(_, prop, receiver);
            },
        }) as unknown as PrismaService;
    }
    
    async function runSubTransaction<T>(transaction: Prisma.TransactionClient, callback: () => Promise<T>): Promise<T> {
        const savepointName = randomUUID();
    
        await transaction.$executeRawUnsafe(`SAVEPOINT "${savepointName}";`);
    
        try {
            const result = await callback();
    
            await transaction.$executeRawUnsafe(`RELEASE SAVEPOINT "${savepointName}";`);
    
            return result;
        } catch (e) {
            await transaction.$executeRawUnsafe(`ROLLBACK TO "${savepointName}";`);
    
            throw e;
        }
    }

    Prisma service

    @Injectable()
    export class PrismaService extends PrismaClient implements OnModuleInit {
        async onModuleInit(): Promise<void> {
            await this.$connect();
        }
    
        $transaction<P extends Array<Prisma.PrismaPromise<unknown>>>(
            arg: [...P],
            options?: {isolationLevel?: Prisma.TransactionIsolationLevel; propagation?: Propagation}
        ): Promise<runtime.Types.Utils.UnwrapTuple<P>>;
    
        $transaction<R>(
            fn: (prisma: Omit<PrismaClient, runtime.ITXClientDenyList>) => Promise<R>,
            options?: {
                maxWait?: number;
                timeout?: number;
                isolationLevel?: Prisma.TransactionIsolationLevel;
                propagation?: Propagation;
            }
        ): Promise<R>;
    
        $transaction(input: never, options?: never) {
            return super.$transaction(input, options);
        }
    }

    The usage

    Repository

    export abstract class PrismaRepository {
        constructor(protected readonly prismaProvider: PrismaProvider) {}
    
        protected get prisma(): PrismaService {
            return this.prismaProvider.client;
        }
    }
    
    @Injectable()
    export class ProductPrismaRepository extends PrismaRepository implements ProductRepository {
        constructor(
            protected readonly prismaProvider: PrismaProvider
        ) {
            super(prismaProvider);
        }
    
        async save(product: Product): Promise<void> {
            await this.prisma.product.upsert(...);
    
            await this.prisma.$transaction(async (prisma) => {
                await prisma.saleItem.upsert(...);
                await prisma.productStock.upsert(...);
            });
        }
    
        async safeDelete(): Promise<void> {
            const where = {...};
            try {
                /**
                 * A nested transaction is required so that the delete operation, when it fails for a foreign key violation,
                 * does not abort a parent transaction if one exists.
                 */
                await this.prisma.$transaction(
                    async (prisma) => {
                        await prisma.product.delete(where);
                    },
                    {
                        propagation: Propagation.NESTED,
                    }
                );
            } catch (e) {
                if (this.checkForeignKeyViolation(e)) {
                    await prisma.product.update({
                        where: where,
                        data: {
                            deletedAt: new Date(),
                        },
                    });
    
                    return;
                }
    
                throw e;
            }
        }
    }

    Service

    @Injectable()
    export class ProductService {
        constructor(
            private readonly productRepository: ProductRepository,
            private readonly atomicExecutor: AtomicExecutor,
            protected readonly eventDispatcher: EventDispatcher
        ) {}
    
        @Transactional()
        async doStuff(payload): Promise<void> {
            const product = new Product(payload);
    
            await this.productRepository.save(product);
            await this.doThingsInSameTransaction();
            await this.doThingsInNestedTransaction();
            this.atomicExecutor.defer(() => {
                // Only will be executed after parent transaction is committed, if the safeDelete below fails, this will not be executed.
                this.eventDispatcher.dispatch(product.getEvents());
            });
            await this.productRepository.safeDelete(product);
        }
    
        @Transactional()
        async doThingsInSameTransaction(): Promise<void> {
            ...
        }
    
        @Transactional(Propagation.NESTED)
        async doThingsInNestedTransaction(): Promise<void> {
            ...
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featuretech/typescripttopic: transaction

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions