Skip to content

Commit 58f55b6

Browse files
authored
ON DUPLICATE KEY: Prevent adding a comma if key isn't in the first position (#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
1 parent 4b0dab5 commit 58f55b6

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

tests/WP_SQLite_Query_Tests.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,21 @@ public function testRecoverSerialized() {
505505
$this->assertEquals( $obj, $unserialized );
506506
}
507507

508+
public function testOnDuplicateKey() {
509+
$this->assertQuery(
510+
'CREATE TABLE `test` (
511+
`id` INT PRIMARY KEY,
512+
`text` VARCHAR(255),
513+
);'
514+
);
515+
// The order is deliberate to test that the query works with the keys in any order.
516+
$this->assertQuery(
517+
'INSERT INTO test (`text`, `id`)
518+
VALUES ("test", 1)
519+
ON DUPLICATE KEY UPDATE `text` = "test1"'
520+
);
521+
}
522+
508523
public function testShowColumns() {
509524

510525
$query = 'SHOW COLUMNS FROM wp_posts';

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2803,9 +2803,10 @@ private function translate_on_duplicate_key( $table_name ) {
28032803
$this->rewriter->add( new WP_SQLite_Token( '(', WP_SQLite_Token::TYPE_OPERATOR ) );
28042804

28052805
$max = count( $conflict_columns );
2806-
foreach ( $conflict_columns as $i => $conflict_column ) {
2806+
$i = 0;
2807+
foreach ( $conflict_columns as $conflict_column ) {
28072808
$this->rewriter->add( new WP_SQLite_Token( '"' . $conflict_column . '"', WP_SQLite_Token::TYPE_KEYWORD, WP_SQLite_Token::FLAG_KEYWORD_KEY ) );
2808-
if ( $i !== $max - 1 ) {
2809+
if ( ++$i < $max ) {
28092810
$this->rewriter->add( new WP_SQLite_Token( ',', WP_SQLite_Token::TYPE_OPERATOR ) );
28102811
$this->rewriter->add( new WP_SQLite_Token( ' ', WP_SQLite_Token::TYPE_WHITESPACE ) );
28112812
}

0 commit comments

Comments
 (0)