MySQL transactions: use COMMIT and ROLLBACK in WordPress

MySQL transactions in WordPress: COMMIT and ROLLBACK with $wpdb

Some changes consist of several queries that only make sense together: an order and its line items, a transfer between two balances, a record and its log entry. If the second query fails after the first succeeded, the data is left half-written. A transaction groups the queries: either all of them are saved (COMMIT) or none (ROLLBACK).

Problem: A plugin saves an order in one custom table and its items in another, and when inserting an item fails, an order without items stays in the database.

Solution: Start a transaction with $wpdb->query( 'START TRANSACTION' ), check the result of every query, call ROLLBACK on the first failure and COMMIT at the end. The tables must use the InnoDB engine.

The pattern

<?php
function ha_create_order( $user_id, array $items ) {
    global $wpdb;

    $orders = $wpdb->prefix . 'ha_orders';
    $lines  = $wpdb->prefix . 'ha_order_items';

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

    $ok = $wpdb->insert(
        $orders,
        array( 'user_id' => (int) $user_id, 'status' => 'pending', 'created_at' => current_time( 'mysql', true ) ),
        array( '%d', '%s', '%s' )
    );

    if ( ! $ok ) {
        $wpdb->query( 'ROLLBACK' );
        return new WP_Error( 'ha_order', 'Could not create the order: ' . $wpdb->last_error );
    }

    $order_id = (int) $wpdb->insert_id;

    foreach ( $items as $item ) {
        $ok = $wpdb->insert(
            $lines,
            array(
                'order_id'   => $order_id,
                'product_id' => absint( $item['product_id'] ),
                'qty'        => absint( $item['qty'] ),
                'price'      => (float) $item['price'],
            ),
            array( '%d', '%d', '%d', '%f' )
        );

        if ( ! $ok ) {
            $wpdb->query( 'ROLLBACK' );
            return new WP_Error( 'ha_order', 'Could not add an item: ' . $wpdb->last_error );
        }
    }

    $wpdb->query( 'COMMIT' );

    return $order_id;
}

$wpdb->insert() returns false on failure and the number of rows otherwise, so every call is checked. After ROLLBACK the order row is gone, as if nothing had happened.

Requirements and limits

  • Only InnoDB tables support transactions. MyISAM ignores START TRANSACTION silently and saves every query immediately. Create custom tables with ENGINE=InnoDB (the default on MySQL 5.5.5 and newer) and check old ones with SHOW TABLE STATUS.
  • Statements that change the structure (CREATE TABLE, ALTER TABLE, also inside dbDelta()) commit the open transaction implicitly. Do not mix them into a transaction.
  • WordPress functions like wp_insert_post() or update_option() also write to the database, and caches and hooks around them do not know about your transaction. A rollback undoes their rows, but not the object cache entries or the actions that already ran. Use transactions for your own tables and plain $wpdb queries.

Locking a row

When two requests can change the same row at the same time (a stock counter, a balance), read it with FOR UPDATE inside the transaction. The second request then waits until the first one commits:

<?php
$wpdb->query( 'START TRANSACTION' );

$stock = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT stock FROM {$wpdb->prefix}ha_stock WHERE product_id = %d FOR UPDATE",
    $product_id
) );

if ( $stock < $qty ) {
    $wpdb->query( 'ROLLBACK' );
    return new WP_Error( 'ha_stock', 'Not enough stock.' );
}

$wpdb->update( $wpdb->prefix . 'ha_stock', array( 'stock' => $stock - $qty ), array( 'product_id' => $product_id ), array( '%d' ), array( '%d' ) );
$wpdb->query( 'COMMIT' );

NOTE: Keep transactions short. While one is open, the rows it locked are blocked for other requests; a transaction that waits for a remote API call or processes thousands of rows makes the rest of the site wait too. Do the slow work before START TRANSACTION and only the writes inside it.