Debian Codegraph @

django/db/backends/mysql/compiler.py

raw
1 from django.core.exceptions import FieldError, FullResultSet
2 from django.db.models.expressions import Col
3 from django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler
4 from django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler
5 from django.db.models.sql.compiler import SQLInsertCompiler
6 from django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler
7
8 __all__ = [
9 "SQLAggregateCompiler",
10 "SQLCompiler",
11 "SQLDeleteCompiler",
12 "SQLInsertCompiler",
13 "SQLUpdateCompiler",
14 ]
15
16
17 class SQLDeleteCompiler(BaseSQLDeleteCompiler):
18 def as_sql(self):
19 # Prefer the non-standard DELETE FROM syntax over the SQL generated by
20 # the SQLDeleteCompiler's default implementation when multiple tables
21 # are involved since MySQL/MariaDB will generate a more efficient query
22 # plan than when using a subquery.
23 where, having, qualify = self.query.where.split_having_qualify(
24 must_group_by=self.query.group_by is not None
25 )
26 if self.single_alias or having or qualify:
27 # DELETE FROM cannot be used when filtering against aggregates or
28 # window functions as it doesn't allow for GROUP BY/HAVING clauses
29 # and the subquery wrapping (necessary to emulate QUALIFY).
30 return super().as_sql()
31 result = [
32 "DELETE %s FROM"
33 % self.quote_name_unless_alias(self.query.get_initial_alias())
34 ]
35 from_sql, params = self.get_from_clause()
36 result.extend(from_sql)
37 try:
38 where_sql, where_params = self.compile(where)
39 except FullResultSet:
40 pass
41 else:
42 result.append("WHERE %s" % where_sql)
43 params.extend(where_params)
44 return " ".join(result), tuple(params)
45
46
47 class SQLUpdateCompiler(BaseSQLUpdateCompiler):
48 def as_sql(self):
49 update_query, update_params = super().as_sql()
50 # MySQL and MariaDB support UPDATE ... ORDER BY syntax.
51 if self.query.order_by:
52 order_by_sql = []
53 order_by_params = []
54 db_table = self.query.get_meta().db_table
55 try:
56 for resolved, (sql, params, _) in self.get_order_by():
57 if (
58 isinstance(resolved.expression, Col)
59 and resolved.expression.alias != db_table
60 ):
61 # Ignore ordering if it contains joined fields, because
62 # they cannot be used in the ORDER BY clause.
63 raise FieldError
64 order_by_sql.append(sql)
65 order_by_params.extend(params)
66 update_query += " ORDER BY " + ", ".join(order_by_sql)
67 update_params += tuple(order_by_params)
68 except FieldError:
69 # Ignore ordering if it contains annotations, because they're
70 # removed in .update() and cannot be resolved.
71 pass
72 return update_query, update_params