Debian Codegraph @

django/db/backends/postgresql/compiler.py

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