diff --git a/CHANGELOG.md b/CHANGELOG.md index 3abc3d6..a784f73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Unreleased ---------- - Extend date field range (trthhrtz) - Fix parsing of server errors in ClickHouse v19.3.3+ +- Fix pagination when asking for the last page on a query that matches no records v1.0.4 ------ diff --git a/src/infi/clickhouse_orm/database.py b/src/infi/clickhouse_orm/database.py index 7e72e99..f7b6e87 100644 --- a/src/infi/clickhouse_orm/database.py +++ b/src/infi/clickhouse_orm/database.py @@ -285,7 +285,7 @@ class Database(object): count = self.count(model_class, conditions) pages_total = int(ceil(count / float(page_size))) if page_num == -1: - page_num = pages_total + page_num = max(pages_total, 1) elif page_num < 1: raise ValueError('Invalid page number: %d' % page_num) offset = (page_num - 1) * page_size @@ -296,7 +296,7 @@ class Database(object): query += ' LIMIT %d, %d' % (offset, page_size) query = self._substitute(query, model_class) return Page( - objects=list(self.select(query, model_class, settings)), + objects=list(self.select(query, model_class, settings)) if count else [], number_of_objects=count, pages_total=pages_total, number=page_num, diff --git a/tests/test_database.py b/tests/test_database.py index dd8776e..c563862 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -112,6 +112,14 @@ class DatabaseTestCase(TestCaseWithData): self.assertEqual([obj.to_tsv() for obj in page_a.objects], [obj.to_tsv() for obj in page_b.objects]) + def test_pagination_empty_page(self): + for page_num in (-1, 1, 2): + page = self.database.paginate(Person, 'first_name, last_name', page_num, 10, conditions="first_name = 'Ziggy'") + self.assertEqual(page.number_of_objects, 0) + self.assertEqual(page.objects, []) + self.assertEqual(page.pages_total, 0) + self.assertEqual(page.number, max(page_num, 1)) + def test_pagination_invalid_page(self): self._insert_and_check(self._sample_data(), len(data)) for page_num in (0, -2, -100):