| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\Database\Migrations; |
| 4 |
|
| 5 |
class SubmissionMeta |
| 6 |
{ |
| 7 |
/** |
| 8 |
* Migrate the table. |
| 9 |
* |
| 10 |
* @return void |
| 11 |
*/ |
| 12 |
public static function migrate() |
| 13 |
{ |
| 14 |
global $wpdb; |
| 15 |
|
| 16 |
$charsetCollate = $wpdb->get_charset_collate(); |
| 17 |
|
| 18 |
$table = $wpdb->prefix . 'fluentform_submission_meta'; |
| 19 |
|
| 20 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Migration file, direct query needed |
| 21 |
if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) != $table) { |
| 22 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange -- Migration file, schema change is the purpose |
| 23 |
$sql = "CREATE TABLE $table ( |
| 24 |
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, |
| 25 |
`response_id` BIGINT(20) UNSIGNED NULL, |
| 26 |
`form_id` INT UNSIGNED NULL, |
| 27 |
`meta_key` VARCHAR(45) NULL, |
| 28 |
`value` LONGTEXT NULL, |
| 29 |
`status` VARCHAR(45) NULL, |
| 30 |
`user_id` INT UNSIGNED NULL, |
| 31 |
`name` VARCHAR(45) NULL, |
| 32 |
`created_at` TIMESTAMP NULL, |
| 33 |
`updated_at` TIMESTAMP NULL, |
| 34 |
PRIMARY KEY (`id`), |
| 35 |
KEY `response_id_meta_key` (`response_id`, `meta_key`)) $charsetCollate;"; |
| 36 |
require_once ABSPATH . 'wp-admin/includes/upgrade.php'; |
| 37 |
dbDelta($sql); |
| 38 |
} else { |
| 39 |
// Add indexes to existing tables |
| 40 |
self::maybeAddIndexes(); |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Add indexes to existing tables for better query performance. |
| 46 |
* |
| 47 |
* @return void |
| 48 |
*/ |
| 49 |
private static function maybeAddIndexes() |
| 50 |
{ |
| 51 |
global $wpdb; |
| 52 |
|
| 53 |
$table = $wpdb->prefix . 'fluentform_submission_meta'; |
| 54 |
|
| 55 |
// Check if indexes already exist |
| 56 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder -- Migration file, checking indexes, %1s is for identifier |
| 57 |
$indexes = $wpdb->get_results($wpdb->prepare("SHOW INDEX FROM %1s", $table), ARRAY_A); |
| 58 |
|
| 59 |
$existingIndexes = []; |
| 60 |
foreach ($indexes as $index) { |
| 61 |
$existingIndexes[] = $index['Key_name']; |
| 62 |
} |
| 63 |
|
| 64 |
// Add composite index if it doesn't exist |
| 65 |
if (!in_array('response_id_meta_key', $existingIndexes)) { |
| 66 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder -- Migration file, adding composite index for performance, %1s is for identifier |
| 67 |
$wpdb->query($wpdb->prepare("ALTER TABLE %1s ADD KEY `response_id_meta_key` (`response_id`, `meta_key`)", $table)); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
} |
| 72 |
} |
| 73 |
|