From 4e1debf6700c9c787ea18bb660a939f82e3d4fb7 Mon Sep 17 00:00:00 2001 From: Piotr M Date: Thu, 6 Apr 2017 13:53:55 +0200 Subject: [PATCH] Fix duplicate key value violation in setValues DB function --- lib/private/DB/Connection.php | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index 2c5f81c568e2..d1737167bd8b 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -260,7 +260,7 @@ private function getType($value) { } /** - * Insert or update a row value + * Insert or update a row value. * * @param string $table * @param array $keys (column name => value) @@ -271,16 +271,13 @@ private function getType($value) { * @throws PreConditionNotMetException */ public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { - try { - $insertQb = $this->getQueryBuilder(); - $insertQb->insert($table) - ->values( - array_map(function($value) use ($insertQb) { - return $insertQb->createNamedParameter($value, $this->getType($value)); - }, array_merge($keys, $values)) - ); - return $insertQb->execute(); - } catch (ConstraintViolationException $e) { + // Try to insert whole record into the table ($toInsert) if predicate NOT EXISTS ($compare) is satisfied + $toInsert = array_merge($keys, $values); + $compare = array_keys($keys); + $tableName = $this->tablePrefix . $table; + $affected = $this->adapter->insertIfNotExist($tableName, $toInsert, $compare); + + if ($affected === 0) { // value already exists, try update $updateQb = $this->getQueryBuilder(); $updateQb->update($table); @@ -303,8 +300,9 @@ public function setValues($table, array $keys, array $values, array $updatePreco throw new PreConditionNotMetException(); } - return 0; } + + return $affected; } /**