Skip to content

WP Bones v3.4.1 is out! Check the Release Notes →

WP Bones
DocumentationAbout

Database

/

Migrations

Migrations

This document explains how migrations work in WP Bones. A migration is a file in database/migrations/ that changes the database: it creates a table, adds a column, inserts the rows a plugin needs. Since v3.0.0 each migration runs once per site, in file name order, and WP Bones records which ones ran. The document covers php bones migrate:create, when migrations run, what happens when one fails, the migrate and migrate:status commands, and multisite.

Overview

A migration file returns an object that extends Migration and has an up() method. WP Bones includes the file, calls up() once, and records the file name, so that the migration never runs again on that site.

Create one with php bones migrate:create, giving it the table name:

php bones migrate:create Products

You’ll see a new file in the database/migrations/ folder, named after the time you created it and the table, such as database/migrations/2026_10_06_142824_create_products_table.php:

<?php

if (! defined('ABSPATH')) {
    exit;
}

use WPKirk\WPBones\Database\Migration;

/*
 * Runs once on every site, in file name order, the first time the plugin loads after it
 * arrives (php bones migrate runs it on this site now). Once released, leave it as it is:
 * a change to the table goes in a new migration.
 */
return new class extends Migration
{

  public function up()
  {
    // Create your table, for example:

    $this->create("Products",
      "(
         id bigint(20) unsigned NOT NULL auto_increment,
         user_id bigint(20) unsigned NOT NULL default '0',
         name varchar(20) NOT NULL default '',
         description varchar(20) NOT NULL default '',
         price bigint(20) unsigned NOT NULL default '0',
         created_at datetime NOT NULL default '0000-00-00 00:00:00',
         updated_at datetime NOT NULL default '0000-00-00 00:00:00',
         PRIMARY KEY  (id),
         KEY user_id (user_id)
         ) {$this->charsetCollate};");
  }
};

Edit the schema to the table you need. The table name goes through the same conversion as a model’s: Products becomes products, MyTable becomes my_table, and WP Bones adds the WordPress prefix. You’ll see a table named wp_products in the database.

create() runs the WordPress dbDelta() function, so the rules of dbDelta() apply: one column per line, and two spaces after PRIMARY KEY.

When migrations run

Since v3.0.0 the pending migrations run:

  • When the plugin is activated, whatever the state.
  • When the plugin’s version changes. On init, at priority 1, WP Bones compares the Version header of your plugin with the version the database was last migrated for. When they differ, the request runs the pending migrations. This covers every way an update arrives: the dashboard, an uploaded ZIP, FTP, git, Composer. Any request can be that request, a public page included.
  • When you run php bones migrate from the plugin folder.

Two requests never run them together: a lock, kept in the options table, lets one request at a time in. They don’t run while WordPress checks a fresh automatic update (the request that carries wp_scrape_key), nor while WordPress installs.

Migrations run on init at priority 1, before the plugin’s own init: the custom post types and taxonomies your plugin registers there, and its text domain, are not loaded yet when a migration runs.

Finishing an update

When the version changed and the migrations ran, the same request finishes the update, still under the lock: it aligns the plugin options with config/options.php, then includes plugin/updated.php. In that file, $previousVersion holds the version the update came from:

<?php

if (!defined('ABSPATH')) {
  exit();
}

if ($previousVersion !== null && version_compare($previousVersion, '1.2.0', '<')) {
  // Something only the sites coming from a version before 1.2.0 need.
}

$previousVersion is null when the version is unknown: on the first request of a site that ran a 2.x version of your plugin, which kept no version, and on a site of a network where the plugin never ran. A first activation is an installation, not an update: there plugin/updated.php does not run.

The stored version moves last. If a migration, or plugin/updated.php, throws, the version stays where it was, and the next run finishes the update again.

The record of what ran

WP Bones keeps its state in four options of the site, named after your plugin’s slug. The slug is the plugin name, sanitized, with - turned into _, plus _slug: wp_kirk_slug for a plugin named WP Kirk.

OptionWhat it holds
{slug}_db_versionThe plugin version the database was last migrated for. Autoloaded, so the check on every request costs no query.
{slug}_migrationsThe migrations that ran, by file name, each with its batch, the plugin version and the time.
{slug}_migrations_failureThe failure that stopped the last run, empty once a run completes.
{slug}_migrations.lockThe lock, while a request runs migrations.

A migration does not belong to a plugin version. The version is only the signal that something may have changed; what runs is every file on disk whose name is not recorded yet. A migration added during development, or backported to an older branch of your plugin, still runs exactly once wherever it is missing.

Order

Migrations run in file name order. php bones migrate:create prefixes every file with a Y_m_d_His timestamp, so name order is creation order, as in Laravel. A migration that needs another one is normally written after it, so its name sorts later.

Two branches merged in a different order than their timestamps can bring a site a migration whose name sorts before one that already ran there. It still runs, but WP Bones warns you: the PHP error log gets a [WP Bones] line, php bones migrate prints a warning, and php bones migrate:status marks it. Check that it does not depend on the migrations that ran before it: on a fresh site it runs before them.

When a migration fails

A run stops at the first migration that throws or leaves a database error behind. That migration is not recorded, the ones after it don’t run, and the stored version does not move, so the next run starts again from the failed migration.

  • Administrators see an error notice on every admin page, with the migration and the reason, until it runs.
  • The PHP error log gets a [WP Bones] line.
  • With the version unchanged, only an administrator’s admin page retries it, at most once a minute, so that a broken migration does not run on every page load. php bones migrate and a reactivation retry it at once. A new version of the plugin retries it on any request, since it may carry the fix.

