From 1cbaff643f8d524fc0f7b347f659d18a67884f16 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Wed, 6 Dec 2017 16:22:31 -0500 Subject: [PATCH] Disable eager loads for exists() The :meth:`.Query.exists` method will now disable eager loaders for when the query is rendered. Previously, joined-eager load joins would be rendered unnecessarily as well as subquery eager load queries would be needlessly generated. The new behavior matches that of the :meth:`.Query.subquery` method. Fixes: #4032 Change-Id: Iacafc76aa9ae0b71928037fa9637e85ad434ee3a --- doc/build/changelog/unreleased_12/4032.rst | 9 +++++++++ lib/sqlalchemy/orm/query.py | 3 ++- test/orm/test_query.py | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 doc/build/changelog/unreleased_12/4032.rst diff --git a/doc/build/changelog/unreleased_12/4032.rst b/doc/build/changelog/unreleased_12/4032.rst new file mode 100644 index 0000000000..869be35292 --- /dev/null +++ b/doc/build/changelog/unreleased_12/4032.rst @@ -0,0 +1,9 @@ +.. change:: + :tags: bug, orm + :tickets: 4032 + + The :meth:`.Query.exists` method will now disable eager loaders for when + the query is rendered. Previously, joined-eager load joins would be rendered + unnecessarily as well as subquery eager load queries would be needlessly + generated. The new behavior matches that of the :meth:`.Query.subquery` + method. \ No newline at end of file diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index b3bb5302f7..209bb6d6a5 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -3066,7 +3066,8 @@ class Query(object): # omitting the FROM clause from a query(X) (#2818); # .with_only_columns() after we have a core select() so that # we get just "SELECT 1" without any entities. - return sql.exists(self.add_columns('1').with_labels(). + return sql.exists(self.enable_eagerloads(False).add_columns('1'). + with_labels(). statement.with_only_columns([1])) def count(self): diff --git a/test/orm/test_query.py b/test/orm/test_query.py index 19adf8983f..3b91f5ffaf 100644 --- a/test/orm/test_query.py +++ b/test/orm/test_query.py @@ -1489,6 +1489,26 @@ class ExpressionTest(QueryTest, AssertsCompiledSQL): "FROM users WHERE users.id = :id_1)" ) + def test_subquery_no_eagerloads(self): + User = self.classes.User + s = Session() + + self.assert_compile( + s.query(User).options(joinedload(User.addresses)).subquery(), + "SELECT users.id, users.name FROM users" + ) + + def test_exists_no_eagerloads(self): + User = self.classes.User + s = Session() + + self.assert_compile( + s.query( + s.query(User).options(joinedload(User.addresses)).exists() + ), + "SELECT EXISTS (SELECT 1 FROM users) AS anon_1" + ) + def test_named_subquery(self): User = self.classes.User -- 2.47.3