From a8a0ce21211024e91a2435c7a5f2183615f1028d Mon Sep 17 00:00:00 2001 From: peptiderepo Date: Tue, 14 Apr 2026 12:02:49 +0700 Subject: [PATCH] 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 --- peptide-search-ai.php | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/peptide-search-ai.php b/peptide-search-ai.php index f9f6826..e6da0bb 100755 --- a/peptide-search-ai.php +++ b/peptide-search-ai.php @@ -48,9 +48,33 @@ add_action( 'init', 'psa_init' ); function psa_admin_init() { PSA_Post_Type::init_admin(); + psa_maybe_run_upgrades(); } 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. * Uses is_page() which is reliable even in block templates.