Skip to content

Commit

Permalink
prevent count queries from re-executing due to sort/page options
Browse files Browse the repository at this point in the history
  • Loading branch information
guruofgentoo committed Aug 15, 2022
1 parent b6537ab commit 0cf55e6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
13 changes: 9 additions & 4 deletions webgrid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1210,7 +1210,7 @@ def set_sort(self, *args):
that key, prepend with a "-".
E.g. `grid.set_sort('author', '-post_date')`
"""
self.clear_record_cache()
self.clear_record_cache(preserve_count=True)
self.order_by = []

for key in args:
Expand All @@ -1232,14 +1232,19 @@ def set_paging(self, per_page, on_page):
per_page (int): Record limit for each page.
on_page (int): With `per_page`, computes the offset.
"""
self.clear_record_cache()
self.clear_record_cache(preserve_count=True)
self.per_page = per_page
self.on_page = on_page

def clear_record_cache(self):
def clear_record_cache(self, preserve_count=False):
"""Reset records and record count cached from previous queries.
Args:
preserve_count (bool): Direct grid to retain count of records, effectively removing
only the table of records itself.
"""
self._record_count = None
if not preserve_count:
self._record_count = None
self._records = None

@property
Expand Down
27 changes: 27 additions & 0 deletions webgrid/tests/test_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,33 @@ def test_record_count(self, m_debug):
for idx, call in enumerate(m_debug.call_args_list):
assert re.match(expected[idx], call[0][0])

@mock.patch('logging.Logger.debug')
def test_record_count_preserved_during_sort(self, m_debug):
g = self.TG()
assert g.record_count == 5
assert m_debug.call_count == 3
g.set_sort('firstname')
assert g.record_count == 5
assert m_debug.call_count == 3

@mock.patch('logging.Logger.debug')
def test_record_count_preserved_during_paging(self, m_debug):
g = self.TG()
assert g.record_count == 5
assert m_debug.call_count == 3
g.set_paging(25, 1)
assert g.record_count == 5
assert m_debug.call_count == 3

@mock.patch('logging.Logger.debug')
def test_record_count_cleared_during_filter(self, m_debug):
g = self.KeyGrid()
g.record_count
assert m_debug.call_count == 3
g.set_filter('id', 'eq', '5')
g.record_count
assert m_debug.call_count == 6

def test_column_iterators_for_rendering(self):
class TG(Grid):
Column('C1', Person.firstname)
Expand Down

0 comments on commit 0cf55e6

Please sign in to comment.