From b2f2df5f5957acb30f0d55874e650d3cae182844 Mon Sep 17 00:00:00 2001 From: Jana Cupova Date: Jan 15 2024 10:28:10 +0000 Subject: Add DISTINCT to QueryProcessor Fixes: https://pagure.io/koji/issue/3972 --- diff --git a/kojihub/db.py b/kojihub/db.py index a7cd1cf..b484902 100644 --- a/kojihub/db.py +++ b/kojihub/db.py @@ -665,7 +665,7 @@ class QueryProcessor(object): def __str__(self): query = \ """ -SELECT %(col_str)s +SELECT %(distinct)s%(col_str)s FROM %(table_str)s %(join_str)s %(clause_str)s @@ -688,6 +688,12 @@ SELECT %(col_str)s col_str = 'count(*)' else: col_str = self._seqtostr(self.columns) + if self.opts.get('distinct') and not self.opts.get('countOnly'): + distinct = 'DISTINCT ' + elif self.opts.get('distinct') and self.opts.get('countOnly'): + koji.GenericError('DISTINCT cannot be used with countOnly.') + else: + distinct = '' table_str = self._seqtostr(self.tables, sort=True) join_str = self._joinstr() clause_str = self._seqtostr(self.clauses, sep=')\n AND (') diff --git a/tests/test_lib/test_query_processor.py b/tests/test_lib/test_query_processor.py index ab469cc..31bee31 100644 --- a/tests/test_lib/test_query_processor.py +++ b/tests/test_lib/test_query_processor.py @@ -139,3 +139,13 @@ class TestQueryProcessor(unittest.TestCase): results = proc.execute() self.assertEqual( results, [['result_1_col_1', 'result_1_col_2'], ['result_2_col_1', 'result_2_col_2']]) + + def test_distinct_and_count(self): + proc = kojihub.QueryProcessor( + columns=['something'], + tables=['awesome'], + opts={'distinct': True} + ) + actual = " ".join([token for token in str(proc).split() if token]) + expected = "SELECT DISTINCT something FROM awesome" + self.assertEqual(actual, expected)