Skip to content

sa.union_all() fails with sa.text() if use ORDER BY. #6385

@p-frolov

Description

@p-frolov

Describe the bug
Not sure that it's bug, but when I use union all with sa.text as queries and the queries contains ORDER BY (or something except FROM) - I get syntax error.
I got sql from the error, added brackets manually to selects and it works.
How to add brackets to sql from SA side? Or I should to that by adding directly to text? May be there is way to "ask" SqlAlchemy to do that?

sorry for not fully working example, but it seems this is a simple to reproduce. I have simplified the code.

OK

        for bu in bu_ids:
            view_name = f'view_{bu}'
            queries.append(
                sa.text(f'''
                    SELECT run_id
                    FROM {view_name}
                ''')
            )
        q_union = sa.union_all(*queries)
        result = conn.execute(q_union).fetchall()
    SELECT run_id
    FROM view_26416
 UNION ALL
    SELECT run_id
    FROM view_192582

NOK

        for bu in bu_ids:
            view_name = f'view_{bu}'
            queries.append(
                sa.text(f'''
                    SELECT run_id
                    FROM {view_name}
                    ORDER BY {run_id} DESC
                    LIMIT 1
                ''')
            )
        q_union = sa.union_all(*queries)
        result = conn.execute(q_union).fetchall()
    SELECT run_id
    FROM view_26416
    ORDER BY run_id DESC
    LIMIT 1
 UNION ALL
    SELECT run_id
    FROM view_192582
    ORDER BY run_id DESC
    LIMIT 1

Error

ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near "UNION"
LINE 9:                  UNION ALL 
                         ^

[SQL: 
                    SELECT run_id,
                    FROM view_26416
                    ORDER BY run_id DESC
                    LIMIT 1
                 UNION ALL 
                    SELECT run_id
                    FROM view_192582
                    ORDER BY run_id DESC
                    LIMIT 1
                ]
(Background on this error at: http://sqlalche.me/e/13/f405)

FIXED SQL

(
    SELECT run_id
    FROM view_26416
    ORDER BY run_id DESC
    LIMIT 1
)
 UNION ALL
(
    SELECT run_id
    FROM view_192582
    ORDER BY run_id DESC
    LIMIT 1
)

Versions.

  • OS: Linux Mint 20.1 Cinnamon
  • Python: Python 3.7.9
  • SQLAlchemy: 1.3.19
  • Database: PostgreSQL 11.1
  • DBAPI: psycopg2-binary==2.7.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionissue where a "fix" on the SQLAlchemy side is unlikely, hence more of a usage question

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions