summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--doc/build/changelog/unreleased_12/4032.rst9
-rw-r--r--lib/sqlalchemy/orm/query.py3
-rw-r--r--test/orm/test_query.py20
3 files changed, 31 insertions, 1 deletions
diff --git a/doc/build/changelog/unreleased_12/4032.rst b/doc/build/changelog/unreleased_12/4032.rst
new file mode 100644
index 000000000..869be3529
--- /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 b3bb5302f..209bb6d6a 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 19adf8983..3b91f5ffa 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