operations.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import json
  2. from functools import lru_cache, partial
  3. from django.conf import settings
  4. from django.db.backends.base.operations import BaseDatabaseOperations
  5. from django.db.backends.postgresql.compiler import InsertUnnest
  6. from django.db.backends.postgresql.psycopg_any import (
  7. Inet,
  8. Jsonb,
  9. errors,
  10. is_psycopg3,
  11. mogrify,
  12. )
  13. from django.db.backends.utils import split_tzname_delta
  14. from django.db.models.constants import OnConflict
  15. from django.db.models.functions import Cast
  16. from django.utils.regex_helper import _lazy_re_compile
  17. @lru_cache
  18. def get_json_dumps(encoder):
  19. if encoder is None:
  20. return json.dumps
  21. return partial(json.dumps, cls=encoder)
  22. class DatabaseOperations(BaseDatabaseOperations):
  23. compiler_module = "django.db.backends.postgresql.compiler"
  24. cast_char_field_without_max_length = "varchar"
  25. explain_prefix = "EXPLAIN"
  26. explain_options = frozenset(
  27. [
  28. "ANALYZE",
  29. "BUFFERS",
  30. "COSTS",
  31. "GENERIC_PLAN",
  32. "MEMORY",
  33. "SETTINGS",
  34. "SERIALIZE",
  35. "SUMMARY",
  36. "TIMING",
  37. "VERBOSE",
  38. "WAL",
  39. ]
  40. )
  41. cast_data_types = {
  42. "AutoField": "integer",
  43. "BigAutoField": "bigint",
  44. "SmallAutoField": "smallint",
  45. }
  46. if is_psycopg3:
  47. from psycopg.types import numeric
  48. integerfield_type_map = {
  49. "SmallIntegerField": numeric.Int2,
  50. "IntegerField": numeric.Int4,
  51. "BigIntegerField": numeric.Int8,
  52. "PositiveSmallIntegerField": numeric.Int2,
  53. "PositiveIntegerField": numeric.Int4,
  54. "PositiveBigIntegerField": numeric.Int8,
  55. }
  56. def unification_cast_sql(self, output_field):
  57. internal_type = output_field.get_internal_type()
  58. if internal_type in (
  59. "GenericIPAddressField",
  60. "IPAddressField",
  61. "TimeField",
  62. "UUIDField",
  63. ):
  64. # PostgreSQL will resolve a union as type 'text' if input types are
  65. # 'unknown'.
  66. # https://www.postgresql.org/docs/current/typeconv-union-case.html
  67. # These fields cannot be implicitly cast back in the default
  68. # PostgreSQL configuration so we need to explicitly cast them.
  69. # We must also remove components of the type within brackets:
  70. # varchar(255) -> varchar.
  71. return (
  72. "CAST(%%s AS %s)" % output_field.db_type(self.connection).split("(")[0]
  73. )
  74. return "%s"
  75. # EXTRACT format cannot be passed in parameters.
  76. _extract_format_re = _lazy_re_compile(r"[A-Z_]+")
  77. def date_extract_sql(self, lookup_type, sql, params):
  78. # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
  79. if lookup_type == "week_day":
  80. # For consistency across backends, we return Sunday=1, Saturday=7.
  81. return f"EXTRACT(DOW FROM {sql}) + 1", params
  82. elif lookup_type == "iso_week_day":
  83. return f"EXTRACT(ISODOW FROM {sql})", params
  84. elif lookup_type == "iso_year":
  85. return f"EXTRACT(ISOYEAR FROM {sql})", params
  86. lookup_type = lookup_type.upper()
  87. if not self._extract_format_re.fullmatch(lookup_type):
  88. raise ValueError(f"Invalid lookup type: {lookup_type!r}")
  89. return f"EXTRACT({lookup_type} FROM {sql})", params
  90. def date_trunc_sql(self, lookup_type, sql, params, tzname=None):
  91. sql, params = self._convert_sql_to_tz(sql, params, tzname)
  92. # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  93. return f"DATE_TRUNC(%s, {sql})", (lookup_type, *params)
  94. def _prepare_tzname_delta(self, tzname):
  95. tzname, sign, offset = split_tzname_delta(tzname)
  96. if offset:
  97. sign = "-" if sign == "+" else "+"
  98. return f"{tzname}{sign}{offset}"
  99. return tzname
  100. def _convert_sql_to_tz(self, sql, params, tzname):
  101. if tzname and settings.USE_TZ:
  102. tzname_param = self._prepare_tzname_delta(tzname)
  103. return f"{sql} AT TIME ZONE %s", (*params, tzname_param)
  104. return sql, params
  105. def datetime_cast_date_sql(self, sql, params, tzname):
  106. sql, params = self._convert_sql_to_tz(sql, params, tzname)
  107. return f"({sql})::date", params
  108. def datetime_cast_time_sql(self, sql, params, tzname):
  109. sql, params = self._convert_sql_to_tz(sql, params, tzname)
  110. return f"({sql})::time", params
  111. def datetime_extract_sql(self, lookup_type, sql, params, tzname):
  112. sql, params = self._convert_sql_to_tz(sql, params, tzname)
  113. if lookup_type == "second":
  114. # Truncate fractional seconds.
  115. return f"EXTRACT(SECOND FROM DATE_TRUNC(%s, {sql}))", ("second", *params)
  116. return self.date_extract_sql(lookup_type, sql, params)
  117. def datetime_trunc_sql(self, lookup_type, sql, params, tzname):
  118. sql, params = self._convert_sql_to_tz(sql, params, tzname)
  119. # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  120. return f"DATE_TRUNC(%s, {sql})", (lookup_type, *params)
  121. def time_extract_sql(self, lookup_type, sql, params):
  122. if lookup_type == "second":
  123. # Truncate fractional seconds.
  124. return f"EXTRACT(SECOND FROM DATE_TRUNC(%s, {sql}))", ("second", *params)
  125. return self.date_extract_sql(lookup_type, sql, params)
  126. def time_trunc_sql(self, lookup_type, sql, params, tzname=None):
  127. sql, params = self._convert_sql_to_tz(sql, params, tzname)
  128. return f"DATE_TRUNC(%s, {sql})::time", (lookup_type, *params)
  129. def deferrable_sql(self):
  130. return " DEFERRABLE INITIALLY DEFERRED"
  131. def bulk_insert_sql(self, fields, placeholder_rows):
  132. if isinstance(placeholder_rows, InsertUnnest):
  133. return f"SELECT * FROM {placeholder_rows}"
  134. return super().bulk_insert_sql(fields, placeholder_rows)
  135. def lookup_cast(self, lookup_type, internal_type=None):
  136. lookup = "%s"
  137. # Cast text lookups to text to allow things like filter(x__contains=4)
  138. if lookup_type in (
  139. "iexact",
  140. "contains",
  141. "icontains",
  142. "startswith",
  143. "istartswith",
  144. "endswith",
  145. "iendswith",
  146. "regex",
  147. "iregex",
  148. ):
  149. if internal_type in ("IPAddressField", "GenericIPAddressField"):
  150. lookup = "HOST(%s)"
  151. else:
  152. lookup = "%s::text"
  153. # Use UPPER(x) for case-insensitive lookups; it's faster.
  154. if lookup_type in ("iexact", "icontains", "istartswith", "iendswith"):
  155. lookup = "UPPER(%s)" % lookup
  156. return lookup
  157. def no_limit_value(self):
  158. return None
  159. def prepare_sql_script(self, sql):
  160. return [sql]
  161. def quote_name(self, name):
  162. if name.startswith('"') and name.endswith('"'):
  163. return name # Quoting once is enough.
  164. return '"%s"' % name
  165. def compose_sql(self, sql, params):
  166. return mogrify(sql, params, self.connection)
  167. def set_time_zone_sql(self):
  168. return "SELECT set_config('TimeZone', %s, false)"
  169. def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
  170. if not tables:
  171. return []
  172. # Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows us
  173. # to truncate tables referenced by a foreign key in any other table.
  174. sql_parts = [
  175. style.SQL_KEYWORD("TRUNCATE"),
  176. ", ".join(style.SQL_FIELD(self.quote_name(table)) for table in tables),
  177. ]
  178. if reset_sequences:
  179. sql_parts.append(style.SQL_KEYWORD("RESTART IDENTITY"))
  180. if allow_cascade:
  181. sql_parts.append(style.SQL_KEYWORD("CASCADE"))
  182. return ["%s;" % " ".join(sql_parts)]
  183. def sequence_reset_by_name_sql(self, style, sequences):
  184. # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL
  185. # statements to reset sequence indices
  186. sql = []
  187. for sequence_info in sequences:
  188. table_name = sequence_info["table"]
  189. # 'id' will be the case if it's an m2m using an autogenerated
  190. # intermediate table (see BaseDatabaseIntrospection.sequence_list).
  191. column_name = sequence_info["column"] or "id"
  192. sql.append(
  193. "%s setval(pg_get_serial_sequence('%s','%s'), 1, false);"
  194. % (
  195. style.SQL_KEYWORD("SELECT"),
  196. style.SQL_TABLE(self.quote_name(table_name)),
  197. style.SQL_FIELD(column_name),
  198. )
  199. )
  200. return sql
  201. def tablespace_sql(self, tablespace, inline=False):
  202. if inline:
  203. return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace)
  204. else:
  205. return "TABLESPACE %s" % self.quote_name(tablespace)
  206. def sequence_reset_sql(self, style, model_list):
  207. from django.db import models
  208. output = []
  209. qn = self.quote_name
  210. for model in model_list:
  211. # Use `coalesce` to set the sequence for each model to the max pk
  212. # value if there are records, or 1 if there are none. Set the
  213. # `is_called` property (the third argument to `setval`) to true if
  214. # there are records (as the max pk value is already in use),
  215. # otherwise set it to false. Use pg_get_serial_sequence to get the
  216. # underlying sequence name from the table name and column name.
  217. for f in model._meta.local_fields:
  218. if isinstance(f, models.AutoField):
  219. output.append(
  220. "%s setval(pg_get_serial_sequence('%s','%s'), "
  221. "coalesce(max(%s), 1), max(%s) %s null) %s %s;"
  222. % (
  223. style.SQL_KEYWORD("SELECT"),
  224. style.SQL_TABLE(qn(model._meta.db_table)),
  225. style.SQL_FIELD(f.column),
  226. style.SQL_FIELD(qn(f.column)),
  227. style.SQL_FIELD(qn(f.column)),
  228. style.SQL_KEYWORD("IS NOT"),
  229. style.SQL_KEYWORD("FROM"),
  230. style.SQL_TABLE(qn(model._meta.db_table)),
  231. )
  232. )
  233. # Only one AutoField is allowed per model, so don't bother
  234. # continuing.
  235. break
  236. return output
  237. def prep_for_iexact_query(self, x):
  238. return x
  239. def max_name_length(self):
  240. """
  241. Return the maximum length of an identifier.
  242. The maximum length of an identifier is 63 by default, but can be
  243. changed by recompiling PostgreSQL after editing the NAMEDATALEN
  244. macro in src/include/pg_config_manual.h.
  245. This implementation returns 63, but can be overridden by a custom
  246. database backend that inherits most of its behavior from this one.
  247. """
  248. return 63
  249. def distinct_sql(self, fields, params):
  250. if fields:
  251. params = [param for param_list in params for param in param_list]
  252. return (["DISTINCT ON (%s)" % ", ".join(fields)], params)
  253. else:
  254. return ["DISTINCT"], []
  255. if is_psycopg3:
  256. def last_executed_query(self, cursor, sql, params):
  257. if self.connection.features.uses_server_side_binding:
  258. try:
  259. return self.compose_sql(sql, params)
  260. except errors.DataError:
  261. return super().last_executed_query(cursor, sql, params)
  262. else:
  263. if cursor._query and cursor._query.query is not None:
  264. return cursor._query.query.decode()
  265. return super().last_executed_query(cursor, sql, params)
  266. else:
  267. def last_executed_query(self, cursor, sql, params):
  268. # https://www.psycopg.org/docs/cursor.html#cursor.query
  269. # The query attribute is a Psycopg extension to the DB API 2.0.
  270. if cursor.query is not None:
  271. return cursor.query.decode()
  272. return super().last_executed_query(cursor, sql, params)
  273. if is_psycopg3:
  274. def adapt_integerfield_value(self, value, internal_type):
  275. if value is None or hasattr(value, "resolve_expression"):
  276. return value
  277. return self.integerfield_type_map[internal_type](value)
  278. def adapt_datefield_value(self, value):
  279. return value
  280. def adapt_datetimefield_value(self, value):
  281. return value
  282. def adapt_durationfield_value(self, value):
  283. return value
  284. def adapt_timefield_value(self, value):
  285. return value
  286. def adapt_ipaddressfield_value(self, value):
  287. if value:
  288. return Inet(value)
  289. return None
  290. def adapt_json_value(self, value, encoder):
  291. return Jsonb(value, dumps=get_json_dumps(encoder))
  292. def subtract_temporals(self, internal_type, lhs, rhs):
  293. if internal_type == "DateField":
  294. lhs_sql, lhs_params = lhs
  295. rhs_sql, rhs_params = rhs
  296. params = (*lhs_params, *rhs_params)
  297. return "(interval '1 day' * (%s - %s))" % (lhs_sql, rhs_sql), params
  298. return super().subtract_temporals(internal_type, lhs, rhs)
  299. def explain_query_prefix(self, format=None, **options):
  300. extra = {}
  301. if serialize := options.pop("serialize", None):
  302. if serialize.upper() in {"TEXT", "BINARY"}:
  303. extra["SERIALIZE"] = serialize.upper()
  304. # Normalize options.
  305. if options:
  306. options = {
  307. name.upper(): "true" if value else "false"
  308. for name, value in options.items()
  309. }
  310. for valid_option in self.explain_options:
  311. value = options.pop(valid_option, None)
  312. if value is not None:
  313. extra[valid_option] = value
  314. prefix = super().explain_query_prefix(format, **options)
  315. if format:
  316. extra["FORMAT"] = format
  317. if extra:
  318. prefix += " (%s)" % ", ".join("%s %s" % i for i in extra.items())
  319. return prefix
  320. def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields):
  321. if on_conflict == OnConflict.IGNORE:
  322. return "ON CONFLICT DO NOTHING"
  323. if on_conflict == OnConflict.UPDATE:
  324. return "ON CONFLICT(%s) DO UPDATE SET %s" % (
  325. ", ".join(map(self.quote_name, unique_fields)),
  326. ", ".join(
  327. [
  328. f"{field} = EXCLUDED.{field}"
  329. for field in map(self.quote_name, update_fields)
  330. ]
  331. ),
  332. )
  333. return super().on_conflict_suffix_sql(
  334. fields,
  335. on_conflict,
  336. update_fields,
  337. unique_fields,
  338. )
  339. def prepare_join_on_clause(self, lhs_table, lhs_field, rhs_table, rhs_field):
  340. lhs_expr, rhs_expr = super().prepare_join_on_clause(
  341. lhs_table, lhs_field, rhs_table, rhs_field
  342. )
  343. if lhs_field.db_type(self.connection) != rhs_field.db_type(self.connection):
  344. rhs_expr = Cast(rhs_expr, lhs_field)
  345. return lhs_expr, rhs_expr