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.

graph.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. from functools import total_ordering
  2. from django.db.migrations.state import ProjectState
  3. from .exceptions import CircularDependencyError, NodeNotFoundError
  4. @total_ordering
  5. class Node:
  6. """
  7. A single node in the migration graph. Contains direct links to adjacent
  8. nodes in either direction.
  9. """
  10. def __init__(self, key):
  11. self.key = key
  12. self.children = set()
  13. self.parents = set()
  14. def __eq__(self, other):
  15. return self.key == other
  16. def __lt__(self, other):
  17. return self.key < other
  18. def __hash__(self):
  19. return hash(self.key)
  20. def __getitem__(self, item):
  21. return self.key[item]
  22. def __str__(self):
  23. return str(self.key)
  24. def __repr__(self):
  25. return "<%s: (%r, %r)>" % (self.__class__.__name__, self.key[0], self.key[1])
  26. def add_child(self, child):
  27. self.children.add(child)
  28. def add_parent(self, parent):
  29. self.parents.add(parent)
  30. class DummyNode(Node):
  31. """
  32. A node that doesn't correspond to a migration file on disk.
  33. (A squashed migration that was removed, for example.)
  34. After the migration graph is processed, all dummy nodes should be removed.
  35. If there are any left, a nonexistent dependency error is raised.
  36. """
  37. def __init__(self, key, origin, error_message):
  38. super().__init__(key)
  39. self.origin = origin
  40. self.error_message = error_message
  41. def raise_error(self):
  42. raise NodeNotFoundError(self.error_message, self.key, origin=self.origin)
  43. class MigrationGraph:
  44. """
  45. Represent the digraph of all migrations in a project.
  46. Each migration is a node, and each dependency is an edge. There are
  47. no implicit dependencies between numbered migrations - the numbering is
  48. merely a convention to aid file listing. Every new numbered migration
  49. has a declared dependency to the previous number, meaning that VCS
  50. branch merges can be detected and resolved.
  51. Migrations files can be marked as replacing another set of migrations -
  52. this is to support the "squash" feature. The graph handler isn't responsible
  53. for these; instead, the code to load them in here should examine the
  54. migration files and if the replaced migrations are all either unapplied
  55. or not present, it should ignore the replaced ones, load in just the
  56. replacing migration, and repoint any dependencies that pointed to the
  57. replaced migrations to point to the replacing one.
  58. A node should be a tuple: (app_path, migration_name). The tree special-cases
  59. things within an app - namely, root nodes and leaf nodes ignore dependencies
  60. to other apps.
  61. """
  62. def __init__(self):
  63. self.node_map = {}
  64. self.nodes = {}
  65. def add_node(self, key, migration):
  66. assert key not in self.node_map
  67. node = Node(key)
  68. self.node_map[key] = node
  69. self.nodes[key] = migration
  70. def add_dummy_node(self, key, origin, error_message):
  71. node = DummyNode(key, origin, error_message)
  72. self.node_map[key] = node
  73. self.nodes[key] = None
  74. def add_dependency(self, migration, child, parent, skip_validation=False):
  75. """
  76. This may create dummy nodes if they don't yet exist. If
  77. `skip_validation=True`, validate_consistency() should be called
  78. afterward.
  79. """
  80. if child not in self.nodes:
  81. error_message = (
  82. "Migration %s dependencies reference nonexistent"
  83. " child node %r" % (migration, child)
  84. )
  85. self.add_dummy_node(child, migration, error_message)
  86. if parent not in self.nodes:
  87. error_message = (
  88. "Migration %s dependencies reference nonexistent"
  89. " parent node %r" % (migration, parent)
  90. )
  91. self.add_dummy_node(parent, migration, error_message)
  92. self.node_map[child].add_parent(self.node_map[parent])
  93. self.node_map[parent].add_child(self.node_map[child])
  94. if not skip_validation:
  95. self.validate_consistency()
  96. def remove_replaced_nodes(self, replacement, replaced):
  97. """
  98. Remove each of the `replaced` nodes (when they exist). Any
  99. dependencies that were referencing them are changed to reference the
  100. `replacement` node instead.
  101. """
  102. # Cast list of replaced keys to set to speed up lookup later.
  103. replaced = set(replaced)
  104. try:
  105. replacement_node = self.node_map[replacement]
  106. except KeyError as err:
  107. raise NodeNotFoundError(
  108. "Unable to find replacement node %r. It was either never added"
  109. " to the migration graph, or has been removed." % (replacement,),
  110. replacement,
  111. ) from err
  112. for replaced_key in replaced:
  113. self.nodes.pop(replaced_key, None)
  114. replaced_node = self.node_map.pop(replaced_key, None)
  115. if replaced_node:
  116. for child in replaced_node.children:
  117. child.parents.remove(replaced_node)
  118. # We don't want to create dependencies between the replaced
  119. # node and the replacement node as this would lead to
  120. # self-referencing on the replacement node at a later iteration.
  121. if child.key not in replaced:
  122. replacement_node.add_child(child)
  123. child.add_parent(replacement_node)
  124. for parent in replaced_node.parents:
  125. parent.children.remove(replaced_node)
  126. # Again, to avoid self-referencing.
  127. if parent.key not in replaced:
  128. replacement_node.add_parent(parent)
  129. parent.add_child(replacement_node)
  130. def remove_replacement_node(self, replacement, replaced):
  131. """
  132. The inverse operation to `remove_replaced_nodes`. Almost. Remove the
  133. replacement node `replacement` and remap its child nodes to `replaced`
  134. - the list of nodes it would have replaced. Don't remap its parent
  135. nodes as they are expected to be correct already.
  136. """
  137. self.nodes.pop(replacement, None)
  138. try:
  139. replacement_node = self.node_map.pop(replacement)
  140. except KeyError as err:
  141. raise NodeNotFoundError(
  142. "Unable to remove replacement node %r. It was either never added"
  143. " to the migration graph, or has been removed already."
  144. % (replacement,),
  145. replacement,
  146. ) from err
  147. replaced_nodes = set()
  148. replaced_nodes_parents = set()
  149. for key in replaced:
  150. replaced_node = self.node_map.get(key)
  151. if replaced_node:
  152. replaced_nodes.add(replaced_node)
  153. replaced_nodes_parents |= replaced_node.parents
  154. # We're only interested in the latest replaced node, so filter out
  155. # replaced nodes that are parents of other replaced nodes.
  156. replaced_nodes -= replaced_nodes_parents
  157. for child in replacement_node.children:
  158. child.parents.remove(replacement_node)
  159. for replaced_node in replaced_nodes:
  160. replaced_node.add_child(child)
  161. child.add_parent(replaced_node)
  162. for parent in replacement_node.parents:
  163. parent.children.remove(replacement_node)
  164. # NOTE: There is no need to remap parent dependencies as we can
  165. # assume the replaced nodes already have the correct ancestry.
  166. def validate_consistency(self):
  167. """Ensure there are no dummy nodes remaining in the graph."""
  168. [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
  169. def forwards_plan(self, target):
  170. """
  171. Given a node, return a list of which previous nodes (dependencies) must
  172. be applied, ending with the node itself. This is the list you would
  173. follow if applying the migrations to a database.
  174. """
  175. if target not in self.nodes:
  176. raise NodeNotFoundError("Node %r not a valid node" % (target,), target)
  177. return self.iterative_dfs(self.node_map[target])
  178. def backwards_plan(self, target):
  179. """
  180. Given a node, return a list of which dependent nodes (dependencies)
  181. must be unapplied, ending with the node itself. This is the list you
  182. would follow if removing the migrations from a database.
  183. """
  184. if target not in self.nodes:
  185. raise NodeNotFoundError("Node %r not a valid node" % (target,), target)
  186. return self.iterative_dfs(self.node_map[target], forwards=False)
  187. def iterative_dfs(self, start, forwards=True):
  188. """Iterative depth-first search for finding dependencies."""
  189. visited = []
  190. visited_set = set()
  191. stack = [(start, False)]
  192. while stack:
  193. node, processed = stack.pop()
  194. if node in visited_set:
  195. pass
  196. elif processed:
  197. visited_set.add(node)
  198. visited.append(node.key)
  199. else:
  200. stack.append((node, True))
  201. stack += [
  202. (n, False)
  203. for n in sorted(node.parents if forwards else node.children)
  204. ]
  205. return visited
  206. def root_nodes(self, app=None):
  207. """
  208. Return all root nodes - that is, nodes with no dependencies inside
  209. their app. These are the starting point for an app.
  210. """
  211. roots = set()
  212. for node in self.nodes:
  213. if all(key[0] != node[0] for key in self.node_map[node].parents) and (
  214. not app or app == node[0]
  215. ):
  216. roots.add(node)
  217. return sorted(roots)
  218. def leaf_nodes(self, app=None):
  219. """
  220. Return all leaf nodes - that is, nodes with no dependents in their app.
  221. These are the "most current" version of an app's schema.
  222. Having more than one per app is technically an error, but one that
  223. gets handled further up, in the interactive command - it's usually the
  224. result of a VCS merge and needs some user input.
  225. """
  226. leaves = set()
  227. for node in self.nodes:
  228. if all(key[0] != node[0] for key in self.node_map[node].children) and (
  229. not app or app == node[0]
  230. ):
  231. leaves.add(node)
  232. return sorted(leaves)
  233. def ensure_not_cyclic(self):
  234. # Algo from GvR:
  235. # https://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html
  236. todo = set(self.nodes)
  237. while todo:
  238. node = todo.pop()
  239. stack = [node]
  240. while stack:
  241. top = stack[-1]
  242. for child in self.node_map[top].children:
  243. # Use child.key instead of child to speed up the frequent
  244. # hashing.
  245. node = child.key
  246. if node in stack:
  247. cycle = stack[stack.index(node) :]
  248. raise CircularDependencyError(
  249. ", ".join("%s.%s" % n for n in cycle)
  250. )
  251. if node in todo:
  252. stack.append(node)
  253. todo.remove(node)
  254. break
  255. else:
  256. node = stack.pop()
  257. def __str__(self):
  258. return "Graph: %s nodes, %s edges" % self._nodes_and_edges()
  259. def __repr__(self):
  260. nodes, edges = self._nodes_and_edges()
  261. return "<%s: nodes=%s, edges=%s>" % (self.__class__.__name__, nodes, edges)
  262. def _nodes_and_edges(self):
  263. return len(self.nodes), sum(
  264. len(node.parents) for node in self.node_map.values()
  265. )
  266. def _generate_plan(self, nodes, at_end):
  267. plan = []
  268. for node in nodes:
  269. for migration in self.forwards_plan(node):
  270. if migration not in plan and (at_end or migration not in nodes):
  271. plan.append(migration)
  272. return plan
  273. def make_state(self, nodes=None, at_end=True, real_apps=None):
  274. """
  275. Given a migration node or nodes, return a complete ProjectState for it.
  276. If at_end is False, return the state before the migration has run.
  277. If nodes is not provided, return the overall most current project state.
  278. """
  279. if nodes is None:
  280. nodes = list(self.leaf_nodes())
  281. if not nodes:
  282. return ProjectState()
  283. if not isinstance(nodes[0], tuple):
  284. nodes = [nodes]
  285. plan = self._generate_plan(nodes, at_end)
  286. project_state = ProjectState(real_apps=real_apps)
  287. for node in plan:
  288. project_state = self.nodes[node].mutate_state(project_state, preserve=False)
  289. return project_state
  290. def __contains__(self, node):
  291. return node in self.nodes