Class: RR::TableSorter

Inherits:
Object
  • Object
show all
Includes:
TSort
Defined in:
lib/rubyrep/table_sorter.rb

Overview

This class sorts a given list of tables so that tables referencing other tables via foreign keys are placed behind those referenced tables.

Rationale: If tables are sorted in that sequence, the risk of foreign key violations is smaller.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(session, tables) ⇒ TableSorter

Initializes the TableSorter

  • session: The active Session instance

  • tables: an array of table names



65
66
67
68
# File 'lib/rubyrep/table_sorter.rb', line 65

def initialize(session, tables)
  self.session = session
  self.tables = tables
end

Instance Attribute Details

#sessionObject

The active Session



17
18
19
# File 'lib/rubyrep/table_sorter.rb', line 17

def session
  @session
end

#tablesObject

The list of table names to be ordered



20
21
22
# File 'lib/rubyrep/table_sorter.rb', line 20

def tables
  @tables
end

Instance Method Details

#referenced_tablesObject

The table dependencies. Format as described e. g. here: PostgreSQLExtender#referenced_tables



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rubyrep/table_sorter.rb', line 24

def referenced_tables
  unless @referenced_tables
    @referenced_tables = session.left.referenced_tables(tables)

    # Strip away all unrelated tables
    @referenced_tables.each_pair do |table, references|
      references.delete_if do |reference|
        not tables.include? reference
      end
    end
  end
  @referenced_tables
end

#sortObject



53
54
55
56
57
58
59
60
# File 'lib/rubyrep/table_sorter.rb', line 53

def sort
  # Note:
  # We should not use TSort#tsort as this one throws an exception if
  # there are cyclic redundancies.
  # (Our goal is to just get the best ordering that is possible and then
  # take our chances.)
  strongly_connected_components.flatten
end

#tsort_each_child(table) ⇒ Object

Yields all tables that are references by table.



47
48
49
50
51
# File 'lib/rubyrep/table_sorter.rb', line 47

def tsort_each_child(table)
  referenced_tables[table].each do |reference|
    yield reference
  end
end

#tsort_each_nodeObject

Yields each table. For details see standard library: TSort#sort_each_node.



40
41
42
43
44
# File 'lib/rubyrep/table_sorter.rb', line 40

def tsort_each_node
  referenced_tables.each_key do |table|
    yield table
  end
end