]> source.dussan.org Git - sonarqube.git/blob
ac730f9590a2e43cbaf75b4f0d3b02f963016cd6
[sonarqube.git] /
1 module JdbcSpec
2   module MissingFunctionalityHelper
3     #Taken from SQLite adapter
4
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?}
9
10       transaction do
11         move_table(table_name, altered_table_name, options)
12         move_table(altered_table_name, table_name, &caller)
13       end
14     end
15     
16     def move_table(from, to, options = {}, &block) #:nodoc:
17       copy_table(from, to, options, &block)
18       drop_table(from)
19     end
20
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,
31                              :null => column.null)
32         end
33         @definition.primary_key(primary_key(from))
34         yield @definition if block_given?
35       end
36       
37       copy_table_indexes(from, to)
38       copy_table_contents(from, to, 
39                           @definition.columns, 
40                           options[:rename] || {})
41     end
42     
43     def copy_table_indexes(from, to) #:nodoc:
44       indexes(from).each do |index|
45         name = index.name.downcase
46         if to == "altered_#{from}"
47           name = "temp_#{name}"
48         elsif from == "altered_#{to}"
49           name = name[5..-1]
50         end
51         
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)
56       end
57     end
58     
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)} * ', '
67         sql << ')'
68         execute sql
69       end
70     end
71   end
72 end