Commits

diana committed 59e5d09

adding convenience method exists() to Query (see # 2673)

Comments (0)

Files changed (3)

doc/build/changelog/changelog_08.rst

     :version: 0.8.1
 
     .. change::
+        :tags: feature, orm
+        :tickets: 2673
+
+    Added a convenience method to Query that turns a query into an
+    EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...)
+
+    .. change::
       :tags: bug, mssql
       :pullreq: 47
 

lib/sqlalchemy/orm/query.py

                 kwargs.get('offset') is not None or
                 kwargs.get('distinct', False))
 
+    def exists(self):
+        """A convenience method that turns a query into an EXISTS subquery
+        of the form EXISTS (SELECT 1 FROM ... WHERE ...).
+
+        e.g.::
+
+            q = session.query(User).filter(User.name == 'fred')
+            session.query(q.exists())
+
+        Producing SQL similar to::
+
+            SELECT EXISTS (
+                SELECT 1 FROM users WHERE users.name = :name_1
+            ) AS anon_1
+
+        .. versionadded:: 0.8.1
+
+        """
+        return sql.exists(self.with_entities('1').statement)
+
     def count(self):
         """Return a count of rows this Query would return.
 

test/orm/test_query.py

 
         assert [User(name=u'jack',id=7), User(name=u'fred',id=9)] == sess.query(User).order_by(User.id).group_by(User).join('addresses').having(func.count(Address.id)< 2).all()
 
+
+class ExistsTest(QueryTest, AssertsCompiledSQL):
+
+    def test_exists(self):
+        User = self.classes.User
+        sess = create_session()
+        q1 = sess.query(User).filter(User.name == 'fred')
+        self.assert_compile(sess.query(q1.exists()),
+            'SELECT EXISTS ('
+                'SELECT 1 FROM users WHERE users.name = :name_1'
+            ') AS anon_1',
+            dialect=default.DefaultDialect()
+        )
+
+
 class CountTest(QueryTest):
     def test_basic(self):
         users, User = self.tables.users, self.classes.User