Advertisement
Guest User

Untitled

a guest
Oct 9th, 2015
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. # Get everything! handles every single possible select query required
  2. # by the app..
  3. # note: field_map is not the nicest thing in the world..
  4. # it should be replaced by something wiser sometime!
  5. def query(g, params, tables, query_fields=None, query_op='ilike', what='*',
  6. join=None, where=None, field_map=None, group_by=None, order_by=None,
  7. include_total=True, debug=False):
  8. if query_fields is None:
  9. query_fields = ()
  10. if join is None:
  11. join = {}
  12. if where is None:
  13. where = {}
  14. if field_map is None:
  15. field_map = {}
  16. assert query_fields.__class__ is tuple
  17. cursor = g.db.cursor()
  18. if 'sort' in params:
  19. assert order_by is None
  20. sort_args = json.loads(params['sort'])
  21. order_by = ','.join(['%s %s' % (field_map.get(sa['property'],
  22. sa['property']),
  23. sa['direction']) for sa in sort_args])
  24.  
  25. # todo: put that somewhere that makes more sense
  26. comp_op_map = {'lt': '<', 'gt': '>', 'le': '<=', 'ge': '>=', 'eq': '='}
  27.  
  28. if params.get('filter', '').strip():
  29. for filter_arg in json.loads(params['filter']):
  30. f = filter_arg['field']
  31. if filter_arg['type'] == 'string':
  32. s = set(['%%%s%%' % v for v in filter_arg['value'].split()])
  33. where[(field_map.get(f, f), 'ilike', 'unaccent')] = s
  34. elif filter_arg['type'] == 'list':
  35. where[field_map.get(f, f)] = tuple(filter_arg['value'])
  36. else:
  37. fav = filter_arg['value']
  38. where[(field_map.get(f, f),
  39. comp_op_map[filter_arg.get('comparison', 'eq')])] = fav
  40.  
  41. if params.get('query', '').strip():
  42. # autocomplete query
  43. if query_op.lower() in ['ilike', 'like']:
  44. # this is needed because the concat operator (||)
  45. # doesn't work with null values
  46. query_fields = ["coalesce(%s::text, '')" % ff
  47. for ff in query_fields]
  48. s = set(['%%%s%%' % v for v in params['query'].split()])
  49. where[('||'.join(query_fields), query_op, 'unaccent')] = s
  50. # exact field query: assumes only 1 field,
  51. # because there is only 1 query value
  52. else:
  53. assert len(query_fields) == 1
  54. where[(query_fields[0], query_op)] = params['query']
  55.  
  56. json_out = {'success': True}
  57. if include_total and not debug:
  58. json_out['total'] = pg.count(cursor, tables, what=what, join=join,
  59. where=where, group_by=group_by,
  60. debug_assert=False)
  61. json_out['rows'] = pg.select(cursor, tables, what=what, join=join,
  62. where=where, offset=params.get('start', None),
  63. limit=params.get('limit', None) or None,
  64. group_by=group_by, order_by=order_by,
  65. debug_assert=debug)
  66. return json_out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement