Skip to content

refine distinct + order_by "add primary cols" logic for non wrapped selectable #3641

@sqlalchemy-bot

Description

@sqlalchemy-bot

Migrated issue, originally created by Mehdi GMIRA (@mehdigmira)

I encountred a bug with the postgres specific "DISTINCT ON" in SQLAlchemy
The real SA query I'm using is more complicated than this, but it sums up to :

query = db.session.query(c1, c2, c3, c4).distinct(c1, c2).order_by(c1, c2, c3)

when i compile the query by doing:

query.statement.compile(dialect=postgres.dialect())

The actual query is

SELECT DISTINCT ON (c1, c2) c1, c2, c3, c4, c1, c2, c3 FROM .... ORDER BY c1, c2, c3

As you can see, the columns c1, c2, c3 are repeated. After some investigation, it seems like this is caused by the order_by() part of the query (removing order by removes the repeated columns).
The weird thing is that when actually running the query (query.all()), I only get the column that I requested, and not the repeated ones as in the compiled statement.
This would have been fine with me. But the problem is it's preventing me from using a union(), because SA thinks I'm requesting more columns on one side of union().

I think It's a bug, but maybe I'm just doing something wrong.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingorm

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions