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
API for interactive transactions with dependencies between write-operations #1844
There already is a GitHub issue asking for a way to submit multiple mutations within the same HTTP request where all mutations are executed as one transaction.
However, this feature does not allow for creating a transaction where the mutations depend on each other. Here is an example where the second operation depends on the first:
prisma.transaction(asynctx=>{constuser=awaittx.createUser({
name,})// compute some stuffawaittx.updateOrder(user.id)awaittx.commit()})
This is currently not possible with the Prisma API as it would require having a long-running connection where the results of the operations are sent back and forth between Prisma and the database.
Reacted by Jacob Pargin, Erik Weilow, mattwilson1024, nsignes-mediakind, Pablo Rocha, Lupascu Rares, Henrik Nygren, Fran Dios, Eddie Wang, Angelo Ashmore and 139 more
Reacted by ravshansbox, Costea, Thenesh, Nick Vander Kolk, m.e., Narcis Bugeag, Eugenio Berretta, loclv and Domagoj Vukovic
Reacted by vfa-trungtt3, Bogon Park, Hugo Hammarström, Rupert Dunk, Nikolai Kolodziej, Moritz Hedtke, Maxim Filippovicz, Eliya Cohen, CDDelta, ravshansbox and 10 more
Reacted by Kristóf Poduszló, Олег Кинема, m.e., Narcis Bugeag, Eugenio Berretta and Domagoj Vukovic
Reacted by Tafel, Rupert Dunk, Maxim Filippovicz, Eliya Cohen, CDDelta, Brian Kim, ravshansbox, Thenesh, Costea, Олег Кинема and 6 more
👍 This seems like a very useful (if not essential) feature to me and has been the only real pain point for me so far as a new Prisma user.
As you've identified, there are situations where you need to perform several mutations in sequence, making use of the response data as you go, but with the confidence that it'll be a single transaction that rolls back in the case of a failure. In my opinion, neither nested mutations or transactions for independent mutations seem quite sufficient for these use-cases.
Looking into ORM's for Node, Prism looks REALLY good (website, documentation, activity on Github, etc). But lacking/missing (manual) migrations transactions is a HUGE no-go for me. I looked at Prisma 2's change-log and article. I only see something about nested migrations transactions, which is not the same (it can't replace manual transactions (grouping)).
edit: Oops, I said migrations in place of transaction 🤦♂️
Reacted by Mikhail Podgurskiy, Raheel Riaz, Trevin Miller, Keyan, Kevin Abatan and perfect
I've always thought that if you have to explain terminology, it's probably not ideal. Sounds like I maybe the only one that doesn't know about "interactive transactions", then in that case... named well. If not though, I'd still rather see them called transactions. No one needs to explain to me what a long running transaction is so my thinking is just call them "Transactions" and "Long Running Transactions". IMHO 🙂.
We recommend you use interactive transactions as a last resort. The Prisma Client's nested write and atomic operations cover most of the use cases for transactions. Interactive transactions will fill in the gaps.
When you do need to reach for interactive transactions, please use them with caution. Keeping transactions open for a long time hurts database performance and can even cause deadlocks. Try to avoid performing unbound network requests and executing slow queries inside your transaction functions. As a rule of thumb: get in and out as quick as possible!
Note that we're tracking the following as separate feature requests:
Reacted by Eugenio Berretta, Trevor Paley, Powersource and Roman Scher
Reacted by Juan Martín Seery, Tim Suchanek, ravshansbox, Daniel Norman, pierre, Michiel Swaanen, Mawis, Brook Mezgebu, Cauê Nolasco, Daniel Muñoz and 8 more
Reacted by Juan Martín Seery, Tim Suchanek, ravshansbox, Daniel Norman, Michiel Swaanen, Rahul Muthyam, Cauê Nolasco, Daniel Muñoz, Eugenio Berretta, Michele Riva and 1 more
Argument of type '(prisma: any) => Promise<any>' is not assignable to parameter of type 'PrismaPromise<any>[]'.\n Type '(prisma: any) => Promise<any>' is missing the following properties from type 'PrismaPromise<any>[]': pop, push, concat, join, and 27 more.",
Argument of type '(prisma: any) => Promise<any>' is not assignable to parameter of type 'PrismaPromise<any>[]'.\n Type '(prisma: any) => Promise<any>' is missing the following properties from type 'PrismaPromise<any>[]': pop, push, concat, join, and 27 more.",
You are providing promise where array of promises is expected.
TypeError: promises is not iterable at PrismaClient.$___transactionInternal (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/@prisma/client/runtime/index.js:37853:23) at PrismaClient.$___transaction (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/@prisma/client/runtime/index.js:37881:21) at PrismaClient.$transaction (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/@prisma/client/runtime/index.js:37889:21) at /home/machado/Documents/projetos/seduc/iseduc-matricula/service.js:20:32 at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:42:32) at /home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-router/lib/router.js:372:16 at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:42:32) at /home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:34:12 at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-router/lib/router.js:377:31) at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:42:32)
@matthewmueller Seems like a good start. Another proposal would be a way to get the tx without having to be in the callback. Something like:
asyncfunctionmain(){constprisma=newPrismaClient()consttx=awaitprisma.$begin()constuser=awaittx.user.findUnique({where: {email: '[email protected]'}})if(!user){awaittx.$rollback()thrownewError('User does not exist')}constpost1=awaittx.post.create({data: {title: copiedPost1['title'],content: copiedPost1['content'],author: {connect: {email: '[email protected]'}}}})awaittx.$commit()}
I'd love to have that approach. It'll allow us to use transactions for tests:
describe('some test',()=>{
let trx: Transaction;beforeEach(async()=>{trx=awaitprisma.$begin();jest.mock('./prisma',()=>trx);});afterEach(async()=>{awaittrx.$rollback();});it('.....',()=>{// ....});});
Reacted by Hwantae Ji, Michał Lytek, trompx, Toni Villena, Benjamin Klotz, sibeliuz, Anmol Jawandha, tufailra97, Henry Kehlmann, Douglas Silva and 19 more
the default timeout of 2000 ms is quite low. I suspect many people who are reporting issues like this: #13713
might actually be running into timeouts.
Would be worth increasing to something like 30 seconds IMHO.
Also printing some kind of log/warning when timeout happens would be amazing-at least on dev.
for now, I've worked around this using this snippet:
// helper, because the default prisma transaction timeouts are too smallexportconstprismaTransaction=<R>(fn: (prisma: Prisma.TransactionClient)=>Promise<R>)=>{returnprismaClient.$transaction(fn,{timeout: 30000,maxWait: 60000})}
but we need a way to set these timeouts when we instantiate a prisma client
@matthewmueller Seems like a good start. Another proposal would be a way to get the tx without having to be in the callback. Something like:
asyncfunctionmain(){constprisma=newPrismaClient()consttx=awaitprisma.$begin()constuser=awaittx.user.findUnique({where: {email: '[email protected]'}})if(!user){awaittx.$rollback()thrownewError('User does not exist')}constpost1=awaittx.post.create({data: {title: copiedPost1['title'],content: copiedPost1['content'],author: {connect: {email: '[email protected]'}}}})awaittx.$commit()}
This syntax allows for easier testing and more freedom with business logic.
the concern with "transactions being left open" can be mitigated in the context of an HTTP request or a worker session by doing a clean-up at the end of request or session
Reacted by glaser06, Markus Schicker, Garrett Kirschbaum, JQ-pawelwypustek, dalosa14, Marco Avila, Takuro Sugahara, Antonius Joshua, sottleben, Bennet Hölscher and 12 more
Reacted by Marco Avila, sottleben, Gordon Westerman and Ale Guzman
Activity
mattwilson1024 commentedon Feb 4, 2019
👍 This seems like a very useful (if not essential) feature to me and has been the only real pain point for me so far as a new Prisma user.
As you've identified, there are situations where you need to perform several mutations in sequence, making use of the response data as you go, but with the confidence that it'll be a single transaction that rolls back in the case of a failure. In my opinion, neither nested mutations or transactions for independent mutations seem quite sufficient for these use-cases.
If it helps to have example use-cases for discussion, there's a little more detail about my specific requirement here: https://www.prisma.io/forum/t/transactions-when-the-business-logic-requires-more-than-just-a-nested-insert/5904
pantharshit00 commentedon Feb 18, 2019
@matthewhuang-camelot
Yes, raw sql queries are possible see: https://www.prisma.io/docs/prisma-graphql-api/reference/raw-database-access-qwe4/
matthewhuang-camelot commentedon Feb 18, 2019
@pantharshit00 Thanks! Just saw that too :D
savioserra commentedon May 11, 2019
Hi guys, any updates on this? :(
pantharshit00 commentedon May 13, 2019
@savioserra
We are working on a new client which will have this.
Please check here: https://github.com/prisma/rfcs/blob/new-ts-client-rfc/text/0000-new-ts-client.md
savioserra commentedon May 13, 2019
@pantharshit00 Nice :) Gonna take a look. For now, I'm using stored procedures and Prisma's
executeRawmutation as a workaround.waleCloud commentedon Aug 26, 2019
arvinlorenz commentedon Sep 9, 2019
hi any update on this?
iamclaytonray commentedon Jan 16, 2020
Will this be part of Prisma 2?
Ilyes512 commentedon Feb 1, 2020
Looking into ORM's for Node, Prism looks REALLY good (website, documentation, activity on Github, etc). But lacking/missing (manual)
migrationstransactions is a HUGE no-go for me. I looked at Prisma 2's change-log and article. I only see something about nestedmigrationstransactions, which is not the same (it can't replace manual transactions (grouping)).edit: Oops, I said migrations in place of transaction 🤦♂️
113 remaining items
pkellner commentedon Aug 10, 2021
I've always thought that if you have to explain terminology, it's probably not ideal. Sounds like I maybe the only one that doesn't know about "interactive transactions", then in that case... named well. If not though, I'd still rather see them called transactions. No one needs to explain to me what a long running transaction is so my thinking is just call them "Transactions" and "Long Running Transactions". IMHO 🙂.
matthewmueller commentedon Aug 10, 2021
Interactive Transactions are in Preview 🚀
You can enable them by upgrading to the latest Prisma (
>=2.29.0) and setting theinteractiveTransactionspreview feature in your Prisma Schema:Here's a basic example that shows how you can add custom logic in between two writes within a single transaction:
You can learn more in the documentation. You can share your feedback in this issue.
We recommend you use interactive transactions as a last resort. The Prisma Client's nested write and atomic operations cover most of the use cases for transactions. Interactive transactions will fill in the gaps.
When you do need to reach for interactive transactions, please use them with caution. Keeping transactions open for a long time hurts database performance and can even cause deadlocks. Try to avoid performing unbound network requests and executing slow queries inside your transaction functions. As a rule of thumb: get in and out as quick as possible!
Note that we're tracking the following as separate feature requests:
u007 commentedon Sep 23, 2021
why am i getting this error with the samle code?
ravshansbox commentedon Sep 23, 2021
You are providing promise where array of promises is expected.
Filip3Dev commentedon Sep 29, 2021
Guys, i'm getting this error:
TypeError: promises is not iterable at PrismaClient.$___transactionInternal (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/@prisma/client/runtime/index.js:37853:23) at PrismaClient.$___transaction (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/@prisma/client/runtime/index.js:37881:21) at PrismaClient.$transaction (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/@prisma/client/runtime/index.js:37889:21) at /home/machado/Documents/projetos/seduc/iseduc-matricula/service.js:20:32 at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:42:32) at /home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-router/lib/router.js:372:16 at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:42:32) at /home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:34:12 at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-router/lib/router.js:377:31) at dispatch (/home/machado/Documents/projetos/seduc/iseduc-matricula/node_modules/koa-compose/index.js:42:32)Here is my code:
Someone can help me?
janpio commentedon Sep 29, 2021
@Filip3Dev Please open a new issue and fill the bug issue template. Thanks.
scefali commentedon Dec 16, 2021
I'm getting this even with version 3.6.0 and
interactiveTransactionsin my configjanpio commentedon Dec 16, 2021
@scefali Please open a new issue and fill the bug issue template. Thanks.
leandrofinger commentedon Mar 14, 2022
I'd love to have that approach. It'll allow us to use transactions for tests:
kasir-barati commentedon Mar 16, 2022
did you found any proper solution for this situation, Separating transactions from business logic. Or a good enough compromised solution?
Thanks regardless
dougecomp commentedon Mar 21, 2022
As soon as the prisma allows the possibility of getting the transaction reference, that would be great! Just like @leandrofinger exemplified.
On my case, i can't open a database transaction on my API endpoint without coupling my interface and prisma implementations. On Knex or TypeORM was very simple. Just like this snippet: https://github.com/rmanguinho/advanced-node/blob/aa69e98291b9f63c4ea0f7c19a551818b4208a7e/src/infra/repos/postgres/helpers/connection.ts
capaj commentedon Aug 26, 2022
the default timeout of 2000 ms is quite low. I suspect many people who are reporting issues like this: #13713
might actually be running into timeouts.
Would be worth increasing to something like 30 seconds IMHO.
Also printing some kind of log/warning when timeout happens would be amazing-at least on dev.
capaj commentedon Aug 26, 2022
for now, I've worked around this using this snippet:
but we need a way to set these timeouts when we instantiate a prisma client
millsp commentedon Aug 26, 2022
Hey @capaj, I think it's a nice idea would you mind opening a feature request?
terryli0095 commentedon Dec 20, 2022
This syntax allows for easier testing and more freedom with business logic.
the concern with "transactions being left open" can be mitigated in the context of an HTTP request or a worker session by doing a clean-up at the end of request or session