Skip to content

Commit

Permalink
[#2733] Implement datastore_search sort parameter.
Browse files Browse the repository at this point in the history
  • Loading branch information
johnglover committed Jul 31, 2012
1 parent e391811 commit 67e6f4c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
9 changes: 7 additions & 2 deletions ckanext/datastore/db.py
Expand Up @@ -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]

Expand Down
35 changes: 34 additions & 1 deletion ckanext/datastore/tests/test_datastore.py
Expand Up @@ -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}
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 67e6f4c

Please sign in to comment.