Skip to content

Commit

Permalink
Fixed #32226 -- Fixed JSON format of QuerySet.explain() on PostgreSQL.
Browse files Browse the repository at this point in the history
  • Loading branch information
whtsky authored and felixxm committed Jul 5, 2021
1 parent b3b04ad commit aba9c2d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,7 @@ answer newbie questions, and generally made Django that much better:
Wilson Miner <[email protected]>
Wim Glenn <[email protected]>
wojtek
Wu Haotian <[email protected]>
Xavier Francisco <[email protected]>
Xia Kai <https://blog.xiaket.org/>
Yann Fouillat <[email protected]>
Expand Down
4 changes: 3 additions & 1 deletion django/db/models/sql/compiler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections
import json
import re
from functools import partial
from itertools import chain
Expand Down Expand Up @@ -1250,9 +1251,10 @@ def explain_query(self):
result = list(self.execute_sql())
# Some backends return 1 item tuples with strings, and others return
# tuples with integers and strings. Flatten them out into strings.
output_formatter = json.dumps if self.query.explain_format == 'json' else str
for row in result[0]:
if not isinstance(row, str):
yield ' '.join(str(c) for c in row)
yield ' '.join(output_formatter(c) for c in row)
else:
yield row

Expand Down
8 changes: 8 additions & 0 deletions tests/queries/test_explain.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import unittest
import xml.etree.ElementTree

Expand Down Expand Up @@ -39,6 +40,13 @@ def test_basic(self):
self.fail(
f'QuerySet.explain() result is not valid XML: {e}'
)
elif format == 'json':
try:
json.loads(result)
except json.JSONDecodeError as e:
self.fail(
f'QuerySet.explain() result is not valid JSON: {e}'
)

@skipUnlessDBFeature('validates_explain_options')
def test_unknown_options(self):
Expand Down

0 comments on commit aba9c2d

Please sign in to comment.