| 1 |
<?php |
| 2 |
/** |
| 3 |
* Schema introspection helpers shared by Texty migrations. |
| 4 |
* |
| 5 |
* Lives outside the migration class hierarchy on purpose — wp-kit's |
| 6 |
* `BaseMigration::run()` auto-invokes every public/protected static on the |
| 7 |
* migration class as a step, so helpers attached to that hierarchy would be |
| 8 |
* called with no arguments and crash. Put them here, call as |
| 9 |
* `Schema::column_exists(...)` from any migration. |
| 10 |
* |
| 11 |
* @package Texty\Migrations |
| 12 |
* @since TEXTY_VERSION |
| 13 |
*/ |
| 14 |
|
| 15 |
namespace Texty\Migrations; |
| 16 |
|
| 17 |
defined( 'ABSPATH' ) || exit; |
| 18 |
|
| 19 |
/** |
| 20 |
* Schema introspection helpers. |
| 21 |
*/ |
| 22 |
final class Schema { |
| 23 |
|
| 24 |
/** |
| 25 |
* Whether a table exists in the current database. |
| 26 |
* |
| 27 |
* @param string $table Fully-prefixed table name. |
| 28 |
* |
| 29 |
* @return bool |
| 30 |
* @since TEXTY_VERSION |
| 31 |
*/ |
| 32 |
public static function table_exists( string $table ): bool { |
| 33 |
global $wpdb; |
| 34 |
|
| 35 |
$found = $wpdb->get_var( |
| 36 |
$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) |
| 37 |
); |
| 38 |
|
| 39 |
return $found === $table; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Whether a column exists on a table. |
| 44 |
* |
| 45 |
* @param string $table Fully-prefixed table name. |
| 46 |
* @param string $column Column name. |
| 47 |
* |
| 48 |
* @return bool |
| 49 |
* @since TEXTY_VERSION |
| 50 |
*/ |
| 51 |
public static function column_exists( string $table, string $column ): bool { |
| 52 |
global $wpdb; |
| 53 |
|
| 54 |
$found = $wpdb->get_var( |
| 55 |
$wpdb->prepare( |
| 56 |
'SELECT COLUMN_NAME FROM information_schema.COLUMNS |
| 57 |
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s', |
| 58 |
$table, |
| 59 |
$column |
| 60 |
) |
| 61 |
); |
| 62 |
|
| 63 |
return $found === $column; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Whether an index exists on a table. |
| 68 |
* |
| 69 |
* @param string $table Fully-prefixed table name. |
| 70 |
* @param string $index Index name. |
| 71 |
* |
| 72 |
* @return bool |
| 73 |
* @since TEXTY_VERSION |
| 74 |
*/ |
| 75 |
public static function index_exists( string $table, string $index ): bool { |
| 76 |
global $wpdb; |
| 77 |
|
| 78 |
$found = $wpdb->get_var( |
| 79 |
$wpdb->prepare( |
| 80 |
'SELECT INDEX_NAME FROM information_schema.STATISTICS |
| 81 |
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND INDEX_NAME = %s |
| 82 |
LIMIT 1', |
| 83 |
$table, |
| 84 |
$index |
| 85 |
) |
| 86 |
); |
| 87 |
|
| 88 |
return $found === $index; |
| 89 |
} |
| 90 |
} |
| 91 |
|