create() fails, by throwing, when the table or one of the columns it declares is not there afterwards. Anything else dbDelta() could not apply to an existing table, a default MySQL refuses to change for instance, is written to the PHP error log and tolerated. The helpers that write (insert(), truncate(), query()) throw when the database refuses the statement.

A retry runs the failed migration again from its first statement, and whatever it changed before it failed is still there: each query WordPress sends is committed as soon as it runs, and MySQL cannot roll back a CREATE, ALTER or DROP even inside a transaction. So write every migration so that it can run twice: create() already can, since dbDelta() applies only what differs from the table that is there; rows that must not go in twice go behind a check such as isEmpty(), as in Seeding; and a statement you write by hand checks first that its change is still to be made (see Changing a table).

Changing a table

Once you release a migration, leave it as it is: a site that already ran it will never run it again. A change to the table goes in a new migration. Since create() runs dbDelta(), the new migration can give the table its whole new schema, and dbDelta() adds what is missing:

<?php

use WPKirk\WPBones\Database\Migration;

return new class extends Migration {
  public function up()
  {
    $this->create('products', "(
              id bigint(20) unsigned NOT NULL auto_increment,
              user_id bigint(20) unsigned NOT NULL default '0',
              name varchar(20) NOT NULL default '',
              description varchar(20) NOT NULL default '',
              sku varchar(32) NOT NULL default '',
              price bigint(20) unsigned NOT NULL default '0',
              created_at datetime NOT NULL default '0000-00-00 00:00:00',
              updated_at datetime NOT NULL default '0000-00-00 00:00:00',
              PRIMARY KEY  (id),
              KEY user_id (user_id)
         ) {$this->charsetCollate};");
  }
};

dbDelta() never drops a column or a table. For that, and for anything else, $this->query() runs any SQL statement, and $this->table('products') gives you the full table name. Check first that the change is still to be made: if the migration runs again, a plain DROP COLUMN fails on a column that is already gone, and MySQL has no DROP COLUMN IF EXISTS. Ask with SHOW COLUMNS, not DESCRIBE. On a missing table DESCRIBE comes back empty without stopping the migration, which would then be recorded as done: WP Bones ignores its errors on MySQL, since dbDelta() leaves one behind for every new table, and on SQLite it raises none. SHOW COLUMNS reports the missing table on both, and the migration stops:

global $wpdb;

$table = $this->table('products');

if ($wpdb->get_var("SHOW COLUMNS FROM `{$table}` LIKE 'description'") !== null) {
  $this->query("ALTER TABLE `{$table}` DROP COLUMN description");
}

Commands

php bones migrate

Runs the migrations that have not run on this site, the same way the plugin does when its version changes, and lists them:

php bones migrate

During development, a new migration without a version bump does not trigger the check on init: run php bones migrate, or deactivate and activate the plugin. The command exits with 1 when a migration fails, and prints why.

php bones migrate:status

Lists every migration in database/migrations/ with its state: ✓ with its batch and plugin version when it ran, pending when it did not, and a warning for a pending migration that sorts before one that already ran. It also prints the last failure, if there is one.

php bones migrate:status

Both commands need the database, so the plugin must sit in the wp-content/plugins folder of a WordPress install: they load WordPress and work on the site it loads.

Multisite

The record is kept in the options of each site, so on a network every site keeps its own and runs its own migrations: when the plugin is activated there, or the first time one of its pages loads after the plugin arrives or is updated. With the WordPress prefix, create() makes a table for each site (wp_2_products for the second site).

Seed data

Since v3.0.0 the rows your plugin needs are inserted by a migration too: seeders do not run any more. See Seeding.

WordPress prefix

As you know, the real name of the table products is {prefix}_products. Usually, {prefix} is wp_ for default. Anyway, you don’t need to use the WordPress prefix, WP Bones will do that for you.

Remove the WordPress prefix

Starting from version 1.7.0, you can remove the WordPress prefix. You may use the usePrefix property in the migration class:

use WPKirk\WPBones\Database\Migration;

return new class extends Migration {

  protected $usePrefix = false;

  public function up()
  {

    $this->create('products', "(
              log_id bigint(20) unsigned NOT NULL auto_increment,
              user_id bigint(20) unsigned NOT NULL default '0',
              activity varchar(20) NOT NULL default 'updated',
              object_id bigint(20) unsigned NOT NULL default '0',
              object_type varchar(20) NOT NULL default 'post',
              activity_date datetime NOT NULL default '0000-00-00 00:00:00',
              PRIMARY KEY  (log_id),
              KEY user_id (user_id)
         ) {$this->charsetCollate};" );

  }
};

In this case the table will be named products.

Uninstall

Migrations have no down() step: deactivating a plugin must not lose its data. Remove the tables in your plugin’s uninstall.php, which WordPress runs when the plugin is deleted.

When uninstall.php drops the tables, delete the record of the migrations too. Otherwise a new installation finds every migration recorded, and creates nothing:

<?php

if (!defined('WP_UNINSTALL_PLUGIN')) {
  exit();
}

global $wpdb;

$wpdb->query("DROP TABLE IF EXISTS `{$wpdb->prefix}products`");

// The record of the migrations, so that a new installation creates the tables again.
foreach (['_db_version', '_migrations', '_migrations_failure', '_migrations.lock'] as $suffix) {
  delete_option('wp_kirk_slug' . $suffix);
}

Where the framework is loaded, \WPKirk\WPBones\Database\Migrations\OptionRepository::forget('wp_kirk_slug') deletes the same four options, and \WPKirk\WPBones\Support\Storage::delete(basename(__DIR__)) the plugin’s logs and compiled views in the uploads directory.