Skip to content

Commit dea3efd

Browse files
akirkaristathbrandonpayton
authored
Ensure that an index is also created using IF NOT EXISTS if it comes from a CREATE TABLE IF NOT EXISTS (#134)
Before this the unit test failed. cc @JanJakes --------- Co-authored-by: Ari Stathopoulos <[email protected]> Co-authored-by: Brandon Payton <[email protected]>
1 parent f691c22 commit dea3efd

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

tests/WP_SQLite_Query_Tests.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,27 @@ public function testOnDuplicateKeyWithUnnamedKeys() {
537537
);
538538
}
539539

540+
public function testOnCreateTableIfNotExistsWithIndexAdded() {
541+
$this->assertQuery(
542+
'CREATE TABLE IF not EXISTS `test` (
543+
`id` INT,
544+
`name` VARCHAR(255),
545+
`other` VARCHAR(255),
546+
PRIMARY KEY (id),
547+
UNIQUE KEY (name)
548+
);'
549+
);
550+
$this->assertQuery(
551+
'CREATE TABLE if NOT ExisTS `test` (
552+
`id` INT,
553+
`name` VARCHAR(255),
554+
`other` VARCHAR(255),
555+
PRIMARY KEY (id),
556+
UNIQUE KEY (name)
557+
);'
558+
);
559+
}
560+
540561
public function testShowColumns() {
541562

542563
$query = 'SHOW COLUMNS FROM wp_posts';

wp-includes/sqlite/class-wp-sqlite-translator.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,8 @@ private function execute_create_table() {
895895
')'
896896
);
897897

898+
$if_not_exists = preg_match( '/\bIF\s+NOT\s+EXISTS\b/i', $create_query ) ? 'IF NOT EXISTS' : '';
899+
898900
$this->execute_sqlite_query( $create_query );
899901
$this->results = $this->last_exec_returned;
900902
$this->return_value = $this->results;
@@ -907,7 +909,7 @@ private function execute_create_table() {
907909
}
908910
$index_name = $this->generate_index_name( $table->name, $constraint->name );
909911
$this->execute_sqlite_query(
910-
"CREATE $unique INDEX \"$index_name\" ON \"{$table->name}\" (\"" . implode( '", "', $constraint->columns ) . '")'
912+
"CREATE $unique INDEX $if_not_exists \"$index_name\" ON \"{$table->name}\" (\"" . implode( '", "', $constraint->columns ) . '")'
911913
);
912914
$this->update_data_type_cache(
913915
$table->name,

0 commit comments

Comments
 (0)