From 6607cb4222794640a06bc91cb1c351755e6c69e8 Mon Sep 17 00:00:00 2001 From: Jean Praloran Date: Fri, 23 Aug 2019 11:50:39 +1200 Subject: [PATCH] add support for sub-query, https://github.com/sdispater/orator/pull/309 --- orator/query/builder.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/orator/query/builder.py b/orator/query/builder.py index 6e8aaa6c..9c7e2e59 100644 --- a/orator/query/builder.py +++ b/orator/query/builder.py @@ -63,7 +63,7 @@ def __init__(self, connection, grammar, processor): self._processor = processor self._connection = connection self._bindings = OrderedDict() - for type in ["select", "join", "where", "having", "order"]: + for type in ["select", "from", "join", "where", "having", "order"]: self._bindings[type] = [] self.aggregate_ = None @@ -188,8 +188,31 @@ def from_(self, table): :return: The current QueryBuilder instance :rtype: QueryBuilder """ + self.set_bindings([], "from") self.from__ = table + return self + + def from_sub(self, query, as_): + """ + Set the query target table to a subquery + + :param query: The QueryBuilder to set as from expression + :type query: QueryBuilder + + :param as_: The alias name for the subquery + :type as_: str + + :return: The current QueryBuilder instance + :rtype: QueryBuilder + """ + if not isinstance(query, QueryBuilder): + raise ArgumentError("From expression must be a QueryBuilder") + + bindings = query.get_bindings() + query = "(%s) AS %s" % (query.to_sql(), self._grammar.wrap(as_)) + self.set_bindings(bindings, "from") + self.from__ = QueryExpression(query) return self def join(self, table, one=None, operator=None, two=None, type="inner", where=False):