2014-05-04 17:26:43 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2014-09-02 22:32:44 +00:00
|
|
|
|
2014-05-04 17:26:43 +00:00
|
|
|
|
2014-08-12 08:16:57 +00:00
|
|
|
#does not work in sqlite
|
|
|
|
#from sqlalchemy.sql.expression import nullslast
|
2016-02-26 05:51:16 +00:00
|
|
|
from sqlalchemy.sql.expression import text
|
2014-08-12 08:16:57 +00:00
|
|
|
|
2014-09-02 22:32:44 +00:00
|
|
|
from . import models
|
2014-08-12 08:16:57 +00:00
|
|
|
import settings
|
2014-05-04 17:26:43 +00:00
|
|
|
import utils
|
|
|
|
|
2016-03-17 14:44:06 +00:00
|
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2014-05-04 17:26:43 +00:00
|
|
|
def parse(data):
|
|
|
|
query = {}
|
|
|
|
query['range'] = [0, 100]
|
2019-01-17 10:27:55 +00:00
|
|
|
if 'group' not in data:
|
|
|
|
query['sort'] = [{'key': 'title', 'operator': '+'}]
|
2014-05-04 17:26:43 +00:00
|
|
|
for key in ('keys', 'group', 'list', 'range', 'sort', 'query'):
|
|
|
|
if key in data:
|
|
|
|
query[key] = data[key]
|
2016-03-17 14:44:06 +00:00
|
|
|
if [r for r in query['range'] if not isinstance(r, int)]:
|
|
|
|
logger.error('range must be 2 integers! got this: %s', query['range'])
|
|
|
|
query['range'] = [0, 0]
|
2016-01-10 09:10:38 +00:00
|
|
|
query['qs'] = models.Item.find(data)
|
2019-01-17 10:27:55 +00:00
|
|
|
if 'group' not in query:
|
2014-05-04 17:26:43 +00:00
|
|
|
query['qs'] = order(query['qs'], query['sort'])
|
|
|
|
return query
|
|
|
|
|
2014-05-21 22:41:29 +00:00
|
|
|
def order(qs, sort, prefix='sort.'):
|
2014-05-04 17:26:43 +00:00
|
|
|
order_by = []
|
|
|
|
if len(sort) == 1:
|
|
|
|
additional_sort = settings.config['user']['ui']['listSort']
|
|
|
|
key = utils.get_by_id(models.Item.item_keys, sort[0]['key'])
|
|
|
|
for s in key.get('additionalSort', additional_sort):
|
|
|
|
if s['key'] not in [e['key'] for e in sort]:
|
|
|
|
sort.append(s)
|
|
|
|
for e in sort:
|
|
|
|
operator = e['operator']
|
|
|
|
if operator != '-':
|
|
|
|
operator = ''
|
|
|
|
else:
|
|
|
|
operator = ' DESC'
|
|
|
|
key = {}.get(e['key'], e['key'])
|
|
|
|
if key not in ('fixme', ):
|
|
|
|
key = "%s%s" % (prefix, key)
|
|
|
|
order = '%s%s' % (key, operator)
|
|
|
|
order_by.append(order)
|
|
|
|
if order_by:
|
|
|
|
#nulllast not supported in sqlite, use IS NULL hack instead
|
|
|
|
#order_by = map(nullslast, order_by)
|
|
|
|
_order_by = []
|
|
|
|
for order in order_by:
|
|
|
|
nulls = "%s IS NULL" % order.split(' ')[0]
|
2016-02-22 12:30:55 +00:00
|
|
|
_order_by.append(text(nulls))
|
|
|
|
_order_by.append(text(order))
|
2014-05-04 17:26:43 +00:00
|
|
|
order_by = _order_by
|
2014-05-21 22:41:29 +00:00
|
|
|
qs = qs.join(models.Sort).order_by(*order_by)
|
2014-05-04 17:26:43 +00:00
|
|
|
return qs
|