Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from django.db.migrations.utils import get_migration_name_timestamp
  2. from django.db.transaction import atomic
  3. from .exceptions import IrreversibleError
  4. class Migration:
  5. """
  6. The base class for all migrations.
  7. Migration files will import this from django.db.migrations.Migration
  8. and subclass it as a class called Migration. It will have one or more
  9. of the following attributes:
  10. - operations: A list of Operation instances, probably from
  11. 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)
  51. and self.name == other.name
  52. and 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. schema_editor.collected_sql.append("-- %s" % operation.describe())
  86. schema_editor.collected_sql.append("--")
  87. if not operation.reduces_to_sql:
  88. schema_editor.collected_sql.append(
  89. "-- THIS OPERATION CANNOT BE WRITTEN AS SQL"
  90. )
  91. continue
  92. collected_sql_before = len(schema_editor.collected_sql)
  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 (
  98. self.atomic and operation.atomic is not False
  99. )
  100. if not schema_editor.atomic_migration and atomic_operation:
  101. # Force a transaction on a non-transactional-DDL backend or an
  102. # atomic operation inside a non-atomic migration.
  103. with atomic(schema_editor.connection.alias):
  104. operation.database_forwards(
  105. self.app_label, schema_editor, old_state, project_state
  106. )
  107. else:
  108. # Normal behaviour
  109. operation.database_forwards(
  110. self.app_label, schema_editor, old_state, project_state
  111. )
  112. if collect_sql and collected_sql_before == len(schema_editor.collected_sql):
  113. schema_editor.collected_sql.append("-- (no-op)")
  114. return project_state
  115. def unapply(self, project_state, schema_editor, collect_sql=False):
  116. """
  117. Take a project_state representing all migrations prior to this one
  118. and a schema_editor for a live database and apply the migration
  119. in a reverse order.
  120. The backwards migration process consists of two phases:
  121. 1. The intermediate states from right before the first until right
  122. after the last operation inside this migration are preserved.
  123. 2. The operations are applied in reverse order using the states
  124. recorded in step 1.
  125. """
  126. # Construct all the intermediate states we need for a reverse migration
  127. to_run = []
  128. new_state = project_state
  129. # Phase 1
  130. for operation in self.operations:
  131. # If it's irreversible, error out
  132. if not operation.reversible:
  133. raise IrreversibleError(
  134. "Operation %s in %s is not reversible" % (operation, self)
  135. )
  136. # Preserve new state from previous run to not tamper the same state
  137. # over all operations
  138. new_state = new_state.clone()
  139. old_state = new_state.clone()
  140. operation.state_forwards(self.app_label, new_state)
  141. to_run.insert(0, (operation, old_state, new_state))
  142. # Phase 2
  143. for operation, to_state, from_state in to_run:
  144. if collect_sql:
  145. schema_editor.collected_sql.append("--")
  146. schema_editor.collected_sql.append("-- %s" % operation.describe())
  147. schema_editor.collected_sql.append("--")
  148. if not operation.reduces_to_sql:
  149. schema_editor.collected_sql.append(
  150. "-- THIS OPERATION CANNOT BE WRITTEN AS SQL"
  151. )
  152. continue
  153. collected_sql_before = len(schema_editor.collected_sql)
  154. atomic_operation = operation.atomic or (
  155. self.atomic and operation.atomic is not False
  156. )
  157. if not schema_editor.atomic_migration and atomic_operation:
  158. # Force a transaction on a non-transactional-DDL backend or an
  159. # atomic operation inside a non-atomic migration.
  160. with atomic(schema_editor.connection.alias):
  161. operation.database_backwards(
  162. self.app_label, schema_editor, from_state, to_state
  163. )
  164. else:
  165. # Normal behaviour
  166. operation.database_backwards(
  167. self.app_label, schema_editor, from_state, to_state
  168. )
  169. if collect_sql and collected_sql_before == len(schema_editor.collected_sql):
  170. schema_editor.collected_sql.append("-- (no-op)")
  171. return project_state
  172. def suggest_name(self):
  173. """
  174. Suggest a name for the operations this migration might represent. Names
  175. are not guaranteed to be unique, but put some effort into the fallback
  176. name to avoid VCS conflicts if possible.
  177. """
  178. if self.initial:
  179. return "initial"
  180. raw_fragments = [op.migration_name_fragment for op in self.operations]
  181. fragments = [name for name in raw_fragments if name]
  182. if not fragments or len(fragments) != len(self.operations):
  183. return "auto_%s" % get_migration_name_timestamp()
  184. name = fragments[0]
  185. for fragment in fragments[1:]:
  186. new_name = f"{name}_{fragment}"
  187. if len(new_name) > 52:
  188. name = f"{name}_and_more"
  189. break
  190. name = new_name
  191. return name
  192. class SwappableTuple(tuple):
  193. """
  194. Subclass of tuple so Django can tell this was originally a swappable
  195. dependency when it reads the migration file.
  196. """
  197. def __new__(cls, value, setting):
  198. self = tuple.__new__(cls, value)
  199. self.setting = setting
  200. return self
  201. def swappable_dependency(value):
  202. """Turn a setting value into a dependency."""
  203. return SwappableTuple((value.split(".", 1)[0], "__first__"), value)