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.

migration.py 8.0KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. from django.db.transaction import atomic
  2. from .exceptions import IrreversibleError
  3. class Migration:
  4. """
  5. The base class for all migrations.
  6. Migration files will import this from django.db.migrations.Migration
  7. and subclass it as a class called Migration. It will have one or more
  8. of the following attributes:
  9. - operations: A list of Operation instances, probably from django.db.migrations.operations
  10. - dependencies: A list of tuples of (app_path, migration_name)
  11. - run_before: A list of tuples of (app_path, migration_name)
  12. - replaces: A list of migration_names
  13. Note that all migrations come out of migrations and into the Loader or
  14. Graph as instances, having been initialized with their app label and name.
  15. """
  16. # Operations to apply during this migration, in order.
  17. operations = []
  18. # Other migrations that should be run before this migration.
  19. # Should be a list of (app, migration_name).
  20. dependencies = []
  21. # Other migrations that should be run after this one (i.e. have
  22. # this migration added to their dependencies). Useful to make third-party
  23. # apps' migrations run after your AUTH_USER replacement, for example.
  24. run_before = []
  25. # Migration names in this app that this migration replaces. If this is
  26. # non-empty, this migration will only be applied if all these migrations
  27. # are not applied.
  28. replaces = []
  29. # Is this an initial migration? Initial migrations are skipped on
  30. # --fake-initial if the table or fields already exist. If None, check if
  31. # the migration has any dependencies to determine if there are dependencies
  32. # to tell if db introspection needs to be done. If True, always perform
  33. # introspection. If False, never perform introspection.
  34. initial = None
  35. # Whether to wrap the whole migration in a transaction. Only has an effect
  36. # on database backends which support transactional DDL.
  37. atomic = True
  38. def __init__(self, name, app_label):
  39. self.name = name
  40. self.app_label = app_label
  41. # Copy dependencies & other attrs as we might mutate them at runtime
  42. self.operations = list(self.__class__.operations)
  43. self.dependencies = list(self.__class__.dependencies)
  44. self.run_before = list(self.__class__.run_before)
  45. self.replaces = list(self.__class__.replaces)
  46. def __eq__(self, other):
  47. return (
  48. isinstance(other, Migration) and
  49. self.name == other.name and
  50. self.app_label == other.app_label
  51. )
  52. def __repr__(self):
  53. return "<Migration %s.%s>" % (self.app_label, self.name)
  54. def __str__(self):
  55. return "%s.%s" % (self.app_label, self.name)
  56. def __hash__(self):
  57. return hash("%s.%s" % (self.app_label, self.name))
  58. def mutate_state(self, project_state, preserve=True):
  59. """
  60. Take a ProjectState and return a new one with the migration's
  61. operations applied to it. Preserve the original object state by
  62. default and return a mutated state from a copy.
  63. """
  64. new_state = project_state
  65. if preserve:
  66. new_state = project_state.clone()
  67. for operation in self.operations:
  68. operation.state_forwards(self.app_label, new_state)
  69. return new_state
  70. def apply(self, project_state, schema_editor, collect_sql=False):
  71. """
  72. Take a project_state representing all migrations prior to this one
  73. and a schema_editor for a live database and apply the migration
  74. in a forwards order.
  75. Return the resulting project state for efficient reuse by following
  76. Migrations.
  77. """
  78. for operation in self.operations:
  79. # If this operation cannot be represented as SQL, place a comment
  80. # there instead
  81. if collect_sql:
  82. schema_editor.collected_sql.append("--")
  83. if not operation.reduces_to_sql:
  84. schema_editor.collected_sql.append(
  85. "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:"
  86. )
  87. schema_editor.collected_sql.append("-- %s" % operation.describe())
  88. schema_editor.collected_sql.append("--")
  89. if not operation.reduces_to_sql:
  90. continue
  91. # Save the state before the operation has run
  92. old_state = project_state.clone()
  93. operation.state_forwards(self.app_label, project_state)
  94. # Run the operation
  95. atomic_operation = operation.atomic or (self.atomic and operation.atomic is not False)
  96. if not schema_editor.atomic_migration and atomic_operation:
  97. # Force a transaction on a non-transactional-DDL backend or an
  98. # atomic operation inside a non-atomic migration.
  99. with atomic(schema_editor.connection.alias):
  100. operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  101. else:
  102. # Normal behaviour
  103. operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  104. return project_state
  105. def unapply(self, project_state, schema_editor, collect_sql=False):
  106. """
  107. Take a project_state representing all migrations prior to this one
  108. and a schema_editor for a live database and apply the migration
  109. in a reverse order.
  110. The backwards migration process consists of two phases:
  111. 1. The intermediate states from right before the first until right
  112. after the last operation inside this migration are preserved.
  113. 2. The operations are applied in reverse order using the states
  114. recorded in step 1.
  115. """
  116. # Construct all the intermediate states we need for a reverse migration
  117. to_run = []
  118. new_state = project_state
  119. # Phase 1
  120. for operation in self.operations:
  121. # If it's irreversible, error out
  122. if not operation.reversible:
  123. raise IrreversibleError("Operation %s in %s is not reversible" % (operation, self))
  124. # Preserve new state from previous run to not tamper the same state
  125. # over all operations
  126. new_state = new_state.clone()
  127. old_state = new_state.clone()
  128. operation.state_forwards(self.app_label, new_state)
  129. to_run.insert(0, (operation, old_state, new_state))
  130. # Phase 2
  131. for operation, to_state, from_state in to_run:
  132. if collect_sql:
  133. schema_editor.collected_sql.append("--")
  134. if not operation.reduces_to_sql:
  135. schema_editor.collected_sql.append(
  136. "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:"
  137. )
  138. schema_editor.collected_sql.append("-- %s" % operation.describe())
  139. schema_editor.collected_sql.append("--")
  140. if not operation.reduces_to_sql:
  141. continue
  142. atomic_operation = operation.atomic or (self.atomic and operation.atomic is not False)
  143. if not schema_editor.atomic_migration and atomic_operation:
  144. # Force a transaction on a non-transactional-DDL backend or an
  145. # atomic operation inside a non-atomic migration.
  146. with atomic(schema_editor.connection.alias):
  147. operation.database_backwards(self.app_label, schema_editor, from_state, to_state)
  148. else:
  149. # Normal behaviour
  150. operation.database_backwards(self.app_label, schema_editor, from_state, to_state)
  151. return project_state
  152. class SwappableTuple(tuple):
  153. """
  154. Subclass of tuple so Django can tell this was originally a swappable
  155. dependency when it reads the migration file.
  156. """
  157. def __new__(cls, value, setting):
  158. self = tuple.__new__(cls, value)
  159. self.setting = setting
  160. return self
  161. def swappable_dependency(value):
  162. """Turn a setting value into a dependency."""
  163. return SwappableTuple((value.split(".", 1)[0], "__first__"), value)