base.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import enum
  2. from django.db import router
  3. class OperationCategory(str, enum.Enum):
  4. ADDITION = "+"
  5. REMOVAL = "-"
  6. ALTERATION = "~"
  7. PYTHON = "p"
  8. SQL = "s"
  9. MIXED = "?"
  10. class Operation:
  11. """
  12. Base class for migration operations.
  13. It's responsible for both mutating the in-memory model state
  14. (see db/migrations/state.py) to represent what it performs, as well
  15. as actually performing it against a live database.
  16. Note that some operations won't modify memory state at all (e.g. data
  17. copying operations), and some will need their modifications to be
  18. optionally specified by the user (e.g. custom Python code snippets)
  19. Due to the way this class deals with deconstruction, it should be
  20. considered immutable.
  21. """
  22. # If this migration can be run in reverse.
  23. # Some operations are impossible to reverse, like deleting data.
  24. reversible = True
  25. # Can this migration be represented as SQL? (things like RunPython cannot)
  26. reduces_to_sql = True
  27. # Should this operation be forced as atomic even on backends with no
  28. # DDL transaction support (i.e., does it have no DDL, like RunPython)
  29. atomic = False
  30. # Should this operation be considered safe to elide and optimize across?
  31. elidable = False
  32. serialization_expand_args = []
  33. category = None
  34. def __new__(cls, *args, **kwargs):
  35. # We capture the arguments to make returning them trivial
  36. self = object.__new__(cls)
  37. self._constructor_args = (args, kwargs)
  38. return self
  39. def deconstruct(self):
  40. """
  41. Return a 3-tuple of class import path (or just name if it lives
  42. under django.db.migrations), positional arguments, and keyword
  43. arguments.
  44. """
  45. return (
  46. self.__class__.__name__,
  47. self._constructor_args[0],
  48. self._constructor_args[1],
  49. )
  50. def state_forwards(self, app_label, state):
  51. """
  52. Take the state from the previous migration, and mutate it
  53. so that it matches what this migration would perform.
  54. """
  55. raise NotImplementedError(
  56. "subclasses of Operation must provide a state_forwards() method"
  57. )
  58. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  59. """
  60. Perform the mutation on the database schema in the normal
  61. (forwards) direction.
  62. """
  63. raise NotImplementedError(
  64. "subclasses of Operation must provide a database_forwards() method"
  65. )
  66. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  67. """
  68. Perform the mutation on the database schema in the reverse
  69. direction - e.g. if this were CreateModel, it would in fact
  70. drop the model's table.
  71. """
  72. raise NotImplementedError(
  73. "subclasses of Operation must provide a database_backwards() method"
  74. )
  75. def describe(self):
  76. """
  77. Output a brief summary of what the action does.
  78. """
  79. return "%s: %s" % (self.__class__.__name__, self._constructor_args)
  80. def formatted_description(self):
  81. """Output a description prefixed by a category symbol."""
  82. description = self.describe()
  83. if self.category is None:
  84. return f"{OperationCategory.MIXED.value} {description}"
  85. return f"{self.category.value} {description}"
  86. @property
  87. def migration_name_fragment(self):
  88. """
  89. A filename part suitable for automatically naming a migration
  90. containing this operation, or None if not applicable.
  91. """
  92. return None
  93. def references_model(self, name, app_label):
  94. """
  95. Return True if there is a chance this operation references the given
  96. model name (as a string), with an app label for accuracy.
  97. Used for optimization. If in doubt, return True;
  98. returning a false positive will merely make the optimizer a little
  99. less efficient, while returning a false negative may result in an
  100. unusable optimized migration.
  101. """
  102. return True
  103. def references_field(self, model_name, name, app_label):
  104. """
  105. Return True if there is a chance this operation references the given
  106. field name, with an app label for accuracy.
  107. Used for optimization. If in doubt, return True.
  108. """
  109. return self.references_model(model_name, app_label)
  110. def allow_migrate_model(self, connection_alias, model):
  111. """
  112. Return whether or not a model may be migrated.
  113. This is a thin wrapper around router.allow_migrate_model() that
  114. preemptively rejects any proxy, swapped out, or unmanaged model.
  115. """
  116. if not model._meta.can_migrate(connection_alias):
  117. return False
  118. return router.allow_migrate_model(connection_alias, model)
  119. def reduce(self, operation, app_label):
  120. """
  121. Return either a list of operations the actual operation should be
  122. replaced with or a boolean that indicates whether or not the specified
  123. operation can be optimized across.
  124. """
  125. if self.elidable:
  126. return [operation]
  127. elif operation.elidable:
  128. return [self]
  129. return False
  130. def __repr__(self):
  131. return "<%s %s%s>" % (
  132. self.__class__.__name__,
  133. ", ".join(map(repr, self._constructor_args[0])),
  134. ",".join(" %s=%r" % x for x in self._constructor_args[1].items()),
  135. )