| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\Database\Migrations; |
| 4 |
|
| 5 |
class MetaMigrator |
| 6 |
{ |
| 7 |
static $tableName = 'fs_meta'; |
| 8 |
|
| 9 |
public static function migrate() |
| 10 |
{ |
| 11 |
global $wpdb; |
| 12 |
|
| 13 |
$charsetCollate = $wpdb->get_charset_collate(); |
| 14 |
|
| 15 |
$table = $wpdb->prefix . static::$tableName; |
| 16 |
|
| 17 |
if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) != $table) { |
| 18 |
$sql = "CREATE TABLE $table ( |
| 19 |
`id` BIGINT(20) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, |
| 20 |
`object_type` VARCHAR(192) NULL, |
| 21 |
`object_id` BIGINT(20) NULL, |
| 22 |
`key` VARCHAR(192) NULL, |
| 23 |
`value` LONGTEXT NULL, |
| 24 |
`created_at` TIMESTAMP NULL, |
| 25 |
`updated_at` TIMESTAMP NULL, |
| 26 |
INDEX `idx_object_type` (`object_type`), |
| 27 |
INDEX `idx_object_id` (`object_id`), |
| 28 |
INDEX `idx_key` (`key`) |
| 29 |
) $charsetCollate;"; |
| 30 |
$created = dbDelta($sql); |
| 31 |
return $created; |
| 32 |
} else { |
| 33 |
static::alterTable($table); |
| 34 |
} |
| 35 |
|
| 36 |
return false; |
| 37 |
} |
| 38 |
|
| 39 |
public static function alterTable($table) |
| 40 |
{ |
| 41 |
static::addMissingIndexes($table); |
| 42 |
} |
| 43 |
|
| 44 |
public static function addMissingIndexes($table) |
| 45 |
{ |
| 46 |
global $wpdb; |
| 47 |
|
| 48 |
// $table is always $wpdb->prefix . 'fs_meta' — not user input. |
| 49 |
// esc_sql() is the correct escaping for SQL identifiers; $wpdb->prepare() |
| 50 |
// cannot quote identifiers in WP < 6.2 (no %i placeholder available). |
| 51 |
$table = esc_sql($table); |
| 52 |
|
| 53 |
// Get existing indexes |
| 54 |
$existing_indexes = $wpdb->get_results("SHOW INDEX FROM `{$table}`"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 55 |
$existing_index_names = []; |
| 56 |
|
| 57 |
foreach ($existing_indexes as $index) { |
| 58 |
$existing_index_names[] = $index->Key_name; |
| 59 |
} |
| 60 |
|
| 61 |
// Desired indexes — keys and values are all hardcoded string literals. |
| 62 |
$indexes = [ |
| 63 |
'idx_object_type' => 'object_type', |
| 64 |
'idx_object_id' => 'object_id', |
| 65 |
'idx_key' => 'key', |
| 66 |
]; |
| 67 |
|
| 68 |
// Add missing indexes. $table is esc_sql()'d above; $index_name and |
| 69 |
// $column_name are hardcoded array literals — no user input reaches this query. |
| 70 |
foreach ($indexes as $index_name => $column_name) { |
| 71 |
if (!in_array($index_name, $existing_index_names)) { |
| 72 |
// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQL.NotPrepared -- all identifiers are either esc_sql()'d or hardcoded literals. |
| 73 |
$wpdb->query("ALTER TABLE `{$table}` ADD INDEX `{$index_name}` (`{$column_name}`)"); |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
|