MySql stored procedures, transactions and rollbacks - mysql

I can't find an optimal way to use transactions in a MySql Stored Procedure. I want to ROLLBACK if anything fails:
BEGIN
SET autocommit=0;
START TRANSACTION;
DELETE FROM customers;
INSERT INTO customers VALUES(100);
INSERT INTO customers VALUES('wrong type');
COMMIT;
END
1) Is autocommit=0 required?
2) If the second INSERT breaks (and it does of course) the first INSERT is not rolled back. The procedure simply continues down to the COMMIT. How can I prevent this?
3) I've found I can DECLARE HANDLER, should I use this instruction or is there a simpler way to say that if any command fails, the stored procedure should ROLLBACK and fail too?
DECLARE HANDLER works fine, but since I have MySql version 5.1 I can't use RESIGNAL. So if an error occurs, the caller won't be notified:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
-- RESIGNAL; not in my version :(
END;
START TRANSACTION;

Answer to 1: You don't need to set autocommit=0
With START TRANSACTION, autocommit remains disabled until you end the
transaction with COMMIT or ROLLBACK. The autocommit mode then reverts
to its previous state.
http://dev.mysql.com/doc/refman/5.6/en/commit.html

Different Approach to Answer 2: You could use a boolean variable to know if you should COMMIT or ROLLBACK. For example:
BEGIN
DECLARE `should_rollback` BOOL DEFAULT FALSE;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET `should_rollback` = TRUE;
START TRANSACTION;
DELETE FROM customers;
INSERT INTO customers VALUES(100);
INSERT INTO customers VALUES('wrong type');
IF `should_rollback` THEN
ROLLBACK;
ELSE
COMMIT;
END IF;
END
Or, you could use your very usefull 3)

Related

How can I log errors from a Stored Procedure in MySQL even when a ROLLBACK occurs?

