Skip to content

Does Prisma offer Transactions across multiple files? #12975

Open

Description

@jaequery

Discussed in #12974

Originally posted by jaequery April 23, 2022
Coming from TypeORM, I am surprised to see that Prisma does not have any way to perform transactions in a similar way TypeORM does.

With TypeORM and the transactional-cls-hooked decorator, we can do such as:

@Transactional()
async updateManyThings() {
   await this.productService.updateStuff();
   await this.categoryService.updateAnotherStuff();
   await this.customerService.changeOtherStuff();
}

This allows so that if there is an error on any of the service calls, it'd safely rollback.

Does Prisma offer anything close to that? Only thing that I've come across is to perform the operation all inside a single method, which is not all that useful for us, as we rely heavily on using service files to perform mutable operations respectively.

Activity

  1. jaequery commented on Apr 24, 2022

    @jaequery
    Author

    https://www.prisma.io/docs/concepts/components/prisma-client/transactions

    I think this is what you need.

    I am not sure if any of them works across different files but do correct me if I'm wrong.

  2. kasir-barati commented on Apr 26, 2022

    @kasir-barati

    Any thought on doing this @jaequery, @salvajavier: Returning $transaction to the user and pass it to the API interface as a argument. Something like this:

    const transactionObj = prisma.createTransaction();
    const user = await prisma.user.create({
      data: {
        email: '[email protected]',
        name: 'Elsa Prisma',
      },
      { transactions: transactionObj }
    })
    const temp = prisma.temp.update({ where: { id: 1}, data: {f1: 1},  { transactions: transactionObj }})
  3. salvajavier commented on Apr 26, 2022

    @salvajavier

    @jaequery, @kasir-barati I think the point is that you cannot return a transaction built in another function because if you do it just run. So as the prisma.transaction$ functions receives an array as argument I do this:

    async function mainFunction(){
    
        //This function can be anywhere an returns an array of transactions.
        let prismaExternalOperations = await getPrismaOperation() 
    
        let prismaLocalOperation= prisma.product.update()
       
        // Use the spread operator to pass to prisma.transactions$ function all the arguments
        // returned from getPrismaOperation 
        prisma.transactions$([prismaLocalOperation, ...prismaExternalOperations])
    }
    
    
    function prismaOperation (data) {
        let transactions$ = []
    
        let firstTransaction = prisma.customer.create({data})
        let secondTransaction = prisma.local.create({data})
    
        transactions$.push(firstTransaction, secondTransaction)
    
        // Instead of returning the prisma operation you wrap them into an array so they can be returned without executing.
        return transactions$
    }
    
  4. ramiresdallago commented on Aug 10, 2022

    @ramiresdallago

    I'm facing this same problem. I created repositories for each of my database entities, to be able to isolate the prism of my use cases. But in services where I need to interact with different repositories, I get stuck in not being able to control the transaction of the repositories' methods, in a centralized way.

    Is there any existing way to resolve this?

  5. adrian-goe commented on Sep 20, 2022

    @adrian-goe

    Hi, I'm from the Issues #12458 @millsp said I should look there for other issues.

    I am working in a NestJs project with the CleanArchitecture. That means, we have our business logic in a domain layer and call single accessors from there, which then call prisma functions around a model (e.g. user).

    Since we have business logic that needs to access multiple accessors, we can't use the callback transaction at all.

    Here is a super simplified example:

    @Injectable()
    export class UserAccessor {
      constructor(private prismaClient: PrismaClient) {
      }
    
      async create(...): Promise<User> {
        return this.prismaClient.user.create(...)
      }
    }
    
    @Injectable()
    export class SettingsAccessor {
      constructor(private prismaClient: PrismaClient) {
      }
    
      async create(user: User): Promise<Settings> {
        return this.prismaClient.userSettings.create(...)
      }
    }
    
    
    @Injectable()
    export class UserDomain {
      constructor(private readonly userAccessor: UserAccessor,
                  private readonly settingsAccessor: SettingsAccessor,
      ) {
      }
    
      async createUser(...) {
        // start Transaction
        const user = await this.userAccessor.create(...)
        // maybe more stuff done between this accessor calls
        const settings = await this.settingsAccessor.create(user)
        // end Transaction
      }
    }

    As @sijakubo pointed this out in the other Issue, Java/Spring/Hibernate uses this too in form of the @Transactional() Annotation around a service or function and also in tests. Spring Transaction Management: @Transactional In-Depth

    This Topic is also Discussed in #13004

  6. roberto-souza commented on Oct 5, 2022

    @roberto-souza

    I have the same problem. I use CleanArchitecture and I can't work with transactions.

  7. jaequery commented on Oct 5, 2022

    @jaequery
    Author

    I don't have the time to understand the internals of Prisma but I believe such feature can work by utilizing a series of hooks and event emitters. Has anyone from Prisma attempted to replicate the @transactional() decorator? I'm curious if there is some kind of a technological blocker that makes it impossible atm.

  8. Rykuno commented on Oct 12, 2022

    @Rykuno

    I'll add onto this. Utilizing NestJS and cannot utilize transactions across multiple services.

  9. callumthomson commented on Feb 8, 2023

    @callumthomson

    Also looking for a solution to this. No way, it seems, to create a transaction which contains Prisma client invocations inside other classes. Also using NestJS

  10. 16 remaining items

  11. yigitahmetsahin commented on Dec 17, 2023

    @yigitahmetsahin

    @Kainar01 would be nice if you can also share your solution so that we can get benefit of the alternative approach to this problem rather than limiting it to request context.

  12. yigitahmetsahin commented on Jan 2, 2024

    @yigitahmetsahin

    @Kainar01 any update from your solution which can work without context of a request?

  13. Kainar01 commented on Jan 2, 2024

    @Kainar01

    Happy new year all!

    @yigitahmetsahin sorry for taking long. Here is the snippet I use.

    I created context manager with async_hooks

    import { AsyncLocalStorage } from 'async_hooks';
    import { PrismaClient } from '@prisma/client';
    import { ITXClientDenyList } from '@prisma/client/runtime/library';
    
    export type PrismaTransactionClient = Omit<PrismaClient, ITXClientDenyList>;
    
    type Context = {
      transaction: PrismaTransactionClient;
    };
    
    export class TransactionContextService {
      private static readonly cls = new AsyncLocalStorage<Context>();
    
      static getTransaction() {
        const context = this.getContext();
    
        return context?.transaction;
      }
    
      private static getContext(): Context | undefined {
        return this.cls.getStore();
      }
    
      static async runInContext<T>(tx: PrismaTransactionClient, handler: () => Promise<T>): Promise<T> {
        return this.cls.run({ transaction: tx }, handler);
      }
    }

    And created extended prisma client

    import { Prisma, PrismaClient } from '@prisma/client';
    
    import { TransactionContextService } from './transaction-context.service';
    
    /**
     * This function creates a new transaction if there is none in the current context.
     * It will commit the transaction if it completes successfully, or abort if an error is encountered.
     * @param {PrismaClient} client - The PrismaClient instance.
     * @param {Function} handler - The function that will be performed within the transaction.
     * @return {Promise<T>} - The result of the transaction.
     */
    async function performTransaction<T>(client: PrismaClient, handler: () => Promise<T>) {
      if (TransactionContextService.getTransaction()) {
        return handler();
      }
    
      return client.$transaction(async (tx) => TransactionContextService.runInContext(tx, handler));
    }
    
    function createExtendedPrismaClient(options?: Prisma.PrismaClientOptions) {
      const client = new PrismaClient(options);
    
      return client.$extends({
        client: {
          async $transaction<T>(handler: () => Promise<T>) {
            return performTransaction(client, handler);
          },
        },
        query: {
          $allModels: {
            $allOperations({ model, operation, args, query }) {
              const tx = TransactionContextService.getTransaction();
    
              if (tx) {
                // eslint-disable-next-line @typescript-eslint/no-unsafe-call
                return tx[model][operation](args);
              }
    
              return query(args);
            },
          },
        },
      });
    }
    
    export type IExtendedPrismaClient = new (options?: Prisma.PrismaClientOptions) => PrismaClient & {
      $transaction: <T>(handler: () => Promise<T>) => Promise<T>;
    };
    
    export const ExtendedPrismaClient = class {
      constructor(options?: Prisma.PrismaClientOptions) {
        // eslint-disable-next-line no-constructor-return
        return createExtendedPrismaClient(options);
      }
    } as IExtendedPrismaClient;

    Initiate as regular prisma client and use it in code as this:

     this.prisma.$transaction(async () => {
      await this.prisma.account.create(); // transaction taken from context
    })
  14. yigitahmetsahin commented on Jan 2, 2024

    @yigitahmetsahin

    @Kainar01 thanks for sharing this detailed answer. I have one question, you are using AsyncLocalStorage for storing the transaction context. How this can work without request? Because as far as i know async local storage is only present if there is a request.

  15. Kainar01 commented on Jan 2, 2024

    @Kainar01

    @yigitahmetsahin from the nestjs docs

    It is similar to a thread-local storage in other languages.

    It is not necessarily bound to request

  16. renatoaraujoc commented on Jan 2, 2024

    @renatoaraujoc

    I just wanted to give me 2 cents on this topic because the absence of @transactional decorator is also being very damaging to my clean architecture application here.

    The reality is that every single solution presented here "solves" one or another use case, the ideal world is where we could control the transactions on method level by passing properties like Spring Framework does, it's the gold standard.

    TypeORM folks have developed a literal copy of this functionality here:

    https://www.npmjs.com/package/typeorm-transactional

    The idea is to simply copy their idea and do this via AsyncLocalStorage or nest-cls package, considering all the options.

    Unfortunately I'm running against time else I'd spend some days trying to implement this myself.

  17. kasir-barati commented on Jan 2, 2024

    @kasir-barati

    @renatoaraujoc can you share some link to the way that "Spring Framework" handles transaction in the way you have explained it. Btw I don't remember that typeorm-transactional decorator gives you the ability to pass properties to it.

    I also didn't get what you meant by properties, do you mean like passing entities as prop to indicate which tables should be included in the transaction. 🤔

  18. jaequery commented on Jan 2, 2024

    @jaequery
    Author

    by looking at the source code of the TypeORM transactional repo, it looks like they are using EventEmitters to signal start and end of transaction.

    I just used ChatGPT to help write something up here but i think something like this can work:

    import { PrismaClient } from '@prisma/client';
    const prisma = new PrismaClient();
    
    // Transactional decorator
    function Transactional() {
      return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;
    
        descriptor.value = async function (...args: any[]) {
          return await prisma.$transaction(async (transaction) => {
            // Add transaction to the Prisma context for this execution
            const contextWithTransaction = { ...this, prisma: transaction };
    
            // Call the original method with the transaction context
            return await originalMethod.apply(contextWithTransaction, args);
          });
        };
    
        return descriptor;
      };
    }
    
    class MyService {
      // The service methods don't need to be aware of transactions
      @Transactional()
      async myMethod() {
        const data1 = await this.otherService.method();
        const data2 = await this.otherService2.method();
        const data3 = await this.otherService3.method();
        
        return this.findById(x);
      }
    }
    
  19. renatoaraujoc commented on Jan 4, 2024

    @renatoaraujoc

    @renatoaraujoc can you share some link to the way that "Spring Framework" handles transaction in the way you have explained it. Btw I don't remember that typeorm-transactional decorator gives you the ability to pass properties to it.

    I also didn't get what you meant by properties, do you mean like passing entities as prop to indicate which tables should be included in the transaction. 🤔

    @kasir-barati hey,

    Their @transactional decorator is very much like Spring Framework's one, they accept the same isolation/propagation methods, etc, see:

    https://github.com/Aliheym/typeorm-transactional/blob/master/src/decorators/transactional.ts

    The options:

    export interface WrapInTransactionOptions {
      /**
       * For compatibility with `typeorm-transactional-cls-hooked` we use `connectionName`
       */
      connectionName?: DataSourceName;
    
      propagation?: Propagation;
    
      isolationLevel?: IsolationLevel;
    
      name?: string | symbol;
    }

    I believe we don't need such "perfect" Spring-like functionality, but implementing isolation and propagation should be pretty standard when the basic decorator is up. nest-cls package should be enough to implement this (or let the user pass their favorite thread-like runner like AsyncLocalStorage.

  20. renatoaraujoc commented on Jan 4, 2024

    @renatoaraujoc

    by looking at the source code of the TypeORM transactional repo, it looks like they are using EventEmitters to signal start and end of transaction.

    I just used ChatGPT to help write something up here but i think something like this can work:

    import { PrismaClient } from '@prisma/client';
    const prisma = new PrismaClient();
    
    // Transactional decorator
    function Transactional() {
      return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;
    
        descriptor.value = async function (...args: any[]) {
          return await prisma.$transaction(async (transaction) => {
            // Add transaction to the Prisma context for this execution
            const contextWithTransaction = { ...this, prisma: transaction };
    
            // Call the original method with the transaction context
            return await originalMethod.apply(contextWithTransaction, args);
          });
        };
    
        return descriptor;
      };
    }
    
    class MyService {
      // The service methods don't need to be aware of transactions
      @Transactional()
      async myMethod() {
        const data1 = await this.otherService.method();
        const data2 = await this.otherService2.method();
        const data3 = await this.otherService3.method();
        
        return this.findById(x);
      }
    }
    

    @jaequery it's a good start but it's not as simple as that since we can have @transactional methods that call other @transactional annotated methods, that's where the propagation kicks in.

    In reality, you have to work with a proxied prisma object that will return the proper prisma object or the transaction object given if we're in a transaction and it's propagation.

  21. yigitahmetsahin commented on Jan 30, 2024

    @yigitahmetsahin
  22. YahiaBadr commented on Jul 18, 2024

    @YahiaBadr

    any update on this issue guys?? i am facing the same problem with clean architecture.

  23. m1than commented on Jan 6, 2025

    @m1than

    I have solved it like this:

    import { AsyncLocalStorage } from 'async_hooks'
    import { Prisma, PrismaClient } from '@prisma/client'
    
    export type PrismaTransactionClient = PrismaClient
    
    interface Context {
      transaction: PrismaTransactionClient
    }
    
    export class TransactionContext {
      private static readonly cls = new AsyncLocalStorage<Context>()
    
      static getTransaction(): PrismaTransactionClient | undefined {
        const context = this.getContext()
    
        return context?.transaction
      }
    
      private static getContext(): Context | undefined {
        return this.cls.getStore()
      }
    
      static async runInContext<T>(tx: PrismaTransactionClient, handler: () => Promise<T>): Promise<T> {
        return this.cls.run({ transaction: tx }, handler)
      }
    }
    
    // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
    async function performTransaction<T>(client: PrismaClient, handler: () => Promise<T>) {
      if (TransactionContext.getTransaction()) {
        return handler()
      }
    
      return client.$transaction(async (tx: PrismaTransactionClient) => TransactionContext.runInContext(tx, handler))
    }
    
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types,@typescript-eslint/explicit-function-return-type
    export function createExtendedPrismaClient(options?: Prisma.PrismaClientOptions) {
      const client = new PrismaClient(options)
    
      return client.$extends({
        client: {
          async $transaction<T>(handler: () => Promise<T>) {
            return performTransaction(client, handler)
          },
        },
        query: {
          $allModels: {
            $allOperations({ model, operation, args, query }) {
              const tx = TransactionContext.getTransaction()
              if (tx) {
                const lowerCaseModel = (model.charAt(0).toLowerCase() + model.slice(1)) as keyof PrismaTransactionClient
    
                const modelOperations = tx[lowerCaseModel] as unknown as Record<string, (args: unknown) => Promise<unknown>>
    
                if (modelOperations && operation in modelOperations) {
                  return modelOperations[operation](args)
                }
              }
    
              return query(args)
            },
          },
        },
      })
    }
    
    
    
    export type IExtendedPrismaClient = new (options?: Prisma.PrismaClientOptions) => PrismaClient & {
      $transaction: <T>(handler: () => Promise<T>) => Promise<T>
    }
    
    import { Prisma } from '@prisma/client'
    import { IExtendedPrismaClient, createExtendedPrismaClient } from './transaction-context'
    
    export const ExtendedPrismaClient = class {
      constructor(options?: Prisma.PrismaClientOptions) {
        // eslint-disable-next-line no-constructor-return
        return createExtendedPrismaClient(options)
      }
    } as IExtendedPrismaClient
    
    
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

    topic: $transactiontopic: transaction

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions