feat: auto-run schema upgrades on version change

Adds psa_maybe_run_upgrades() that compares stored psa_db_version
against PSA_VERSION on admin_init. When the code version is newer,
re-runs PSA_Cost_Tracker::create_table() so dbDelta picks up additive
schema changes (like the new token_source column) without requiring
the admin to deactivate/reactivate the plugin.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
peptiderepo
2026-04-14 12:02:49 +07:00
parent 5d5019bda3
commit a8a0ce2121

View File

@@ -48,9 +48,33 @@ add_action( 'init', 'psa_init' );
function psa_admin_init() { function psa_admin_init() {
PSA_Post_Type::init_admin(); PSA_Post_Type::init_admin();
psa_maybe_run_upgrades();
} }
add_action( 'admin_init', 'psa_admin_init' ); add_action( 'admin_init', 'psa_admin_init' );
/**
* Run database upgrades when the installed code version is newer than the
* stored `psa_db_version` option. Keeps users from needing to
* deactivate/reactivate the plugin after a schema change.
*
* Triggered on admin_init so dbDelta runs once per upgrade, not on every
* frontend page load.
*
* @return void
*/
function psa_maybe_run_upgrades() {
$stored = get_option( 'psa_db_version', '0.0.0' );
if ( version_compare( $stored, PSA_VERSION, '>=' ) ) {
return;
}
// Re-run CREATE TABLE via dbDelta — additive schema changes (new columns)
// will be applied automatically.
PSA_Cost_Tracker::create_table();
update_option( 'psa_db_version', PSA_VERSION, false );
}
/** /**
* Check if current page is the Echo KB main page. * Check if current page is the Echo KB main page.
* Uses is_page() which is reliable even in block templates. * Uses is_page() which is reliable even in block templates.