Class: PactBroker::DB::TableDependencyCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/pact_broker/db/table_dependency_calculator.rb

Overview

Returns a list of the tables in the database in the order in which they can be truncated or dropped

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ TableDependencyCalculator

Returns a new instance of TableDependencyCalculator.



12
13
14
# File 'lib/pact_broker/db/table_dependency_calculator.rb', line 12

def initialize connection
  @connection = connection
end

Class Method Details

.call(connection) ⇒ Object



8
9
10
# File 'lib/pact_broker/db/table_dependency_calculator.rb', line 8

def self.call connection
  new(connection).call
end

Instance Method Details

#callObject



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/pact_broker/db/table_dependency_calculator.rb', line 16

def call
  ordered_table_names = []
  dependencies = @connection
    .tables
    .collect{|it| @connection.foreign_key_list(it)
    .collect{|fk| {from: it, to: fk[:table]} } }
    .flatten
    .uniq
  table_names = @connection.tables - [:schema_migrations, :schema_info]
  check(table_names, dependencies, ordered_table_names)
  ordered_table_names
end

#check(table_names, deps, ordered_table_names) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/pact_broker/db/table_dependency_calculator.rb', line 33

def check table_names, deps, ordered_table_names
  return if table_names.size == 0
  remaining_dependencies = deps_on(table_names.first, deps) - ordered_table_names
  if remaining_dependencies.size == 0
    ordered_table_names << table_names.first
    check(table_names[1..-1], deps, ordered_table_names)
  else
    check((remaining_dependencies + table_names).uniq, deps, ordered_table_names)
  end
end

#deps_on(table_name, deps) ⇒ Object



29
30
31
# File 'lib/pact_broker/db/table_dependency_calculator.rb', line 29

def deps_on table_name, deps
  deps.select{ | d| d[:to] == table_name }.collect{ |d| d[:from] }
end