From 40fdff5b8073f370daf347f24d9d95d111e62b96 Mon Sep 17 00:00:00 2001 From: Christoph Wurst Date: Thu, 6 Sep 2018 08:46:18 +0200 Subject: Add QBMapper::insertOrUpdate() This allows elegant upserts where the entity ID is provided (e.g. by an external system) and when that data is fed into our database multiple times. Signed-off-by: Christoph Wurst --- lib/public/AppFramework/Db/QBMapper.php | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/public/AppFramework/Db/QBMapper.php b/lib/public/AppFramework/Db/QBMapper.php index a9b38732a30..b8ebd379b4d 100644 --- a/lib/public/AppFramework/Db/QBMapper.php +++ b/lib/public/AppFramework/Db/QBMapper.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace OCP\AppFramework\Db; +use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; @@ -123,7 +124,23 @@ abstract class QBMapper { return $entity; } - + /** + * Tries to creates a new entry in the db from an entity and + * updates an existing entry if duplicate keys are detected + * by the database + * + * @param Entity $entity the entity that should be created/updated + * @return Entity the saved entity with the (new) id + * @since 15.0.0 + * @suppress SqlInjectionChecker + */ + public function insertOrUpdate(Entity $entity): Entity { + try { + return $this->insert($entity); + } catch (UniqueConstraintViolationException $ex) { + return $this->update($entity); + } + } /** * Updates an entry in the db from an entity -- cgit v1.2.3 From 3f594fc1b7fbd34461d9fdfba71f416abb935e25 Mon Sep 17 00:00:00 2001 From: Christoph Wurst Date: Fri, 14 Sep 2018 15:50:55 +0200 Subject: Document possibly thrown excption of QBMapper::insertOrUpdate Signed-off-by: Christoph Wurst --- lib/public/AppFramework/Db/QBMapper.php | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/public/AppFramework/Db/QBMapper.php b/lib/public/AppFramework/Db/QBMapper.php index b8ebd379b4d..dbc47d2d43d 100644 --- a/lib/public/AppFramework/Db/QBMapper.php +++ b/lib/public/AppFramework/Db/QBMapper.php @@ -131,6 +131,7 @@ abstract class QBMapper { * * @param Entity $entity the entity that should be created/updated * @return Entity the saved entity with the (new) id + * @throws \InvalidArgumentException if entity has no id * @since 15.0.0 * @suppress SqlInjectionChecker */ -- cgit v1.2.3