Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Rollback if COMMIT TRANSACTION is not reached

Tags:

Consider the following:

START TRANSACTION;  BEGIN;  INSERT INTO prp_property1 (module_name,environment_name,NAME,VALUE) VALUES ('','production','','300000');  /** Assume there is syntax error SQL here...**/ Blah blah blah  DELETE FROM prp_property1 WHERE environment_name = 'production';  COMMIT TRANSACTION; 

Question:

I noticed that the transaction automatically rolls back and the record insert attempt fails.

If I don't provide a error handler or error check along with ROLLBACK TRANSACTION as above, is it safe as it seems to be doing the job in an example like above because the COMMIT TRANSACTION never gets executed?

I assume the transaction is rolled back immediately and discarded as soon as a error occurs.

like image 646
Koekiebox Avatar asked May 25 '11 09:05

Koekiebox


2 Answers

No, transactions are not rolled back as soon as an error occurs. But you may be using a client-application which applies this policy.

For example, if you are using the mysql command-line client, then it normally stops executing when an error occurs and will quit. Quitting while a transaction is in progress does cause it to be rolled back.

When you are writing your own application, you can control the policy on rollback, but there are some exceptions:

  • Quitting (i.e. disconnecting from the database) always rolls back a transaction in progress
  • A deadlock or lock-wait timeout implicitly causes a rollback

Other than these conditions, if you invoke a command which generates an error, the error is returned as normal, and you are free to do whatever you like, including committing the transaction anyway.

like image 66
MarkR Avatar answered Sep 30 '22 10:09

MarkR


Use Mysql stored procedure

   BEGIN     DECLARE exit handler for sqlexception       BEGIN       ROLLBACK;    END;     DECLARE exit handler for sqlwarning      BEGIN      ROLLBACK;    END;     START TRANSACTION;     INSERT INTO prp_property1 (module_name,environment_name,NAME,VALUE) VALUES ('','production','','300000');     [ERROR]     COMMIT;     END 

You can set if warning or error rollback, then you don't need delete, with transaction all entry is deleted.

like image 25
Rogerio de Moraes Avatar answered Sep 30 '22 11:09

Rogerio de Moraes