operations.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. from psycopg2.extras import Inet
  2. from django.conf import settings
  3. from django.db.backends.base.operations import BaseDatabaseOperations
  4. class DatabaseOperations(BaseDatabaseOperations):
  5. cast_char_field_without_max_length = 'varchar'
  6. explain_prefix = 'EXPLAIN'
  7. explain_options = frozenset(
  8. [
  9. "ANALYZE",
  10. "BUFFERS",
  11. "COSTS",
  12. "SETTINGS",
  13. "SUMMARY",
  14. "TIMING",
  15. "VERBOSE",
  16. "WAL",
  17. ]
  18. )
  19. cast_data_types = {
  20. 'AutoField': 'integer',
  21. 'BigAutoField': 'bigint',
  22. 'SmallAutoField': 'smallint',
  23. }
  24. def unification_cast_sql(self, output_field):
  25. internal_type = output_field.get_internal_type()
  26. if internal_type in ("GenericIPAddressField", "IPAddressField", "TimeField", "UUIDField"):
  27. # PostgreSQL will resolve a union as type 'text' if input types are
  28. # 'unknown'.
  29. # https://www.postgresql.org/docs/current/typeconv-union-case.html
  30. # These fields cannot be implicitly cast back in the default
  31. # PostgreSQL configuration so we need to explicitly cast them.
  32. # We must also remove components of the type within brackets:
  33. # varchar(255) -> varchar.
  34. return 'CAST(%%s AS %s)' % output_field.db_type(self.connection).split('(')[0]
  35. return '%s'
  36. def date_extract_sql(self, lookup_type, field_name):
  37. # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
  38. if lookup_type == 'week_day':
  39. # For consistency across backends, we return Sunday=1, Saturday=7.
  40. return "EXTRACT('dow' FROM %s) + 1" % field_name
  41. elif lookup_type == 'iso_week_day':
  42. return "EXTRACT('isodow' FROM %s)" % field_name
  43. elif lookup_type == 'iso_year':
  44. return "EXTRACT('isoyear' FROM %s)" % field_name
  45. else:
  46. return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
  47. def date_trunc_sql(self, lookup_type, field_name, tzname=None):
  48. field_name = self._convert_field_to_tz(field_name, tzname)
  49. # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  50. return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
  51. def _prepare_tzname_delta(self, tzname):
  52. if '+' in tzname:
  53. return tzname.replace('+', '-')
  54. elif '-' in tzname:
  55. return tzname.replace('-', '+')
  56. return tzname
  57. def _convert_field_to_tz(self, field_name, tzname):
  58. if tzname and settings.USE_TZ:
  59. field_name = "%s AT TIME ZONE '%s'" % (field_name, self._prepare_tzname_delta(tzname))
  60. return field_name
  61. def datetime_cast_date_sql(self, field_name, tzname):
  62. field_name = self._convert_field_to_tz(field_name, tzname)
  63. return '(%s)::date' % field_name
  64. def datetime_cast_time_sql(self, field_name, tzname):
  65. field_name = self._convert_field_to_tz(field_name, tzname)
  66. return '(%s)::time' % field_name
  67. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  68. field_name = self._convert_field_to_tz(field_name, tzname)
  69. return self.date_extract_sql(lookup_type, field_name)
  70. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  71. field_name = self._convert_field_to_tz(field_name, tzname)
  72. # https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  73. return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
  74. def time_trunc_sql(self, lookup_type, field_name, tzname=None):
  75. field_name = self._convert_field_to_tz(field_name, tzname)
  76. return "DATE_TRUNC('%s', %s)::time" % (lookup_type, field_name)
  77. def deferrable_sql(self):
  78. return " DEFERRABLE INITIALLY DEFERRED"
  79. def fetch_returned_insert_rows(self, cursor):
  80. """
  81. Given a cursor object that has just performed an INSERT...RETURNING
  82. statement into a table, return the tuple of returned data.
  83. """
  84. return cursor.fetchall()
  85. def lookup_cast(self, lookup_type, internal_type=None):
  86. lookup = '%s'
  87. # Cast text lookups to text to allow things like filter(x__contains=4)
  88. if lookup_type in ('iexact', 'contains', 'icontains', 'startswith',
  89. 'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'):
  90. if internal_type in ('IPAddressField', 'GenericIPAddressField'):
  91. lookup = "HOST(%s)"
  92. elif internal_type in ('CICharField', 'CIEmailField', 'CITextField'):
  93. lookup = '%s::citext'
  94. else:
  95. lookup = "%s::text"
  96. # Use UPPER(x) for case-insensitive lookups; it's faster.
  97. if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'):
  98. lookup = 'UPPER(%s)' % lookup
  99. return lookup
  100. def no_limit_value(self):
  101. return None
  102. def prepare_sql_script(self, sql):
  103. return [sql]
  104. def quote_name(self, name):
  105. if name.startswith('"') and name.endswith('"'):
  106. return name # Quoting once is enough.
  107. return '"%s"' % name
  108. def set_time_zone_sql(self):
  109. return "SET TIME ZONE %s"
  110. def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
  111. if not tables:
  112. return []
  113. # Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows us
  114. # to truncate tables referenced by a foreign key in any other table.
  115. sql_parts = [
  116. style.SQL_KEYWORD('TRUNCATE'),
  117. ', '.join(style.SQL_FIELD(self.quote_name(table)) for table in tables),
  118. ]
  119. if reset_sequences:
  120. sql_parts.append(style.SQL_KEYWORD('RESTART IDENTITY'))
  121. if allow_cascade:
  122. sql_parts.append(style.SQL_KEYWORD('CASCADE'))
  123. return ['%s;' % ' '.join(sql_parts)]
  124. def sequence_reset_by_name_sql(self, style, sequences):
  125. # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements
  126. # to reset sequence indices
  127. sql = []
  128. for sequence_info in sequences:
  129. table_name = sequence_info['table']
  130. # 'id' will be the case if it's an m2m using an autogenerated
  131. # intermediate table (see BaseDatabaseIntrospection.sequence_list).
  132. column_name = sequence_info['column'] or 'id'
  133. sql.append("%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" % (
  134. style.SQL_KEYWORD('SELECT'),
  135. style.SQL_TABLE(self.quote_name(table_name)),
  136. style.SQL_FIELD(column_name),
  137. ))
  138. return sql
  139. def tablespace_sql(self, tablespace, inline=False):
  140. if inline:
  141. return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace)
  142. else:
  143. return "TABLESPACE %s" % self.quote_name(tablespace)
  144. def sequence_reset_sql(self, style, model_list):
  145. from django.db import models
  146. output = []
  147. qn = self.quote_name
  148. for model in model_list:
  149. # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
  150. # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
  151. # if there are records (as the max pk value is already in use), otherwise set it to false.
  152. # Use pg_get_serial_sequence to get the underlying sequence name from the table name
  153. # and column name (available since PostgreSQL 8)
  154. for f in model._meta.local_fields:
  155. if isinstance(f, models.AutoField):
  156. output.append(
  157. "%s setval(pg_get_serial_sequence('%s','%s'), "
  158. "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
  159. style.SQL_KEYWORD('SELECT'),
  160. style.SQL_TABLE(qn(model._meta.db_table)),
  161. style.SQL_FIELD(f.column),
  162. style.SQL_FIELD(qn(f.column)),
  163. style.SQL_FIELD(qn(f.column)),
  164. style.SQL_KEYWORD('IS NOT'),
  165. style.SQL_KEYWORD('FROM'),
  166. style.SQL_TABLE(qn(model._meta.db_table)),
  167. )
  168. )
  169. break # Only one AutoField is allowed per model, so don't bother continuing.
  170. return output
  171. def prep_for_iexact_query(self, x):
  172. return x
  173. def max_name_length(self):
  174. """
  175. Return the maximum length of an identifier.
  176. The maximum length of an identifier is 63 by default, but can be
  177. changed by recompiling PostgreSQL after editing the NAMEDATALEN
  178. macro in src/include/pg_config_manual.h.
  179. This implementation returns 63, but can be overridden by a custom
  180. database backend that inherits most of its behavior from this one.
  181. """
  182. return 63
  183. def distinct_sql(self, fields, params):
  184. if fields:
  185. params = [param for param_list in params for param in param_list]
  186. return (['DISTINCT ON (%s)' % ', '.join(fields)], params)
  187. else:
  188. return ['DISTINCT'], []
  189. def last_executed_query(self, cursor, sql, params):
  190. # https://www.psycopg.org/docs/cursor.html#cursor.query
  191. # The query attribute is a Psycopg extension to the DB API 2.0.
  192. if cursor.query is not None:
  193. return cursor.query.decode()
  194. return None
  195. def return_insert_columns(self, fields):
  196. if not fields:
  197. return '', ()
  198. columns = [
  199. '%s.%s' % (
  200. self.quote_name(field.model._meta.db_table),
  201. self.quote_name(field.column),
  202. ) for field in fields
  203. ]
  204. return 'RETURNING %s' % ', '.join(columns), ()
  205. def bulk_insert_sql(self, fields, placeholder_rows):
  206. placeholder_rows_sql = (", ".join(row) for row in placeholder_rows)
  207. values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql)
  208. return "VALUES " + values_sql
  209. def adapt_datefield_value(self, value):
  210. return value
  211. def adapt_datetimefield_value(self, value):
  212. return value
  213. def adapt_timefield_value(self, value):
  214. return value
  215. def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
  216. return value
  217. def adapt_ipaddressfield_value(self, value):
  218. if value:
  219. return Inet(value)
  220. return None
  221. def subtract_temporals(self, internal_type, lhs, rhs):
  222. if internal_type == 'DateField':
  223. lhs_sql, lhs_params = lhs
  224. rhs_sql, rhs_params = rhs
  225. params = (*lhs_params, *rhs_params)
  226. return "(interval '1 day' * (%s - %s))" % (lhs_sql, rhs_sql), params
  227. return super().subtract_temporals(internal_type, lhs, rhs)
  228. def explain_query_prefix(self, format=None, **options):
  229. extra = {}
  230. # Normalize options.
  231. if options:
  232. options = {
  233. name.upper(): "true" if value else "false"
  234. for name, value in options.items()
  235. }
  236. for valid_option in self.explain_options:
  237. value = options.pop(valid_option, None)
  238. if value is not None:
  239. extra[valid_option.upper()] = value
  240. prefix = super().explain_query_prefix(format, **options)
  241. if format:
  242. extra['FORMAT'] = format
  243. if extra:
  244. prefix += ' (%s)' % ', '.join('%s %s' % i for i in extra.items())
  245. return prefix
  246. def ignore_conflicts_suffix_sql(self, ignore_conflicts=None):
  247. return 'ON CONFLICT DO NOTHING' if ignore_conflicts else super().ignore_conflicts_suffix_sql(ignore_conflicts)