dictinct(Model) generates unexpected query

Issue #3318 duplicate
tosh created an issue

Hi there,

I use SQLAlchemy 0.8.3 (so maybe it's fixed in newer releases) with MySQL 5.1.73.
When I do the query

Session.query(distinct(Model))

it generates something like

SELECT DISTINCT :param_1 AS anon_1;

Where :param_1 is replaced with Model.__repr__() which is a simple string.

Maybe it would be more obvious if such SQLAlchemy-queries generated the following code?

SELECT DISTINCT id AS anon_1 FROM model_table;

Optionally, SQLAlchemy could raise an exception if a model was passed as an argument.

Comments (7)

  1. Mike Bayer repo owner

    if you want DISTINCT id AS anon_1, then call distinct(Model.id).

    Perhaps you're looking for simple Session.query(Model).distinct()? The standalone distinct() call is for the specific case of DISTINCT on just one column, as opposed to a DISTINCT for the statement overall, this is documented.

  2. tosh reporter

    Okay,

    this is documented

    Oops, my fault, sorry.

    I just think about consistency or something like this. At least, standalone distinct could raise an error when Model is passed. Such behaviour is more expected, you know.

  3. Mike Bayer repo owner

    well you can pass literal values, like strings and ints, to a column expression and it is automatically turned into a bound parameter. at the moment SQLAlchemy doesn't make any assumptions about objects in this case as they could very well be something that the backend DBAPI knows how to interpret, like date objects and such. It is possibly a good idea that SQLAlchemy adopt a stricter policy on bound parameter values at some point, perhaps checking with the dialect for expected types or just checking that the object isn't a known SQLAlchemy object like a mapped class that doesn't belong, but that's a bigger scope than what we have here. Would be a 1.1 thing at this point.

  4. Log in to comment