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

#belongs_toObject



19
20
21
22
23
# File 'lib/table_saw/queries/foreign_key_relationships.rb', line 19

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

#constraint_namesObject



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

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

#has_manyObject



25
26
27
28
29
# File 'lib/table_saw/queries/foreign_key_relationships.rb', line 25

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