Module: Foreigner::ConnectionAdapters::SQLite3Adapter

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

Instance Method Summary collapse

Instance Method Details

#add_foreign_key(from_table, to_table, options = {}) ⇒ Object



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

def add_foreign_key(from_table, to_table, options = {})

  fk_column_name = options[:column] || foreign_key_column(to_table)
  pk_column_name = options[:primary_key] || 'id'

  meta_results = exec_query("select sql from sqlite_master where name = $1", nil, [[nil, from_table]])
  if meta_results.nil? || meta_results.rows.size == 0 
    raise "  [sqlite3-foreigner] error: '#{from_table}' is not found!\n\n"
  end
  create_table = meta_results[0]['sql']

  count = exec_query("select count(1) c from #{from_table}")[0]['c'].to_i
  if count > 0 
    puts "\n *** [sqlite3-foreigner]: Skipped non empty table (table: #{from_table}) ***\n\n"
    return
  end

  execute("drop table #{from_table}")

  re_create_table = create_table.gsub(/("#{fk_column_name}"\s+[^,\)]+)([,\)])/, "\\1 references #{to_table}(#{pk_column_name})\\2")
  execute(re_create_table)
end

#remove_foreign_key(table, options) ⇒ Object



42
43
44
45
# File 'lib/foreigner/connection_adapters/sqlite3_adapter.rb', line 42

def remove_foreign_key(table, options)
  column = options[:name].gsub(/^#{table.to_s.singularize}_/, '').gsub(/_foreign_key$/, '')
  ActiveRecord::Base.connection.remove_column(table, column)
end