1 """SQLAlchemy extensions for dak
3 @copyright: 2014, Ansgar Burchardt <ansgar@debian.org>
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 from sqlalchemy.ext.compiler import compiles
22 from sqlalchemy.sql.expression import ColumnElement, ClauseElement, ClauseList, literal
23 from sqlalchemy.types import Text
24 from sqlalchemy.util import to_list
26 class array_agg(ColumnElement):
27 def __init__(self, expr, order_by=None):
28 self.expr = ClauseElement(expr)
30 if order_by is not None:
31 self.order_by = ClauseList(*to_list(order_by))
34 def compile_array_agg(element, compiler, **kw):
35 if element.order_by is not None:
36 return "ARRAY_AGG({0} ORDER BY {1})".format(compiler.process(element.expr), compiler.process(element.order_by))
37 return "ARRAY_AGG({0})".format(compiler.process(element.expr))
39 class string_agg(ColumnElement):
41 def __init__(self, column, seperator, order_by=None):
42 self.column = ClauseList(*to_list(column))
43 self.seperator = literal(seperator)
45 if order_by is not None:
46 self.order_by = ClauseList(*to_list(order_by))
49 def compile_string_agg(element, compiler, **kw):
50 if element.order_by is not None:
51 return "STRING_AGG({0}, {1} ORDER BY {2})".format(compiler.process(element.column), compiler.process(element.seperator), compiler.process(element.order_by))
52 return "STRING_AGG({0}, {1})".format(compiler.process(element.column), compiler.process(element.seperator))