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
Some users are asking for a less restricted way for opening an interactive transaction. Instead of having a callback for the transaction, there would be manual calls to $begin, $commit, and $rollback.
Reacted by Sven Röttering, Simon Jakubowski, Benjamin Klotz, Damian Głowala, Maksim Zaborovskiy, Chanwoo Noh, Iddan Aaronsohn, PoffM, Toby Moore, Joonas Harjukallio and 69 more
Reacted by Marco Avila, karljv, Pedro Sliuzas, Luan Figueredo, sottleben, SparkElf, Matías Marcó del Pont, tbdrz, Nikolay Georgiev, Giuseppe Miragliotta and 1 more
I would love this feature as well. In my use case we have integration tests running with jest that need to be wrapped in a transaction so we can run many tests in parallel without bothering about side effects for other tests. There are of course techniques like cloning databases or using multiple schemas but they have limits. So a simple transaction would in most cases be more than enough. With the callback solution this is not possible right now.
The proposed API already looks promising for this.
We are trying to ramp up our CI speed and in order to do so, we need to run the database integration tests in parallel. This is currently not possible, due to the lack of manual transaction handling within prisma.
I have multiple years of experience in Java / Spring where it is almost default behavior to run your tests within a transaction, which rollbacks after the execution of the test to run several tests in parallel.
The suggested example is exactly what we would need to increase our CI speed significantly
Reacted by Andreas Kristiansen, Andrew Smith, Florian Cassayre, Helson Taveras, Gabe, Diego Paris, Gniewomir Świechowski, Diego V.S., jaka-allermi, Christoph Werner and 8 more
Hey folks, I prototyped something today (with type safety!). Do you mind giving it a try and share your feedback?
Prototype setup
import{PrismaClient}from"@prisma/client"typeCtorParams<C>=Cextendsnew(...args: infer P)=>any ? P[0] : nevertypeTxClient=Parameters<Parameters<PrismaClient['$transaction']>[0]>[0]constROLLBACK={[Symbol.for('prisma.client.extension.rollback')]: true}asyncfunction$begin(client: PrismaClient){letsetTxClient: (txClient: TxClient)=>voidletcommit: ()=>voidletrollback: ()=>void// a promise for getting the tx inner clientconsttxClient=newPromise<TxClient>((res)=>{setTxClient=(txClient)=>res(txClient)})// a promise for controlling the transactionconsttxPromise=newPromise((_res,_rej)=>{commit=()=>_res(undefined)rollback=()=>_rej(ROLLBACK)})// opening a transaction to control externallyconsttx=client.$transaction((txClient)=>{setTxClient(txClientasTxClient)returntxPromise.catch((e)=>{if(e===ROLLBACK)returnthrowe})})returnObject.assign(awaittxClient,{$commit: async()=>{commit();awaittx},$rollback: async()=>{rollback();awaittx}}asTxClient&{$commit: ()=>Promise<void>,$rollback: ()=>Promise<void>})}// patches the prisma client with a $begin methodfunctiongetTxClient(options?: CtorParams<typeofPrismaClient>){constclient=newPrismaClient(options)returnObject.assign(client,{$begin: ()=>$begin(client)})asPrismaClient&{$begin: ()=>ReturnType<typeof$begin>}}
Reacted by Daniil Kulchenko, Andreas Kristiansen, Zach Goldberg, Leonardo, Diego Paris, steven pinker, Diego V.S., SparkElf, kimsungwon and Gyunseo Lee
Maybe someone finds it useful but In my case I needed to wrap transaction object so I can pass it around different layers of my app and publish events after commit succeeds and I ended up using two promises to prevent premature commit:
Thank you so much for the idea!
I think I managed to create my own Transactional decorator:
constasyncLocalStorage=newAsyncLocalStorage();typeTransactionalPrisma=Omit<PrismaClient<Prisma.PrismaClientOptions,never,Prisma.RejectOnNotFound|Prisma.RejectPerOperation|undefined>,"$connect"|"$disconnect"|"$on"|"$transaction"|"$use">;constdbMap=newMap<string,TransactionalPrisma>();exportfunctiongetDB(){constid=z.string().parse(asyncLocalStorage.getStore());constdb=dbMap.get(id);if(!db)thrownewError("No db found");returndb;}exportfunctionTransactional(target: {prototype: Object}){constprototype=target.prototype;// for each methodfor(constpropertyNameofObject.getOwnPropertyNames(prototype)){constdescriptor=Object.getOwnPropertyDescriptor(prototype,propertyName);constisMethod=descriptor?.valueinstanceofFunction;if(!isMethod)continue;constoriginalMethod=descriptor.valueas{apply: Function};// wrap methoddescriptor.value=asyncfunction(...args: unknown[]){try{getDB();// check if db exists, i.e. we are in a transactionreturnawaitoriginalMethod.apply(this,args);}catch(e){returnprisma.$transaction(async(db)=>{constid=randomUUID();dbMap.set(id,db);constresult=awaitasyncLocalStorage.run(id,async()=>{returnawaitoriginalMethod.apply(this,args);});dbMap.delete(id);returnresult;});}};Object.defineProperty(prototype,propertyName,descriptor);}}
Note that this is a first draft, so improvements and corrections are more than welcome. 😅
Any solution to this problem? I'd like to have understand how extensions can solve this:
constresult=awaitprisma.$transaction(async(tx)=>{constrating=awaittx.rating.upsert({where: {},create: {},update: {},include: {},});//update (user|product) overall ratingoverall_rating=ratedProduct
? awaitratingService.updateProductOverallRating({product: ratedProduct,
tx,//passing tx as a parameter to another function has no effect and gets db data messy})
: awaitratingService.updateUserOverallRating({user: ratedUser??-1,
tx,//passing tx as a parameter to another function has no effect and gets db data messy});return{ ...rating, overall_rating };});returnresult;
I'd like to be able to manually commit or rollback transactions within a given context of mine
Hey, don't know if anyone will find this useful but after a bit of work, I found it hard to make @Omer-Shahar's version work, but using the same sort of idea I came up with this
import{PrismaClient}from"@prisma/client";import{AsyncLocalStorage}from"async_hooks";import{cuid}from"../generators/id.js";import{Exception}from"~sdk";constasyncLocalStorage=newAsyncLocalStorage();exporttypeTransactionalPrisma=Omit<PrismaClient,"$connect"|"$disconnect"|"$on"|"$transaction"|"$use">;constdbMap=newMap<string,TransactionalPrisma>();exportfunctiongetDB(){constid=asyncLocalStorage.getStore()asstring;constdb=dbMap.get(id);if(!db)thrownewError("No db found");returndb;}exportfunctionTx(prisma: PrismaClient){returnfunction(target: Object,propertyKey: string|symbol,parameterIndex: number){constoriginalMethod=target[propertyKeyasstring]as{apply: Function;};target[propertyKeyasstring]=asyncfunction(...args: unknown[]){try{constdb=getDB();args[parameterIndex]=db;returnawaitoriginalMethod.apply(this,args);}catch(e){returnnewPromise(async(res)=>{try{awaitprisma.$transaction(async(db)=>{constid=cuid();dbMap.set(id,dbasTransactionalPrisma);constresult=awaitasyncLocalStorage.run(id,async()=>{try{args[parameterIndex]=db;constresult=awaitoriginalMethod.apply(this,args);if(resultinstanceofException){res(result);throwresult;}returnresult;}catch(e){console.log(e);res(newException(e.message,'transactionError'));throwe;}});dbMap.delete(id);returnresult;});}catch(e){console.log(e);res(newException(e.message,'transactionError'));}});}};returntargetasany;};};
I've been trying to implement a solution based on @PiotrJozefow approach for managing transactions in Prisma 5.7.0, PostgreSQL 15, and Node.js 18. However, I'm encountering an error when attempting to execute more than 15 simultaneous transactions. The error is "PrismaClientKnownRequestError: Transaction API error: Unable to start a transaction in the given time." My implementation involves sharing a transaction across multiple repositories through a context. I'm looking for insights into this issue and any recommended strategies for handling multiple simultaneous transactions in a shared context. Here is my code for reference:
Thank you so much for the idea!
I think I managed to create my own Transactional decorator:
Hi @barnc@dvnkboi,
I've decided to write everything I did here in a much more organized way and add some new features. This is the link to the repo.
The example here is using drizzle, but it should work with prisma with little or no modifications.
Feel free to ask questions, add improvements and fix any bugs that you find :)
I wanted to mention another use case that might help justify adding this feature to prisma's API.
Streaming requests are often managed with Async Generator functions. Imagine an API that performs some long-running task and streams incremental responses. If that tasks has database side-effects, it would be nice if the bolus of work could be wrapped in a transaction boundary, but I don't see a way to do this with the callback syntax since it doesn't support async generators.
Activity
sijakubo commentedon Mar 31, 2022
That would be great to have. We are currently facing the exact same issue
janpio commentedon Mar 31, 2022
Can you elaborate on your use case @sijakubo? That is always valuable to have in such issues as signal why someone wants a feature really.
sroettering commentedon Apr 1, 2022
I would love this feature as well. In my use case we have integration tests running with jest that need to be wrapped in a transaction so we can run many tests in parallel without bothering about side effects for other tests. There are of course techniques like cloning databases or using multiple schemas but they have limits. So a simple transaction would in most cases be more than enough. With the callback solution this is not possible right now.
The proposed API already looks promising for this.
sijakubo commentedon Apr 1, 2022
Hi @janpio,
We are trying to ramp up our CI speed and in order to do so, we need to run the database integration tests in parallel. This is currently not possible, due to the lack of manual transaction handling within prisma.
I have multiple years of experience in Java / Spring where it is almost default behavior to run your tests within a transaction, which rollbacks after the execution of the test to run several tests in parallel.
The suggested example is exactly what we would need to increase our CI speed significantly
garrensmith commentedon Apr 4, 2022
I was thinking that instead of having a manual transactions, why not rather change the test to be something like:
With the function
describeInTransactionbeing a wrapper over a transaction and the jest test.millsp commentedon Apr 4, 2022
Hey folks, I prototyped something today (with type safety!). Do you mind giving it a try and share your feedback?
Prototype setup
Example
13 remaining items
PiotrJozefow commentedon Mar 22, 2023
Maybe someone finds it useful but In my case I needed to wrap transaction object so I can pass it around different layers of my app and publish events after commit succeeds and I ended up using two promises to prevent premature commit:
And in the instance:
Omer-Shahar commentedon May 24, 2023
Thank you so much for the idea!
I think I managed to create my own Transactional decorator:
Note that this is a first draft, so improvements and corrections are more than welcome. 😅
barnc commentedon Jun 16, 2023
Hi @Omer-Shahar - thanks a bunch for this, looks very interesting. Do you have an example of this being used anywhere?
salahmedamin commentedon Jul 7, 2023
Any solution to this problem? I'd like to have understand how extensions can solve this:
I'd like to be able to manually commit or rollback transactions within a given context of mine
dvnkboi commentedon Aug 8, 2023
Hi @Omer-Shahar, it would really help if you could share an example of using this on a class.
dvnkboi commentedon Aug 8, 2023
Hey, don't know if anyone will find this useful but after a bit of work, I found it hard to make @Omer-Shahar's version work, but using the same sort of idea I came up with this
This is an example of using it:
Hope this helps anyone.
janpio commentedon Aug 22, 2023
Related: #12975 + #13004
vineboneto commentedon Dec 8, 2023
I've been trying to implement a solution based on @PiotrJozefow approach for managing transactions in Prisma 5.7.0, PostgreSQL 15, and Node.js 18. However, I'm encountering an error when attempting to execute more than 15 simultaneous transactions. The error is "PrismaClientKnownRequestError: Transaction API error: Unable to start a transaction in the given time." My implementation involves sharing a transaction across multiple repositories through a context. I'm looking for insights into this issue and any recommended strategies for handling multiple simultaneous transactions in a shared context. Here is my code for reference:
gyunseo commentedon Mar 16, 2024
I tried to use db transaction
rollback, but the code of main branch has the following problem.so check out this PR if you're trying to use
rollback. It worked for me.Omer-Shahar commentedon May 19, 2024
Hi @barnc @dvnkboi,
I've decided to write everything I did here in a much more organized way and add some new features.
This is the link to the repo.
The example here is using drizzle, but it should work with prisma with little or no modifications.
Feel free to ask questions, add improvements and fix any bugs that you find :)
sgoodrow commentedon Aug 9, 2024
Thanks for the extension code.
I wanted to mention another use case that might help justify adding this feature to prisma's API.
Streaming requests are often managed with Async Generator functions. Imagine an API that performs some long-running task and streams incremental responses. If that tasks has database side-effects, it would be nice if the bolus of work could be wrapped in a transaction boundary, but I don't see a way to do this with the callback syntax since it doesn't support async generators.
For a specific, simplified example of what a streamed response might look like, see this example: https://bsorrentino.github.io/bsorrentino/web/2024/03/05/how-to-stream-data-in-nextjs.html
Thanks!