Manage WordPress database migrations with dbDelta and versioned SQL scripts

Versioned database migrations for a WordPress plugin

A plugin with its own tables changes over time: a new column, a new index, data moved from options into a table. The activation hook runs only when the plugin is activated, not when it is updated, so a plugin needs its own way to bring the database of every site up to date after an update. The usual pattern is a stored database version and a list of migration steps.

Problem: Version 1.2 of a plugin adds a column and an index to its table and moves settings from an option into the table, and every site that updates must get these changes without anybody running SQL by hand.

Solution: Store the database version in an option, compare it with the plugin’s current version on plugins_loaded, run each migration step whose version is newer than the stored one, in order, and save the new version after each successful step. Use dbDelta() for the table structure.

The runner

<?php
define( 'HA_DB_VERSION', '1.2.0' );

add_action( 'plugins_loaded', 'ha_maybe_migrate' );

function ha_maybe_migrate() {
    $installed = get_option( 'ha_db_version', '0' );

    if ( version_compare( $installed, HA_DB_VERSION, '>=' ) ) {
        return; // up to date: one autoloaded option read per request, nothing else
    }

    $steps = array(
        '1.0.0' => 'ha_migrate_1_0_0',
        '1.1.0' => 'ha_migrate_1_1_0',
        '1.2.0' => 'ha_migrate_1_2_0',
    );

    foreach ( $steps as $version => $callback ) {
        if ( version_compare( $installed, $version, '<' ) ) {
            call_user_func( $callback );
            update_option( 'ha_db_version', $version ); // remember each finished step
        }
    }
}

Saving the version after every step means that a migration interrupted halfway (a timeout, a fatal error) continues with the next missing step on the next request, instead of starting over or skipping steps.

The structure with dbDelta()

<?php
function ha_migrate_1_0_0() {
    ha_create_tables();
}

function ha_migrate_1_1_0() {
    ha_create_tables(); // the same definition, now with the new column
}

function ha_create_tables() {
    global $wpdb;
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $table   = $wpdb->prefix . 'ha_logs';
    $charset = $wpdb->get_charset_collate();

    dbDelta( "CREATE TABLE $table (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  level varchar(20) NOT NULL DEFAULT 'info',
  message text NOT NULL,
  context longtext NULL,
  created_at datetime NOT NULL,
  PRIMARY KEY  (id),
  KEY level (level),
  KEY created_at (created_at)
) $charset;" );
}

dbDelta() compares the definition with the existing table and adds missing columns and indexes. It does not remove or rename columns, and it is picky about formatting: one field per line, two spaces after PRIMARY KEY, KEY instead of INDEX. Keep one current definition of each table and call it from every structural migration.

Data migrations

<?php
function ha_migrate_1_2_0() {
    global $wpdb;

    // Rename a column: dbDelta() cannot do this
    $table   = $wpdb->prefix . 'ha_logs';
    $columns = $wpdb->get_col( "SHOW COLUMNS FROM $table" );
    if ( in_array( 'msg', $columns, true ) && ! in_array( 'message', $columns, true ) ) {
        $wpdb->query( "ALTER TABLE $table CHANGE msg message text NOT NULL" );
    }

    // Move old settings out of an option
    $old = get_option( 'ha_old_settings' );
    if ( is_array( $old ) ) {
        update_option( 'ha_settings', array_merge( array( 'level' => 'info' ), $old ) );
        delete_option( 'ha_old_settings' );
    }
}

Each step checks the current state before changing it (does the old column exist?), so running it twice does no harm. That makes migrations safe when two requests start them at the same time or when a database is restored from an older backup.

The activation and uninstall side of the same plugin is described in activation, deactivation and uninstall hooks.

NOTE: Big data migrations (millions of rows) do not belong in a page request. Let the migration step only schedule a background job that processes the rows in batches with WP-Cron or Action Scheduler, and show an admin notice until it is done.