compiler.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from django.db.models.sql.compiler import ( # isort:skip
  2. SQLAggregateCompiler,
  3. SQLCompiler,
  4. SQLDeleteCompiler,
  5. SQLInsertCompiler as BaseSQLInsertCompiler,
  6. SQLUpdateCompiler,
  7. )
  8. __all__ = [
  9. "SQLAggregateCompiler",
  10. "SQLCompiler",
  11. "SQLDeleteCompiler",
  12. "SQLInsertCompiler",
  13. "SQLUpdateCompiler",
  14. ]
  15. class InsertUnnest(list):
  16. """
  17. Sentinel value to signal DatabaseOperations.bulk_insert_sql() that the
  18. UNNEST strategy should be used for the bulk insert.
  19. """
  20. def __str__(self):
  21. return "UNNEST(%s)" % ", ".join(self)
  22. class SQLInsertCompiler(BaseSQLInsertCompiler):
  23. def assemble_as_sql(self, fields, value_rows):
  24. # Specialize bulk-insertion of literal values through UNNEST to
  25. # reduce the time spent planning the query.
  26. if (
  27. # The optimization is not worth doing if there is a single
  28. # row as it will result in the same number of placeholders.
  29. len(value_rows) <= 1
  30. # Lack of fields denote the usage of the DEFAULT keyword
  31. # for the insertion of empty rows.
  32. or any(field is None for field in fields)
  33. # Field.get_placeholder_sql takes value as an argument, so the
  34. # resulting placeholder might be dependent on the value.
  35. # in UNNEST requires a single placeholder to "fit all values" in
  36. # the array.
  37. or any(hasattr(field, "get_placeholder_sql") for field in fields)
  38. # Fields that don't use standard internal types might not be
  39. # unnest'able (e.g. array and geometry types are known to be
  40. # problematic).
  41. or any(
  42. (field.target_field if field.is_relation else field).get_internal_type()
  43. not in self.connection.data_types
  44. for field in fields
  45. )
  46. # Compilable cannot be combined in an array of literal values.
  47. or any(any(hasattr(value, "as_sql") for value in row) for row in value_rows)
  48. ):
  49. return super().assemble_as_sql(fields, value_rows)
  50. # Manually remove parameters from `db_type` to ensure no data
  51. # truncation takes place (e.g. varchar[] instead of varchar(50)[]).
  52. db_types = [field.db_type(self.connection).split("(")[0] for field in fields]
  53. return InsertUnnest(["(%%s)::%s[]" % db_type for db_type in db_types]), [
  54. list(map(list, zip(*value_rows)))
  55. ]