I have the following code in a Store Procedure in MySQL (see below). When I don't put everything in a transaction, I can log errors on the Sproc directly into a table in the database. But when I put a START TRANSACTION, COMMIT, and ROLLBACK around the entire thing, my logging no longer works. I'm guessing because it's rolling back my logging? How do I get around this?
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS condition 1
#SQLState = RETURNED_SQLSTATE, #SQLMessage = MESSAGE_TEXT;
SELECT CONCAT('Database error occurred, state - ',#SQLState, '; error msg - ', #SQLMessage) INTO #errorString;
CALL Log_Errors
(#errorString,
'MySprocName',
some_variable_1,
some_variable_2);
ROLLBACK;
END;
START TRANSACTION;
-- do some stuff
-- error happens somewhere in here
COMMIT;
One option is to use a MyISAM table for logging. The MyISAM engine is not transactional. A row that is inserted into a MyISAM table stays inserted, even if a ROLLBACK is issued.
Using MyISAM for the logging table does introduce some other limitations. There's no enforcement of referential integrity (foreign key constraints). And no concurrent DML operations.
The question is old, but for who needs an answer, you must call the ROLLBACK before the LOG and then call a COMMIT:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS condition 1
#SQLState = RETURNED_SQLSTATE, #SQLMessage = MESSAGE_TEXT;
SELECT CONCAT('Database error occurred, state - ',#SQLState, '; error msg - ', #SQLMessage) INTO #errorString;
ROLLBACK;
CALL Log_Errors
(#errorString,
'MySprocName',
some_variable_1,
some_variable_2);
COMMIT;
END;
START TRANSACTION;
-- do some stuff
-- error happens somewhere in here
COMMIT;
When exiting, just do a SELECT and allow the calling application to handle logging like this:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
...
SELECT
CONCAT('Database error occurred, state - ',#SQLState, '; error msg - ', #SQLMessage) as #errorString,
'MySprocName' as proc,
some_variable_1 as var1,
some_variable_2 as var2;
ROLLBACK;
END;
START TRANSACTION;
-- do some stuff
COMMIT;
The caller PHP/Python/whatever will catch the resultset and analyze it for errors. If error is found, it will call Log_Errors. That will also allow you to log to filesystem if needed.
Here is the example of rollback code block with ability to log the error to some other table without loosing the exception details in MySQL and throwing the error again after logging it. You should get diagnostics BEFORE the ROLLBACK and the logging part - AFTER.
# CREATE PROCEDURE AND OTHER DECLARE STATEMENTS HERE
# ....
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1 #sqlstate = RETURNED_SQLSTATE, #errno = MYSQL_ERRNO, #text = MESSAGE_TEXT;
ROLLBACK;
SET #full_error = CONCAT('ERR:', #errno, '(', #sqlstate, '):', #text);
CALL sp_logaction(#full_error); # Some logging procedure
RESIGNAL; # Rethrow the error into the wild
END;
# PROCEDURE BODY WITH START TRANSACTION & COMMIT HERE
# .....

Log errors on SQLException to table

I have stored procedures that are likes this overall:
BEGIN
DECLARE exit handler for sqlexception
BEGIN
SHOW ERRORS; # this shows a result set with the errors that occured
ROLLBACK; # this rollbacks all the magic i tried to to, making this whole stuff atomic, YAY!
insert into LogTest select 1,2; # this is just a test to make sure it would work
END;
START TRANSACTION;
# do some magic
COMMIT
END
Now, what i need to do is change the Handler to something like this, obviously semi-pseudocode:
DECLARE exit handler for sqlexception
BEGIN
ROLLBACK; # this rollbacks all the magic i tried to to, making this whole stuff atomic, YAY!
insert into LogTest # and this tells me what timey whimey hit the maelstorm
select now(),*,'some id', ... <some more stuff maybe?>
from (Show errors) as Errors
END;
Any one any experience/idea/knowledge?

ERROR 1305 (42000): SAVEPOINT ... does not exist

I have this SQL in my MYSQL DB (sproc with empty body so I guess no implicit commits ?).
DROP PROCEDURE IF EXISTS doOrder;
DELIMITER $$
CREATE PROCEDURE doOrder(IN orderUUID VARCHAR(40))
BEGIN
SAVEPOINT sp_doOrder;
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO sp_doOrder;
-- doing my updates and selects here...
END;
RELEASE SAVEPOINT sp_doOrder;
END $$
DELIMITER ;
When I
call doOrder('some-unique-id');
I get: ERROR 1305 (42000): SAVEPOINT sp_doOrder does not exist.
I might overlook something... Any idea?
Since this is the top answer on Google when searching for "savepoint does not exist", I'll add my solution here as well.
I had a TRUNCATE statement within the code executed in my transaction, which caused an implicit commit and thus ended the transaction. Creating a savepoint outside of a transaction does not cause an error, it will just not be executed. This means the first time you'll notice something is wrong is when you try to release your savepoint / rollback it back.
This is the full list of statements that cause an implicit commit: https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
You have to use START TRANSACTION instead of BEGIN to start a transaction in a stored procedure.
Also, you may need to move the SAVEPOINT statement to be after the DECLARE (depending upon where you put the START TRANSACTION)
Note
Within all stored programs (stored procedures and functions, triggers,
and events), the parser treats BEGIN [WORK] as the beginning of a
BEGIN ... END block. Begin a transaction in this context with START
TRANSACTION instead.
Cf: http://dev.mysql.com/doc/refman/5.6/en/commit.html
This worked at the end. Thanks udog.
DROP PROCEDURE IF EXISTS doOrder;
DELIMITER $$
CREATE PROCEDURE doOrder(IN orderUUID VARCHAR(40))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK TO sp_order;
START TRANSACTION;
SAVEPOINT sp_order;
-- doing my updates and selects here...
COMMIT;
END $$
DELIMITER ;

MySQL stored procedure the reason of rollback

MySQL stored procedure will throw the error out if there is no rollback command for SQLEXCEPTION, but it has changed some data before the exception.
I add rollback command for SQL exceptions:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
But I can not know the reason of the rollback now.
I know we can define every SQL exception and it's handler, but it's too complex and I just want to know why the rollback occurred.
Is there a simple method to get the reason of rollback in MySQL stored procedure?
Thanks #kordirko. I have get one solution with RESIGNAL. But it is only supported until MySQL 5.5.
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SET #flag = 1;
IF #flag = 1 THEN RESIGNAL;END IF;
ROLLBACK;
END;

How to rollback and stop execution from an inner stored procedure

Let's say I have two stored procedures, Outer and Inner:
CREATE PROCEDURE dbo.Outer
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRAN
EXEC Inner
-- Perform additional processing (which should not occur if there is
-- a ROLLBACK in Inner)
...
COMMIT
END;
GO
The Outer stored procedure turns on XACT_ABORT and starts an explicit transaction. It then calls the Inner stored procedure inside the transaction.
CREATE PROCEDURE dbo.Inner
AS
BEGIN
DECLARE #Id INT=(SELECT Id FROM SomeTable WHERE ...);
IF (#Id IS NOT NULL)
ROLLBACK;
INSERT INTO SomeTable(...)
VALUES (...);
END;
GO
The Inner stored procedure performs a check to see if something is present and if it is wants to rollback the entire transaction started in the Outer stored procedure and abort all further processing in both Inner and Outer.
The thing that happens instead of what I expect as outlined above, is that I get the error message:
In Inner:
Transaction count after EXECUTE indicates a mismatching number of
BEGIN and COMMIT statements. Previous count = 1, current count = 0.
In Outer:
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
Clearly, the ROLLBACK even with XACT_ABORT turned on does not stop the flow of execution. Putting a RETURN statement after the ROLLBACK gets us out of Inner, but execution in Outer continues. What do I need to do in order to cause the ROLLBACK to stop all further processing and effectively cause an exit out of Outer?
Thanks for any help.
Issuing the rollback does not abort the batch (Regardless of the XACT_ABORT setting). The batch will automatically abort in your case if an error is thrown with the high enough severity - either system or custom generated via RAISERROR.
You have to implement Exception Handling
Begin Try
Set NOCOUNT ON
SET XACT_ABORT ON
Begin Tran
--Your Code
Commit Tran
End Try
Begin Catch
Rollback Tran
End Catch