Skip to content

Commit

Permalink
Improve acyclic check spec
Browse files Browse the repository at this point in the history
  • Loading branch information
ellmetha committed Mar 14, 2023
1 parent 0778be7 commit 2ccf646
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
3 changes: 2 additions & 1 deletion spec/marten/db/management/migrations/graph_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,15 @@ describe Marten::DB::Management::Migrations::Graph do
app_2_migration_3 = Marten::DB::Management::Migrations::GraphSpec::TestMigration5.new

graph = Marten::DB::Management::Migrations::Graph.new
graph.add_node(app_1_migration_1)
graph.add_node(app_2_migration_1)
graph.add_node(app_2_migration_2)
graph.add_node(app_2_migration_3)
graph.add_node(app_1_migration_1)

graph.add_dependency(app_2_migration_2, app_2_migration_1.id)
graph.add_dependency(app_2_migration_3, app_2_migration_2.id)
graph.add_dependency(app_2_migration_3, app_1_migration_1.id)
graph.add_dependency(app_1_migration_1, app_2_migration_2.id)

graph.ensure_acyclic_property.should be_nil
end
Expand Down
8 changes: 6 additions & 2 deletions src/marten/db/management/migrations/graph.cr
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ module Marten
remaining_nodes = @nodes.keys

while !remaining_nodes.empty?
node = remaining_nodes.pop
stack = [node]
# Build a stack starting from the last node in the remaining set and then iterate over the stack last
# item's dependencies. If a dependency node is already in the stack, this means that the graph is cyclic.
# If it's not and if the node wasn't already traversed, this means that the node must be added to the
# stack (and removed from the remaining nodes set). At every iteration the last node is removed from the
# stack if the size of the stack did not change.
stack = [remaining_nodes.pop]

while !stack.empty?
stack_updated = false
Expand Down

0 comments on commit 2ccf646

Please sign in to comment.