operations.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. from __future__ import unicode_literals
  2. from django.conf import settings
  3. from django.db.backends import BaseDatabaseOperations
  4. class DatabaseOperations(BaseDatabaseOperations):
  5. def __init__(self, connection):
  6. super(DatabaseOperations, self).__init__(connection)
  7. def date_extract_sql(self, lookup_type, field_name):
  8. # http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
  9. if lookup_type == 'week_day':
  10. # For consistency across backends, we return Sunday=1, Saturday=7.
  11. return "EXTRACT('dow' FROM %s) + 1" % field_name
  12. else:
  13. return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
  14. def date_interval_sql(self, sql, connector, timedelta):
  15. """
  16. implements the interval functionality for expressions
  17. format for Postgres:
  18. (datefield + interval '3 days 200 seconds 5 microseconds')
  19. """
  20. modifiers = []
  21. if timedelta.days:
  22. modifiers.append('%s days' % timedelta.days)
  23. if timedelta.seconds:
  24. modifiers.append('%s seconds' % timedelta.seconds)
  25. if timedelta.microseconds:
  26. modifiers.append('%s microseconds' % timedelta.microseconds)
  27. mods = ' '.join(modifiers)
  28. conn = ' %s ' % connector
  29. return '(%s)' % conn.join([sql, 'interval \'%s\'' % mods])
  30. def date_trunc_sql(self, lookup_type, field_name):
  31. # http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  32. return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
  33. def datetime_extract_sql(self, lookup_type, field_name, tzname):
  34. if settings.USE_TZ:
  35. field_name = "%s AT TIME ZONE %%s" % field_name
  36. params = [tzname]
  37. else:
  38. params = []
  39. # http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
  40. if lookup_type == 'week_day':
  41. # For consistency across backends, we return Sunday=1, Saturday=7.
  42. sql = "EXTRACT('dow' FROM %s) + 1" % field_name
  43. else:
  44. sql = "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
  45. return sql, params
  46. def datetime_trunc_sql(self, lookup_type, field_name, tzname):
  47. if settings.USE_TZ:
  48. field_name = "%s AT TIME ZONE %%s" % field_name
  49. params = [tzname]
  50. else:
  51. params = []
  52. # http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  53. sql = "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
  54. return sql, params
  55. def deferrable_sql(self):
  56. return " DEFERRABLE INITIALLY DEFERRED"
  57. def lookup_cast(self, lookup_type):
  58. lookup = '%s'
  59. # Cast text lookups to text to allow things like filter(x__contains=4)
  60. if lookup_type in ('iexact', 'contains', 'icontains', 'startswith',
  61. 'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'):
  62. lookup = "%s::text"
  63. # Use UPPER(x) for case-insensitive lookups; it's faster.
  64. if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'):
  65. lookup = 'UPPER(%s)' % lookup
  66. return lookup
  67. def field_cast_sql(self, db_type, internal_type):
  68. if internal_type == "GenericIPAddressField" or internal_type == "IPAddressField":
  69. return 'HOST(%s)'
  70. return '%s'
  71. def last_insert_id(self, cursor, table_name, pk_name):
  72. # Use pg_get_serial_sequence to get the underlying sequence name
  73. # from the table name and column name (available since PostgreSQL 8)
  74. cursor.execute("SELECT CURRVAL(pg_get_serial_sequence('%s','%s'))" % (
  75. self.quote_name(table_name), pk_name))
  76. return cursor.fetchone()[0]
  77. def no_limit_value(self):
  78. return None
  79. def prepare_sql_script(self, sql, _allow_fallback=False):
  80. return [sql]
  81. def quote_name(self, name):
  82. if name.startswith('"') and name.endswith('"'):
  83. return name # Quoting once is enough.
  84. return '"%s"' % name
  85. def set_time_zone_sql(self):
  86. return "SET TIME ZONE %s"
  87. def sql_flush(self, style, tables, sequences, allow_cascade=False):
  88. if tables:
  89. # Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows
  90. # us to truncate tables referenced by a foreign key in any other
  91. # table.
  92. tables_sql = ', '.join(
  93. style.SQL_FIELD(self.quote_name(table)) for table in tables)
  94. if allow_cascade:
  95. sql = ['%s %s %s;' % (
  96. style.SQL_KEYWORD('TRUNCATE'),
  97. tables_sql,
  98. style.SQL_KEYWORD('CASCADE'),
  99. )]
  100. else:
  101. sql = ['%s %s;' % (
  102. style.SQL_KEYWORD('TRUNCATE'),
  103. tables_sql,
  104. )]
  105. sql.extend(self.sequence_reset_by_name_sql(style, sequences))
  106. return sql
  107. else:
  108. return []
  109. def sequence_reset_by_name_sql(self, style, sequences):
  110. # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements
  111. # to reset sequence indices
  112. sql = []
  113. for sequence_info in sequences:
  114. table_name = sequence_info['table']
  115. column_name = sequence_info['column']
  116. if not (column_name and len(column_name) > 0):
  117. # This will be the case if it's an m2m using an autogenerated
  118. # intermediate table (see BaseDatabaseIntrospection.sequence_list)
  119. column_name = '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("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" %
  144. (style.SQL_KEYWORD('SELECT'),
  145. style.SQL_TABLE(qn(model._meta.db_table)),
  146. style.SQL_FIELD(f.column),
  147. style.SQL_FIELD(qn(f.column)),
  148. style.SQL_FIELD(qn(f.column)),
  149. style.SQL_KEYWORD('IS NOT'),
  150. style.SQL_KEYWORD('FROM'),
  151. style.SQL_TABLE(qn(model._meta.db_table))))
  152. break # Only one AutoField is allowed per model, so don't bother continuing.
  153. for f in model._meta.many_to_many:
  154. if not f.rel.through:
  155. output.append("%s setval(pg_get_serial_sequence('%s','%s'), 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. 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, num_values):
  191. items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
  192. return "VALUES " + ", ".join([items_sql] * num_values)