You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

operations.py 12KB

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