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.
 
 
 
 

242 lines
9.9 KiB

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