2016-09-26 19:16:03 +08:00
|
|
|
from django.contrib.postgres.fields import JSONField
|
2015-02-08 23:21:48 +08:00
|
|
|
from django.db.models.aggregates import Aggregate
|
|
|
|
|
|
|
|
__all__ = [
|
2016-11-13 04:42:20 +08:00
|
|
|
'ArrayAgg', 'BitAnd', 'BitOr', 'BoolAnd', 'BoolOr', 'JSONBAgg', 'StringAgg',
|
2015-02-08 23:21:48 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
class ArrayAgg(Aggregate):
|
|
|
|
function = 'ARRAY_AGG'
|
2017-01-23 23:34:42 +08:00
|
|
|
template = '%(function)s(%(distinct)s%(expressions)s)'
|
|
|
|
|
|
|
|
def __init__(self, expression, distinct=False, **extra):
|
|
|
|
super().__init__(expression, distinct='DISTINCT ' if distinct else '', **extra)
|
2015-02-08 23:21:48 +08:00
|
|
|
|
|
|
|
def convert_value(self, value, expression, connection, context):
|
|
|
|
if not value:
|
|
|
|
return []
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
class BitAnd(Aggregate):
|
|
|
|
function = 'BIT_AND'
|
|
|
|
|
|
|
|
|
|
|
|
class BitOr(Aggregate):
|
|
|
|
function = 'BIT_OR'
|
|
|
|
|
|
|
|
|
|
|
|
class BoolAnd(Aggregate):
|
|
|
|
function = 'BOOL_AND'
|
|
|
|
|
|
|
|
|
|
|
|
class BoolOr(Aggregate):
|
|
|
|
function = 'BOOL_OR'
|
|
|
|
|
|
|
|
|
2016-11-13 04:42:20 +08:00
|
|
|
class JSONBAgg(Aggregate):
|
2016-09-26 19:16:03 +08:00
|
|
|
function = 'JSONB_AGG'
|
|
|
|
_output_field = JSONField()
|
|
|
|
|
|
|
|
def convert_value(self, value, expression, connection, context):
|
|
|
|
if not value:
|
|
|
|
return []
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
2015-02-08 23:21:48 +08:00
|
|
|
class StringAgg(Aggregate):
|
|
|
|
function = 'STRING_AGG'
|
2016-05-15 17:53:16 +08:00
|
|
|
template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s')"
|
2015-02-08 23:21:48 +08:00
|
|
|
|
2016-05-15 17:53:16 +08:00
|
|
|
def __init__(self, expression, delimiter, distinct=False, **extra):
|
|
|
|
distinct = 'DISTINCT ' if distinct else ''
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(expression, delimiter=delimiter, distinct=distinct, **extra)
|
2015-02-08 23:21:48 +08:00
|
|
|
|
|
|
|
def convert_value(self, value, expression, connection, context):
|
|
|
|
if not value:
|
|
|
|
return ''
|
|
|
|
return value
|