1. Michael Bayer
  2. sqlalchemy
  3. Issues

Issues

Issue #2818 resolved

Query.exists() don't works with queries without filters

Vladimir Magamedov
created an issue

Action:

db.session.query(User).exists()

Expectation:

SELECT 1 FROM users

Current result:

SELECT 1

Solution:

diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py
index b71bfe0..d64575a 100644
--- a/lib/sqlalchemy/orm/query.py
+++ b/lib/sqlalchemy/orm/query.py
@@ -2494,7 +2494,7 @@ class Query(object):
         .. versionadded:: 0.8.1

         """
-        return sql.exists(self.with_entities('1').statement)
+        return sql.exists(self.statement.with_only_columns(['1']('1')))

     def count(self):
         """Return a count of rows this Query would return.
diff --git a/test/orm/test_query.py b/test/orm/test_query.py
index 0973dc3..bc56668 100644
--- a/test/orm/test_query.py
+++ b/test/orm/test_query.py
@@ -1730,9 +1730,16 @@ class ExistsTest(QueryTest, AssertsCompiledSQL):
     def test_exists(self):
         User = self.classes.User
         sess = create_session()
-        q1 = sess.query(User).filter(User.name == 'fred')
+        q1 = sess.query(User)
         self.assert_compile(sess.query(q1.exists()),
             'SELECT EXISTS ('
+                'SELECT 1 FROM users'
+            ') AS anon_1',
+            dialect=default.DefaultDialect()
+        )
+        q2 = sess.query(User).filter(User.name == 'fred')
+        self.assert_compile(sess.query(q2.exists()),
+            'SELECT EXISTS ('
                 'SELECT 1 FROM users WHERE users.name = :name_1'
             ') AS anon_1',
             dialect=default.DefaultDialect()

P.S. Is it normal to send pull requests on GitHub? Or you prefer Trac/patches?

Comments (7)

  1. Michael Bayer repo owner
    • changed status to open
    • removed status

    bit of a glitch:

    import sqlalchemy as sa
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    class ModelBase(Base):
        __tablename__ = 'ModelBases'
        id = sa.Column(sa.Integer, primary_key=True)
        model_type = sa.Column(sa.Integer)
        __mapper_args__ = {'polymorphic_on': model_type}
    
    class Model(ModelBase):
        __tablename__ = 'Models'
        __mapper_args__ = {'polymorphic_identity': 1}
        id = sa.Column(sa.ForeignKey(ModelBase.id), primary_key=True)
    
    sess = sa.orm.Session()
    
    print sess.query(Model).exists()
    

    generates a select columns warning because use_labels isn't set.

  2. Log in to comment