views:

252

answers:

2

When in a mysql innodb transaction, I would expect a duplicate key error to cause a rollback. It doesn't, instead it simply throws an error and continues on to the next command. Once the COMMIT command is reached, the transaction will be committed, sans the duplicate key causing command.

Is this the expected behaviour? If so, how would one go about setting it up so that the transaction is rolled back instead of committed when such an error occurs?

test environment:

CREATE TABLE `test` (  
  `id` int(11) NOT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

BEGIN;
     INSERT INTO test VALUES (5);
     INSERT INTO test VALUES (5);
COMMIT;

expected result: table test is empty

actual result: table test contains one record with value 5

+2  A: 

If an insert fails because of a duplicate, the database rolls the transaction back to the start of that statement.

It uses an internal savepoint made at the beginning of the statement, then rolls back to that savepoint.

It does NOT roll back the entire transaction, because that might not have been what you wanted.

The behaviour of the mysql client is configurable using command line parameters. It can either quit (which would implicitly rollback) or continue.

If you're using your own app, what it does is up to you.


Mysql does not impose POLICY on how you handle failures - it leaves that up to your application. So what you do about them is your own business - you can ignore them if you like.

MarkR
i want to give you like 100 rep points for "Mysql does not impose POLICY on how you handle failures - it leaves that up to your application. So what you do about them is your own business - you can ignore them if you like."
longneck
so is there a way to set up a transaction so it automatically rolls back on a duplicate key error? or do I have to monitor the result of each query and then explicitly roll back to get this behaviour?
AlliXSenoS
+2  A: 

DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING, NOT FOUND BEGIN ROLLBACK; CALL ERROR_ROLLBACK_OCCURRED; END;

janon