Skip to content

Support manual rollback in interactive transactions #15211

Open

Description

@aniravi24

Problem

To rollback an interactive transaction, you have to throw an error. It would be awesome to have a manual rollback function (that potentially takes a data argument to pass back to the parent caller). Throwing errors makes code less predictable and weakly typed. We try to reserve throwing errors for unexpected errors, not for expected ones.

Suggested solution

When in a transaction block, be able to call rollback on the prisma client. One potential implementation:

await prisma.$transaction(
  async (prisma) => {
    // Code running in a transaction...
  prisma.rollback();
  // or with arbitrary data/error
  prisma.rollback(err);
  }
)

Alternatives

We don't really have an alternative here as we can't rollback without an error.

Additional context

Initially suggested here

Activity

  1. saboorajat commented on Nov 5, 2023

    @saboorajat

    Any update on this? i can't find this feature on official documentation.

  2. josethoz commented on Nov 6, 2023

    @josethoz

    any updates?

  3. rojiwon123 commented on Nov 20, 2023

    @rojiwon123

    interactive transaction inner function have to end with rollback or commit command.

    so I suggest new solution.

    Suggested solution

    • rollback when inner function return Prisma.Rollback instance.
    const prisma = new PrismaClien();
    const response: Prisma.users | "NOT_FOUND_USER" | "UNVERIFIED_USER" = await prisma.$transaction(async (tx) => {
             const user: Prisma.users | null = await tx.users.findFirst({ where: { id: 1 } });
             
             Prisma.Rollback(); // it is just instance, so this line does nothing.
             
             if(user === null) return Prisma.Rollback("NOT_FOUND_USER");
             if(!user.verified) return Prisma.Rollback("UNVERIFIED_USER");
             // ... some transaction code...
             return user;
        });
    class Rollback<T = undefined>{
      constructor(public readonly result: T){};
    }

    Alternatives

    • commit or rollback based on the result of the endHandler.
    const prisma = new PrismaClien();
    const endHandler = (result: Prisma.users | "NOT_FOUND_USER" | "UNVERIFIED_USER"): boolean => 
            typeof response !== 'string';
        
    const response: Prisma.users | "NOT_FOUND_USER" | "UNVERIFIED_USER" = await prisma.$transaction(async (tx) => {
             const user: Prisma.users | null = await tx.users.findFirst({ where: { id: 1 } });        
             if(user === null) return "NOT_FOUND_USER";
             if(!user.verified) return "UNVERIFIED_USER";
             // ... some transaction code...
             return user;
        }, { endHandler });
    };
    type EndHandler = <T = undefined>(result:T) => boolean;
  4. SevInf commented on Nov 20, 2023

    @SevInf
    Contributor

    While there is no built-in functionality for this, it can be implemented via client extension. Here is an example of the one that allows to roll back the transaction by returning rollback symbol:

    class RollbackError extends Error {}
    const rollback = Symbol()
    const prisma = new PrismaClient()
    
    const xprisma = prisma.$extends({
      client: {
        async $noThrowTransaction<T>(
          callback: (client: Prisma.TransactionClient) => Promise<T | typeof rollback>,
        ): Promise<T | undefined> {
          let result: T
          try {
            result = await prisma.$transaction(async (tx) => {
              const innerResult = await callback(tx)
              if (innerResult == rollback) {
                throw new RollbackError()
              }
              return innerResult
            })
          } catch (error) {
            if (error instanceof RollbackError) {
              return undefined
            }
            throw error
          }
        },
      },
    })
    
    // usage
    const result = xprisma.$noThrowTransaction(async (tx) => {
      if (someCondition) {
        return rollback
      }
      return tx.user.findUniqueOrThrow()
    })

    But it also higlights a typesafety problem with this feature request: what should return value of $noThrowTransaction should be if it is using manual rollback? It can not be return value of your callback since transaction is stopped before we got it. In by example it is undefined which creates it's own bundle of problems. It can also be some magic value, for example, the same rollback symbol. But that will poison the return types and you'll have to add if (result !=== rollback) condition every time before you can do anything with the return value. Overall, it does not feel to me that for cases where we care about return value any of the proposed solutions substantially improves ergonomics over throwing errors. You are free to experiment with the extension I provided though - if it works for you then great, if it does not - feel free to adjust it in any way.

  5. added
    status/has-client-extension
    on Nov 20, 2023
  6. pheetah commented on Mar 14, 2024

    @pheetah

    Why wasn't this a feature?

  7. SevInf commented on Mar 14, 2024

    @SevInf
    Contributor

    @pheetah because nobody built it yet. You are free to experiment with the extension I posted in my previous comment. In order for us to consider it as a built-in feature we need good answers to the questions I posted in the end of this comment and so far nobody attempted that.

  8. binishjoshi commented on May 12, 2024

    @binishjoshi

    Something like how sequelize does it: https://sequelize.org/docs/v6/other-topics/transactions/#unmanaged-transactions

    // First, we start a transaction from your connection and save it into a variable
    const t = await sequelize.transaction();
    
    try {
      // Then, we do some calls passing this transaction as an option:
    
      const user = await User.create(
        {
          firstName: 'Bart',
          lastName: 'Simpson',
        },
        { transaction: t },
      );
    
      await user.addSibling(
        {
          firstName: 'Lisa',
          lastName: 'Simpson',
        },
        { transaction: t },
      );
    
      // If the execution reaches this line, no errors were thrown.
      // We commit the transaction.
      await t.commit();
    } catch (error) {
      // If the execution reaches this line, an error was thrown.
      // We rollback the transaction.
      await t.rollback();
    }
  9. Neosoulink commented on Aug 23, 2024

    @Neosoulink

    Any update about this?

  10. saboorajat commented on Oct 15, 2024

    @saboorajat

    #22309 This might help. Although we as team have moved to typeORM for better features.

  11. ferhatte10 commented on Apr 24, 2025

    @ferhatte10

    You can just use => await prisma.$executeRawROLLBACK; to enforce manual sql rollback => working for me

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

    kind/featurestatus/has-client-extensiontopic: interactiveTransactionstopic: rollback

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions