operations.py 12 KB

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