Query.exists() fails if the query doesn't select any columns (worked in 0.8.x)

Issue #2995 resolved
Daniel Grace created an issue

This appears to be a regression:

This (pseudocode) used to run with no issues in 0.8.x:

# [...]
subquery = session.query().select_from(Bar) # Note no selected columns
query = query.filter(subquery.exists())

Now it fails on the .exists() line with the following exception: sqlalchemy.exc.InvalidRequestError: Query contains no columns with which to SELECT from

The documentation for .exists() states that it is a "A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...).".
Thus, there should be no need for the subquery to select any columns of its own since they will all be replaced by the implicit "SELECT 1" from the exists anyways.

Rewriting the above as:

subquery = session.query().select_from(Bar)
query = query.filter(subquery.add_columns(sql.true()).exists())

avoids the exception and makes the query work as intended.

Comments (6)

  1. Mike Bayer repo owner
    • Fixed regression from 0.8.3 as a result of 🎫2818 where :meth:.Query.exists wouldn't work on a query that only had a :meth:.Query.select_from entry but no other entities. re: #2818 fixes #2995

    → <<cset 39a8e2ed375e>>

  2. Mike Bayer repo owner
    • Fixed regression from 0.8.3 as a result of 🎫2818 where :meth:.Query.exists wouldn't work on a query that only had a :meth:.Query.select_from entry but no other entities. re: #2818 fixes #2995

    → <<cset d8aa3d91d7ea>>

  3. Log in to comment