| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\Database\Migrations; |
| 4 |
|
| 5 |
class ConversationsMigrator |
| 6 |
{ |
| 7 |
static $tableName = 'fs_conversations'; |
| 8 |
|
| 9 |
public static function migrate() |
| 10 |
{ |
| 11 |
global $wpdb; |
| 12 |
|
| 13 |
$charsetCollate = $wpdb->get_charset_collate(); |
| 14 |
$table = $wpdb->prefix . static::$tableName; |
| 15 |
|
| 16 |
if ($wpdb->get_var("SHOW TABLES LIKE '$table'") != $table) { |
| 17 |
$sql = "CREATE TABLE $table ( |
| 18 |
`id` BIGINT(20) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, |
| 19 |
`serial` INT(11) UNSIGNED DEFAULT 1, |
| 20 |
`ticket_id` BIGINT(20) UNSIGNED NOT NULL, |
| 21 |
`person_id` BIGINT(20) UNSIGNED NOT NULL, |
| 22 |
`conversation_type` VARCHAR(100) DEFAULT 'response', |
| 23 |
`content` LONGTEXT NULL, |
| 24 |
`source` VARCHAR(100) DEFAULT 'web', |
| 25 |
`content_hash` VARCHAR(192) NULL, |
| 26 |
`message_id` VARCHAR(192) NULL, |
| 27 |
`is_important` ENUM('yes', 'no') DEFAULT 'no', |
| 28 |
`created_at` TIMESTAMP NULL, |
| 29 |
`updated_at` TIMESTAMP NULL, |
| 30 |
INDEX `idx_ticket_id` (`ticket_id`), |
| 31 |
INDEX `idx_person_id` (`person_id`), |
| 32 |
INDEX `idx_created_at` (`created_at`) |
| 33 |
) $charsetCollate;"; |
| 34 |
$created = dbDelta($sql); |
| 35 |
return $created; |
| 36 |
} else { |
| 37 |
static::alterTable($table); |
| 38 |
} |
| 39 |
|
| 40 |
return false; |
| 41 |
} |
| 42 |
|
| 43 |
public static function alterTable($table) |
| 44 |
{ |
| 45 |
static::addMissingIndexes($table); |
| 46 |
} |
| 47 |
|
| 48 |
public static function addMissingIndexes($table) |
| 49 |
{ |
| 50 |
global $wpdb; |
| 51 |
|
| 52 |
// Escape table name |
| 53 |
$table = esc_sql($table); |
| 54 |
|
| 55 |
// Get existing indexes |
| 56 |
$existing_indexes = $wpdb->get_results("SHOW INDEX FROM `$table`"); |
| 57 |
$existing_index_names = []; |
| 58 |
|
| 59 |
foreach ($existing_indexes as $index) { |
| 60 |
$existing_index_names[] = $index->Key_name; |
| 61 |
} |
| 62 |
|
| 63 |
// Desired indexes |
| 64 |
$indexes = [ |
| 65 |
'idx_ticket_id' => 'ticket_id', |
| 66 |
'idx_person_id' => 'person_id', |
| 67 |
'idx_created_at' => 'created_at', |
| 68 |
]; |
| 69 |
|
| 70 |
// Add missing indexes |
| 71 |
foreach ($indexes as $index_name => $column_name) { |
| 72 |
if (!in_array($index_name, $existing_index_names)) { |
| 73 |
$sql = "ALTER TABLE `$table` ADD INDEX `$index_name` (`$column_name`)"; |
| 74 |
$wpdb->query($sql); |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
|