Skip to content

Manual transaction commit, rollback #22309

Open

Description

@saboorajat

Problem

Since Prisma does not offer manual transaction rollbacks which is one of the reason TypeORM is preferred by users over Prisma. I intended to perform an E2E test on the production database, but I didn't want to contaminate it, which isn't possible till we reverse the transaction or, in the worst situation, manually remove it (obviously no). What then could be done?

Suggested solution

I found prisma-client-extensions after looking through thousands of pages 💯 goldmine. I developed an implementation for poc (Nest Js), but we still need to investigate whether there is performance overhead in applications with a lot of traffic.

We tested it setting request headers request.headers['x-testing'] === 'true'; will cause our transaction to be immediately rolled back. The normal execution will continue if the flag is not set.

  1. Created a interceptor as i wanted every request to be encapsulated with transaction :
type PrismaFlatTransactionClient = Prisma.TransactionClient & {
  $commit: () => Promise<void>;
  $rollback: () => Promise<void>;
};

@Injectable()
export class TransactionInterceptor implements NestInterceptor {
  readonly ROLLBACK = {
    [Symbol.for('prisma.client.extension.rollback')]: true,
  };

  public readonly prisma = new PrismaClient({ log: ["query"] }).$extends({
    client: {
      async $begin() {
        const prisma = Prisma.getExtensionContext(this);
        let setTxClient: (txClient: Prisma.TransactionClient) => void;
        let commit: () => void;
        let rollback: () => void;

        // a promise for getting the tx inner client
        const txClient = new Promise<Prisma.TransactionClient>((res) => {
          setTxClient = (txClient) => res(txClient);
        });

        // a promise for controlling the transaction
        const txPromise = new Promise((_res, _rej) => {
          commit = () => {
            return _res(undefined);
          };
          rollback = () => {
            return _rej(this.ROLLBACK);
          };
        });

        // opening a transaction to control externally
        if (
          '$transaction' in prisma &&
          typeof prisma.$transaction === 'function'
        ) {
          const tx = prisma
            .$transaction((txClient) => {
              setTxClient(txClient);

              return txPromise;
            })
            .catch((e) => {
              if (e === this.ROLLBACK) return;
              throw e;
            });

          // return a proxy TransactionClient with `$commit` and `$rollback` methods
          return new Proxy(await txClient, {
            get(target, prop) {
              if (prop === '$commit') {
                return () => {
                  commit();
                  return tx;
                };
              }
              if (prop === '$rollback') {
                return () => {
                  rollback();
                  return tx;
                };
              }
              // eslint-disable-next-line @typescript-eslint/no-unsafe-return
              return target[prop];
              // return target[prop as keyof typeof target];
            },
          }) as PrismaFlatTransactionClient;
        }

        throw new Error('Transactions are not supported by this client');
      },
    },
  });

  async intercept(
    context: ExecutionContext,
    next: CallHandler
  ): Promise<Observable<any>> {
    const tx = await this.prisma.$begin();

    // Attach PrismaClient to the request object
    // introduce hooks and check connection
    const request = context.switchToHttp().getRequest();
    request.transaction = tx;
    const shouldRollback = request.headers['x-testing'] === 'true';
    return next.handle().pipe(
      tap(async () => {
        console.log("envoked interceptor with e2e and checking flag : " + shouldRollback);
        if (!shouldRollback) {
          await tx.$commit();
          await this.prisma.$disconnect();
        }
      }),
      catchError(async (error) => {
        await tx.$rollback();
        await this.prisma.$disconnect();
        return throwError(() => error);
      })
    );
  }
}
  1. Providing the service in app.module.ts
providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: TransactionInterceptor,
    },]
  1. Controller would look like
@Controller('users')
export class UsersController {
  constructor() {}

  @Get()
  async findAll(@Req() req): Promise<User[]> {
    const prisma = req['transaction'];
    console.log();
    const err = 'Rollback';
    // throw err;
    return prisma.user.findMany(); // Example: Return all users
  }

  @Get(':id')
  async findOne(@Param('id') id: string, @Req() req): Promise<User | null> {
    const prisma = req['transaction'];
    return prisma.user.findUnique({
      where: { id: parseInt(id, 10) },
    });
  }
}

Activity

  1. added
    kind/feature
    tech/typescript
    status/has-client-extension
    on Dec 8, 2023
  2. aqrln commented on Dec 8, 2023

    @aqrln
    Member

    Thanks for opening the issue and sharing your solution @saboorajat, good to know a client extension worked for you.

    We already have a couple of feature requests open open about this, I'm gonna link them here for the ease of discovery: #12458, #15211.

    As to your original question:

    Since Prisma does not offer manual transaction rollbacks which is one the reason TypeORM is preferred by users over Prisma. I intended to perform an E2E test on the production database, but I didn't want to contaminate it, which isn't possible till we reverse the transaction or, in the worst situation, manually remove it (obviously no). What then could be done?

    If I understood the problem correctly, the answer using vanilla Prisma Client API is: just throw an error inside an interactive transaction callback, this will roll back the transaction.

  3. janpio commented on Mar 14, 2024

    @janpio
    Contributor

    Is there anything in your request @saboorajat that is not covered by #12458 or #15211?
    Otherwise I would suggest to close this issue here and focus on the other ones instead.

  4. ferhatte10 commented on Apr 24, 2025

    @ferhatte10

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

  5. di-sukharev commented on Aug 18, 2025

    @di-sukharev

    @ferhatte10 could you share a code example please 🙏

  6. ferhatte10 commented on Aug 18, 2025

    @ferhatte10

    @ferhatte10 could you share a code example please 🙏

    Image

    In this example, we are inside a transactional block of code. So it will depend of the database syntaxte (in my case its PostgreSQL)

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-extensiontech/typescripttopic: client apitopic: clientExtensionstopic: committopic: interactiveTransactionstopic: rollback

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions