base.py 4.9 KB

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