compiler.py 2.9 KB

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