migration.py 8.9 KB

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