discourse/migrations/lib/importer/topological_sorter.rb
Gerhard Schlager 251cac39af DEV: Adds a basic importer for the IntermediateDB
* It only imports users and emails so far
* It stores mapped IDs and usernames in a SQLite DB. In the future, we might want to copy those into the Discourse DB at the end of a migration.
* The importer is split into steps which can mostly be configured with a simple DSL
* Data that needs to be shared between steps can be stored in an instance of the `SharedData` class
* Steps are automatically sorted via their defined dependencies before they are executed
* Common logic for finding unique names (username, group name) is extracted into a helper class
* If possible, steps try to avoid loading already imported data (via `mapping.ids` table)
* And steps should select the `discourse_id` instead of the `original_id` of mapped IDs via SQL
2025-04-07 17:22:36 +02:00

50 lines
1.1 KiB
Ruby
Vendored

# frozen_string_literal: true
module Migrations::Importer
class TopologicalSorter
def self.sort(classes)
new(classes).sort
end
def initialize(classes)
@classes = classes
@dependency_graph = build_dependency_graph
end
def sort
in_degree = Hash.new(0)
@dependency_graph.each_value { |edges| edges.each { |edge| in_degree[edge] += 1 } }
queue = @classes.reject { |cls| in_degree[cls] > 0 }
result = []
while queue.any?
node = queue.shift
result << node
@dependency_graph[node].each do |child|
in_degree[child] -= 1
queue << child if in_degree[child] == 0
end
end
raise "Circular dependency detected" if result.size < @classes.size
result
end
private
def build_dependency_graph
graph = Hash.new { |hash, key| hash[key] = [] }
@classes
.sort_by(&:to_s)
.each do |klass|
dependencies = klass.dependencies || []
dependencies.each { |dependency| graph[dependency] << klass }
graph[klass] ||= []
end
graph
end
end
end