While using a MySQL transaction, is there a problem if you commit
twice? e.g.
START TRANSACTION
/* Various DB UPDATEs */
COMMIT
COMMIT
Having tested it out, it seems the 2nd COMMIT is a NO OP and could equally be a ROLLBACK
, is that correct? Is it harmless or could it ever be a problem?
As I understand it, after the 1st commit, auto-commit would be enabled and so the 2nd commit is meaningless... But would it cause any harm?
Background info:
I'm using PHP and I have a database transaction, e.g.
$dbconnection->getPdoInstance()->beginTransaction();
/* ... Various DB UPDATEs */
$dbconnection->getPdoInstance()->commit();
However, I want to put a MYSQL COMMENT on my commit so that I can identify it when I see it in the SHOW PROCESSLIST
, therefore I can't use PDO, I have to use "raw" SQL:
$dbconnection->getPdoInstance()->beginTransaction();
/* ... various DB UPDATEs */
$dbconnection->createCommand("COMMIT /* My Comment */")->execute();
Except this doesn't work because as far as PDO is concerned the transaction would still be active so it would throw an exception on the next beginTransaction()
, e.g.
exception 'PDOException' with message 'There is already an active transaction'
One workaround would be this:
$dbconnection->getPdoInstance()->beginTransaction();
/* ... various DB UPDATEs */
$dbconnection->createCommand("COMMIT /* My Comment */")->execute();
$dbconnection->getPdoInstance()->commit();
which would mean two COMMITs
are done, the first with my comment, the 2nd as a no-op but would close the transaction for pdo. (hence the question).
Another workaround would be to leave pdo out altogether:
$dbconnection->createCommand("START TRANSACTION")->execute();
/* ... various DB UPDATEs */
$dbconnection->createCommand("COMMIT /* My Comment */")->execute();
But then you lose the pdo features such as intransaction() and you won't get an exception if you try to start a 2nd transaction while already inside a prior transaction.
On Mysql, two commits are not a problem.
On PDO, im not sure. What if you change the first commit to another command like:
$dbconnection->getPdoInstance()->beginTransaction();
/* ... various DB UPDATEs */
$dbconnection->createCommand("SET @dummy_var=1; /* My Comment */")->execute();
$dbconnection->getPdoInstance()->commit();