From 67e6f4c385a414d19192a93f6fd8553593886cba Mon Sep 17 00:00:00 2001 From: John Glover Date: Tue, 31 Jul 2012 17:14:12 +0100 Subject: [PATCH] [#2733] Implement datastore_search sort parameter. --- ckanext/datastore/db.py | 9 ++++-- ckanext/datastore/tests/test_datastore.py | 35 ++++++++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/ckanext/datastore/db.py b/ckanext/datastore/db.py index 3dec899a1ee..207bb7a45e0 100644 --- a/ckanext/datastore/db.py +++ b/ckanext/datastore/db.py @@ -341,10 +341,15 @@ def search_data(context, data_dict): limit = data_dict.get('limit', 100) offset = data_dict.get('offset', 0) + if data_dict.get('sort'): + sort = 'order by {}'.format(data_dict['sort']) + else: + sort = '' + sql_string = '''select {}, count(*) over() as full_count - from "{}" {} limit {} offset {}'''\ + from "{}" {} {} limit {} offset {}'''\ .format(select_columns, data_dict['resource_id'], where_clause, - limit, offset) + sort, limit, offset) results = context['connection'].execute(sql_string, where_values) results = [r for r in results] diff --git a/ckanext/datastore/tests/test_datastore.py b/ckanext/datastore/tests/test_datastore.py index a4474e35b82..6f4d3fa3d07 100644 --- a/ckanext/datastore/tests/test_datastore.py +++ b/ckanext/datastore/tests/test_datastore.py @@ -530,6 +530,40 @@ def test_search_filters(self): assert result['records'] == [{'book': 'annakarenina', 'author': 'tolstoy'}] + def test_search_sort(self): + data = {'resource_id': self.data['resource_id'], + 'sort': 'book asc'} + postparams = '%s=1' % json.dumps(data) + auth = {'Authorization': str(self.sysadmin_user.apikey)} + res = self.app.post('/api/action/datastore_search', params=postparams, + extra_environ=auth) + res_dict = json.loads(res.body) + assert res_dict['success'] is True + result = res_dict['result'] + assert result['total'] == 2 + + expected_records = [ + {'book': 'annakarenina', 'author': 'tolstoy'}, + {'book': 'warandpeace', 'author': 'tolstoy'} + ] + assert result['records'] == expected_records + + data = {'resource_id': self.data['resource_id'], + 'sort': 'book desc'} + postparams = '%s=1' % json.dumps(data) + res = self.app.post('/api/action/datastore_search', params=postparams, + extra_environ=auth) + res_dict = json.loads(res.body) + assert res_dict['success'] is True + result = res_dict['result'] + assert result['total'] == 2 + + expected_records = [ + {'book': 'warandpeace', 'author': 'tolstoy'}, + {'book': 'annakarenina', 'author': 'tolstoy'} + ] + assert result['records'] == expected_records + def test_search_limit(self): data = {'resource_id': self.data['resource_id'], 'limit': 1} @@ -576,7 +610,6 @@ def test_search_full_text(self): data = {'resource_id': self.data['resource_id'], 'q': 'tolstoy'} postparams = '%s=1' % json.dumps(data) - auth = {'Authorization': str(self.sysadmin_user.apikey)} res = self.app.post('/api/action/datastore_search', params=postparams, extra_environ=auth) res_dict = json.loads(res.body)