general.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from django.contrib.postgres.fields import ArrayField
  2. from django.db.models import Aggregate, BooleanField, JSONField, Value
  3. from .mixins import OrderableAggMixin
  4. __all__ = [
  5. 'ArrayAgg', 'BitAnd', 'BitOr', 'BoolAnd', 'BoolOr', 'JSONBAgg', 'StringAgg',
  6. ]
  7. class ArrayAgg(OrderableAggMixin, Aggregate):
  8. function = 'ARRAY_AGG'
  9. template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
  10. allow_distinct = True
  11. @property
  12. def output_field(self):
  13. return ArrayField(self.source_expressions[0].output_field)
  14. def convert_value(self, value, expression, connection):
  15. if not value:
  16. return []
  17. return value
  18. class BitAnd(Aggregate):
  19. function = 'BIT_AND'
  20. class BitOr(Aggregate):
  21. function = 'BIT_OR'
  22. class BoolAnd(Aggregate):
  23. function = 'BOOL_AND'
  24. output_field = BooleanField()
  25. class BoolOr(Aggregate):
  26. function = 'BOOL_OR'
  27. output_field = BooleanField()
  28. class JSONBAgg(OrderableAggMixin, Aggregate):
  29. function = 'JSONB_AGG'
  30. template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
  31. allow_distinct = True
  32. output_field = JSONField()
  33. def convert_value(self, value, expression, connection):
  34. if not value:
  35. return '[]'
  36. return value
  37. class StringAgg(OrderableAggMixin, Aggregate):
  38. function = 'STRING_AGG'
  39. template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
  40. allow_distinct = True
  41. def __init__(self, expression, delimiter, **extra):
  42. delimiter_expr = Value(str(delimiter))
  43. super().__init__(expression, delimiter_expr, **extra)
  44. def convert_value(self, value, expression, connection):
  45. if not value:
  46. return ''
  47. return value