2021-06-30 18:45:10 +08:00
|
|
|
import json
|
2017-09-10 22:34:18 +08:00
|
|
|
import unittest
|
2021-07-05 14:17:31 +08:00
|
|
|
import xml.etree.ElementTree
|
2017-09-10 22:34:18 +08:00
|
|
|
|
|
|
|
from django.db import NotSupportedError, connection, transaction
|
|
|
|
from django.db.models import Count
|
2019-09-08 01:28:19 +08:00
|
|
|
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
|
2017-09-10 22:34:18 +08:00
|
|
|
from django.test.utils import CaptureQueriesContext
|
|
|
|
|
|
|
|
from .models import Tag
|
|
|
|
|
|
|
|
|
|
|
|
@skipUnlessDBFeature("supports_explaining_query_execution")
|
|
|
|
class ExplainTests(TestCase):
|
|
|
|
def test_basic(self):
|
|
|
|
querysets = [
|
|
|
|
Tag.objects.filter(name="test"),
|
|
|
|
Tag.objects.filter(name="test").select_related("parent"),
|
|
|
|
Tag.objects.filter(name="test").prefetch_related("children"),
|
|
|
|
Tag.objects.filter(name="test").annotate(Count("children")),
|
|
|
|
Tag.objects.filter(name="test").values_list("name"),
|
|
|
|
Tag.objects.order_by().union(Tag.objects.order_by().filter(name="test")),
|
2022-02-22 17:29:38 +08:00
|
|
|
Tag.objects.select_for_update().filter(name="test"),
|
2017-09-10 22:34:18 +08:00
|
|
|
]
|
|
|
|
supported_formats = connection.features.supported_explain_formats
|
|
|
|
all_formats = (
|
|
|
|
(None,)
|
|
|
|
+ tuple(supported_formats)
|
|
|
|
+ tuple(f.lower() for f in supported_formats)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2017-09-10 22:34:18 +08:00
|
|
|
for idx, queryset in enumerate(querysets):
|
|
|
|
for format in all_formats:
|
|
|
|
with self.subTest(format=format, queryset=idx):
|
|
|
|
with self.assertNumQueries(1), CaptureQueriesContext(
|
|
|
|
connection
|
|
|
|
) as captured_queries:
|
|
|
|
result = queryset.explain(format=format)
|
|
|
|
self.assertTrue(
|
|
|
|
captured_queries[0]["sql"].startswith(
|
|
|
|
connection.ops.explain_prefix
|
|
|
|
)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2017-09-10 22:34:18 +08:00
|
|
|
self.assertIsInstance(result, str)
|
|
|
|
self.assertTrue(result)
|
2021-07-05 14:17:31 +08:00
|
|
|
if format == "xml":
|
|
|
|
try:
|
|
|
|
xml.etree.ElementTree.fromstring(result)
|
|
|
|
except xml.etree.ElementTree.ParseError as e:
|
|
|
|
self.fail(
|
|
|
|
f"QuerySet.explain() result is not valid XML: {e}"
|
|
|
|
)
|
2021-06-30 18:45:10 +08:00
|
|
|
elif format == "json":
|
|
|
|
try:
|
|
|
|
json.loads(result)
|
|
|
|
except json.JSONDecodeError as e:
|
|
|
|
self.fail(
|
|
|
|
f"QuerySet.explain() result is not valid JSON: {e}"
|
|
|
|
)
|
2017-09-10 22:34:18 +08:00
|
|
|
|
|
|
|
@skipUnlessDBFeature("validates_explain_options")
|
|
|
|
def test_unknown_options(self):
|
|
|
|
with self.assertRaisesMessage(ValueError, "Unknown options: test, test2"):
|
2022-02-22 17:29:38 +08:00
|
|
|
Tag.objects.explain(test=1, test2=1)
|
2017-09-10 22:34:18 +08:00
|
|
|
|
|
|
|
def test_unknown_format(self):
|
|
|
|
msg = "DOES NOT EXIST is not a recognized format."
|
|
|
|
if connection.features.supported_explain_formats:
|
|
|
|
msg += " Allowed formats: %s" % ", ".join(
|
|
|
|
sorted(connection.features.supported_explain_formats)
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2017-09-10 22:34:18 +08:00
|
|
|
with self.assertRaisesMessage(ValueError, msg):
|
2022-02-22 17:29:38 +08:00
|
|
|
Tag.objects.explain(format="does not exist")
|
2017-09-10 22:34:18 +08:00
|
|
|
|
|
|
|
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
|
|
|
|
def test_postgres_options(self):
|
|
|
|
qs = Tag.objects.filter(name="test")
|
|
|
|
test_options = [
|
|
|
|
{"COSTS": False, "BUFFERS": True, "ANALYZE": True},
|
|
|
|
{"costs": False, "buffers": True, "analyze": True},
|
|
|
|
{"verbose": True, "timing": True, "analyze": True},
|
|
|
|
{"verbose": False, "timing": False, "analyze": True},
|
2021-01-19 19:25:20 +08:00
|
|
|
{"summary": True},
|
2017-09-10 22:34:18 +08:00
|
|
|
]
|
2019-10-22 16:31:41 +08:00
|
|
|
if connection.features.is_postgresql_12:
|
|
|
|
test_options.append({"settings": True})
|
2020-08-24 17:47:38 +08:00
|
|
|
if connection.features.is_postgresql_13:
|
|
|
|
test_options.append({"analyze": True, "wal": True})
|
2017-09-10 22:34:18 +08:00
|
|
|
for options in test_options:
|
|
|
|
with self.subTest(**options), transaction.atomic():
|
|
|
|
with CaptureQueriesContext(connection) as captured_queries:
|
|
|
|
qs.explain(format="text", **options)
|
|
|
|
self.assertEqual(len(captured_queries), 1)
|
|
|
|
for name, value in options.items():
|
|
|
|
option = "{} {}".format(name.upper(), "true" if value else "false")
|
|
|
|
self.assertIn(option, captured_queries[0]["sql"])
|
|
|
|
|
|
|
|
@unittest.skipUnless(connection.vendor == "mysql", "MySQL specific")
|
|
|
|
def test_mysql_text_to_traditional(self):
|
2019-10-22 00:32:56 +08:00
|
|
|
# Ensure these cached properties are initialized to prevent queries for
|
|
|
|
# the MariaDB or MySQL version during the QuerySet evaluation.
|
|
|
|
connection.features.supported_explain_formats
|
2017-09-10 22:34:18 +08:00
|
|
|
with CaptureQueriesContext(connection) as captured_queries:
|
|
|
|
Tag.objects.filter(name="test").explain(format="text")
|
|
|
|
self.assertEqual(len(captured_queries), 1)
|
|
|
|
self.assertIn("FORMAT=TRADITIONAL", captured_queries[0]["sql"])
|
|
|
|
|
2019-10-22 00:34:19 +08:00
|
|
|
@unittest.skipUnless(
|
|
|
|
connection.vendor == "mysql", "MariaDB and MySQL >= 8.0.18 specific."
|
|
|
|
)
|
|
|
|
def test_mysql_analyze(self):
|
|
|
|
qs = Tag.objects.filter(name="test")
|
|
|
|
with CaptureQueriesContext(connection) as captured_queries:
|
|
|
|
qs.explain(analyze=True)
|
|
|
|
self.assertEqual(len(captured_queries), 1)
|
|
|
|
prefix = "ANALYZE " if connection.mysql_is_mariadb else "EXPLAIN ANALYZE "
|
|
|
|
self.assertTrue(captured_queries[0]["sql"].startswith(prefix))
|
|
|
|
with CaptureQueriesContext(connection) as captured_queries:
|
|
|
|
qs.explain(analyze=True, format="JSON")
|
|
|
|
self.assertEqual(len(captured_queries), 1)
|
|
|
|
if connection.mysql_is_mariadb:
|
|
|
|
self.assertIn("FORMAT=JSON", captured_queries[0]["sql"])
|
|
|
|
else:
|
|
|
|
self.assertNotIn("FORMAT=JSON", captured_queries[0]["sql"])
|
|
|
|
|
2017-09-10 22:34:18 +08:00
|
|
|
|
|
|
|
@skipIfDBFeature("supports_explaining_query_execution")
|
|
|
|
class ExplainUnsupportedTests(TestCase):
|
|
|
|
def test_message(self):
|
|
|
|
msg = "This backend does not support explaining query execution."
|
|
|
|
with self.assertRaisesMessage(NotSupportedError, msg):
|
|
|
|
Tag.objects.filter(name="test").explain()
|