Search code examples
typescriptdrizzledrizzle-orm

Does drizzle ORM auto rollbacks when there is an exception or do I need to call tx.rollback?


I'm building an API with nestjs and drizzle. When there is an error and I need to early return and respond the Request with an HTTP error, I do:

throw new HttpException('message', code);

and nest will catch it and send the http response. Drizzles documentation do not mention auto rollback and only shows rolling back a transaction by calling tx.rollback().

When I want to rollback a transaction is it enough to throw an HttpException or do I need to first explicitly call tx.rollback() and then throw the exception?


Solution

  • In theory it depends on the DB and driver used.

    But in most (if not all) cases the answer should be yes drizzle does auto rollback. It would be quite a bad implementation of transactions if they didn't: it would mean that any thrown error exposes you to the risk of committing half of your transaction.

    I did the test on a postgres DB, using pg, and I confirm that any uncaught error will rollback the transaction. So you do not need to call tx.rollback if an error is already being thrown.

    Looking a bit at the code of their drivers, it seems that they always implement transactions as just a try..catch (and calling tx.rollback actually simply throws an error)

    Some examples: