From a61a757b854d89941f525dc218c0d5efd2e9dbc6 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 9 Nov 2020 17:43:29 +0100 Subject: [PATCH] allow selecting multiple columns with SELECT DISTINCT Signed-off-by: Robin Appelman --- lib/private/DB/QueryBuilder/QueryBuilder.php | 8 +++- .../lib/DB/QueryBuilder/QueryBuilderTest.php | 38 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/lib/private/DB/QueryBuilder/QueryBuilder.php b/lib/private/DB/QueryBuilder/QueryBuilder.php index 7fdeed1213..c2686f7b4a 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -436,8 +436,14 @@ class QueryBuilder implements IQueryBuilder { * @return $this This QueryBuilder instance. */ public function selectDistinct($select) { + if (!is_array($select)) { + $select = [$select]; + } + + $quotedSelect = $this->helper->quoteColumnNames($select); + $this->queryBuilder->addSelect( - 'DISTINCT ' . $this->helper->quoteColumnName($select) + 'DISTINCT ' . implode(', ', $quotedSelect) ); return $this; diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php index faf06360e1..fe87a201d5 100644 --- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php @@ -314,6 +314,44 @@ class QueryBuilderTest extends \Test\TestCase { $this->deleteTestingRows('testFirstResult2'); } + public function testSelectDistinctMultiple() { + $this->deleteTestingRows('testFirstResult1'); + $this->deleteTestingRows('testFirstResult2'); + $this->createTestingRows('testFirstResult1'); + $this->createTestingRows('testFirstResult2'); + + $this->queryBuilder->selectDistinct(['appid', 'configkey']); + + $this->queryBuilder->from('*PREFIX*appconfig') + ->where($this->queryBuilder->expr()->eq( + 'appid', + $this->queryBuilder->expr()->literal('testFirstResult1') + )) + ->orderBy('appid', 'DESC'); + + $query = $this->queryBuilder->execute(); + $rows = $query->fetchAll(); + $query->closeCursor(); + + $this->assertEquals( + [ + ['appid' => 'testFirstResult1', 'configkey' => 'testing1'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing2'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing3'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing4'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing5'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing6'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing7'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing8'], + ['appid' => 'testFirstResult1', 'configkey' => 'testing9'], + ], + $rows + ); + + $this->deleteTestingRows('testFirstResult1'); + $this->deleteTestingRows('testFirstResult2'); + } + public function dataAddSelect() { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(ILogger::class);