Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rollback on multiple queries

Tags:

database

mysql

How can I do multiple queries, the usen commit(), and if something goes wrong, rollback all queries?

I noticed that if I wrap my queries and commit with inside try / catch, only the unsuccesful queries are rolled back

try{

  $pdo->beginTransaction();

  // create 10 tables
  foreach($queries as $query)
    $result = $pdo->query($query);

  $pdo->commit();

}catch(PDOException $e){

  // here if one of the tables fail to be created, undo all operations
  $pdo->rollBack();  

}
like image 418
Alex Avatar asked Mar 08 '26 23:03

Alex


1 Answers

MySQL does not support embedded transactions.

If you think you are getting a partial rollback, you are checking it wrong. In particular, an unsuccesful query will not even run, so there's nothing to rollback there. What happens is that you don't really have a transaction, either because you forgot the START TRANSACTION statement or because your tables are not InnoDB.

Edit: I've just seen you've updated your question. You cannot rollback DDL statements such as CREATE TABLE. You can only rollback DML statements (SELECT, INSERT, UPDATE...). This is not a MySQL limitation, it's the standard behaviour in all DBMS engines I know.

like image 183
Álvaro González Avatar answered Mar 10 '26 13:03

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!