1 require 'abstract_unit'
3 class CopyTableTest < Test::Unit::TestCase
4 fixtures :companies, :comments
7 @connection = ActiveRecord::Base.connection
9 public :copy_table, :table_structure, :indexes
13 def test_copy_table(from = 'companies', to = 'companies2', options = {})
14 assert_nothing_raised {copy_table(from, to, options)}
15 assert_equal row_count(from), row_count(to)
18 yield from, to, options
20 assert_equal column_names(from), column_names(to)
23 @connection.drop_table(to) rescue nil
26 def test_copy_table_renaming_column
27 test_copy_table('companies', 'companies2',
28 :rename => {'client_of' => 'fan_of'}) do |from, to, options|
29 expected = column_values(from, 'client_of')
30 assert expected.any?, 'only nils in resultset; real values are needed'
31 assert_equal expected, column_values(to, 'fan_of')
35 def test_copy_table_with_index
36 test_copy_table('comments', 'comments_with_index') do
37 @connection.add_index('comments_with_index', ['post_id', 'type'])
38 test_copy_table('comments_with_index', 'comments_with_index2') do
39 assert_equal table_indexes_without_name('comments_with_index'),
40 table_indexes_without_name('comments_with_index2')
45 def test_copy_table_without_primary_key
46 test_copy_table('developers_projects', 'programmers_projects')
50 def copy_table(from, to, options = {})
51 @connection.copy_table(from, to, {:temporary => true}.merge(options))
54 def column_names(table)
55 @connection.table_structure(table).map {|column| column['name']}
58 def column_values(table, column)
59 @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map {|row| row[column]}
62 def table_indexes_without_name(table)
63 @connection.indexes('comments_with_index').delete(:name)
67 @connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count']