2 module MissingFunctionalityHelper
3 #Taken from SQLite adapter
5 def alter_table(table_name, options = {}) #:nodoc:
6 table_name = table_name.to_s.downcase
7 altered_table_name = "altered_#{table_name}"
8 caller = lambda {|definition| yield definition if block_given?}
11 move_table(table_name, altered_table_name, options)
12 move_table(altered_table_name, table_name, &caller)
16 def move_table(from, to, options = {}, &block) #:nodoc:
17 copy_table(from, to, options, &block)
21 def copy_table(from, to, options = {}) #:nodoc:
22 create_table(to, options) do |@definition|
23 columns(from).each do |column|
24 column_name = options[:rename] ?
25 (options[:rename][column.name] ||
26 options[:rename][column.name.to_sym] ||
27 column.name) : column.name
28 column_name = column_name.to_s
29 @definition.column(column_name, column.type,
30 :limit => column.limit, :default => column.default,
33 @definition.primary_key(primary_key(from))
34 yield @definition if block_given?
37 copy_table_indexes(from, to)
38 copy_table_contents(from, to,
40 options[:rename] || {})
43 def copy_table_indexes(from, to) #:nodoc:
44 indexes(from).each do |index|
45 name = index.name.downcase
46 if to == "altered_#{from}"
48 elsif from == "altered_#{to}"
52 # index name can't be the same
53 opts = { :name => name.gsub(/_(#{from})_/, "_#{to}_") }
54 opts[:unique] = true if index.unique
55 add_index(to, index.columns, opts)
59 def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
60 column_mappings = Hash[*columns.map {|col| [col.name, col.name]}.flatten]
61 rename.inject(column_mappings) {|map, a| map[a.last] = a.first; map}
62 from_columns = columns(from).collect {|col| col.name}
63 columns = columns.find_all{|col| from_columns.include?(column_mappings[col.name])}
64 execute("SELECT * FROM #{from}").each do |row|
65 sql = "INSERT INTO #{to} ("+columns.map(&:name)*','+") VALUES ("
66 sql << columns.map {|col| quote(row[column_mappings[col.name]],col)} * ', '