diff --git a/src/InsertOnDuplicateKey.php b/src/InsertOnDuplicateKey.php index 6b9cf6e..c976018 100644 --- a/src/InsertOnDuplicateKey.php +++ b/src/InsertOnDuplicateKey.php @@ -196,16 +196,20 @@ protected static function getColumnList(array $first) /** * Build a value list. * - * @param array $first + * @param array $updatedColumns * * @return string */ - protected static function buildValuesList(array $first) + protected static function buildValuesList(array $updatedColumns) { $out = []; - foreach (array_keys($first) as $key) { - $out[] = sprintf('`%s` = VALUES(`%s`)', $key, $key); + foreach ($updatedColumns as $key => $value) { + if (is_numeric($key)) { + $out[] = sprintf('`%s` = VALUES(`%s`)', $value, $value); + } else { + $out[] = sprintf('%s = %s', $key, $value); + } } return implode(', ', $out); @@ -240,9 +244,9 @@ protected static function buildInsertOnDuplicateSql(array $data, array $updateCo $sql .= 'ON DUPLICATE KEY UPDATE '; if (empty($updateColumns)) { - $sql .= static::buildValuesList($first); + $sql .= static::buildValuesList(array_keys($first)); } else { - $sql .= static::buildValuesList(array_combine($updateColumns, $updateColumns)); + $sql .= static::buildValuesList($updateColumns); } return $sql; diff --git a/tests/MainTest.php b/tests/MainTest.php index 52f7974..9b3d6bd 100644 --- a/tests/MainTest.php +++ b/tests/MainTest.php @@ -63,11 +63,29 @@ public function testGetColumnList() public function testBuildValuesList() { - $data = $this->getDataForInsert(); + $value = [ + 'id', + 'email', + 'name' + ]; $expected = '`id` = VALUES(`id`), `email` = VALUES(`email`), `name` = VALUES(`name`)'; - $result = $this->invokeMethod($this->user, 'buildValuesList', [$data[0]]); + $result = $this->invokeMethod($this->user, 'buildValuesList', [$value]); + + $this->assertEquals($expected, $result); + } + + public function testBuildValuesListAssociativeArray() + { + $value = [ + 'id' => 'id + 1', + 'counter' => 'counter + 2', + ]; + + $expected = 'id = id + 1, counter = counter + 2'; + + $result = $this->invokeMethod($this->user, 'buildValuesList', [$value]); $this->assertEquals($expected, $result); } @@ -152,6 +170,19 @@ public function testBuildInsertOnDuplicateSqlMultipleWithUpdateColumn() $this->assertEquals($expected, $result); } + public function testUpdatedColumnIsAssociativeArray() + { + $data = $this->getDataForInsert(); + + $expected = 'INSERT INTO `prefix_test_user_table`(`id`,`email`,`name`) VALUES +(?,?,?), (?,?,?), (?,?,?) +ON DUPLICATE KEY UPDATE counter = counter + 1'; + + $result = $this->invokeMethod($this->user, 'buildInsertOnDuplicateSql', [$data, ['counter' => 'counter + 1']]); + + $this->assertEquals($expected, $result); + } + public function testBuildInsertIgnoreSqlSimple() { $data = [