Skip to content

API for interactive transactions with dependencies between write-operations #1844

Closed

Description

@nikolasburk

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(async tx => {
  const user = await tx.createUser({
    name,
  })
  // compute some stuff
  await tx.updateOrder(user.id)
  await tx.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.

It should be considered whether it is helpful to add such an API to Prisma, or whether abstractions like nested mutations and the requested transactional execution of multiple independent transactions are the better approach for Prisma.

Activity

  1. mattwilson1024 commented on Feb 4, 2019

    @mattwilson1024

    👍 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

  2. matthewhuang-camelot commented on Feb 18, 2019

    @matthewhuang-camelot

    @pantharshit00 Thanks! Just saw that too :D

  3. savioserra commented on May 11, 2019

    @savioserra

    Hi guys, any updates on this? :(

  4. pantharshit00 commented on May 13, 2019

    @pantharshit00
    Contributor
  5. savioserra commented on May 13, 2019

    @savioserra

    @pantharshit00 Nice :) Gonna take a look. For now, I'm using stored procedures and Prisma's executeRaw mutation as a workaround.

  6. waleCloud commented on Aug 26, 2019

    @waleCloud
  7. arvinlorenz commented on Sep 9, 2019

    @arvinlorenz

    hi any update on this?

  8. iamclaytonray commented on Jan 16, 2020

    @iamclaytonray

    Will this be part of Prisma 2?

  9. Ilyes512 commented on Feb 1, 2020

    @Ilyes512

    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 🤦‍♂️

  10. transferred this issue fromprisma/prisma1on Mar 16, 2020
  11. added
    kind/feature
    on Mar 16, 2020
  12. self-assigned this
    on Mar 28, 2020
  13. 113 remaining items

  14. pkellner commented on Aug 10, 2021

    @pkellner

    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 🙂.

  15. matthewmueller commented on Aug 10, 2021

    @matthewmueller
    Contributor

    Interactive Transactions are in Preview 🚀

    You can enable them by upgrading to the latest Prisma (>=2.29.0) and setting the interactiveTransactions preview feature in your Prisma Schema:

    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["interactiveTransactions"]
    }

    Here's a basic example that shows how you can add custom logic in between two writes within a single transaction:

    const video = await prisma.$transaction(async (prisma) => {
      const video = await prisma.video.create({
        data: {
          shortcode: "",
          url: "video.mp4",
        },
      })
      const shortcode = computeShortCode(video.id)
      return prisma.video.update({
        data: { shortcode },
        where: { id: video.id },
      })
    })

    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:

  16. u007 commented on Sep 23, 2021

    @u007

    why am i getting this error with the samle code?

    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.",
    
  17. ravshansbox commented on Sep 23, 2021

    @ravshansbox

    why am i getting this error with the samle code?

    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.

  18. Filip3Dev commented on Sep 29, 2021

    @Filip3Dev

    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:

    const { PrismaClient } = require('@prisma/client');
    const prisma = new PrismaClient();
    const Router = require('koa-router');
    
    exports.applyViews = function(app) {
      const router = new Router({
        prefix: `/api/`,
      });
    
      router.get('/', async ctx => {
        try {
    
          const foo = await prisma.$transaction( async (_prisma) => {
            const pessoa = await prisma.pI_ACD_Pessoa.findFirst();
            const aluno = await prisma.pI_ACD_Aluno.findFirst();
            return { pessoa, aluno  };
          })
          
          ctx.body = { foo };
        } catch (error) {
          console.log(error);
          ctx.body = error;
        }
      });
    
      app.use(router.routes()).use(router.allowedMethods());
    };
    
    "devDependencies": {
        "@types/node": "^16.10.1",
        "koa": "^2.13.3",
        "prisma": "^3.1.1",
        "ts-node": "^10.2.1",
        "typescript": "^4.4.3"
      } 
    

    Someone can help me?

  19. janpio commented on Sep 29, 2021

    @janpio
    Contributor

    @Filip3Dev Please open a new issue and fill the bug issue template. Thanks.

  20. scefali commented on Dec 16, 2021

    @scefali
    error - TypeError: promises is not iterable
    

    I'm getting this even with version 3.6.0 and interactiveTransactions in my config

  21. janpio commented on Dec 16, 2021

    @janpio
    Contributor

    @scefali Please open a new issue and fill the bug issue template. Thanks.

  22. leandrofinger commented on Mar 14, 2022

    @leandrofinger

    @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:

    async function main() {
      const prisma = new PrismaClient()
    
      const tx = await prisma.$begin()
      const user = await tx.user.findUnique({
        where: {
          email: '[email protected]'
        }
      })
    
      if (!user) {
        await tx.$rollback()
        throw new Error('User does not exist')
      }
    
      const post1 = await tx.post.create({
        data: {
          title: copiedPost1['title'],
          content: copiedPost1['content'],
          author: {
            connect: {
                email: '[email protected]'
            }
          }
        }
      })
    
      await tx.$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 = await prisma.$begin();
          jest.mock('./prisma', () => trx);
       });
    
       afterEach(async () => {
          await trx.$rollback();
       });
    
       it('.....', () => {
          // ....
       });
    });
  23. kasir-barati commented on Mar 16, 2022

    @kasir-barati

    I support fatum's comment. It can easily separate transaction implementation and business logic.

    In my product which uses TypeORM, I have transaction decorator like below. I would like to achieve something like this with Prisma, too.

    I hope this helps you.

    export const TypeORMTransaction = (): ((
      target: unknown,
      propKey: string,
      descriptor: PropertyDescriptor
    ) => PropertyDescriptor) => {
      return (target: unknown, propKey: string, descriptor: PropertyDescriptor): PropertyDescriptor => {
        const original: Function = descriptor.value;
    
        descriptor.value = async (...args: Record<string, unknown>[]): Promise<unknown> => {
          const queryRunner = await someFunctionGetQueryRunner(); // This function returns cached QueryRunner
          // Start transaction
          await queryRunner.startTransaction();
          let result: any;
          try {
            result = await original.apply(target, args);
            // Commit
            await queryRunner.commitTransaction();
          } catch (e) {
            // Rollback
            await queryRunner.rollbackTransaction();
            throw e;
          } finally {
            // Release query runner
            await queryRunner.release();
          }
          return result;
        };
        return descriptor;
      };
    };
    export class Foo {
      @TypeORMTransaction()
      static async SomeBusinessLogic(input: Input): Promise<Output> {
        ...
      }
    }

    did you found any proper solution for this situation, Separating transactions from business logic. Or a good enough compromised solution?

    Thanks regardless

  24. dougecomp commented on Mar 21, 2022

    @dougecomp

    @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:

    async function main() {
      const prisma = new PrismaClient()
    
      const tx = await prisma.$begin()
      const user = await tx.user.findUnique({
        where: {
          email: '[email protected]'
        }
      })
    
      if (!user) {
        await tx.$rollback()
        throw new Error('User does not exist')
      }
    
      const post1 = await tx.post.create({
        data: {
          title: copiedPost1['title'],
          content: copiedPost1['content'],
          author: {
            connect: {
                email: '[email protected]'
            }
          }
        }
      })
    
      await tx.$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 = await prisma.$begin();
          jest.mock('./prisma', () => trx);
       });
    
       afterEach(async () => {
          await trx.$rollback();
       });
    
       it('.....', () => {
          // ....
       });
    });

    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

  25. capaj commented on Aug 26, 2022

    @capaj

    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.

  26. capaj commented on Aug 26, 2022

    @capaj

    for now, I've worked around this using this snippet:

    // helper, because the default prisma transaction timeouts are too small
    export const prismaTransaction = <R>(fn: (prisma: Prisma.TransactionClient) => Promise<R>) => {
      return prismaClient.$transaction(fn, {
        timeout: 30000,
        maxWait: 60000
      })
    }

    but we need a way to set these timeouts when we instantiate a prisma client

  27. millsp commented on Aug 26, 2022

    @millsp
    Contributor

    Hey @capaj, I think it's a nice idea would you mind opening a feature request?

  28. terryli0095 commented on Dec 20, 2022

    @terryli0095

    @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:

    async function main() {
      const prisma = new PrismaClient()
    
      const tx = await prisma.$begin()
      const user = await tx.user.findUnique({
        where: {
          email: '[email protected]'
        }
      })
    
      if (!user) {
        await tx.$rollback()
        throw new Error('User does not exist')
      }
    
      const post1 = await tx.post.create({
        data: {
          title: copiedPost1['title'],
          content: copiedPost1['content'],
          author: {
            connect: {
                email: '[email protected]'
            }
          }
        }
      })
    
      await tx.$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

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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions