Skip to content

Commit

Permalink
ON DUPLICATE KEY: Prevent adding a comma if key isn't in the first po…
Browse files Browse the repository at this point in the history
…sition (#113)

[WordPress Playground observed an
issu](WordPress/wordpress-playground#731
with insert queries that use `ON DUPLICATE KEY` and don't have the KEY
as the first value of the insert.

After investigating it it turns out that the condition for adding commas
didn't work well in case the KEY value is in a "random" place.

This PR ensures the comma is added for all items except for the last
one.

## Testing instructions

- Ensure tests pass
  • Loading branch information
bgrgicak committed May 17, 2024
1 parent 4b0dab5 commit 58f55b6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
15 changes: 15 additions & 0 deletions tests/WP_SQLite_Query_Tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,21 @@ public function testRecoverSerialized() {
$this->assertEquals( $obj, $unserialized );
}

public function testOnDuplicateKey() {
$this->assertQuery(
'CREATE TABLE `test` (
`id` INT PRIMARY KEY,
`text` VARCHAR(255),
);'
);
// The order is deliberate to test that the query works with the keys in any order.
$this->assertQuery(
'INSERT INTO test (`text`, `id`)
VALUES ("test", 1)
ON DUPLICATE KEY UPDATE `text` = "test1"'
);
}

public function testShowColumns() {

$query = 'SHOW COLUMNS FROM wp_posts';
Expand Down
5 changes: 3 additions & 2 deletions wp-includes/sqlite/class-wp-sqlite-translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -2803,9 +2803,10 @@ private function translate_on_duplicate_key( $table_name ) {
$this->rewriter->add( new WP_SQLite_Token( '(', WP_SQLite_Token::TYPE_OPERATOR ) );

$max = count( $conflict_columns );
foreach ( $conflict_columns as $i => $conflict_column ) {
$i = 0;
foreach ( $conflict_columns as $conflict_column ) {
$this->rewriter->add( new WP_SQLite_Token( '"' . $conflict_column . '"', WP_SQLite_Token::TYPE_KEYWORD, WP_SQLite_Token::FLAG_KEYWORD_KEY ) );
if ( $i !== $max - 1 ) {
if ( ++$i < $max ) {
$this->rewriter->add( new WP_SQLite_Token( ',', WP_SQLite_Token::TYPE_OPERATOR ) );
$this->rewriter->add( new WP_SQLite_Token( ' ', WP_SQLite_Token::TYPE_WHITESPACE ) );
}
Expand Down

0 comments on commit 58f55b6

Please sign in to comment.