Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback after error in transaction

Tags:

postgresql

This should be an easy one for those familiar with Postgresql:

My application issues a begin_work, does a number of operations, and then issues a commit. The operations and the commit are wrapped inside a try-catch block, whose catch statement performs a rollback. Assumption: if an error occurs during a SQL operation, Postgresql will automatically rollback the transaction, and therefore my rollback will be redundant but harmless. Is this assumption correct?

(The reason why I'm rollbacking anyway: just in case an exception unrelated to a SQL operation ocurs.)

like image 843
Jon Smark Avatar asked Apr 04 '13 15:04

Jon Smark


People also ask

How do you do the rollback if any failure happens in transaction?

By setting XACT_ABORT to ON and we can rollback all the statements inside a transaction when an error occurred. Thus, let's rewrite the code again in this manner. It will also roll back the transaction when the error occurred in the third statement.

When rollback of a transaction can happen?

Rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside the transaction. You can use ROLLBACK TRANSACTION to erase all data modifications made from the start of the transaction or to a savepoint. It also frees resources held by the transaction.

What is rollback error?

You can define a rollback exception strategy to ensure that a message that throws an exception in a flow is rolled back for reprocessing. Use a rollback exception strategy when you cannot correct an error that occurs in a flow.

Can we rollback transaction after commit?

COMMIT permanently saves the changes made by the current transaction. ROLLBACK undo the changes made by the current transaction. 2. The transaction can not undo changes after COMMIT execution.


1 Answers

If an error occurs, PostgreSQL does not actually rollback the transaction. It fails every subsequent statements with an error. You can try this out in the client.

You need to execute rollback before any statements can be executed successfully.

In the case that you close the connection and start a new one, this is of little consequence. However, if you retain the connection and run other statements which you expect to execute successfully, it will not work.

like image 177
drone.ah Avatar answered Oct 03 '22 03:10

drone.ah