You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Does Prisma offer Transactions across multiple files? #12975
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:
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.
Reacted by Roberto Souza, Carlo Corradini, Leandro Costa, phineasla, Daniel Daukševič, norberg88, Rastsislau Azaronak, Vladislav, Hector Ayala, Marco Avila and 19 more
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:
Reacted by Daniel Daukševič, Supertiger, kran6a, David Oelfke, Alecsander Farias, Matthew Schwartz, Zeeshan Ahmad Khalil, perfect, Lucca, Neo Mxn0 and 3 more
@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$
}
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?
Reacted by João Batista da Silva , Renan Monteiro Pinto Neto, Andrea Marino, Denner, Robin Wieruch and Angel Velásquez
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()exportclassUserAccessor{constructor(privateprismaClient: PrismaClient){}asynccreate(...): Promise<User>{returnthis.prismaClient.user.create(...)}}
@Injectable()exportclassSettingsAccessor{constructor(privateprismaClient: PrismaClient){}asynccreate(user: User): Promise<Settings>{returnthis.prismaClient.userSettings.create(...)}}
@Injectable()exportclassUserDomain{constructor(privatereadonlyuserAccessor: UserAccessor,privatereadonlysettingsAccessor: SettingsAccessor,){}asynccreateUser(...){// start Transactionconstuser=awaitthis.userAccessor.create(...)// maybe more stuff done between this accessor callsconstsettings=awaitthis.settingsAccessor.create(user)// end Transaction}}
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.
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
@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.
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. */asyncfunctionperformTransaction<T>(client: PrismaClient,handler: ()=>Promise<T>){if(TransactionContextService.getTransaction()){returnhandler();}returnclient.$transaction(async(tx)=>TransactionContextService.runInContext(tx,handler));}functioncreateExtendedPrismaClient(options?: Prisma.PrismaClientOptions){constclient=newPrismaClient(options);returnclient.$extends({client: {async$transaction<T>(handler: ()=>Promise<T>){returnperformTransaction(client,handler);},},query: {$allModels: {$allOperations({ model, operation, args, query }){consttx=TransactionContextService.getTransaction();if(tx){// eslint-disable-next-line @typescript-eslint/no-unsafe-callreturntx[model][operation](args);}returnquery(args);},},},});}exporttypeIExtendedPrismaClient=new(options?: Prisma.PrismaClientOptions)=>PrismaClient&{$transaction: <T>(handler: ()=>Promise<T>)=>Promise<T>;};exportconstExtendedPrismaClient=class{constructor(options?: Prisma.PrismaClientOptions){// eslint-disable-next-line no-constructor-returnreturncreateExtendedPrismaClient(options);}}asIExtendedPrismaClient;
Initiate as regular prisma client and use it in code as this:
this.prisma.$transaction(async()=>{awaitthis.prisma.account.create();// transaction taken from context})
@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.
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:
@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. 🤔
@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. 🤔
exportinterfaceWrapInTransactionOptions{/** * 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.
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.
Activity
salvajavier commentedon Apr 24, 2022
https://www.prisma.io/docs/concepts/components/prisma-client/transactions
I think this is what you need.
jaequery commentedon Apr 24, 2022
I am not sure if any of them works across different files but do correct me if I'm wrong.
kasir-barati commentedon Apr 26, 2022
Any thought on doing this @jaequery, @salvajavier: Returning
$transactionto the user and pass it to the API interface as a argument. Something like this:salvajavier commentedon Apr 26, 2022
@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:
ramiresdallago commentedon Aug 10, 2022
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?
adrian-goe commentedon Sep 20, 2022
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:
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-DepthThis Topic is also Discussed in #13004
roberto-souza commentedon Oct 5, 2022
I have the same problem. I use CleanArchitecture and I can't work with transactions.
jaequery commentedon Oct 5, 2022
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.
Rykuno commentedon Oct 12, 2022
I'll add onto this. Utilizing NestJS and cannot utilize transactions across multiple services.
callumthomson commentedon Feb 8, 2023
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
16 remaining items
yigitahmetsahin commentedon Dec 17, 2023
@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.
yigitahmetsahin commentedon Jan 2, 2024
@Kainar01 any update from your solution which can work without context of a request?
Kainar01 commentedon Jan 2, 2024
Happy new year all!
@yigitahmetsahin sorry for taking long. Here is the snippet I use.
I created context manager with
async_hooksAnd created extended prisma client
Initiate as regular prisma client and use it in code as this:
yigitahmetsahin commentedon Jan 2, 2024
@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.
Kainar01 commentedon Jan 2, 2024
@yigitahmetsahin from the nestjs docs
It is not necessarily bound to request
renatoaraujoc commentedon Jan 2, 2024
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.
kasir-barati commentedon Jan 2, 2024
@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. 🤔
jaequery commentedon Jan 2, 2024
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:
renatoaraujoc commentedon Jan 4, 2024
@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:
I believe we don't need such "perfect" Spring-like functionality, but implementing
isolationandpropagationshould be pretty standard when the basic decorator is up.nest-clspackage should be enough to implement this (or let the user pass their favoritethread-likerunner likeAsyncLocalStorage.renatoaraujoc commentedon Jan 4, 2024
@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
propagationkicks in.In reality, you have to work with a
proxied prismaobject that will return the properprismaobject or thetransactionobject given if we're in a transaction and it's propagation.yigitahmetsahin commentedon Jan 30, 2024
@uki1014, @Kainar01, @kasir-barati, @renatoaraujoc, @jaequery good solution is provided as a package here: https://papooch.github.io/nestjs-cls/plugins/available-plugins/transactional
YahiaBadr commentedon Jul 18, 2024
any update on this issue guys?? i am facing the same problem with clean architecture.
m1than commentedon Jan 6, 2025
I have solved it like this: