| 1 |
import django |
| 2 |
from django.core.exceptions import EmptyResultSet |
| 3 |
from django.db.models.sql.constants import LOUTER |
| 4 |
|
| 5 |
from .jitmixin import JITMixin, jit_mixin |
| 6 |
from .join import QJoin |
| 7 |
from ._quoting import quote_name |
| 8 |
|
| 9 |
# NOTE: it is currently not possible to execute delete queries that |
| 10 |
# reference CTEs without patching `QuerySet.delete` (Django method) |
| 11 |
# to call `self.query.chain(sql.DeleteQuery)` instead of |
| 12 |
# `sql.DeleteQuery(self.model)` |
| 13 |
|
| 14 |
|
| 15 |
class CTEQuery(JITMixin): |
| 16 |
"""A Query mixin that processes SQL compilation through a CTE compiler""" |
| 17 |
_jit_mixin_prefix = "CTE" |
| 18 |
_with_ctes = () |
| 19 |
|
| 20 |
@property |
| 21 |
def combined_queries(self): |
| 22 |
return self.__dict__.get("combined_queries", ()) |
| 23 |
|
| 24 |
@combined_queries.setter |
| 25 |
def combined_queries(self, queries): |
| 26 |
ctes = [] |
| 27 |
seen = {cte.name: cte for cte in self._with_ctes} |
| 28 |
for query in queries: |
| 29 |
for cte in getattr(query, "_with_ctes", ()): |
| 30 |
if seen.get(cte.name) is cte: |
| 31 |
continue |
| 32 |
if cte.name in seen: |
| 33 |
raise ValueError( |
| 34 |
f"Found two or more CTEs named '{cte.name}'. " |
| 35 |
"Hint: assign a unique name to each CTE." |
| 36 |
) |
| 37 |
ctes.append(cte) |
| 38 |
seen[cte.name] = cte |
| 39 |
|
| 40 |
if seen: |
| 41 |
def without_ctes(query): |
| 42 |
if getattr(query, "_with_ctes", None): |
| 43 |
query = query.clone() |
| 44 |
del query._with_ctes |
| 45 |
return query |
| 46 |
|
| 47 |
self._with_ctes += tuple(ctes) |
| 48 |
queries = tuple(without_ctes(q) for q in queries) |
| 49 |
self.__dict__["combined_queries"] = queries |
| 50 |
|
| 51 |
def resolve_expression(self, *args, **kwargs): |
| 52 |
clone = super().resolve_expression(*args, **kwargs) |
| 53 |
clone._with_ctes = tuple( |
| 54 |
cte.resolve_expression(*args, **kwargs) |
| 55 |
for cte in clone._with_ctes |
| 56 |
) |
| 57 |
return clone |
| 58 |
|
| 59 |
def get_compiler(self, *args, **kwargs): |
| 60 |
return jit_mixin(super().get_compiler(*args, **kwargs), CTECompiler) |
| 61 |
|
| 62 |
def chain(self, klass=None): |
| 63 |
clone = jit_mixin(super().chain(klass), CTEQuery) |
| 64 |
clone._with_ctes = self._with_ctes |
| 65 |
return clone |
| 66 |
|
| 67 |
|
| 68 |
def generate_cte_sql(connection, query, as_sql): |
| 69 |
if not query._with_ctes: |
| 70 |
return as_sql() |
| 71 |
|
| 72 |
ctes = [] |
| 73 |
params = [] |
| 74 |
for cte in query._with_ctes: |
| 75 |
if django.VERSION > (4, 2): |
| 76 |
_ignore_with_col_aliases(cte.query) |
| 77 |
|
| 78 |
alias = query.alias_map.get(cte.name) |
| 79 |
should_elide_empty = ( |
| 80 |
not isinstance(alias, QJoin) or alias.join_type != LOUTER |
| 81 |
) |
| 82 |
|
| 83 |
compiler = cte.query.get_compiler( |
| 84 |
connection=connection, elide_empty=should_elide_empty |
| 85 |
) |
| 86 |
|
| 87 |
qn = quote_name(compiler) |
| 88 |
try: |
| 89 |
cte_sql, cte_params = compiler.as_sql() |
| 90 |
except EmptyResultSet: |
| 91 |
# If the CTE raises an EmptyResultSet the SqlCompiler still |
| 92 |
# needs to know the information about this base compiler |
| 93 |
# like, col_count and klass_info. |
| 94 |
as_sql() |
| 95 |
raise |
| 96 |
template = get_cte_query_template(cte) |
| 97 |
ctes.append(template.format(name=qn(cte.name), query=cte_sql)) |
| 98 |
params.extend(cte_params) |
| 99 |
|
| 100 |
explain_attribute = "explain_info" |
| 101 |
explain_info = getattr(query, explain_attribute, None) |
| 102 |
explain_format = getattr(explain_info, "format", None) |
| 103 |
explain_options = getattr(explain_info, "options", {}) |
| 104 |
|
| 105 |
explain_query_or_info = getattr(query, explain_attribute, None) |
| 106 |
sql = [] |
| 107 |
if explain_query_or_info: |
| 108 |
sql.append( |
| 109 |
connection.ops.explain_query_prefix( |
| 110 |
explain_format, |
| 111 |
**explain_options |
| 112 |
) |
| 113 |
) |
| 114 |
# this needs to get set to None so that the base as_sql() doesn't |
| 115 |
# insert the EXPLAIN statement where it would end up between the |
| 116 |
# WITH ... clause and the final SELECT |
| 117 |
setattr(query, explain_attribute, None) |
| 118 |
|
| 119 |
if ctes: |
| 120 |
# Always use WITH RECURSIVE |
| 121 |
# https://www.postgresql.org/message-id/13122.1339829536%40sss.pgh.pa.us |
| 122 |
sql.extend(["WITH RECURSIVE", ", ".join(ctes)]) |
| 123 |
base_sql, base_params = as_sql() |
| 124 |
|
| 125 |
if explain_query_or_info: |
| 126 |
setattr(query, explain_attribute, explain_query_or_info) |
| 127 |
|
| 128 |
sql.append(base_sql) |
| 129 |
params.extend(base_params) |
| 130 |
return " ".join(sql), tuple(params) |
| 131 |
|
| 132 |
|
| 133 |
def get_cte_query_template(cte): |
| 134 |
if cte.materialized: |
| 135 |
return "{name} AS MATERIALIZED ({query})" |
| 136 |
return "{name} AS ({query})" |
| 137 |
|
| 138 |
|
| 139 |
def _ignore_with_col_aliases(cte_query): |
| 140 |
if getattr(cte_query, "combined_queries", None): |
| 141 |
cte_query.combined_queries = tuple( |
| 142 |
jit_mixin(q, NoAliasQuery) for q in cte_query.combined_queries |
| 143 |
) |
| 144 |
|
| 145 |
|
| 146 |
class CTECompiler(JITMixin): |
| 147 |
"""Mixin for django.db.models.sql.compiler.SQLCompiler""" |
| 148 |
_jit_mixin_prefix = "CTE" |
| 149 |
|
| 150 |
def as_sql(self, *args, **kwargs): |
| 151 |
def _as_sql(): |
| 152 |
return super(CTECompiler, self).as_sql(*args, **kwargs) |
| 153 |
return generate_cte_sql(self.connection, self.query, _as_sql) |
| 154 |
|
| 155 |
|
| 156 |
class NoAliasQuery(JITMixin): |
| 157 |
"""Mixin for django.db.models.sql.compiler.Query""" |
| 158 |
_jit_mixin_prefix = "NoAlias" |
| 159 |
|
| 160 |
def get_compiler(self, *args, **kwargs): |
| 161 |
return jit_mixin(super().get_compiler(*args, **kwargs), NoAliasCompiler) |
| 162 |
|
| 163 |
|
| 164 |
class NoAliasCompiler(JITMixin): |
| 165 |
"""Mixin for django.db.models.sql.compiler.SQLCompiler""" |
| 166 |
_jit_mixin_prefix = "NoAlias" |
| 167 |
|
| 168 |
def get_select(self, *, with_col_aliases=False, **kw): |
| 169 |
return super().get_select(**kw) |