schema.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import psycopg2
  2. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  3. from django.db.backends.ddl_references import IndexColumns
  4. from django.db.backends.utils import strip_quotes
  5. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  6. sql_create_sequence = "CREATE SEQUENCE %(sequence)s"
  7. sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE"
  8. sql_set_sequence_max = "SELECT setval('%(sequence)s', MAX(%(column)s)) FROM %(table)s"
  9. sql_set_sequence_owner = 'ALTER SEQUENCE %(sequence)s OWNED BY %(table)s.%(column)s'
  10. sql_create_index = "CREATE INDEX %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s%(condition)s"
  11. sql_create_index_concurrently = (
  12. "CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s%(condition)s"
  13. )
  14. sql_delete_index = "DROP INDEX IF EXISTS %(name)s"
  15. sql_delete_index_concurrently = "DROP INDEX CONCURRENTLY IF EXISTS %(name)s"
  16. # Setting the constraint to IMMEDIATE to allow changing data in the same
  17. # transaction.
  18. sql_create_column_inline_fk = (
  19. 'CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(deferrable)s'
  20. '; SET CONSTRAINTS %(name)s IMMEDIATE'
  21. )
  22. # Setting the constraint to IMMEDIATE runs any deferred checks to allow
  23. # dropping it in the same transaction.
  24. sql_delete_fk = "SET CONSTRAINTS %(name)s IMMEDIATE; ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  25. sql_delete_procedure = 'DROP FUNCTION %(procedure)s(%(param_types)s)'
  26. def quote_value(self, value):
  27. if isinstance(value, str):
  28. value = value.replace('%', '%%')
  29. # getquoted() returns a quoted bytestring of the adapted value.
  30. return psycopg2.extensions.adapt(value).getquoted().decode()
  31. def _field_indexes_sql(self, model, field):
  32. output = super()._field_indexes_sql(model, field)
  33. like_index_statement = self._create_like_index_sql(model, field)
  34. if like_index_statement is not None:
  35. output.append(like_index_statement)
  36. return output
  37. def _field_data_type(self, field):
  38. if field.is_relation:
  39. return field.rel_db_type(self.connection)
  40. return self.connection.data_types.get(
  41. field.get_internal_type(),
  42. field.db_type(self.connection),
  43. )
  44. def _create_like_index_sql(self, model, field):
  45. """
  46. Return the statement to create an index with varchar operator pattern
  47. when the column type is 'varchar' or 'text', otherwise return None.
  48. """
  49. db_type = field.db_type(connection=self.connection)
  50. if db_type is not None and (field.db_index or field.unique):
  51. # Fields with database column types of `varchar` and `text` need
  52. # a second index that specifies their operator class, which is
  53. # needed when performing correct LIKE queries outside the
  54. # C locale. See #12234.
  55. #
  56. # The same doesn't apply to array fields such as varchar[size]
  57. # and text[size], so skip them.
  58. if '[' in db_type:
  59. return None
  60. if db_type.startswith('varchar'):
  61. return self._create_index_sql(model, [field], suffix='_like', opclasses=['varchar_pattern_ops'])
  62. elif db_type.startswith('text'):
  63. return self._create_index_sql(model, [field], suffix='_like', opclasses=['text_pattern_ops'])
  64. return None
  65. def _alter_column_type_sql(self, model, old_field, new_field, new_type):
  66. self.sql_alter_column_type = 'ALTER COLUMN %(column)s TYPE %(type)s'
  67. # Cast when data type changed.
  68. if self._field_data_type(old_field) != self._field_data_type(new_field):
  69. self.sql_alter_column_type += ' USING %(column)s::%(type)s'
  70. # Make ALTER TYPE with SERIAL make sense.
  71. table = strip_quotes(model._meta.db_table)
  72. serial_fields_map = {'bigserial': 'bigint', 'serial': 'integer', 'smallserial': 'smallint'}
  73. if new_type.lower() in serial_fields_map:
  74. column = strip_quotes(new_field.column)
  75. sequence_name = "%s_%s_seq" % (table, column)
  76. return (
  77. (
  78. self.sql_alter_column_type % {
  79. "column": self.quote_name(column),
  80. "type": serial_fields_map[new_type.lower()],
  81. },
  82. [],
  83. ),
  84. [
  85. (
  86. self.sql_delete_sequence % {
  87. "sequence": self.quote_name(sequence_name),
  88. },
  89. [],
  90. ),
  91. (
  92. self.sql_create_sequence % {
  93. "sequence": self.quote_name(sequence_name),
  94. },
  95. [],
  96. ),
  97. (
  98. self.sql_alter_column % {
  99. "table": self.quote_name(table),
  100. "changes": self.sql_alter_column_default % {
  101. "column": self.quote_name(column),
  102. "default": "nextval('%s')" % self.quote_name(sequence_name),
  103. }
  104. },
  105. [],
  106. ),
  107. (
  108. self.sql_set_sequence_max % {
  109. "table": self.quote_name(table),
  110. "column": self.quote_name(column),
  111. "sequence": self.quote_name(sequence_name),
  112. },
  113. [],
  114. ),
  115. (
  116. self.sql_set_sequence_owner % {
  117. 'table': self.quote_name(table),
  118. 'column': self.quote_name(column),
  119. 'sequence': self.quote_name(sequence_name),
  120. },
  121. [],
  122. ),
  123. ],
  124. )
  125. else:
  126. return super()._alter_column_type_sql(model, old_field, new_field, new_type)
  127. def _alter_field(self, model, old_field, new_field, old_type, new_type,
  128. old_db_params, new_db_params, strict=False):
  129. # Drop indexes on varchar/text/citext columns that are changing to a
  130. # different type.
  131. if (old_field.db_index or old_field.unique) and (
  132. (old_type.startswith('varchar') and not new_type.startswith('varchar')) or
  133. (old_type.startswith('text') and not new_type.startswith('text')) or
  134. (old_type.startswith('citext') and not new_type.startswith('citext'))
  135. ):
  136. index_name = self._create_index_name(model._meta.db_table, [old_field.column], suffix='_like')
  137. self.execute(self._delete_index_sql(model, index_name))
  138. super()._alter_field(
  139. model, old_field, new_field, old_type, new_type, old_db_params,
  140. new_db_params, strict,
  141. )
  142. # Added an index? Create any PostgreSQL-specific indexes.
  143. if ((not (old_field.db_index or old_field.unique) and new_field.db_index) or
  144. (not old_field.unique and new_field.unique)):
  145. like_index_statement = self._create_like_index_sql(model, new_field)
  146. if like_index_statement is not None:
  147. self.execute(like_index_statement)
  148. # Removed an index? Drop any PostgreSQL-specific indexes.
  149. if old_field.unique and not (new_field.db_index or new_field.unique):
  150. index_to_remove = self._create_index_name(model._meta.db_table, [old_field.column], suffix='_like')
  151. self.execute(self._delete_index_sql(model, index_to_remove))
  152. def _index_columns(self, table, columns, col_suffixes, opclasses):
  153. if opclasses:
  154. return IndexColumns(table, columns, self.quote_name, col_suffixes=col_suffixes, opclasses=opclasses)
  155. return super()._index_columns(table, columns, col_suffixes, opclasses)
  156. def add_index(self, model, index, concurrently=False):
  157. self.execute(index.create_sql(model, self, concurrently=concurrently), params=None)
  158. def remove_index(self, model, index, concurrently=False):
  159. self.execute(index.remove_sql(model, self, concurrently=concurrently))
  160. def _delete_index_sql(self, model, name, sql=None, concurrently=False):
  161. sql = self.sql_delete_index_concurrently if concurrently else self.sql_delete_index
  162. return super()._delete_index_sql(model, name, sql)
  163. def _create_index_sql(
  164. self, model, fields, *, name=None, suffix='', using='',
  165. db_tablespace=None, col_suffixes=(), sql=None, opclasses=(),
  166. condition=None, concurrently=False,
  167. ):
  168. sql = self.sql_create_index if not concurrently else self.sql_create_index_concurrently
  169. return super()._create_index_sql(
  170. model, fields, name=name, suffix=suffix, using=using, db_tablespace=db_tablespace,
  171. col_suffixes=col_suffixes, sql=sql, opclasses=opclasses, condition=condition,
  172. )