Module: Exwiw::DetermineTableProcessingOrder

Defined in:
lib/exwiw/determine_table_processing_order.rb

Class Method Summary collapse

Class Method Details

.compute_table_dependencies(table) ⇒ Object



36
37
38
39
40
# File 'lib/exwiw/determine_table_processing_order.rb', line 36

def compute_table_dependencies(table)
  table.belongs_tos.each_with_object([]) do |relation, acc|
    acc << relation.table_name
  end
end

.run(tables) ⇒ Array<String>



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/exwiw/determine_table_processing_order.rb', line 9

def run(tables)
  return tables.map(&:name) if tables.size < 2

  ordered_table_names = []

  table_by_name = tables.each_with_object({}) do |table, acc|
    acc[table.name] = table
  end

  loop do
    break if table_by_name.empty?

    tables_with_no_dependencies = table_by_name.values.select do |table|
      not_resolved_names = compute_table_dependencies(table) - ordered_table_names - [table.name]

      not_resolved_names.empty?
    end

    tables_with_no_dependencies.each do |table|
      ordered_table_names << table.name
      table_by_name.delete(table.name)
    end
  end

  ordered_table_names
end