Module: Foreigner::ConnectionAdapters::Mysql2Adapter

Includes:
Sql2003
Defined in:
lib/foreigner/connection_adapters/mysql2_adapter.rb

Instance Method Summary collapse

Methods included from Sql2003

#add_foreign_key, #add_foreign_key_sql, #drop_table, #remove_foreign_key, #supports_foreign_keys?

Instance Method Details

#foreign_keys(table_name) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/foreigner/connection_adapters/mysql2_adapter.rb', line 16

def foreign_keys(table_name)
  fk_info = select_all %{
    SELECT fk.referenced_table_name as 'to_table'
          ,fk.referenced_column_name as 'primary_key'
          ,fk.column_name as 'column'
          ,fk.constraint_name as 'name'
    FROM information_schema.key_column_usage fk
    WHERE fk.referenced_column_name is not null
      AND fk.table_schema = '#{@config[:database]}'
      AND fk.table_name = '#{table_name}'
  }

  create_table_info = select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"]

  fk_info.map do |row|
    options = {:column => row['column'], :name => row['name'], :primary_key => row['primary_key']}

    if create_table_info =~ /CONSTRAINT #{quote_column_name(row['name'])} FOREIGN KEY .* REFERENCES .* ON DELETE (CASCADE|SET NULL|RESTRICT)/
      options[:dependent] = case $1
        when 'CASCADE'  then :delete
        when 'SET NULL' then :nullify
        when 'RESTRICT' then :restrict
      end
    end
    ForeignKeyDefinition.new(table_name, row['to_table'], options)
  end
end

#remove_foreign_key_sql(table, options) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/foreigner/connection_adapters/mysql2_adapter.rb', line 6

def remove_foreign_key_sql(table, options)
  if Hash === options
    foreign_key_name = foreign_key_name(table, options[:column], options)
  else
    foreign_key_name = foreign_key_name(table, "#{options.to_s.singularize}_id")
  end

  "DROP FOREIGN KEY #{quote_column_name(foreign_key_name)}"
end