3 class CopyTableTest
< ActiveRecord
::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')
49 def test_copy_table_with_id_col_that_is_not_primary_key
50 test_copy_table('goofy_string_id', 'goofy_string_id2') do |from
, to
, options
|
51 original_id
= @connection.columns('goofy_string_id').detect
{|col
| col
.name
== 'id' }
52 copied_id
= @connection.columns('goofy_string_id2').detect
{|col
| col
.name
== 'id' }
53 assert_equal original_id
.type
, copied_id
.type
54 assert_equal original_id
.sql_type
, copied_id
.sql_type
55 assert_equal original_id
.limit
, copied_id
.limit
56 assert_equal original_id
.primary
, copied_id
.primary
61 def copy_table(from
, to
, options
= {})
62 @connection.copy_table(from
, to
, {:temporary => true}.merge(options
))
65 def column_names(table
)
66 @connection.table_structure(table
).map
{|column
| column
['name']}
69 def column_values(table
, column
)
70 @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map
{|row
| row
[column
]}
73 def table_indexes_without_name(table
)
74 @connection.indexes('comments_with_index').delete(:name)
78 @connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count']