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.

schema.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import psycopg2
  2. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  3. from django.db.backends.ddl_references import IndexColumns
  4. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  5. sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s USING %(column)s::%(type)s"
  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_create_index = "CREATE INDEX %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s%(condition)s"
  10. sql_delete_index = "DROP INDEX IF EXISTS %(name)s"
  11. # Setting the constraint to IMMEDIATE runs any deferred checks to allow
  12. # dropping it in the same transaction.
  13. sql_delete_fk = "SET CONSTRAINTS %(name)s IMMEDIATE; ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  14. sql_delete_procedure = 'DROP FUNCTION %(procedure)s(%(param_types)s)'
  15. def quote_value(self, value):
  16. if isinstance(value, str):
  17. value = value.replace('%', '%%')
  18. # getquoted() returns a quoted bytestring of the adapted value.
  19. return psycopg2.extensions.adapt(value).getquoted().decode()
  20. def _field_indexes_sql(self, model, field):
  21. output = super()._field_indexes_sql(model, field)
  22. like_index_statement = self._create_like_index_sql(model, field)
  23. if like_index_statement is not None:
  24. output.append(like_index_statement)
  25. return output
  26. def _create_like_index_sql(self, model, field):
  27. """
  28. Return the statement to create an index with varchar operator pattern
  29. when the column type is 'varchar' or 'text', otherwise return None.
  30. """
  31. db_type = field.db_type(connection=self.connection)
  32. if db_type is not None and (field.db_index or field.unique):
  33. # Fields with database column types of `varchar` and `text` need
  34. # a second index that specifies their operator class, which is
  35. # needed when performing correct LIKE queries outside the
  36. # C locale. See #12234.
  37. #
  38. # The same doesn't apply to array fields such as varchar[size]
  39. # and text[size], so skip them.
  40. if '[' in db_type:
  41. return None
  42. if db_type.startswith('varchar'):
  43. return self._create_index_sql(model, [field], suffix='_like', opclasses=['varchar_pattern_ops'])
  44. elif db_type.startswith('text'):
  45. return self._create_index_sql(model, [field], suffix='_like', opclasses=['text_pattern_ops'])
  46. return None
  47. def _alter_column_type_sql(self, model, old_field, new_field, new_type):
  48. """Make ALTER TYPE with SERIAL make sense."""
  49. table = model._meta.db_table
  50. if new_type.lower() in ("serial", "bigserial"):
  51. column = new_field.column
  52. sequence_name = "%s_%s_seq" % (table, column)
  53. col_type = "integer" if new_type.lower() == "serial" else "bigint"
  54. return (
  55. (
  56. self.sql_alter_column_type % {
  57. "column": self.quote_name(column),
  58. "type": col_type,
  59. },
  60. [],
  61. ),
  62. [
  63. (
  64. self.sql_delete_sequence % {
  65. "sequence": self.quote_name(sequence_name),
  66. },
  67. [],
  68. ),
  69. (
  70. self.sql_create_sequence % {
  71. "sequence": self.quote_name(sequence_name),
  72. },
  73. [],
  74. ),
  75. (
  76. self.sql_alter_column % {
  77. "table": self.quote_name(table),
  78. "changes": self.sql_alter_column_default % {
  79. "column": self.quote_name(column),
  80. "default": "nextval('%s')" % self.quote_name(sequence_name),
  81. }
  82. },
  83. [],
  84. ),
  85. (
  86. self.sql_set_sequence_max % {
  87. "table": self.quote_name(table),
  88. "column": self.quote_name(column),
  89. "sequence": self.quote_name(sequence_name),
  90. },
  91. [],
  92. ),
  93. ],
  94. )
  95. else:
  96. return super()._alter_column_type_sql(model, old_field, new_field, new_type)
  97. def _alter_field(self, model, old_field, new_field, old_type, new_type,
  98. old_db_params, new_db_params, strict=False):
  99. # Drop indexes on varchar/text/citext columns that are changing to a
  100. # different type.
  101. if (old_field.db_index or old_field.unique) and (
  102. (old_type.startswith('varchar') and not new_type.startswith('varchar')) or
  103. (old_type.startswith('text') and not new_type.startswith('text')) or
  104. (old_type.startswith('citext') and not new_type.startswith('citext'))
  105. ):
  106. index_name = self._create_index_name(model._meta.db_table, [old_field.column], suffix='_like')
  107. self.execute(self._delete_index_sql(model, index_name))
  108. super()._alter_field(
  109. model, old_field, new_field, old_type, new_type, old_db_params,
  110. new_db_params, strict,
  111. )
  112. # Added an index? Create any PostgreSQL-specific indexes.
  113. if ((not (old_field.db_index or old_field.unique) and new_field.db_index) or
  114. (not old_field.unique and new_field.unique)):
  115. like_index_statement = self._create_like_index_sql(model, new_field)
  116. if like_index_statement is not None:
  117. self.execute(like_index_statement)
  118. # Removed an index? Drop any PostgreSQL-specific indexes.
  119. if old_field.unique and not (new_field.db_index or new_field.unique):
  120. index_to_remove = self._create_index_name(model._meta.db_table, [old_field.column], suffix='_like')
  121. self.execute(self._delete_index_sql(model, index_to_remove))
  122. def _index_columns(self, table, columns, col_suffixes, opclasses):
  123. if opclasses:
  124. return IndexColumns(table, columns, self.quote_name, col_suffixes=col_suffixes, opclasses=opclasses)
  125. return super()._index_columns(table, columns, col_suffixes, opclasses)