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 5.8 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import psycopg2
  2. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  3. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  4. sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s USING %(column)s::%(type)s"
  5. sql_create_sequence = "CREATE SEQUENCE %(sequence)s"
  6. sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE"
  7. sql_set_sequence_max = "SELECT setval('%(sequence)s', MAX(%(column)s)) FROM %(table)s"
  8. sql_create_varchar_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s varchar_pattern_ops)%(extra)s"
  9. sql_create_text_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s text_pattern_ops)%(extra)s"
  10. def quote_value(self, value):
  11. return psycopg2.extensions.adapt(value)
  12. def add_field(self, model, field):
  13. super(DatabaseSchemaEditor, self).add_field(model, field)
  14. like_index_statement = self._create_like_index_sql(model, field)
  15. if like_index_statement is not None:
  16. self.deferred_sql.append(like_index_statement)
  17. def _model_indexes_sql(self, model):
  18. output = super(DatabaseSchemaEditor, self)._model_indexes_sql(model)
  19. if not model._meta.managed or model._meta.proxy or model._meta.swapped:
  20. return output
  21. for field in model._meta.local_fields:
  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', sql=self.sql_create_varchar_index)
  44. elif db_type.startswith('text'):
  45. return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_text_index)
  46. return None
  47. def _alter_column_type_sql(self, table, old_field, new_field, new_type):
  48. """
  49. Makes ALTER TYPE with SERIAL make sense.
  50. """
  51. if new_type.lower() == "serial":
  52. column = new_field.column
  53. sequence_name = "%s_%s_seq" % (table, column)
  54. return (
  55. (
  56. self.sql_alter_column_type % {
  57. "column": self.quote_name(column),
  58. "type": "integer",
  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(DatabaseSchemaEditor, self)._alter_column_type_sql(
  97. table, old_field, new_field, new_type
  98. )
  99. def _alter_field(self, model, old_field, new_field, old_type, new_type,
  100. old_db_params, new_db_params, strict=False):
  101. super(DatabaseSchemaEditor, self)._alter_field(
  102. model, old_field, new_field, old_type, new_type, old_db_params,
  103. new_db_params, strict,
  104. )
  105. # Added an index? Create any PostgreSQL-specific indexes.
  106. if not old_field.db_index and not old_field.unique and (new_field.db_index or new_field.unique):
  107. like_index_statement = self._create_like_index_sql(model, new_field)
  108. if like_index_statement is not None:
  109. self.execute(like_index_statement)
  110. # Removed an index? Drop any PostgreSQL-specific indexes.
  111. if (old_field.db_index or old_field.unique) and not (new_field.db_index or new_field.unique):
  112. index_to_remove = self._create_index_name(model, [old_field.column], suffix='_like')
  113. index_names = self._constraint_names(model, [old_field.column], index=True)
  114. for index_name in index_names:
  115. if index_name == index_to_remove:
  116. self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))