Search code examples
node.jstypescriptpg-promise

Will pg-promise transaction rollback, if non sql function inside transaction fails?


I have a use case that I would need to remove a user from an external service if that user is removed from db. In case either of these operations fails the whole removal should be undone. I was thinking that is it possible to do this something like this:


const removeUser = async (user) => {
  await db.tx(async tx => {
    await removeUserFromDB(tx, user)
    await removeUserFromExternalService(user)
  })
} 

In pg-promise docs the transaction docs say that if the tx callback fails, the transaction will be rolled back. Does this hold even if the call to external service that is not using the tx context would fail? Here the transaction should be rolled back if either of those operations inside the callback fails.


Solution

  • From the library's author.


    Transaction callback in pg-promise doesn't care about what you do inside it, it just handles generic exceptions, and executes immediate ROLLBACK on any exception that occurs first, and then re-throws the exception for you to handle on the outside.

    When no exceptions triggered, COMMIT is executed at the end, and then tx resolves with the data returned from the callback.