3

As far as I understand the global $wpdb object utilizes just a single MySQL connection under the hood (by default). Because the object is global every other plugin/theme/whatever seems to be using this connection.

My question is: Is it safe to use MySQL transactions with that or could other plugins/WordPress itself interfere with my transaction(s)?

To visualize how that could look like:

global $wpdb;
$wpdb->query('START TRANSACTION');


$wpdb->query(...);
$wpdb->query(...);
// ... and so on

if ( $condition ) {
    $wpdb->query('COMMIT'); // commit all queries
} else {
    $wpdb->query('ROLLBACK'); // rollback everything
}
fabiancdng
  • 45
  • 3

1 Answers1

3

PHP is by nature single-threaded. Also, a transaction is limited to the scope of the connection it is created in.

If you write a PHP function that starts and commits a transaction without calling into another plugin, there is no way another plugin can interfere with your transaction. Other plugins could be invoked by WordPress before or after your function, but not during.

Other PHP requests running concurrently would have their own database connection (connections cannot be shared between PHP requests), and transactions cannot span multiple connections.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828