Development of an internal social media platform with personalised dashboards for students
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 11KB

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