handle tables with fixed key lengths

This commit is contained in:
Matthew Bucci
2024-01-11 01:10:57 -08:00
parent a90ab01a9b
commit 8f1f65db47
2 changed files with 35 additions and 5 deletions

View File

@ -50,7 +50,7 @@ class CreateTableSQLRewriter extends AbstractSQLRewriter
$sql = trim($sql);
// Add a slash if needed
if (substr($sql,strlen($sql)-1, 1) != ";") {
if (substr($sql, strlen($sql) - 1, 1) != ";") {
$sql = $sql . ";";
}
@ -92,18 +92,18 @@ class CreateTableSQLRewriter extends AbstractSQLRewriter
}
// Support for UNIQUE INDEX creation
$pattern = '/,\s*(UNIQUE |)KEY\s+(`[^`]+`|\w+)\s+\(([^)]+)\)/';
$pattern = '/,\s*(UNIQUE |)KEY\s+(`[^`]+`|\w+)\s+\((.*?)\)(?!\))/';
if(preg_match_all($pattern, $sql, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
$unique = $match[1];
$index = $match[2];
$columns = $match[3];
// Removing backticks from the index names
// Removing backticks from the index names
$index = str_replace('`', '', $index);
// Removing backticks from the columns
$columns = str_replace('`', '', $columns);
// Removing backticks and key length constraints from the columns
$columns = preg_replace(["/`/", "/\(\d+\)/"], '', $columns);
// Creating a unique index name
$indexName = $table . '_' . $index;

View File

@ -304,6 +304,36 @@ final class rewriteTest extends TestCase
}
public function test_it_can_create_keys_with_length()
{
$sql = <<<SQL
CREATE TABLE wp_usermeta (
umeta_id bigint(20) unsigned NOT NULL auto_increment,
user_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (umeta_id),
KEY user_id (user_id),
KEY meta_key (meta_key(191))
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci
SQL;
$expected = <<<SQL
CREATE TABLE wp_usermeta (
umeta_id bigserial,
user_id bigint NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value text,
PRIMARY KEY (umeta_id)
);
CREATE INDEX wp_usermeta_user_id ON wp_usermeta (user_id);
CREATE INDEX wp_usermeta_meta_key ON wp_usermeta (meta_key);
SQL;
$postgresql = pg4wp_rewrite($sql);
$this->assertSame(trim($expected), trim($postgresql));
}
protected function setUp(): void