having.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #
  2. # Copyright 2013 Metamarkets Group Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. try:
  17. import simplejson as json
  18. except ImportError:
  19. import json
  20. class Having:
  21. def __init__(self, **args):
  22. if args['type'] in ('equalTo', 'lessThan', 'greaterThan'):
  23. self.having = {'having': {'type': args['type'],
  24. 'aggregation': args['aggregation'],
  25. 'value': args['value']}}
  26. elif args['type'] == 'and':
  27. self.having = {'having': {'type': 'and',
  28. 'havingSpecs': args['havingSpecs']}}
  29. elif args['type'] == 'or':
  30. self.having = {'having': {'type': 'or',
  31. 'havingSpecs': args['havingSpecs']}}
  32. elif args['type'] == 'not':
  33. self.having = {'having': {'type': 'not',
  34. 'havingSpec': args['havingSpec']}}
  35. else:
  36. raise NotImplemented(
  37. 'Having type: {0} does not exist'.format(args['type']))
  38. def show(self):
  39. print(json.dumps(self.having, indent=4))
  40. def _combine(self, typ, x):
  41. # collapse nested and/ors
  42. if self.having['having']['type'] == typ:
  43. havingSpecs = self.having['having']['havingSpecs'] + [x.having['having']]
  44. return Having(type=typ, havingSpecs=havingSpecs)
  45. elif x.having['having']['type'] == typ:
  46. havingSpecs = [self.having['having']] + x.having['having']['havingSpecs']
  47. return Having(type=typ, havingSpecs=havingSpecs)
  48. else:
  49. return Having(type=typ,
  50. havingSpecs=[self.having['having'], x.having['having']])
  51. def __and__(self, x):
  52. return self._combine('and', x)
  53. def __or__(self, x):
  54. return self._combine('or', x)
  55. def __invert__(self):
  56. return Having(type='not', havingSpec=self.having['having'])
  57. @staticmethod
  58. def build_having(having_obj):
  59. return having_obj.having['having']
  60. class Aggregation:
  61. def __init__(self, agg):
  62. self.aggregation = agg
  63. def __eq__(self, other):
  64. return Having(type='equalTo', aggregation=self.aggregation, value=other)
  65. def __lt__(self, other):
  66. return Having(type='lessThan', aggregation=self.aggregation, value=other)
  67. def __gt__(self, other):
  68. return Having(type='greaterThan', aggregation=self.aggregation, value=other)