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
|