Skip to content

Commit 744d745

Browse files
authored
Merge pull request #91 from SupImDos/master
Fix `.explain()` in Django >=4.0
2 parents 3d4fffe + 09cc92d commit 744d745

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

django_cte/query.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -82,30 +82,40 @@ def generate_sql(cls, connection, query, as_sql):
8282
ctes.append(template.format(name=qn(cte.name), query=cte_sql))
8383
params.extend(cte_params)
8484

85-
explain_query = getattr(query, "explain_query", None)
86-
sql = []
87-
if explain_query:
85+
# Required due to breaking change in django commit
86+
# fc91ea1e50e5ef207f0f291b3f6c1942b10db7c7
87+
if django.VERSION >= (4, 0):
88+
explain_attribute = "explain_info"
89+
explain_info = getattr(query, explain_attribute, None)
90+
explain_format = getattr(explain_info, "format", None)
91+
explain_options = getattr(explain_info, "options", {})
92+
else:
93+
explain_attribute = "explain_query"
8894
explain_format = getattr(query, "explain_format", None)
8995
explain_options = getattr(query, "explain_options", {})
96+
97+
explain_query_or_info = getattr(query, explain_attribute, None)
98+
sql = []
99+
if explain_query_or_info:
90100
sql.append(
91101
connection.ops.explain_query_prefix(
92102
explain_format,
93103
**explain_options
94104
)
95105
)
96-
# this needs to get set to False so that the base as_sql() doesn't
106+
# this needs to get set to None so that the base as_sql() doesn't
97107
# insert the EXPLAIN statement where it would end up between the
98108
# WITH ... clause and the final SELECT
99-
query.explain_query = False
109+
setattr(query, explain_attribute, None)
100110

101111
if ctes:
102112
# Always use WITH RECURSIVE
103113
# https://www.postgresql.org/message-id/13122.1339829536%40sss.pgh.pa.us
104114
sql.extend(["WITH RECURSIVE", ", ".join(ctes)])
105115
base_sql, base_params = as_sql()
106116

107-
if explain_query:
108-
query.explain_query = explain_query
117+
if explain_query_or_info:
118+
setattr(query, explain_attribute, explain_query_or_info)
109119

110120
sql.append(base_sql)
111121
params.extend(base_params)

tests/test_cte.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -561,8 +561,4 @@ def test_explain(self):
561561
.order_by("amount")
562562
)
563563

564-
# the test db (sqlite3) doesn't support EXPLAIN, so let's just check
565-
# to make sure EXPLAIN is at the top
566-
orders.query.explain_query = True
567-
568-
self.assertTrue(str(orders.query).startswith("EXPLAIN "))
564+
self.assertIsInstance(orders.explain(), str)

0 commit comments

Comments
 (0)