Class: TableSaw::Queries::ForeignKeyRelationships

Inherits:
Object
  • Object
show all
Defined in:
lib/table_saw/queries/foreign_key_relationships.rb

Constant Summary collapse

QUERY =
<<~SQL
  select
    tc.constraint_name,
    tc.table_name as from_table,
    kcu.column_name as from_column,
    ccu.table_name as to_table,
    ccu.column_name as to_column
  from information_schema.table_constraints tc
    join information_schema.key_column_usage kcu on tc.constraint_name = kcu.constraint_name
    join information_schema.constraint_column_usage ccu on tc.constraint_name = ccu.constraint_name
  where tc.constraint_type = 'FOREIGN KEY'
SQL

Instance Method Summary collapse

Instance Method Details

#constraint_namesObject



22
23
24
25
26
# File 'lib/table_saw/queries/foreign_key_relationships.rb', line 22

def constraint_names
  @constraint_names ||= result.each_with_object(Hash.new { |h, k| h[k] = [] }) do |row, memo|
    memo[row['from_table']].push(row['constraint_name'])
  end
end

#foreign_keysObject



28
29
30
31
32
33
34
# File 'lib/table_saw/queries/foreign_key_relationships.rb', line 28

def foreign_keys
  @foreign_keys ||= result.map do |row|
    TableSaw::ForeignKey.new(name: row['constraint_name'],
                             from_table: row['from_table'], from_column: row['from_column'],
                             to_table: row['to_table'], to_column: row['to_column'])
  end
end