34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
# File 'lib/also_migrate/migrator.rb', line 34
def create_tables(config)
[ config[:destination] ].flatten.compact.each do |new_table|
if !connection.table_exists?(new_table) && connection.table_exists?(config[:source])
columns = connection.columns(config[:source]).collect(&:name)
columns -= [ config[:subtract] ].flatten.compact.collect(&:to_s)
columns.collect! { |col| connection.quote_column_name(col) }
if config[:indexes]
engine =
if connection.class.to_s.include?('Mysql')
'ENGINE=' + connection.select_one(<<-SQL)['Engine']
SHOW TABLE STATUS
WHERE Name = '#{config[:source]}'
SQL
end
connection.execute(<<-SQL)
CREATE TABLE #{new_table} #{engine}
AS SELECT #{columns.join(',')}
FROM #{config[:source]}
WHERE false;
SQL
[ config[:indexes] ].flatten.compact.each do |column|
connection.add_index(new_table, column)
end
else
if connection.class.to_s.include?('SQLite')
col_string = connection.columns(config[:source]).collect {|c|
"#{c.name} #{c.sql_type}"
}.join(', ')
connection.execute(<<-SQL)
CREATE TABLE #{new_table}
(#{col_string})
SQL
else
connection.execute(<<-SQL)
CREATE TABLE #{new_table}
LIKE #{config[:source]};
SQL
end
end
end
if connection.table_exists?(new_table)
if config[:add] || config[:subtract]
columns = connection.columns(new_table).collect(&:name)
end
if config[:add]
config[:add].each do |column|
unless columns.include?(column[0])
connection.add_column(*([ new_table ] + column))
end
end
end
if config[:subtract]
[ config[:subtract] ].flatten.compact.each do |column|
if columns.include?(column)
connection.remove_column(new_table, column)
end
end
end
end
end
end
|