Do transactions work when you nest them?
Hello, I'm trying to figure out if transactions work correctly when you nest them.
In my example I've got a couple of pretty complex business-logic-required queries, and each might have their own transactions within them:
If
deleteEntityAndReorderAllChildEntitiesForParent
fails from inside the transaction within reorderAllChildEntities
function, will BOTH transactions be rolled back correctly, or is this bad practice?6 Replies
Hi @Jon Higger (He / Him)
We do have an open feature request to support nested transactions as shown here.
I'll advise you structure your code to use a single transaction that encompasses all the operations you want to perform atomically.
This approach ensures that all operations are part of a single transaction and will be rolled back together if any part fails.
GitHub
Issues · prisma/prisma
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB - Issues · prisma/prisma
@RaphaelEtim I had the same question as OP and the follow up question is of course: if all my async function admit of an argument that is either the original prisma connection handler or transaction handler (both exposed by the top-level calling function), in theory all my async functions can be run against either the transaction API or the regular, non-transactional API, correct?
This is what I did, I just passed the prisma instance around
Here's a function I made that basically allows you to either make a transaction inside of a function, or allow you to pass a prisma instance in and use that as the transaction client
Which can then be used like this
Yup, that's very much what I had in mind! I need to test more thoroughly though, in my previous attempt the idea was blocked by a few failing tests.
By the way I noticed that
prisma: TransactionClient
is checked just as prisma: Prisma.Client
. Is there a way of making functions that accept only one reject the other?Only one way, I think you can make something that accepts a full prisma client but not a transaction client, but not vise verce.
Seems so indeed.