Use MySQL Foreign Key Constraints in Custom WordPress Plugin Tables

Foreign keys in custom WordPress plugin tables

WordPress itself uses no foreign keys: the relation between a post and its meta rows exists only in PHP code. A plugin with its own tables can do better and let the database keep the data consistent, for example delete the items of an order together with the order. It works, but there are a few traps that come from the way WordPress creates and deletes its own rows.

Problem: A booking plugin has the tables wp_bookings and wp_booking_items. When a booking is deleted with a plain DELETE, its items stay in the table, and reports count items of bookings that no longer exist.

Solution: Create both tables with InnoDB, add a foreign key from booking_items.booking_id to bookings.id with ON DELETE CASCADE in a separate ALTER TABLE after dbDelta(), check first that the key does not exist yet, and handle the references to WordPress users in PHP instead of a foreign key to wp_users.

Create the tables

dbDelta() does not understand FOREIGN KEY clauses: it parses the statement line by line and would try to add the constraint again on every run. So the tables are created with dbDelta() and the constraint is added afterwards. How dbDelta() wants the SQL formatted: create a custom database table with dbDelta.

register_activation_hook( __FILE__, 'ha_bookings_install' );
function ha_bookings_install(): void {
    global $wpdb;
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $charset_collate = $wpdb->get_charset_collate();
    $bookings        = $wpdb->prefix . 'bookings';
    $items           = $wpdb->prefix . 'booking_items';

    dbDelta( "CREATE TABLE {$bookings} (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  user_id bigint(20) unsigned DEFAULT NULL,
  booked_at datetime NOT NULL,
  status varchar(20) NOT NULL DEFAULT 'pending',
  total decimal(10,2) NOT NULL DEFAULT 0,
  PRIMARY KEY  (id),
  KEY user_id (user_id),
  KEY status (status)
) ENGINE=InnoDB {$charset_collate};" );

    dbDelta( "CREATE TABLE {$items} (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  booking_id bigint(20) unsigned NOT NULL,
  product_id bigint(20) unsigned NOT NULL,
  quantity smallint(5) unsigned NOT NULL DEFAULT 1,
  unit_price decimal(10,2) NOT NULL,
  PRIMARY KEY  (id),
  KEY booking_id (booking_id)
) ENGINE=InnoDB {$charset_collate};" );

    ha_bookings_add_foreign_key( $items, 'ha_fk_items_booking', 'booking_id', $bookings, 'id' );
}

function ha_bookings_add_foreign_key( string $table, string $name, string $column, string $ref_table, string $ref_column ): void {
    global $wpdb;

    $exists = $wpdb->get_var( $wpdb->prepare(
        'SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
         WHERE CONSTRAINT_SCHEMA = DATABASE() AND TABLE_NAME = %s AND CONSTRAINT_NAME = %s',
        $table,
        $name
    ) );
    if ( $exists ) {
        return;
    }

    // Identifiers cannot be passed through prepare(); they come from code, not from input.
    $wpdb->query( "ALTER TABLE `{$table}` ADD CONSTRAINT `{$name}`
        FOREIGN KEY (`{$column}`) REFERENCES `{$ref_table}` (`{$ref_column}`)
        ON DELETE CASCADE" );
}

The constraint name must be unique in the whole database, not only in the table, so it gets the plugin prefix. The column types must match exactly: bigint(20) unsigned on both sides. If they differ (for example signed and unsigned), MySQL refuses with error 150 “Foreign key constraint is incorrectly formed”.

What CASCADE does and does not do

DELETE FROM wp_bookings WHERE id = 42;
-- the rows of wp_booking_items with booking_id = 42 are deleted by the database

The cascade happens inside MySQL. No PHP code runs for the deleted items: no hooks, no cache invalidation. If the plugin caches items with wp_cache_set(), it has to clear that cache when it deletes the booking.

Why not a foreign key to wp_users or wp_posts

It is tempting to add user_id REFERENCES wp_users(ID). In practice it causes more trouble than it solves:

  • On older sites core tables are still MyISAM, and a foreign key to a MyISAM table cannot be created.
  • wp_delete_user() can reassign content to another user first; a database rule does not know about that.
  • Migration and backup tools import tables in alphabetical order and fail on a constraint that points to a table that is not there yet.

A hook is the WordPress way for these references:

add_action( 'deleted_user', 'ha_bookings_detach_user' );
function ha_bookings_detach_user( int $user_id ): void {
    global $wpdb;
    $wpdb->update( $wpdb->prefix . 'bookings', array( 'user_id' => null ), array( 'user_id' => $user_id ), null, array( '%d' ) );
}

The booking stays for the accounting, without a user.

Remove the tables on uninstall, not on deactivation

Deactivation is often temporary (debugging a conflict), so the data must survive it. Drop the tables in uninstall.php, the child table first:

// uninstall.php
defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}booking_items" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}bookings" );

NOTE: An import with a constraint in place fails when the child rows come before the parent rows. Dumps made with mysqldump contain SET FOREIGN_KEY_CHECKS=0 at the top for this reason; when you write an import script yourself, do the same and switch the checks on again at the end.