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.

base.py 5.1KB

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