Using PostgreSQL Aggregate ORDER BY with sqlalchemy

I have a query that uses PostgreSQL syntax to use ORDER BY in an aggregate function, something like this:

SELECT some_agg_func(a ORDER BY b DESC) FROM table;

      

Does anyone know how to do this with sqlalchemy expression language?

+4


source to share


3 answers


You need to use the SQLAlchemy compiler extension for this . Here's an example Postgres function string_agg

:



from sqlalchemy.sql.expression import ColumnElement, _literal_as_column
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.compiler import compiles

class string_agg(ColumnElement):
    def __init__(self, expr, separator, order_by=None):
        self.type = Text()
        self.expr = _literal_as_column(expr)
        self.separator = literal(separator)
        self.order_by = _literal_as_column(order_by)

    @property
    def _from_objects(self):
        return self.expr._from_objects

@compiles(string_agg, 'postgresql')
def compile_string_agg(element, compiler, **kwargs):
    head = 'string_agg(%s, %s' % (
        compiler.process(element.expr),
        compiler.process(element.separator)
    )
    if element.order_by is not None:
        tail = ' ORDER BY %s)' % compiler.process(element.order_by)
    else:
        tail = ')'
    return head + tail

query = session.query(string_agg(Foo.bar, ', ', order_by=Foo.bar.desc()))
# Print compiled SQL query.
print query.statement.compile(dialect=postgresql.dialect())
# Run the query and print result.
print query.scalar()

      

+1


source


I think SqlAlchemy 1.1 has built-in support now string_agg

: http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.aggregate_order_by (search by page "func.string_agg")



+6


source


From the SQLAlchemy docs :

from sqlalchemy.dialects.postgresql import aggregate_order_by

expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc()))
stmt = select([expr])

      

0


source







All Articles