SQLAlchemy: creating a subquery query.from_statement (text (...)), raising AttributeError

I am creating a tool that relies heavily on the SQLAlchemy query builder, but which allows the user to specify the literal text of the subqueries to join in cases where the model is insufficient.

However, when I try something like this:

q = session.query().from_statement(sa.text(subquery_text)).subquery(subquery_name)

... an exception occurs:

  File ".../lib/sqlalchemy/orm/query.py", line 473, in subquery
    return q.alias(name=name)
AttributeError: 'AnnotatedTextClause' object has no attribute 'alias'

A look at the implementation .subquery()in SQLAlchemy codebase enhances some clarity about how we got the AnnotatedTextClause object from the Query object:

def subquery(self, name=None, with_labels=False, reduce_columns=False):
    # docstring in the original omitted here for brevity
    q = self.enable_eagerloads(False)
    if with_labels:
        q = q.with_labels()
    q = q.statement
    if reduce_columns:
        q = q.reduce_columns()
    return q.alias(name=name)

... but I find that I am not aware of whether what I am trying to do is possible, and if so, how it will be done.

+4
source share

Source: https://habr.com/ru/post/1619136/


All Articles