Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions includes/class-events-store.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
class Events_Store extends Singleton {
const TABLE_SUFFIX = 'a8c_cron_control_jobs';

const DB_VERSION = 1;
const DB_VERSION = 2;
const DB_VERSION_OPTION = 'a8c_cron_control_db_version';

const STATUS_PENDING = 'pending';
Expand All @@ -26,6 +26,9 @@ protected function class_init() {

// Keep trying in case we weren't around during the site installation.
add_action( 'shutdown', array( $this, 'maybe_install_during_shutdown' ) );
} elseif ( self::needs_upgrade() ) {
// Table exists but the schema is behind, bring it up to date.
add_action( 'shutdown', array( $this, 'maybe_upgrade_during_shutdown' ) );
}

// Handle adding/removing tables when subsites are created/deleted.
Expand Down Expand Up @@ -109,6 +112,36 @@ public function maybe_install_during_shutdown() {
}
}

/**
* Check if the installed schema is behind the current version.
*/
public static function needs_upgrade(): bool {
return (int) get_option( self::DB_VERSION_OPTION, 0 ) < self::DB_VERSION;
}

/**
* For certain requests, bring an out of date schema up to date on shutdown.
*/
public function maybe_upgrade_during_shutdown() {
$is_cron_or_cli = wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI );
$is_admin = is_admin() && ! wp_doing_ajax();

if ( ! $is_cron_or_cli && ! $is_admin ) {
// Not a request we should try to upgrade on.
return;
}

if ( ! self::needs_upgrade() ) {
// Must have been upgraded earlier on in this request already.
return;
}

if ( wp_cache_add( 'upgrade_lock', true, 'cron-control', \MINUTE_IN_SECONDS ) ) {
// We've claimed the lock, run the upgrade. dbDelta() adds any missing indexes.
$this->_prepare_table();
}
}

/**
* Create the plugin's DB table when necessary
*/
Expand Down Expand Up @@ -141,7 +174,8 @@ protected function _prepare_table() {

PRIMARY KEY (`ID`),
UNIQUE KEY `ts_action_instance_status` (`timestamp`, `action` (191), `instance`, `status`),
KEY `status` (`status`)
KEY `status` (`status`),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about only upgrading the option version if this succeeds?

@sjinks can use your input here

KEY `action_instance_status_ts` (`action` (191), `instance`, `status`, `timestamp`)
) ENGINE=InnoDB;\n";

dbDelta( $schema, true );
Expand Down
Loading