提交 2158a700 编写于 作者: A Aaron Patterson

all tested database support migrations, so stop making the tests conditional

上级 d41e2f1c
...@@ -10,1839 +10,1837 @@ ...@@ -10,1839 +10,1837 @@
require MIGRATIONS_ROOT + "/rename/2_rename_things" require MIGRATIONS_ROOT + "/rename/2_rename_things"
require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers" require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers"
if ActiveRecord::Base.connection.supports_migrations? class BigNumber < ActiveRecord::Base; end
class BigNumber < ActiveRecord::Base; end
class Reminder < ActiveRecord::Base; end class Reminder < ActiveRecord::Base; end
class Thing < ActiveRecord::Base; end class Thing < ActiveRecord::Base; end
class ActiveRecord::Migration class ActiveRecord::Migration
class << self class << self
attr_accessor :message_count attr_accessor :message_count
end end
def puts(text="") def puts(text="")
ActiveRecord::Migration.message_count ||= 0 ActiveRecord::Migration.message_count ||= 0
ActiveRecord::Migration.message_count += 1 ActiveRecord::Migration.message_count += 1
end
end end
end
class MigrationTableAndIndexTest < ActiveRecord::TestCase class MigrationTableAndIndexTest < ActiveRecord::TestCase
def test_add_schema_info_respects_prefix_and_suffix def test_add_schema_info_respects_prefix_and_suffix
conn = ActiveRecord::Base.connection conn = ActiveRecord::Base.connection
conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name) conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
# Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters
ActiveRecord::Base.table_name_prefix = 'p_' ActiveRecord::Base.table_name_prefix = 'p_'
ActiveRecord::Base.table_name_suffix = '_s' ActiveRecord::Base.table_name_suffix = '_s'
conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name) conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
conn.initialize_schema_migrations_table conn.initialize_schema_migrations_table
assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name] assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name]
ensure ensure
ActiveRecord::Base.table_name_prefix = "" ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = "" ActiveRecord::Base.table_name_suffix = ""
end
end end
end
class MigrationTest < ActiveRecord::TestCase class MigrationTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false self.use_transactional_fixtures = false
fixtures :people
def setup
super
ActiveRecord::Migration.verbose = true
ActiveRecord::Migration.message_count = 0
end
def teardown fixtures :people
ActiveRecord::Base.connection.initialize_schema_migrations_table
ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}"
%w(things awesome_things prefix_things_suffix prefix_awesome_things_suffix).each do |table| def setup
Thing.connection.drop_table(table) rescue nil super
end ActiveRecord::Migration.verbose = true
Thing.reset_column_information ActiveRecord::Migration.message_count = 0
end
%w(reminders people_reminders prefix_reminders_suffix).each do |table| def teardown
Reminder.connection.drop_table(table) rescue nil ActiveRecord::Base.connection.initialize_schema_migrations_table
end ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}"
Reminder.reset_column_information
%w(last_name key bio age height wealth birthday favorite_day %w(things awesome_things prefix_things_suffix prefix_awesome_things_suffix).each do |table|
moment_of_truth male administrator funny).each do |column| Thing.connection.drop_table(table) rescue nil
Person.connection.remove_column('people', column) rescue nil
end
Person.connection.remove_column("people", "first_name") rescue nil
Person.connection.remove_column("people", "middle_name") rescue nil
Person.connection.add_column("people", "first_name", :string, :limit => 40)
Person.reset_column_information
end end
Thing.reset_column_information
def test_add_index %w(reminders people_reminders prefix_reminders_suffix).each do |table|
# Limit size of last_name and key columns to support Firebird index limitations Reminder.connection.drop_table(table) rescue nil
Person.connection.add_column "people", "last_name", :string, :limit => 100 end
Person.connection.add_column "people", "key", :string, :limit => 100 Reminder.reset_column_information
Person.connection.add_column "people", "administrator", :boolean
assert_nothing_raised { Person.connection.add_index("people", "last_name") } %w(last_name key bio age height wealth birthday favorite_day
assert_nothing_raised { Person.connection.remove_index("people", "last_name") } moment_of_truth male administrator funny).each do |column|
Person.connection.remove_column('people', column) rescue nil
end
Person.connection.remove_column("people", "first_name") rescue nil
Person.connection.remove_column("people", "middle_name") rescue nil
Person.connection.add_column("people", "first_name", :string, :limit => 40)
Person.reset_column_information
end
# Orcl nds shrt indx nms. Sybs 2. def test_add_index
# OpenBase does not have named indexes. You must specify a single column name # Limit size of last_name and key columns to support Firebird index limitations
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) Person.connection.add_column "people", "last_name", :string, :limit => 100
Person.connection.add_column "people", "key", :string, :limit => 100
Person.connection.add_column "people", "administrator", :boolean
assert_nothing_raised { Person.connection.add_index("people", "last_name") }
assert_nothing_raised { Person.connection.remove_index("people", "last_name") }
# Orcl nds shrt indx nms. Sybs 2.
# OpenBase does not have named indexes. You must specify a single column name
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", :column => ["last_name", "first_name"]) }
# Oracle adapter cannot have specified index name larger than 30 characters
# Oracle adapter is shortening index name when just column list is given
unless current_adapter?(:OracleAdapter)
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) } assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", :column => ["last_name", "first_name"]) } assert_nothing_raised { Person.connection.remove_index("people", :name => :index_people_on_last_name_and_first_name) }
# Oracle adapter cannot have specified index name larger than 30 characters
# Oracle adapter is shortening index name when just column list is given
unless current_adapter?(:OracleAdapter)
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", :name => :index_people_on_last_name_and_first_name) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", "last_name_and_first_name") }
end
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) } assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } assert_nothing_raised { Person.connection.remove_index("people", "last_name_and_first_name") }
assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :length => 10) }
assert_nothing_raised { Person.connection.remove_index("people", "last_name") }
assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :length => {:last_name => 10}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :length => 10) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
end end
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :length => 10) }
assert_nothing_raised { Person.connection.remove_index("people", "last_name") }
assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :length => {:last_name => 10}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :length => 10) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
end
# quoting
# Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word
# OpenBase does not have named indexes. You must specify a single column name
unless current_adapter?(:OpenBaseAdapter)
Person.update_all "#{Person.connection.quote_column_name 'key'}=#{Person.connection.quote_column_name 'id'}" #some databases (including sqlite2 won't add a unique index if existing data non unique)
assert_nothing_raised { Person.connection.add_index("people", ["key"], :name => "key_idx", :unique => true) }
assert_nothing_raised { Person.connection.remove_index("people", :name => "key_idx", :unique => true) }
end
# Sybase adapter does not support indexes on :boolean columns
# OpenBase does not have named indexes. You must specify a single column
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
assert_nothing_raised { Person.connection.add_index("people", %w(last_name first_name administrator), :name => "named_admin") }
assert_nothing_raised { Person.connection.remove_index("people", :name => "named_admin") }
end
# Selected adapters support index sort order
if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :order => {:last_name => :desc}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => :desc) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
end
end
# quoting def test_index_symbol_names
# Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word assert_nothing_raised { Person.connection.add_index :people, :primary_contact_id, :name => :symbol_index_name }
# OpenBase does not have named indexes. You must specify a single column name assert Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name)
unless current_adapter?(:OpenBaseAdapter) assert_nothing_raised { Person.connection.remove_index :people, :name => :symbol_index_name }
Person.update_all "#{Person.connection.quote_column_name 'key'}=#{Person.connection.quote_column_name 'id'}" #some databases (including sqlite2 won't add a unique index if existing data non unique) assert !Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name)
assert_nothing_raised { Person.connection.add_index("people", ["key"], :name => "key_idx", :unique => true) } end
assert_nothing_raised { Person.connection.remove_index("people", :name => "key_idx", :unique => true) }
end
# Sybase adapter does not support indexes on :boolean columns def test_add_index_length_limit
# OpenBase does not have named indexes. You must specify a single column good_index_name = 'x' * Person.connection.index_name_length
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) too_long_index_name = good_index_name + 'x'
assert_nothing_raised { Person.connection.add_index("people", %w(last_name first_name administrator), :name => "named_admin") } assert_raise(ArgumentError) { Person.connection.add_index("people", "first_name", :name => too_long_index_name) }
assert_nothing_raised { Person.connection.remove_index("people", :name => "named_admin") } assert !Person.connection.index_name_exists?("people", too_long_index_name, false)
end assert_nothing_raised { Person.connection.add_index("people", "first_name", :name => good_index_name) }
assert Person.connection.index_name_exists?("people", good_index_name, false)
Person.connection.remove_index("people", :name => good_index_name)
end
# Selected adapters support index sort order def test_remove_nonexistent_index
if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter) # we do this by name, so OpenBase is a wash as noted above
assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :order => {:last_name => :desc}) } unless current_adapter?(:OpenBaseAdapter)
assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) } assert_raise(ArgumentError) { Person.connection.remove_index("people", "no_such_index") }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc}) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => :desc) }
assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
end
end end
end
def test_index_symbol_names def test_rename_index
assert_nothing_raised { Person.connection.add_index :people, :primary_contact_id, :name => :symbol_index_name } unless current_adapter?(:OpenBaseAdapter)
assert Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name) # keep the names short to make Oracle and similar behave
assert_nothing_raised { Person.connection.remove_index :people, :name => :symbol_index_name } Person.connection.add_index('people', [:first_name], :name => 'old_idx')
assert !Person.connection.index_exists?(:people, :primary_contact_id, :name => :symbol_index_name) assert_nothing_raised { Person.connection.rename_index('people', 'old_idx', 'new_idx') }
# if the adapter doesn't support the indexes call, pick defaults that let the test pass
assert !Person.connection.index_name_exists?('people', 'old_idx', false)
assert Person.connection.index_name_exists?('people', 'new_idx', true)
end end
end
def test_add_index_length_limit def test_double_add_index
good_index_name = 'x' * Person.connection.index_name_length unless current_adapter?(:OpenBaseAdapter)
too_long_index_name = good_index_name + 'x' Person.connection.add_index('people', [:first_name], :name => 'some_idx')
assert_raise(ArgumentError) { Person.connection.add_index("people", "first_name", :name => too_long_index_name) } assert_raise(ArgumentError) { Person.connection.add_index('people', [:first_name], :name => 'some_idx') }
assert !Person.connection.index_name_exists?("people", too_long_index_name, false)
assert_nothing_raised { Person.connection.add_index("people", "first_name", :name => good_index_name) }
assert Person.connection.index_name_exists?("people", good_index_name, false)
Person.connection.remove_index("people", :name => good_index_name)
end end
end
def test_remove_nonexistent_index def test_create_table_with_force_true_does_not_drop_nonexisting_table
# we do this by name, so OpenBase is a wash as noted above if Person.connection.table_exists?(:testings2)
unless current_adapter?(:OpenBaseAdapter) Person.connection.drop_table :testings2
assert_raise(ArgumentError) { Person.connection.remove_index("people", "no_such_index") }
end
end end
def test_rename_index # using a copy as we need the drop_table method to
unless current_adapter?(:OpenBaseAdapter) # continue to work for the ensure block of the test
# keep the names short to make Oracle and similar behave temp_conn = Person.connection.dup
Person.connection.add_index('people', [:first_name], :name => 'old_idx') temp_conn.expects(:drop_table).never
assert_nothing_raised { Person.connection.rename_index('people', 'old_idx', 'new_idx') } temp_conn.create_table :testings2, :force => true do |t|
# if the adapter doesn't support the indexes call, pick defaults that let the test pass t.column :foo, :string
assert !Person.connection.index_name_exists?('people', 'old_idx', false)
assert Person.connection.index_name_exists?('people', 'new_idx', true)
end
end end
ensure
Person.connection.drop_table :testings2 rescue nil
end
def test_double_add_index # We specifically do a manual INSERT here, and then test only the SELECT
unless current_adapter?(:OpenBaseAdapter) # functionality. This allows us to more easily catch INSERT being broken,
Person.connection.add_index('people', [:first_name], :name => 'some_idx') # but SELECT actually working fine.
assert_raise(ArgumentError) { Person.connection.add_index('people', [:first_name], :name => 'some_idx') } def test_native_decimal_insert_manual_vs_automatic
end correct_value = '0012345678901234567890.0123456789'.to_d
end
def test_create_table_with_force_true_does_not_drop_nonexisting_table Person.delete_all
if Person.connection.table_exists?(:testings2) Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10'
Person.connection.drop_table :testings2 Person.reset_column_information
end
# using a copy as we need the drop_table method to # Do a manual insertion
# continue to work for the ensure block of the test if current_adapter?(:OracleAdapter)
temp_conn = Person.connection.dup Person.connection.execute "insert into people (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)"
temp_conn.expects(:drop_table).never elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
temp_conn.create_table :testings2, :force => true do |t| Person.connection.execute "insert into people (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)"
t.column :foo, :string elsif current_adapter?(:PostgreSQLAdapter)
end Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())"
ensure else
Person.connection.drop_table :testings2 rescue nil Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)"
end end
# We specifically do a manual INSERT here, and then test only the SELECT # SELECT
# functionality. This allows us to more easily catch INSERT being broken, row = Person.find(:first)
# but SELECT actually working fine. assert_kind_of BigDecimal, row.wealth
def test_native_decimal_insert_manual_vs_automatic
correct_value = '0012345678901234567890.0123456789'.to_d
Person.delete_all # If this assert fails, that means the SELECT is broken!
Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10' unless current_adapter?(:SQLite3Adapter)
Person.reset_column_information assert_equal correct_value, row.wealth
end
# Do a manual insertion # Reset to old state
if current_adapter?(:OracleAdapter) Person.delete_all
Person.connection.execute "insert into people (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)"
elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
Person.connection.execute "insert into people (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)"
elsif current_adapter?(:PostgreSQLAdapter)
Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())"
else
Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)"
end
# SELECT # Now use the Rails insertion
row = Person.find(:first) assert_nothing_raised { Person.create :wealth => BigDecimal.new("12345678901234567890.0123456789") }
assert_kind_of BigDecimal, row.wealth
# If this assert fails, that means the SELECT is broken! # SELECT
unless current_adapter?(:SQLite3Adapter) row = Person.find(:first)
assert_equal correct_value, row.wealth assert_kind_of BigDecimal, row.wealth
end
# Reset to old state # If these asserts fail, that means the INSERT (create function, or cast to SQL) is broken!
Person.delete_all unless current_adapter?(:SQLite3Adapter)
assert_equal correct_value, row.wealth
end
# Now use the Rails insertion # Reset to old state
assert_nothing_raised { Person.create :wealth => BigDecimal.new("12345678901234567890.0123456789") } Person.connection.del_column "people", "wealth" rescue nil
Person.reset_column_information
end
# SELECT def test_add_column_with_precision_and_scale
row = Person.find(:first) Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
assert_kind_of BigDecimal, row.wealth Person.reset_column_information
# If these asserts fail, that means the INSERT (create function, or cast to SQL) is broken! wealth_column = Person.columns_hash['wealth']
unless current_adapter?(:SQLite3Adapter) assert_equal 9, wealth_column.precision
assert_equal correct_value, row.wealth assert_equal 7, wealth_column.scale
end end
# Test SQLite adapter specifically for decimal types with precision and scale
# attributes, since these need to be maintained in schema but aren't actually
# used in SQLite itself
if current_adapter?(:SQLite3Adapter)
def test_change_column_with_new_precision_and_scale
Person.delete_all
Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
Person.reset_column_information
# Reset to old state Person.connection.change_column 'people', 'wealth', :decimal, :precision => 12, :scale => 8
Person.connection.del_column "people", "wealth" rescue nil
Person.reset_column_information Person.reset_column_information
wealth_column = Person.columns_hash['wealth']
assert_equal 12, wealth_column.precision
assert_equal 8, wealth_column.scale
end end
def test_add_column_with_precision_and_scale def test_change_column_preserve_other_column_precision_and_scale
Person.delete_all
Person.connection.add_column 'people', 'last_name', :string
Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7 Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
Person.reset_column_information Person.reset_column_information
wealth_column = Person.columns_hash['wealth'] wealth_column = Person.columns_hash['wealth']
assert_equal 9, wealth_column.precision assert_equal 9, wealth_column.precision
assert_equal 7, wealth_column.scale assert_equal 7, wealth_column.scale
end
# Test SQLite adapter specifically for decimal types with precision and scale
# attributes, since these need to be maintained in schema but aren't actually
# used in SQLite itself
if current_adapter?(:SQLite3Adapter)
def test_change_column_with_new_precision_and_scale
Person.delete_all
Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
Person.reset_column_information
Person.connection.change_column 'people', 'wealth', :decimal, :precision => 12, :scale => 8
Person.reset_column_information
wealth_column = Person.columns_hash['wealth']
assert_equal 12, wealth_column.precision
assert_equal 8, wealth_column.scale
end
def test_change_column_preserve_other_column_precision_and_scale
Person.delete_all
Person.connection.add_column 'people', 'last_name', :string
Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
Person.reset_column_information
wealth_column = Person.columns_hash['wealth'] Person.connection.change_column 'people', 'last_name', :string, :null => false
assert_equal 9, wealth_column.precision Person.reset_column_information
assert_equal 7, wealth_column.scale
Person.connection.change_column 'people', 'last_name', :string, :null => false wealth_column = Person.columns_hash['wealth']
Person.reset_column_information assert_equal 9, wealth_column.precision
assert_equal 7, wealth_column.scale
end
end
wealth_column = Person.columns_hash['wealth'] def test_native_types
assert_equal 9, wealth_column.precision Person.delete_all
assert_equal 7, wealth_column.scale Person.connection.add_column "people", "last_name", :string
Person.connection.add_column "people", "bio", :text
Person.connection.add_column "people", "age", :integer
Person.connection.add_column "people", "height", :float
Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10'
Person.connection.add_column "people", "birthday", :datetime
Person.connection.add_column "people", "favorite_day", :date
Person.connection.add_column "people", "moment_of_truth", :datetime
Person.connection.add_column "people", "male", :boolean
Person.reset_column_information
assert_nothing_raised do
Person.create :first_name => 'bob', :last_name => 'bobsen',
:bio => "I was born ....", :age => 18, :height => 1.78,
:wealth => BigDecimal.new("12345678901234567890.0123456789"),
:birthday => 18.years.ago, :favorite_day => 10.days.ago,
:moment_of_truth => "1782-10-10 21:40:18", :male => true
end
bob = Person.find(:first)
assert_equal 'bob', bob.first_name
assert_equal 'bobsen', bob.last_name
assert_equal "I was born ....", bob.bio
assert_equal 18, bob.age
# Test for 30 significant digits (beyond the 16 of float), 10 of them
# after the decimal place.
unless current_adapter?(:SQLite3Adapter)
assert_equal BigDecimal.new("0012345678901234567890.0123456789"), bob.wealth
end
assert_equal true, bob.male?
assert_equal String, bob.first_name.class
assert_equal String, bob.last_name.class
assert_equal String, bob.bio.class
assert_equal Fixnum, bob.age.class
assert_equal Time, bob.birthday.class
if current_adapter?(:OracleAdapter, :SybaseAdapter)
# Sybase, and Oracle don't differentiate between date/time
assert_equal Time, bob.favorite_day.class
else
assert_equal Date, bob.favorite_day.class
end
# Oracle adapter stores Time or DateTime with timezone value already in _before_type_cast column
# therefore no timezone change is done afterwards when default timezone is changed
unless current_adapter?(:OracleAdapter)
# Test DateTime column and defaults, including timezone.
# FIXME: moment of truth may be Time on 64-bit platforms.
if bob.moment_of_truth.is_a?(DateTime)
with_env_tz 'US/Eastern' do
bob.reload
assert_equal DateTime.local_offset, bob.moment_of_truth.offset
assert_not_equal 0, bob.moment_of_truth.offset
assert_not_equal "Z", bob.moment_of_truth.zone
# US/Eastern is -5 hours from GMT
assert_equal Rational(-5, 24), bob.moment_of_truth.offset
assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM
assert_equal DateTime::ITALY, bob.moment_of_truth.start
end
end end
end end
def test_native_types assert_instance_of TrueClass, bob.male?
Person.delete_all assert_kind_of BigDecimal, bob.wealth
Person.connection.add_column "people", "last_name", :string end
Person.connection.add_column "people", "bio", :text
Person.connection.add_column "people", "age", :integer
Person.connection.add_column "people", "height", :float
Person.connection.add_column "people", "wealth", :decimal, :precision => '30', :scale => '10'
Person.connection.add_column "people", "birthday", :datetime
Person.connection.add_column "people", "favorite_day", :date
Person.connection.add_column "people", "moment_of_truth", :datetime
Person.connection.add_column "people", "male", :boolean
Person.reset_column_information
assert_nothing_raised do if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
Person.create :first_name => 'bob', :last_name => 'bobsen', def test_unabstracted_database_dependent_types
:bio => "I was born ....", :age => 18, :height => 1.78, Person.delete_all
:wealth => BigDecimal.new("12345678901234567890.0123456789"),
:birthday => 18.years.ago, :favorite_day => 10.days.ago,
:moment_of_truth => "1782-10-10 21:40:18", :male => true
end
bob = Person.find(:first) ActiveRecord::Migration.add_column :people, :intelligence_quotient, :tinyint
assert_equal 'bob', bob.first_name Person.reset_column_information
assert_equal 'bobsen', bob.last_name assert_match(/tinyint/, Person.columns_hash['intelligence_quotient'].sql_type)
assert_equal "I was born ....", bob.bio ensure
assert_equal 18, bob.age ActiveRecord::Migration.remove_column :people, :intelligence_quotient rescue nil
end
end
# Test for 30 significant digits (beyond the 16 of float), 10 of them def test_add_remove_single_field_using_string_arguments
# after the decimal place. assert !Person.column_methods_hash.include?(:last_name)
unless current_adapter?(:SQLite3Adapter) ActiveRecord::Migration.add_column 'people', 'last_name', :string
assert_equal BigDecimal.new("0012345678901234567890.0123456789"), bob.wealth
end
assert_equal true, bob.male? Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
assert_equal String, bob.first_name.class ActiveRecord::Migration.remove_column 'people', 'last_name'
assert_equal String, bob.last_name.class
assert_equal String, bob.bio.class
assert_equal Fixnum, bob.age.class
assert_equal Time, bob.birthday.class
if current_adapter?(:OracleAdapter, :SybaseAdapter) Person.reset_column_information
# Sybase, and Oracle don't differentiate between date/time assert !Person.column_methods_hash.include?(:last_name)
assert_equal Time, bob.favorite_day.class end
else
assert_equal Date, bob.favorite_day.class
end
# Oracle adapter stores Time or DateTime with timezone value already in _before_type_cast column def test_add_remove_single_field_using_symbol_arguments
# therefore no timezone change is done afterwards when default timezone is changed assert !Person.column_methods_hash.include?(:last_name)
unless current_adapter?(:OracleAdapter)
# Test DateTime column and defaults, including timezone.
# FIXME: moment of truth may be Time on 64-bit platforms.
if bob.moment_of_truth.is_a?(DateTime)
with_env_tz 'US/Eastern' do
bob.reload
assert_equal DateTime.local_offset, bob.moment_of_truth.offset
assert_not_equal 0, bob.moment_of_truth.offset
assert_not_equal "Z", bob.moment_of_truth.zone
# US/Eastern is -5 hours from GMT
assert_equal Rational(-5, 24), bob.moment_of_truth.offset
assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM
assert_equal DateTime::ITALY, bob.moment_of_truth.start
end
end
end
assert_instance_of TrueClass, bob.male? ActiveRecord::Migration.add_column :people, :last_name, :string
assert_kind_of BigDecimal, bob.wealth
end
if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) Person.reset_column_information
def test_unabstracted_database_dependent_types assert Person.column_methods_hash.include?(:last_name)
Person.delete_all
ActiveRecord::Migration.add_column :people, :intelligence_quotient, :tinyint ActiveRecord::Migration.remove_column :people, :last_name
Person.reset_column_information
assert_match(/tinyint/, Person.columns_hash['intelligence_quotient'].sql_type)
ensure
ActiveRecord::Migration.remove_column :people, :intelligence_quotient rescue nil
end
end
def test_add_remove_single_field_using_string_arguments Person.reset_column_information
assert !Person.column_methods_hash.include?(:last_name) assert !Person.column_methods_hash.include?(:last_name)
end
ActiveRecord::Migration.add_column 'people', 'last_name', :string def test_add_rename
Person.delete_all
begin
Person.connection.add_column "people", "girlfriend", :string
Person.reset_column_information Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name) Person.create :girlfriend => 'bobette'
ActiveRecord::Migration.remove_column 'people', 'last_name' Person.connection.rename_column "people", "girlfriend", "exgirlfriend"
Person.reset_column_information Person.reset_column_information
assert !Person.column_methods_hash.include?(:last_name) bob = Person.find(:first)
end
def test_add_remove_single_field_using_symbol_arguments assert_equal "bobette", bob.exgirlfriend
assert !Person.column_methods_hash.include?(:last_name) ensure
Person.connection.remove_column("people", "girlfriend") rescue nil
Person.connection.remove_column("people", "exgirlfriend") rescue nil
end
ActiveRecord::Migration.add_column :people, :last_name, :string end
def test_rename_column_using_symbol_arguments
begin
names_before = Person.find(:all).map(&:first_name)
Person.connection.rename_column :people, :first_name, :nick_name
Person.reset_column_information Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name) assert Person.column_names.include?("nick_name")
assert_equal names_before, Person.find(:all).map(&:nick_name)
ActiveRecord::Migration.remove_column :people, :last_name ensure
Person.connection.remove_column("people","nick_name")
Person.connection.add_column("people","first_name", :string)
end
end
def test_rename_column
begin
names_before = Person.find(:all).map(&:first_name)
Person.connection.rename_column "people", "first_name", "nick_name"
Person.reset_column_information Person.reset_column_information
assert !Person.column_methods_hash.include?(:last_name) assert Person.column_names.include?("nick_name")
assert_equal names_before, Person.find(:all).map(&:nick_name)
ensure
Person.connection.remove_column("people","nick_name")
Person.connection.add_column("people","first_name", :string)
end end
end
def test_add_rename def test_rename_column_preserves_default_value_not_null
Person.delete_all begin
default_before = Developer.connection.columns("developers").find { |c| c.name == "salary" }.default
begin assert_equal 70000, default_before
Person.connection.add_column "people", "girlfriend", :string Developer.connection.rename_column "developers", "salary", "anual_salary"
Person.reset_column_information Developer.reset_column_information
Person.create :girlfriend => 'bobette' assert Developer.column_names.include?("anual_salary")
default_after = Developer.connection.columns("developers").find { |c| c.name == "anual_salary" }.default
Person.connection.rename_column "people", "girlfriend", "exgirlfriend" assert_equal 70000, default_after
ensure
Person.reset_column_information Developer.connection.rename_column "developers", "anual_salary", "salary"
bob = Person.find(:first) Developer.reset_column_information
assert_equal "bobette", bob.exgirlfriend
ensure
Person.connection.remove_column("people", "girlfriend") rescue nil
Person.connection.remove_column("people", "exgirlfriend") rescue nil
end
end end
end
def test_rename_column_using_symbol_arguments def test_rename_nonexistent_column
begin ActiveRecord::Base.connection.create_table(:hats) do |table|
names_before = Person.find(:all).map(&:first_name) table.column :hat_name, :string, :default => nil
Person.connection.rename_column :people, :first_name, :nick_name
Person.reset_column_information
assert Person.column_names.include?("nick_name")
assert_equal names_before, Person.find(:all).map(&:nick_name)
ensure
Person.connection.remove_column("people","nick_name")
Person.connection.add_column("people","first_name", :string)
end
end end
exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
def test_rename_column ActiveRecord::StatementInvalid
begin else
names_before = Person.find(:all).map(&:first_name) ActiveRecord::ActiveRecordError
Person.connection.rename_column "people", "first_name", "nick_name"
Person.reset_column_information
assert Person.column_names.include?("nick_name")
assert_equal names_before, Person.find(:all).map(&:nick_name)
ensure
Person.connection.remove_column("people","nick_name")
Person.connection.add_column("people","first_name", :string)
end
end end
assert_raise(exception) do
def test_rename_column_preserves_default_value_not_null Person.connection.rename_column "hats", "nonexistent", "should_fail"
begin
default_before = Developer.connection.columns("developers").find { |c| c.name == "salary" }.default
assert_equal 70000, default_before
Developer.connection.rename_column "developers", "salary", "anual_salary"
Developer.reset_column_information
assert Developer.column_names.include?("anual_salary")
default_after = Developer.connection.columns("developers").find { |c| c.name == "anual_salary" }.default
assert_equal 70000, default_after
ensure
Developer.connection.rename_column "developers", "anual_salary", "salary"
Developer.reset_column_information
end
end end
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_rename_nonexistent_column def test_rename_column_with_sql_reserved_word
ActiveRecord::Base.connection.create_table(:hats) do |table| begin
table.column :hat_name, :string, :default => nil assert_nothing_raised { Person.connection.rename_column "people", "first_name", "group" }
end Person.reset_column_information
exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) assert Person.column_names.include?("group")
ActiveRecord::StatementInvalid
else
ActiveRecord::ActiveRecordError
end
assert_raise(exception) do
Person.connection.rename_column "hats", "nonexistent", "should_fail"
end
ensure ensure
ActiveRecord::Base.connection.drop_table(:hats) Person.connection.remove_column("people", "group") rescue nil
Person.connection.add_column("people", "first_name", :string) rescue nil
end end
end
def test_rename_column_with_sql_reserved_word def test_rename_column_with_an_index
begin ActiveRecord::Base.connection.create_table(:hats) do |table|
assert_nothing_raised { Person.connection.rename_column "people", "first_name", "group" } table.column :hat_name, :string, :limit => 100
Person.reset_column_information table.column :hat_size, :integer
assert Person.column_names.include?("group")
ensure
Person.connection.remove_column("people", "group") rescue nil
Person.connection.add_column("people", "first_name", :string) rescue nil
end
end end
Person.connection.add_index :hats, :hat_name
def test_rename_column_with_an_index assert_nothing_raised do
ActiveRecord::Base.connection.create_table(:hats) do |table| Person.connection.rename_column "hats", "hat_name", "name"
table.column :hat_name, :string, :limit => 100
table.column :hat_size, :integer
end
Person.connection.add_index :hats, :hat_name
assert_nothing_raised do
Person.connection.rename_column "hats", "hat_name", "name"
end
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end end
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_remove_column_with_index def test_remove_column_with_index
ActiveRecord::Base.connection.create_table(:hats) do |table| ActiveRecord::Base.connection.create_table(:hats) do |table|
table.column :hat_name, :string, :limit => 100 table.column :hat_name, :string, :limit => 100
table.column :hat_size, :integer table.column :hat_size, :integer
end
ActiveRecord::Base.connection.add_index "hats", "hat_size"
assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") }
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end end
ActiveRecord::Base.connection.add_index "hats", "hat_size"
def test_remove_column_with_multi_column_index assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") }
ActiveRecord::Base.connection.create_table(:hats) do |table| ensure
table.column :hat_name, :string, :limit => 100 ActiveRecord::Base.connection.drop_table(:hats)
table.column :hat_size, :integer end
table.column :hat_style, :string, :limit => 100
end
ActiveRecord::Base.connection.add_index "hats", ["hat_style", "hat_size"], :unique => true
assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") }
ensure
ActiveRecord::Base.connection.drop_table(:hats)
end
def test_remove_column_no_second_parameter_raises_exception def test_remove_column_with_multi_column_index
assert_raise(ArgumentError) { Person.connection.remove_column("funny") } ActiveRecord::Base.connection.create_table(:hats) do |table|
table.column :hat_name, :string, :limit => 100
table.column :hat_size, :integer
table.column :hat_style, :string, :limit => 100
end end
ActiveRecord::Base.connection.add_index "hats", ["hat_style", "hat_size"], :unique => true
def test_change_type_of_not_null_column assert_nothing_raised { Person.connection.remove_column("hats", "hat_size") }
assert_nothing_raised do ensure
Topic.connection.change_column "topics", "written_on", :datetime, :null => false ActiveRecord::Base.connection.drop_table(:hats)
Topic.reset_column_information end
Topic.connection.change_column "topics", "written_on", :datetime, :null => false
Topic.reset_column_information
Topic.connection.change_column "topics", "written_on", :datetime, :null => true
Topic.reset_column_information
end
end
if current_adapter?(:SQLite3Adapter) def test_remove_column_no_second_parameter_raises_exception
def test_rename_table_for_sqlite_should_work_with_reserved_words assert_raise(ArgumentError) { Person.connection.remove_column("funny") }
begin end
assert_nothing_raised do
ActiveRecord::Base.connection.rename_table :references, :old_references
ActiveRecord::Base.connection.create_table :octopuses do |t|
t.column :url, :string
end
end
assert_nothing_raised { ActiveRecord::Base.connection.rename_table :octopuses, :references } def test_change_type_of_not_null_column
assert_nothing_raised do
Topic.connection.change_column "topics", "written_on", :datetime, :null => false
Topic.reset_column_information
# Using explicit id in insert for compatibility across all databases Topic.connection.change_column "topics", "written_on", :datetime, :null => false
con = ActiveRecord::Base.connection Topic.reset_column_information
assert_nothing_raised do
con.execute "INSERT INTO 'references' (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://rubyonrails.com')"
end
assert_equal 'http://rubyonrails.com', ActiveRecord::Base.connection.select_value("SELECT url FROM 'references' WHERE id=1")
ensure Topic.connection.change_column "topics", "written_on", :datetime, :null => true
ActiveRecord::Base.connection.drop_table :references Topic.reset_column_information
ActiveRecord::Base.connection.rename_table :old_references, :references
end
end
end end
end
def test_rename_table if current_adapter?(:SQLite3Adapter)
def test_rename_table_for_sqlite_should_work_with_reserved_words
begin begin
ActiveRecord::Base.connection.create_table :octopuses do |t| assert_nothing_raised do
t.column :url, :string ActiveRecord::Base.connection.rename_table :references, :old_references
ActiveRecord::Base.connection.create_table :octopuses do |t|
t.column :url, :string
end
end end
ActiveRecord::Base.connection.rename_table :octopuses, :octopi
assert_nothing_raised { ActiveRecord::Base.connection.rename_table :octopuses, :references }
# Using explicit id in insert for compatibility across all databases # Using explicit id in insert for compatibility across all databases
con = ActiveRecord::Base.connection con = ActiveRecord::Base.connection
con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter) assert_nothing_raised do
assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" } con.execute "INSERT INTO 'references' (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://rubyonrails.com')"
con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter) end
assert_equal 'http://rubyonrails.com', ActiveRecord::Base.connection.select_value("SELECT url FROM 'references' WHERE id=1")
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1")
ensure ensure
ActiveRecord::Base.connection.drop_table :octopuses rescue nil ActiveRecord::Base.connection.drop_table :references
ActiveRecord::Base.connection.drop_table :octopi rescue nil ActiveRecord::Base.connection.rename_table :old_references, :references
end end
end end
end
def test_change_column_nullability def test_rename_table
Person.delete_all begin
Person.connection.add_column "people", "funny", :boolean ActiveRecord::Base.connection.create_table :octopuses do |t|
Person.reset_column_information t.column :url, :string
assert Person.columns_hash["funny"].null, "Column 'funny' must initially allow nulls" end
Person.connection.change_column "people", "funny", :boolean, :null => false, :default => true ActiveRecord::Base.connection.rename_table :octopuses, :octopi
Person.reset_column_information
assert !Person.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point"
Person.connection.change_column "people", "funny", :boolean, :null => true
Person.reset_column_information
assert Person.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point"
end
def test_rename_table_with_an_index
begin
ActiveRecord::Base.connection.create_table :octopuses do |t|
t.column :url, :string
end
ActiveRecord::Base.connection.add_index :octopuses, :url
ActiveRecord::Base.connection.rename_table :octopuses, :octopi # Using explicit id in insert for compatibility across all databases
con = ActiveRecord::Base.connection
con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" }
con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
# Using explicit id in insert for compatibility across all databases assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1")
con = ActiveRecord::Base.connection
con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" }
con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1") ensure
assert ActiveRecord::Base.connection.indexes(:octopi).first.columns.include?("url") ActiveRecord::Base.connection.drop_table :octopuses rescue nil
ensure ActiveRecord::Base.connection.drop_table :octopi rescue nil
ActiveRecord::Base.connection.drop_table :octopuses rescue nil
ActiveRecord::Base.connection.drop_table :octopi rescue nil
end
end end
end
def test_change_column def test_change_column_nullability
Person.connection.add_column 'people', 'age', :integer Person.delete_all
label = "test_change_column Columns" Person.connection.add_column "people", "funny", :boolean
old_columns = Person.connection.columns(Person.table_name, label) Person.reset_column_information
assert old_columns.find { |c| c.name == 'age' and c.type == :integer } assert Person.columns_hash["funny"].null, "Column 'funny' must initially allow nulls"
Person.connection.change_column "people", "funny", :boolean, :null => false, :default => true
assert_nothing_raised { Person.connection.change_column "people", "age", :string } Person.reset_column_information
assert !Person.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point"
Person.connection.change_column "people", "funny", :boolean, :null => true
Person.reset_column_information
assert Person.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point"
end
new_columns = Person.connection.columns(Person.table_name, label) def test_rename_table_with_an_index
assert_nil new_columns.find { |c| c.name == 'age' and c.type == :integer } begin
assert new_columns.find { |c| c.name == 'age' and c.type == :string } ActiveRecord::Base.connection.create_table :octopuses do |t|
t.column :url, :string
end
ActiveRecord::Base.connection.add_index :octopuses, :url
old_columns = Topic.connection.columns(Topic.table_name, label) ActiveRecord::Base.connection.rename_table :octopuses, :octopi
assert old_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => false }
new_columns = Topic.connection.columns(Topic.table_name, label)
assert_nil new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
assert new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == false }
assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => true }
end
def test_change_column_with_nil_default # Using explicit id in insert for compatibility across all databases
Person.connection.add_column "people", "contributor", :boolean, :default => true con = ActiveRecord::Base.connection
Person.reset_column_information con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
assert Person.new.contributor? assert_nothing_raised { con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')" }
con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_nothing_raised { Person.connection.change_column "people", "contributor", :boolean, :default => nil } assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', ActiveRecord::Base.connection.select_value("SELECT url FROM octopi WHERE id=1")
Person.reset_column_information assert ActiveRecord::Base.connection.indexes(:octopi).first.columns.include?("url")
assert !Person.new.contributor?
assert_nil Person.new.contributor
ensure ensure
Person.connection.remove_column("people", "contributor") rescue nil ActiveRecord::Base.connection.drop_table :octopuses rescue nil
ActiveRecord::Base.connection.drop_table :octopi rescue nil
end end
end
def test_change_column_with_new_default def test_change_column
Person.connection.add_column "people", "administrator", :boolean, :default => true Person.connection.add_column 'people', 'age', :integer
Person.reset_column_information label = "test_change_column Columns"
assert Person.new.administrator? old_columns = Person.connection.columns(Person.table_name, label)
assert old_columns.find { |c| c.name == 'age' and c.type == :integer }
assert_nothing_raised { Person.connection.change_column "people", "age", :string }
new_columns = Person.connection.columns(Person.table_name, label)
assert_nil new_columns.find { |c| c.name == 'age' and c.type == :integer }
assert new_columns.find { |c| c.name == 'age' and c.type == :string }
old_columns = Topic.connection.columns(Topic.table_name, label)
assert old_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => false }
new_columns = Topic.connection.columns(Topic.table_name, label)
assert_nil new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
assert new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == false }
assert_nothing_raised { Topic.connection.change_column :topics, :approved, :boolean, :default => true }
end
assert_nothing_raised { Person.connection.change_column "people", "administrator", :boolean, :default => false } def test_change_column_with_nil_default
Person.reset_column_information Person.connection.add_column "people", "contributor", :boolean, :default => true
assert !Person.new.administrator? Person.reset_column_information
ensure assert Person.new.contributor?
Person.connection.remove_column("people", "administrator") rescue nil
end assert_nothing_raised { Person.connection.change_column "people", "contributor", :boolean, :default => nil }
Person.reset_column_information
assert !Person.new.contributor?
assert_nil Person.new.contributor
ensure
Person.connection.remove_column("people", "contributor") rescue nil
end
def test_change_column_default def test_change_column_with_new_default
Person.connection.change_column_default "people", "first_name", "Tester" Person.connection.add_column "people", "administrator", :boolean, :default => true
Person.reset_column_information Person.reset_column_information
assert_equal "Tester", Person.new.first_name assert Person.new.administrator?
end
def test_change_column_default_to_null assert_nothing_raised { Person.connection.change_column "people", "administrator", :boolean, :default => false }
Person.connection.change_column_default "people", "first_name", nil Person.reset_column_information
Person.reset_column_information assert !Person.new.administrator?
assert_nil Person.new.first_name ensure
end Person.connection.remove_column("people", "administrator") rescue nil
end
def test_add_table
assert !Reminder.table_exists?
WeNeedReminders.up
assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
WeNeedReminders.down
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
end
def test_add_table_with_decimals
Person.connection.drop_table :big_numbers rescue nil
assert !BigNumber.table_exists?
GiveMeBigNumbers.up
assert BigNumber.create(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3,
:value_of_e => BigDecimal("2.7182818284590452353602875")
)
b = BigNumber.find(:first)
assert_not_nil b
assert_not_nil b.bank_balance
assert_not_nil b.big_bank_balance
assert_not_nil b.world_population
assert_not_nil b.my_house_population
assert_not_nil b.value_of_e
# TODO: set world_population >= 2**62 to cover 64-bit platforms and test
# is_a?(Bignum)
assert_kind_of Integer, b.world_population
assert_equal 6000000000, b.world_population
assert_kind_of Fixnum, b.my_house_population
assert_equal 3, b.my_house_population
assert_kind_of BigDecimal, b.bank_balance
assert_equal BigDecimal("1586.43"), b.bank_balance
assert_kind_of BigDecimal, b.big_bank_balance
assert_equal BigDecimal("1000234000567.95"), b.big_bank_balance
# This one is fun. The 'value_of_e' field is defined as 'DECIMAL' with
# precision/scale explicitly left out. By the SQL standard, numbers
# assigned to this field should be truncated but that's seldom respected.
if current_adapter?(:PostgreSQLAdapter)
# - PostgreSQL changes the SQL spec on columns declared simply as
# "decimal" to something more useful: instead of being given a scale
# of 0, they take on the compile-time limit for precision and scale,
# so the following should succeed unless you have used really wacky
# compilation options
# - SQLite2 has the default behavior of preserving all data sent in,
# so this happens there too
assert_kind_of BigDecimal, b.value_of_e
assert_equal BigDecimal("2.7182818284590452353602875"), b.value_of_e
elsif current_adapter?(:SQLite3Adapter)
# - SQLite3 stores a float, in violation of SQL
assert_kind_of BigDecimal, b.value_of_e
assert_in_delta BigDecimal("2.71828182845905"), b.value_of_e, 0.00000000000001
else
# - SQL standard is an integer
assert_kind_of Fixnum, b.value_of_e
assert_equal 2, b.value_of_e
end
GiveMeBigNumbers.down def test_change_column_default
assert_raise(ActiveRecord::StatementInvalid) { BigNumber.find(:first) } Person.connection.change_column_default "people", "first_name", "Tester"
end Person.reset_column_information
assert_equal "Tester", Person.new.first_name
end
def test_migrator def test_change_column_default_to_null
assert !Person.column_methods_hash.include?(:last_name) Person.connection.change_column_default "people", "first_name", nil
assert !Reminder.table_exists? Person.reset_column_information
assert_nil Person.new.first_name
end
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid") def test_add_table
assert !Reminder.table_exists?
assert_equal 3, ActiveRecord::Migrator.current_version WeNeedReminders.up
Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid") assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
assert_equal 0, ActiveRecord::Migrator.current_version WeNeedReminders.down
Person.reset_column_information assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
assert !Person.column_methods_hash.include?(:last_name) end
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
end
def test_filtering_migrations def test_add_table_with_decimals
assert !Person.column_methods_hash.include?(:last_name) Person.connection.drop_table :big_numbers rescue nil
assert !Reminder.table_exists?
assert !BigNumber.table_exists?
GiveMeBigNumbers.up
assert BigNumber.create(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3,
:value_of_e => BigDecimal("2.7182818284590452353602875")
)
b = BigNumber.find(:first)
assert_not_nil b
assert_not_nil b.bank_balance
assert_not_nil b.big_bank_balance
assert_not_nil b.world_population
assert_not_nil b.my_house_population
assert_not_nil b.value_of_e
# TODO: set world_population >= 2**62 to cover 64-bit platforms and test
# is_a?(Bignum)
assert_kind_of Integer, b.world_population
assert_equal 6000000000, b.world_population
assert_kind_of Fixnum, b.my_house_population
assert_equal 3, b.my_house_population
assert_kind_of BigDecimal, b.bank_balance
assert_equal BigDecimal("1586.43"), b.bank_balance
assert_kind_of BigDecimal, b.big_bank_balance
assert_equal BigDecimal("1000234000567.95"), b.big_bank_balance
# This one is fun. The 'value_of_e' field is defined as 'DECIMAL' with
# precision/scale explicitly left out. By the SQL standard, numbers
# assigned to this field should be truncated but that's seldom respected.
if current_adapter?(:PostgreSQLAdapter)
# - PostgreSQL changes the SQL spec on columns declared simply as
# "decimal" to something more useful: instead of being given a scale
# of 0, they take on the compile-time limit for precision and scale,
# so the following should succeed unless you have used really wacky
# compilation options
# - SQLite2 has the default behavior of preserving all data sent in,
# so this happens there too
assert_kind_of BigDecimal, b.value_of_e
assert_equal BigDecimal("2.7182818284590452353602875"), b.value_of_e
elsif current_adapter?(:SQLite3Adapter)
# - SQLite3 stores a float, in violation of SQL
assert_kind_of BigDecimal, b.value_of_e
assert_in_delta BigDecimal("2.71828182845905"), b.value_of_e, 0.00000000000001
else
# - SQL standard is an integer
assert_kind_of Fixnum, b.value_of_e
assert_equal 2, b.value_of_e
end
GiveMeBigNumbers.down
assert_raise(ActiveRecord::StatementInvalid) { BigNumber.find(:first) }
end
name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" } def test_migrator
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", &name_filter) assert !Person.column_methods_hash.include?(:last_name)
assert !Reminder.table_exists?
Person.reset_column_information ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid")
assert Person.column_methods_hash.include?(:last_name)
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", &name_filter) assert_equal 3, ActiveRecord::Migrator.current_version
Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
Person.reset_column_information ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
assert !Person.column_methods_hash.include?(:last_name)
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
end
class MockMigration < ActiveRecord::Migration assert_equal 0, ActiveRecord::Migrator.current_version
attr_reader :went_up, :went_down Person.reset_column_information
def initialize assert !Person.column_methods_hash.include?(:last_name)
@went_up = false assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
@went_down = false end
end
def up def test_filtering_migrations
@went_up = true assert !Person.column_methods_hash.include?(:last_name)
super assert !Reminder.table_exists?
end
def down name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" }
@went_down = true ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", &name_filter)
super
end
end
def test_instance_based_migration_up Person.reset_column_information
migration = MockMigration.new assert Person.column_methods_hash.include?(:last_name)
assert !migration.went_up, 'have not gone up' assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
assert !migration.went_down, 'have not gone down'
migration.migrate :up ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", &name_filter)
assert migration.went_up, 'have gone up'
assert !migration.went_down, 'have not gone down' Person.reset_column_information
assert !Person.column_methods_hash.include?(:last_name)
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
end
class MockMigration < ActiveRecord::Migration
attr_reader :went_up, :went_down
def initialize
@went_up = false
@went_down = false
end end
def test_instance_based_migration_down def up
migration = MockMigration.new @went_up = true
assert !migration.went_up, 'have not gone up' super
assert !migration.went_down, 'have not gone down' end
migration.migrate :down def down
assert !migration.went_up, 'have gone up' @went_down = true
assert migration.went_down, 'have not gone down' super
end end
end
def test_migrator_one_up def test_instance_based_migration_up
assert !Person.column_methods_hash.include?(:last_name) migration = MockMigration.new
assert !Reminder.table_exists? assert !migration.went_up, 'have not gone up'
assert !migration.went_down, 'have not gone down'
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) migration.migrate :up
assert migration.went_up, 'have gone up'
assert !migration.went_down, 'have not gone down'
end
Person.reset_column_information def test_instance_based_migration_down
assert Person.column_methods_hash.include?(:last_name) migration = MockMigration.new
assert !Reminder.table_exists? assert !migration.went_up, 'have not gone up'
assert !migration.went_down, 'have not gone down'
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 2) migration.migrate :down
assert !migration.went_up, 'have gone up'
assert migration.went_down, 'have not gone down'
end
assert Reminder.create("content" => "hello world", "remind_at" => Time.now) def test_migrator_one_up
assert_equal "hello world", Reminder.find(:first).content assert !Person.column_methods_hash.include?(:last_name)
end assert !Reminder.table_exists?
def test_migrator_one_down ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid")
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 1) Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
assert !Reminder.table_exists?
Person.reset_column_information ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 2)
assert Person.column_methods_hash.include?(:last_name)
assert !Reminder.table_exists?
end
def test_migrator_one_up_one_down assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) assert_equal "hello world", Reminder.find(:first).content
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) end
assert !Person.column_methods_hash.include?(:last_name) def test_migrator_one_down
assert !Reminder.table_exists? ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid")
end
def test_migrator_double_up ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 1)
assert_equal(0, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1)
assert_nothing_raised { ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) }
assert_equal(1, ActiveRecord::Migrator.current_version)
end
def test_migrator_double_down Person.reset_column_information
assert_equal(0, ActiveRecord::Migrator.current_version) assert Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) assert !Reminder.table_exists?
ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) end
assert_nothing_raised { ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) }
assert_equal(0, ActiveRecord::Migrator.current_version)
end
if ActiveRecord::Base.connection.supports_ddl_transactions? def test_migrator_one_up_one_down
def test_migrator_one_up_with_exception_and_rollback ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
assert !Person.column_methods_hash.include?(:last_name) ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0)
e = assert_raise(StandardError) do assert !Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/broken", 100) assert !Reminder.table_exists?
end end
assert_equal "An error has occurred, this and all later migrations canceled:\n\nSomething broke", e.message def test_migrator_double_up
assert_equal(0, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1)
assert_nothing_raised { ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1) }
assert_equal(1, ActiveRecord::Migrator.current_version)
end
Person.reset_column_information def test_migrator_double_down
assert !Person.column_methods_hash.include?(:last_name) assert_equal(0, ActiveRecord::Migrator.current_version)
end ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/valid", 1)
end ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1)
assert_nothing_raised { ActiveRecord::Migrator.run(:down, MIGRATIONS_ROOT + "/valid", 1) }
assert_equal(0, ActiveRecord::Migrator.current_version)
end
def test_finds_migrations if ActiveRecord::Base.connection.supports_ddl_transactions?
migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").migrations def test_migrator_one_up_with_exception_and_rollback
assert !Person.column_methods_hash.include?(:last_name)
[[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i| e = assert_raise(StandardError) do
assert_equal migrations[i].version, pair.first ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/broken", 100)
assert_equal migrations[i].name, pair.last
end end
end
def test_finds_migrations_in_subdirectories assert_equal "An error has occurred, this and all later migrations canceled:\n\nSomething broke", e.message
migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid_with_subdirectories").migrations
[[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i| Person.reset_column_information
assert_equal migrations[i].version, pair.first assert !Person.column_methods_hash.include?(:last_name)
assert_equal migrations[i].name, pair.last
end
end end
end
def test_finds_migrations_from_two_directories def test_finds_migrations
directories = [MIGRATIONS_ROOT + '/valid_with_timestamps', MIGRATIONS_ROOT + '/to_copy_with_timestamps'] migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid").migrations
migrations = ActiveRecord::Migrator.new(:up, directories).migrations
[[20090101010101, "PeopleHaveHobbies"], [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i|
[20090101010202, "PeopleHaveDescriptions"], assert_equal migrations[i].version, pair.first
[20100101010101, "ValidWithTimestampsPeopleHaveLastNames"], assert_equal migrations[i].name, pair.last
[20100201010101, "ValidWithTimestampsWeNeedReminders"],
[20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i|
assert_equal pair.first, migrations[i].version
assert_equal pair.last, migrations[i].name
end
end end
end
def test_dump_schema_information_outputs_lexically_ordered_versions def test_finds_migrations_in_subdirectories
migration_path = MIGRATIONS_ROOT + '/valid_with_timestamps' migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid_with_subdirectories").migrations
ActiveRecord::Migrator.run(:up, migration_path, 20100301010101)
ActiveRecord::Migrator.run(:up, migration_path, 20100201010101)
schema_info = ActiveRecord::Base.connection.dump_schema_information [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i|
assert_match(/20100201010101.*20100301010101/m, schema_info) assert_equal migrations[i].version, pair.first
assert_equal migrations[i].name, pair.last
end end
end
def test_finds_pending_migrations def test_finds_migrations_from_two_directories
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2", 1) directories = [MIGRATIONS_ROOT + '/valid_with_timestamps', MIGRATIONS_ROOT + '/to_copy_with_timestamps']
migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2").pending_migrations migrations = ActiveRecord::Migrator.new(:up, directories).migrations
assert_equal 1, migrations.size [[20090101010101, "PeopleHaveHobbies"],
assert_equal migrations[0].version, 3 [20090101010202, "PeopleHaveDescriptions"],
assert_equal migrations[0].name, 'InterleavedInnocentJointable' [20100101010101, "ValidWithTimestampsPeopleHaveLastNames"],
[20100201010101, "ValidWithTimestampsWeNeedReminders"],
[20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i|
assert_equal pair.first, migrations[i].version
assert_equal pair.last, migrations[i].name
end end
end
def test_relative_migrations def test_dump_schema_information_outputs_lexically_ordered_versions
list = Dir.chdir(MIGRATIONS_ROOT) do migration_path = MIGRATIONS_ROOT + '/valid_with_timestamps'
ActiveRecord::Migrator.up("valid/", 1) ActiveRecord::Migrator.run(:up, migration_path, 20100301010101)
end ActiveRecord::Migrator.run(:up, migration_path, 20100201010101)
migration_proxy = list.find { |item| schema_info = ActiveRecord::Base.connection.dump_schema_information
item.name == 'ValidPeopleHaveLastNames' assert_match(/20100201010101.*20100301010101/m, schema_info)
} end
assert migration_proxy, 'should find pending migration'
end
def test_only_loads_pending_migrations def test_finds_pending_migrations
# migrate up to 1 ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2", 1)
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2").pending_migrations
proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil) assert_equal 1, migrations.size
assert_equal migrations[0].version, 3
assert_equal migrations[0].name, 'InterleavedInnocentJointable'
end
names = proxies.map(&:name) def test_relative_migrations
assert !names.include?('ValidPeopleHaveLastNames') list = Dir.chdir(MIGRATIONS_ROOT) do
assert names.include?('WeNeedReminders') ActiveRecord::Migrator.up("valid/", 1)
assert names.include?('InnocentJointable')
end end
def test_target_version_zero_should_run_only_once migration_proxy = list.find { |item|
# migrate up to 1 item.name == 'ValidPeopleHaveLastNames'
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) }
assert migration_proxy, 'should find pending migration'
end
# migrate down to 0 def test_only_loads_pending_migrations
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) # migrate up to 1
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
# migrate down to 0 again proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", nil)
proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
assert_equal [], proxies
end
def test_migrator_db_has_no_schema_migrations_table names = proxies.map(&:name)
# Oracle adapter raises error if semicolon is present as last character assert !names.include?('ValidPeopleHaveLastNames')
if current_adapter?(:OracleAdapter) assert names.include?('WeNeedReminders')
ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations") assert names.include?('InnocentJointable')
else end
ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations;")
end
assert_nothing_raised do
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1)
end
end
def test_migrator_verbosity def test_target_version_zero_should_run_only_once
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) # migrate up to 1
assert_not_equal 0, ActiveRecord::Migration.message_count ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1)
ActiveRecord::Migration.message_count = 0
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) # migrate down to 0
assert_not_equal 0, ActiveRecord::Migration.message_count ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
ActiveRecord::Migration.message_count = 0
end # migrate down to 0 again
proxies = ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
assert_equal [], proxies
end
def test_migrator_verbosity_off def test_migrator_db_has_no_schema_migrations_table
ActiveRecord::Migration.verbose = false # Oracle adapter raises error if semicolon is present as last character
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) if current_adapter?(:OracleAdapter)
assert_equal 0, ActiveRecord::Migration.message_count ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations")
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0) else
assert_equal 0, ActiveRecord::Migration.message_count ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations;")
end
assert_nothing_raised do
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1)
end end
end
def test_migrator_going_down_due_to_version_target def test_migrator_verbosity
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1) ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0) assert_not_equal 0, ActiveRecord::Migration.message_count
ActiveRecord::Migration.message_count = 0
assert !Person.column_methods_hash.include?(:last_name) ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0)
assert !Reminder.table_exists? assert_not_equal 0, ActiveRecord::Migration.message_count
ActiveRecord::Migration.message_count = 0
end
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") def test_migrator_verbosity_off
ActiveRecord::Migration.verbose = false
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
assert_equal 0, ActiveRecord::Migration.message_count
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", 0)
assert_equal 0, ActiveRecord::Migration.message_count
end
Person.reset_column_information def test_migrator_going_down_due_to_version_target
assert Person.column_methods_hash.include?(:last_name) ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
assert Reminder.create("content" => "hello world", "remind_at" => Time.now) ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 0)
assert_equal "hello world", Reminder.find(:first).content
end
def test_migrator_rollback assert !Person.column_methods_hash.include?(:last_name)
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") assert !Reminder.table_exists?
assert_equal(3, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
assert_equal(2, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") Person.reset_column_information
assert_equal(1, ActiveRecord::Migrator.current_version) assert Person.column_methods_hash.include?(:last_name)
assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
end
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") def test_migrator_rollback
assert_equal(0, ActiveRecord::Migrator.current_version) ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
assert_equal(3, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
assert_equal(0, ActiveRecord::Migrator.current_version) assert_equal(2, ActiveRecord::Migrator.current_version)
end
def test_migrator_forward ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1) assert_equal(1, ActiveRecord::Migrator.current_version)
assert_equal(1, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid", 2) ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
assert_equal(3, ActiveRecord::Migrator.current_version) assert_equal(0, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid") ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
assert_equal(3, ActiveRecord::Migrator.current_version) assert_equal(0, ActiveRecord::Migrator.current_version)
end end
def test_get_all_versions def test_migrator_forward
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid") ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid", 1)
assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions) assert_equal(1, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid", 2)
assert_equal([1,2], ActiveRecord::Migrator.get_all_versions) assert_equal(3, ActiveRecord::Migrator.current_version)
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") ActiveRecord::Migrator.forward(MIGRATIONS_ROOT + "/valid")
assert_equal([1], ActiveRecord::Migrator.get_all_versions) assert_equal(3, ActiveRecord::Migrator.current_version)
end
ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid") def test_get_all_versions
assert_equal([], ActiveRecord::Migrator.get_all_versions) ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
end assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions)
def test_schema_migrations_table_name ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
ActiveRecord::Base.table_name_prefix = "prefix_" assert_equal([1,2], ActiveRecord::Migrator.get_all_versions)
ActiveRecord::Base.table_name_suffix = "_suffix"
Reminder.reset_table_name
assert_equal "prefix_schema_migrations_suffix", ActiveRecord::Migrator.schema_migrations_table_name
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
Reminder.reset_table_name
assert_equal "schema_migrations", ActiveRecord::Migrator.schema_migrations_table_name
ensure
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
end
def test_proper_table_name
assert_equal "table", ActiveRecord::Migrator.proper_table_name('table')
assert_equal "table", ActiveRecord::Migrator.proper_table_name(:table)
assert_equal "reminders", ActiveRecord::Migrator.proper_table_name(Reminder)
Reminder.reset_table_name
assert_equal Reminder.table_name, ActiveRecord::Migrator.proper_table_name(Reminder)
# Use the model's own prefix/suffix if a model is given
ActiveRecord::Base.table_name_prefix = "ARprefix_"
ActiveRecord::Base.table_name_suffix = "_ARsuffix"
Reminder.table_name_prefix = 'prefix_'
Reminder.table_name_suffix = '_suffix'
Reminder.reset_table_name
assert_equal "prefix_reminders_suffix", ActiveRecord::Migrator.proper_table_name(Reminder)
Reminder.table_name_prefix = ''
Reminder.table_name_suffix = ''
Reminder.reset_table_name
# Use AR::Base's prefix/suffix if string or symbol is given
ActiveRecord::Base.table_name_prefix = "prefix_"
ActiveRecord::Base.table_name_suffix = "_suffix"
Reminder.reset_table_name
assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name('table')
assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name(:table)
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
Reminder.reset_table_name
end
def test_rename_table_with_prefix_and_suffix
assert !Thing.table_exists?
ActiveRecord::Base.table_name_prefix = 'prefix_'
ActiveRecord::Base.table_name_suffix = '_suffix'
Thing.reset_table_name
Thing.reset_sequence_name
WeNeedThings.up
assert Thing.create("content" => "hello world")
assert_equal "hello world", Thing.find(:first).content
RenameThings.up
Thing.table_name = "prefix_awesome_things_suffix"
assert_equal "hello world", Thing.find(:first).content
ensure
ActiveRecord::Base.table_name_prefix = ''
ActiveRecord::Base.table_name_suffix = ''
Thing.reset_table_name
Thing.reset_sequence_name
end
def test_add_drop_table_with_prefix_and_suffix
assert !Reminder.table_exists?
ActiveRecord::Base.table_name_prefix = 'prefix_'
ActiveRecord::Base.table_name_suffix = '_suffix'
Reminder.reset_table_name
Reminder.reset_sequence_name
WeNeedReminders.up
assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
WeNeedReminders.down
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
ensure
ActiveRecord::Base.table_name_prefix = ''
ActiveRecord::Base.table_name_suffix = ''
Reminder.reset_table_name
Reminder.reset_sequence_name
end
def test_create_table_with_binary_column ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
Person.connection.drop_table :binary_testings rescue nil assert_equal([1], ActiveRecord::Migrator.get_all_versions)
assert_nothing_raised { ActiveRecord::Migrator.rollback(MIGRATIONS_ROOT + "/valid")
Person.connection.create_table :binary_testings do |t| assert_equal([], ActiveRecord::Migrator.get_all_versions)
t.column "data", :binary, :null => false end
end
} def test_schema_migrations_table_name
ActiveRecord::Base.table_name_prefix = "prefix_"
ActiveRecord::Base.table_name_suffix = "_suffix"
Reminder.reset_table_name
assert_equal "prefix_schema_migrations_suffix", ActiveRecord::Migrator.schema_migrations_table_name
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
Reminder.reset_table_name
assert_equal "schema_migrations", ActiveRecord::Migrator.schema_migrations_table_name
ensure
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
end
def test_proper_table_name
assert_equal "table", ActiveRecord::Migrator.proper_table_name('table')
assert_equal "table", ActiveRecord::Migrator.proper_table_name(:table)
assert_equal "reminders", ActiveRecord::Migrator.proper_table_name(Reminder)
Reminder.reset_table_name
assert_equal Reminder.table_name, ActiveRecord::Migrator.proper_table_name(Reminder)
# Use the model's own prefix/suffix if a model is given
ActiveRecord::Base.table_name_prefix = "ARprefix_"
ActiveRecord::Base.table_name_suffix = "_ARsuffix"
Reminder.table_name_prefix = 'prefix_'
Reminder.table_name_suffix = '_suffix'
Reminder.reset_table_name
assert_equal "prefix_reminders_suffix", ActiveRecord::Migrator.proper_table_name(Reminder)
Reminder.table_name_prefix = ''
Reminder.table_name_suffix = ''
Reminder.reset_table_name
# Use AR::Base's prefix/suffix if string or symbol is given
ActiveRecord::Base.table_name_prefix = "prefix_"
ActiveRecord::Base.table_name_suffix = "_suffix"
Reminder.reset_table_name
assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name('table')
assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name(:table)
ActiveRecord::Base.table_name_prefix = ""
ActiveRecord::Base.table_name_suffix = ""
Reminder.reset_table_name
end
def test_rename_table_with_prefix_and_suffix
assert !Thing.table_exists?
ActiveRecord::Base.table_name_prefix = 'prefix_'
ActiveRecord::Base.table_name_suffix = '_suffix'
Thing.reset_table_name
Thing.reset_sequence_name
WeNeedThings.up
assert Thing.create("content" => "hello world")
assert_equal "hello world", Thing.find(:first).content
RenameThings.up
Thing.table_name = "prefix_awesome_things_suffix"
assert_equal "hello world", Thing.find(:first).content
ensure
ActiveRecord::Base.table_name_prefix = ''
ActiveRecord::Base.table_name_suffix = ''
Thing.reset_table_name
Thing.reset_sequence_name
end
def test_add_drop_table_with_prefix_and_suffix
assert !Reminder.table_exists?
ActiveRecord::Base.table_name_prefix = 'prefix_'
ActiveRecord::Base.table_name_suffix = '_suffix'
Reminder.reset_table_name
Reminder.reset_sequence_name
WeNeedReminders.up
assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
assert_equal "hello world", Reminder.find(:first).content
WeNeedReminders.down
assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) }
ensure
ActiveRecord::Base.table_name_prefix = ''
ActiveRecord::Base.table_name_suffix = ''
Reminder.reset_table_name
Reminder.reset_sequence_name
end
columns = Person.connection.columns(:binary_testings) def test_create_table_with_binary_column
data_column = columns.detect { |c| c.name == "data" } Person.connection.drop_table :binary_testings rescue nil
if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) assert_nothing_raised {
assert_equal '', data_column.default Person.connection.create_table :binary_testings do |t|
else t.column "data", :binary, :null => false
assert_nil data_column.default
end end
}
columns = Person.connection.columns(:binary_testings)
data_column = columns.detect { |c| c.name == "data" }
Person.connection.drop_table :binary_testings rescue nil if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
assert_equal '', data_column.default
else
assert_nil data_column.default
end end
def test_migrator_with_duplicates Person.connection.drop_table :binary_testings rescue nil
assert_raise(ActiveRecord::DuplicateMigrationVersionError) do end
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate", nil)
end def test_migrator_with_duplicates
assert_raise(ActiveRecord::DuplicateMigrationVersionError) do
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate", nil)
end end
end
def test_migrator_with_duplicate_names def test_migrator_with_duplicate_names
assert_raise(ActiveRecord::DuplicateMigrationNameError, "Multiple migrations have the name Chunky") do assert_raise(ActiveRecord::DuplicateMigrationNameError, "Multiple migrations have the name Chunky") do
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate_names", nil) ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/duplicate_names", nil)
end
end end
end
def test_migrator_with_missing_version_numbers def test_migrator_with_missing_version_numbers
assert_raise(ActiveRecord::UnknownMigrationVersionError) do assert_raise(ActiveRecord::UnknownMigrationVersionError) do
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/missing", 500) ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/missing", 500)
end
end end
end
def test_create_table_with_custom_sequence_name def test_create_table_with_custom_sequence_name
return unless current_adapter? :OracleAdapter return unless current_adapter? :OracleAdapter
# table name is 29 chars, the standard sequence name will # table name is 29 chars, the standard sequence name will
# be 33 chars and should be shortened # be 33 chars and should be shortened
assert_nothing_raised do assert_nothing_raised do
begin begin
Person.connection.create_table :table_with_name_thats_just_ok do |t| Person.connection.create_table :table_with_name_thats_just_ok do |t|
t.column :foo, :string, :null => false t.column :foo, :string, :null => false
end
ensure
Person.connection.drop_table :table_with_name_thats_just_ok rescue nil
end end
ensure
Person.connection.drop_table :table_with_name_thats_just_ok rescue nil
end end
end
# should be all good w/ a custom sequence name # should be all good w/ a custom sequence name
assert_nothing_raised do assert_nothing_raised do
begin begin
Person.connection.create_table :table_with_name_thats_just_ok, Person.connection.create_table :table_with_name_thats_just_ok,
:sequence_name => 'suitably_short_seq' do |t| :sequence_name => 'suitably_short_seq' do |t|
t.column :foo, :string, :null => false t.column :foo, :string, :null => false
end
Person.connection.execute("select suitably_short_seq.nextval from dual")
ensure
Person.connection.drop_table :table_with_name_thats_just_ok,
:sequence_name => 'suitably_short_seq' rescue nil
end end
end
# confirm the custom sequence got dropped
assert_raise(ActiveRecord::StatementInvalid) do
Person.connection.execute("select suitably_short_seq.nextval from dual") Person.connection.execute("select suitably_short_seq.nextval from dual")
end
end
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
ensure ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') Person.connection.drop_table :table_with_name_thats_just_ok,
:sequence_name => 'suitably_short_seq' rescue nil
end end
end
# confirm the custom sequence got dropped
assert_raise(ActiveRecord::StatementInvalid) do
Person.connection.execute("select suitably_short_seq.nextval from dual")
end
end end
class MigrationLoggerTest < ActiveRecord::TestCase protected
def test_migration_should_be_run_without_logger def with_env_tz(new_tz = 'US/Eastern')
previous_logger = ActiveRecord::Base.logger old_tz, ENV['TZ'] = ENV['TZ'], new_tz
ActiveRecord::Base.logger = nil yield
assert_nothing_raised do
ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
end
ensure ensure
ActiveRecord::Base.logger = previous_logger old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end end
end
class InterleavedMigrationsTest < ActiveRecord::TestCase
def test_migrator_interleaved_migrations
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_1")
assert_nothing_raised do end
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2")
end
Person.reset_column_information class MigrationLoggerTest < ActiveRecord::TestCase
assert Person.column_methods_hash.include?(:last_name) def test_migration_should_be_run_without_logger
previous_logger = ActiveRecord::Base.logger
assert_nothing_raised do ActiveRecord::Base.logger = nil
proxies = ActiveRecord::Migrator.down( assert_nothing_raised do
MIGRATIONS_ROOT + "/interleaved/pass_3") ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/valid")
names = proxies.map(&:name)
assert names.include?('InterleavedPeopleHaveLastNames')
assert names.include?('InterleavedInnocentJointable')
end
end end
ensure
ActiveRecord::Base.logger = previous_logger
end end
end
class ReservedWordsMigrationTest < ActiveRecord::TestCase class InterleavedMigrationsTest < ActiveRecord::TestCase
def test_drop_index_from_table_named_values def test_migrator_interleaved_migrations
connection = Person.connection ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_1")
connection.create_table :values, :force => true do |t|
t.integer :value
end
assert_nothing_raised do
connection.add_index :values, :value
connection.remove_index :values, :column => :value
end
connection.drop_table :values rescue nil assert_nothing_raised do
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2")
end end
end
Person.reset_column_information
assert Person.column_methods_hash.include?(:last_name)
class ChangeTableMigrationsTest < ActiveRecord::TestCase assert_nothing_raised do
def setup proxies = ActiveRecord::Migrator.down(
@connection = Person.connection MIGRATIONS_ROOT + "/interleaved/pass_3")
@connection.create_table :delete_me, :force => true do |t| names = proxies.map(&:name)
end assert names.include?('InterleavedPeopleHaveLastNames')
assert names.include?('InterleavedInnocentJointable')
end end
end
end
def teardown class ReservedWordsMigrationTest < ActiveRecord::TestCase
Person.connection.drop_table :delete_me rescue nil def test_drop_index_from_table_named_values
connection = Person.connection
connection.create_table :values, :force => true do |t|
t.integer :value
end end
def test_references_column_type_adds_id assert_nothing_raised do
with_change_table do |t| connection.add_index :values, :value
@connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {}) connection.remove_index :values, :column => :value
t.references :customer
end
end end
def test_remove_references_column_type_removes_id connection.drop_table :values rescue nil
with_change_table do |t| end
@connection.expects(:remove_column).with(:delete_me, 'customer_id') end
t.remove_references :customer
end
class ChangeTableMigrationsTest < ActiveRecord::TestCase
def setup
@connection = Person.connection
@connection.create_table :delete_me, :force => true do |t|
end end
end
def test_add_belongs_to_works_like_add_references def teardown
with_change_table do |t| Person.connection.drop_table :delete_me rescue nil
@connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {}) end
t.belongs_to :customer
end def test_references_column_type_adds_id
with_change_table do |t|
@connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {})
t.references :customer
end end
end
def test_remove_belongs_to_works_like_remove_references def test_remove_references_column_type_removes_id
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_column).with(:delete_me, 'customer_id') @connection.expects(:remove_column).with(:delete_me, 'customer_id')
t.remove_belongs_to :customer t.remove_references :customer
end
end end
end
def test_references_column_type_with_polymorphic_adds_type def test_add_belongs_to_works_like_add_references
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {}) @connection.expects(:add_column).with(:delete_me, 'customer_id', :integer, {})
@connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {}) t.belongs_to :customer
t.references :taggable, :polymorphic => true
end
end end
end
def test_remove_references_column_type_with_polymorphic_removes_type def test_remove_belongs_to_works_like_remove_references
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_column).with(:delete_me, 'taggable_type') @connection.expects(:remove_column).with(:delete_me, 'customer_id')
@connection.expects(:remove_column).with(:delete_me, 'taggable_id') t.remove_belongs_to :customer
t.remove_references :taggable, :polymorphic => true
end
end end
end
def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag def test_references_column_type_with_polymorphic_adds_type
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {:null => false}) @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {})
@connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {:null => false}) @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {})
t.references :taggable, :polymorphic => true, :null => false t.references :taggable, :polymorphic => true
end
end end
end
def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag def test_remove_references_column_type_with_polymorphic_removes_type
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_column).with(:delete_me, 'taggable_type') @connection.expects(:remove_column).with(:delete_me, 'taggable_type')
@connection.expects(:remove_column).with(:delete_me, 'taggable_id') @connection.expects(:remove_column).with(:delete_me, 'taggable_id')
t.remove_references :taggable, :polymorphic => true, :null => false t.remove_references :taggable, :polymorphic => true
end
end end
end
def test_timestamps_creates_updated_at_and_created_at def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_timestamps).with(:delete_me) @connection.expects(:add_column).with(:delete_me, 'taggable_type', :string, {:null => false})
t.timestamps @connection.expects(:add_column).with(:delete_me, 'taggable_id', :integer, {:null => false})
end t.references :taggable, :polymorphic => true, :null => false
end end
end
def test_remove_timestamps_creates_updated_at_and_created_at def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_timestamps).with(:delete_me) @connection.expects(:remove_column).with(:delete_me, 'taggable_type')
t.remove_timestamps @connection.expects(:remove_column).with(:delete_me, 'taggable_id')
end t.remove_references :taggable, :polymorphic => true, :null => false
end end
end
def string_column def test_timestamps_creates_updated_at_and_created_at
if current_adapter?(:PostgreSQLAdapter) with_change_table do |t|
"character varying(255)" @connection.expects(:add_timestamps).with(:delete_me)
elsif current_adapter?(:OracleAdapter) t.timestamps
'VARCHAR2(255)'
else
'varchar(255)'
end
end end
end
def integer_column def test_remove_timestamps_creates_updated_at_and_created_at
if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter) with_change_table do |t|
'int(11)' @connection.expects(:remove_timestamps).with(:delete_me)
elsif current_adapter?(:OracleAdapter) t.remove_timestamps
'NUMBER(38)'
else
'integer'
end
end end
end
def test_integer_creates_integer_column def string_column
with_change_table do |t| if current_adapter?(:PostgreSQLAdapter)
@connection.expects(:add_column).with(:delete_me, :foo, integer_column, {}) "character varying(255)"
@connection.expects(:add_column).with(:delete_me, :bar, integer_column, {}) elsif current_adapter?(:OracleAdapter)
t.integer :foo, :bar 'VARCHAR2(255)'
end else
'varchar(255)'
end end
end
def test_string_creates_string_column def integer_column
with_change_table do |t| if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
@connection.expects(:add_column).with(:delete_me, :foo, string_column, {}) 'int(11)'
@connection.expects(:add_column).with(:delete_me, :bar, string_column, {}) elsif current_adapter?(:OracleAdapter)
t.string :foo, :bar 'NUMBER(38)'
end else
'integer'
end end
end
def test_column_creates_column def test_integer_creates_integer_column
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_column).with(:delete_me, :bar, :integer, {}) @connection.expects(:add_column).with(:delete_me, :foo, integer_column, {})
t.column :bar, :integer @connection.expects(:add_column).with(:delete_me, :bar, integer_column, {})
end t.integer :foo, :bar
end end
end
def test_column_creates_column_with_options def test_string_creates_string_column
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_column).with(:delete_me, :bar, :integer, {:null => false}) @connection.expects(:add_column).with(:delete_me, :foo, string_column, {})
t.column :bar, :integer, :null => false @connection.expects(:add_column).with(:delete_me, :bar, string_column, {})
end t.string :foo, :bar
end end
end
def test_index_creates_index def test_column_creates_column
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_index).with(:delete_me, :bar, {}) @connection.expects(:add_column).with(:delete_me, :bar, :integer, {})
t.index :bar t.column :bar, :integer
end
end end
end
def test_index_creates_index_with_options def test_column_creates_column_with_options
with_change_table do |t| with_change_table do |t|
@connection.expects(:add_index).with(:delete_me, :bar, {:unique => true}) @connection.expects(:add_column).with(:delete_me, :bar, :integer, {:null => false})
t.index :bar, :unique => true t.column :bar, :integer, :null => false
end
end end
end
def test_index_exists def test_index_creates_index
with_change_table do |t| with_change_table do |t|
@connection.expects(:index_exists?).with(:delete_me, :bar, {}) @connection.expects(:add_index).with(:delete_me, :bar, {})
t.index_exists?(:bar) t.index :bar
end
end end
end
def test_index_exists_with_options def test_index_creates_index_with_options
with_change_table do |t| with_change_table do |t|
@connection.expects(:index_exists?).with(:delete_me, :bar, {:unique => true}) @connection.expects(:add_index).with(:delete_me, :bar, {:unique => true})
t.index_exists?(:bar, :unique => true) t.index :bar, :unique => true
end
end end
end
def test_change_changes_column def test_index_exists
with_change_table do |t| with_change_table do |t|
@connection.expects(:change_column).with(:delete_me, :bar, :string, {}) @connection.expects(:index_exists?).with(:delete_me, :bar, {})
t.change :bar, :string t.index_exists?(:bar)
end
end end
end
def test_change_changes_column_with_options def test_index_exists_with_options
with_change_table do |t| with_change_table do |t|
@connection.expects(:change_column).with(:delete_me, :bar, :string, {:null => true}) @connection.expects(:index_exists?).with(:delete_me, :bar, {:unique => true})
t.change :bar, :string, :null => true t.index_exists?(:bar, :unique => true)
end
end end
end
def test_change_default_changes_column def test_change_changes_column
with_change_table do |t| with_change_table do |t|
@connection.expects(:change_column_default).with(:delete_me, :bar, :string) @connection.expects(:change_column).with(:delete_me, :bar, :string, {})
t.change_default :bar, :string t.change :bar, :string
end
end end
end
def test_remove_drops_single_column def test_change_changes_column_with_options
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_column).with(:delete_me, [:bar]) @connection.expects(:change_column).with(:delete_me, :bar, :string, {:null => true})
t.remove :bar t.change :bar, :string, :null => true
end
end end
end
def test_remove_drops_multiple_columns def test_change_default_changes_column
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_column).with(:delete_me, [:bar, :baz]) @connection.expects(:change_column_default).with(:delete_me, :bar, :string)
t.remove :bar, :baz t.change_default :bar, :string
end
end end
end
def test_remove_index_removes_index_with_options def test_remove_drops_single_column
with_change_table do |t| with_change_table do |t|
@connection.expects(:remove_index).with(:delete_me, {:unique => true}) @connection.expects(:remove_column).with(:delete_me, [:bar])
t.remove_index :unique => true t.remove :bar
end
end end
end
def test_rename_renames_column def test_remove_drops_multiple_columns
with_change_table do |t| with_change_table do |t|
@connection.expects(:rename_column).with(:delete_me, :bar, :baz) @connection.expects(:remove_column).with(:delete_me, [:bar, :baz])
t.rename :bar, :baz t.remove :bar, :baz
end
end end
end
protected def test_remove_index_removes_index_with_options
def with_change_table with_change_table do |t|
Person.connection.change_table :delete_me do |t| @connection.expects(:remove_index).with(:delete_me, {:unique => true})
yield t t.remove_index :unique => true
end
end end
end end
if ActiveRecord::Base.connection.supports_bulk_alter? def test_rename_renames_column
class BulkAlterTableMigrationsTest < ActiveRecord::TestCase with_change_table do |t|
def setup @connection.expects(:rename_column).with(:delete_me, :bar, :baz)
@connection = Person.connection t.rename :bar, :baz
@connection.create_table(:delete_me, :force => true) {|t| } end
end end
def teardown protected
Person.connection.drop_table(:delete_me) rescue nil def with_change_table
end Person.connection.change_table :delete_me do |t|
yield t
end
end
end
def test_adding_multiple_columns if ActiveRecord::Base.connection.supports_bulk_alter?
assert_queries(1) do class BulkAlterTableMigrationsTest < ActiveRecord::TestCase
with_bulk_change_table do |t| def setup
t.column :name, :string @connection = Person.connection
t.string :qualification, :experience @connection.create_table(:delete_me, :force => true) {|t| }
t.integer :age, :default => 0 end
t.date :birthdate
t.timestamps
end
end
assert_equal 8, columns.size def teardown
[:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type } Person.connection.drop_table(:delete_me) rescue nil
assert_equal 0, column(:age).default end
end
def test_removing_columns def test_adding_multiple_columns
assert_queries(1) do
with_bulk_change_table do |t| with_bulk_change_table do |t|
t.column :name, :string
t.string :qualification, :experience t.string :qualification, :experience
t.integer :age, :default => 0
t.date :birthdate
t.timestamps
end end
end
[:qualification, :experience].each {|c| assert column(c) } assert_equal 8, columns.size
[:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type }
assert_queries(1) do assert_equal 0, column(:age).default
with_bulk_change_table do |t| end
t.remove :qualification, :experience
t.string :qualification_experience
end
end
[:qualification, :experience].each {|c| assert ! column(c) } def test_removing_columns
assert column(:qualification_experience) with_bulk_change_table do |t|
t.string :qualification, :experience
end end
def test_adding_indexes [:qualification, :experience].each {|c| assert column(c) }
with_bulk_change_table do |t|
t.string :username
t.string :name
t.integer :age
end
# Adding an index fires a query every time to check if an index already exists or not assert_queries(1) do
assert_queries(3) do with_bulk_change_table do |t|
with_bulk_change_table do |t| t.remove :qualification, :experience
t.index :username, :unique => true, :name => :awesome_username_index t.string :qualification_experience
t.index [:name, :age]
end
end end
end
assert_equal 2, indexes.size [:qualification, :experience].each {|c| assert ! column(c) }
assert column(:qualification_experience)
name_age_index = index(:index_delete_me_on_name_and_age) end
assert_equal ['name', 'age'].sort, name_age_index.columns.sort
assert ! name_age_index.unique
assert index(:awesome_username_index).unique def test_adding_indexes
with_bulk_change_table do |t|
t.string :username
t.string :name
t.integer :age
end end
def test_removing_index # Adding an index fires a query every time to check if an index already exists or not
assert_queries(3) do
with_bulk_change_table do |t| with_bulk_change_table do |t|
t.string :name t.index :username, :unique => true, :name => :awesome_username_index
t.index :name t.index [:name, :age]
end end
end
assert index(:index_delete_me_on_name) assert_equal 2, indexes.size
assert_queries(3) do name_age_index = index(:index_delete_me_on_name_and_age)
with_bulk_change_table do |t| assert_equal ['name', 'age'].sort, name_age_index.columns.sort
t.remove_index :name assert ! name_age_index.unique
t.index :name, :name => :new_name_index, :unique => true
end
end
assert ! index(:index_delete_me_on_name) assert index(:awesome_username_index).unique
end
new_name_index = index(:new_name_index) def test_removing_index
assert new_name_index.unique with_bulk_change_table do |t|
t.string :name
t.index :name
end end
def test_changing_columns assert index(:index_delete_me_on_name)
assert_queries(3) do
with_bulk_change_table do |t| with_bulk_change_table do |t|
t.string :name t.remove_index :name
t.date :birthdate t.index :name, :name => :new_name_index, :unique => true
end end
end
assert ! column(:name).default assert ! index(:index_delete_me_on_name)
assert_equal :date, column(:birthdate).type
# One query for columns (delete_me table) new_name_index = index(:new_name_index)
# One query for primary key (delete_me table) assert new_name_index.unique
# One query to do the bulk change end
assert_queries(3) do
with_bulk_change_table do |t|
t.change :name, :string, :default => 'NONAME'
t.change :birthdate, :datetime
end
end
assert_equal 'NONAME', column(:name).default def test_changing_columns
assert_equal :datetime, column(:birthdate).type with_bulk_change_table do |t|
t.string :name
t.date :birthdate
end end
protected assert ! column(:name).default
assert_equal :date, column(:birthdate).type
def with_bulk_change_table # One query for columns (delete_me table)
# Reset columns/indexes cache as we're changing the table # One query for primary key (delete_me table)
@columns = @indexes = nil # One query to do the bulk change
assert_queries(3) do
Person.connection.change_table(:delete_me, :bulk => true) do |t| with_bulk_change_table do |t|
yield t t.change :name, :string, :default => 'NONAME'
t.change :birthdate, :datetime
end end
end end
def column(name) assert_equal 'NONAME', column(:name).default
columns.detect {|c| c.name == name.to_s } assert_equal :datetime, column(:birthdate).type
end end
def columns protected
@columns ||= Person.connection.columns('delete_me')
end
def index(name) def with_bulk_change_table
indexes.detect {|i| i.name == name.to_s } # Reset columns/indexes cache as we're changing the table
end @columns = @indexes = nil
def indexes Person.connection.change_table(:delete_me, :bulk => true) do |t|
@indexes ||= Person.connection.indexes('delete_me') yield t
end end
end # AlterTableMigrationsTest end
end def column(name)
columns.detect {|c| c.name == name.to_s }
end
class CopyMigrationsTest < ActiveRecord::TestCase def columns
def setup @columns ||= Person.connection.columns('delete_me')
end end
def clear def index(name)
ActiveRecord::Base.timestamped_migrations = true indexes.detect {|i| i.name == name.to_s }
to_delete = Dir[@migrations_path + "/*.rb"] - @existing_migrations
File.delete(*to_delete)
end end
def test_copying_migrations_without_timestamps def indexes
ActiveRecord::Base.timestamped_migrations = false @indexes ||= Person.connection.indexes('delete_me')
@migrations_path = MIGRATIONS_ROOT + "/valid" end
@existing_migrations = Dir[@migrations_path + "/*.rb"] end # AlterTableMigrationsTest
end
class CopyMigrationsTest < ActiveRecord::TestCase
def setup
end
def clear
ActiveRecord::Base.timestamped_migrations = true
to_delete = Dir[@migrations_path + "/*.rb"] - @existing_migrations
File.delete(*to_delete)
end
def test_copying_migrations_without_timestamps
ActiveRecord::Base.timestamped_migrations = false
@migrations_path = MIGRATIONS_ROOT + "/valid"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename)
expected = "# This migration comes from bukkits (originally 1)"
assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty?
ensure
clear
end
def test_copying_migrations_without_timestamps_from_2_sources
ActiveRecord::Base.timestamped_migrations = false
@migrations_path = MIGRATIONS_ROOT + "/valid"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
sources = ActiveSupport::OrderedHash.new
sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy"
sources[:omg] = MIGRATIONS_ROOT + "/to_copy2"
ActiveRecord::Migration.copy(@migrations_path, sources)
assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
assert File.exists?(@migrations_path + "/6_create_articles.omg.rb")
assert File.exists?(@migrations_path + "/7_create_comments.omg.rb")
files_count = Dir[@migrations_path + "/*.rb"].length
ActiveRecord::Migration.copy(@migrations_path, sources)
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
ensure
clear
end
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) def test_copying_migrations_with_timestamps
assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") @existing_migrations = Dir[@migrations_path + "/*.rb"]
assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename)
expected = "# This migration comes from bukkits (originally 1)" Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb",
@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"]
assert_equal expected, copied.map(&:filename)
files_count = Dir[@migrations_path + "/*.rb"].length files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty? assert copied.empty?
ensure
clear
end end
ensure
clear
end
def test_copying_migrations_without_timestamps_from_2_sources def test_copying_migrations_with_timestamps_from_2_sources
ActiveRecord::Base.timestamped_migrations = false @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@migrations_path = MIGRATIONS_ROOT + "/valid" @existing_migrations = Dir[@migrations_path + "/*.rb"]
@existing_migrations = Dir[@migrations_path + "/*.rb"]
sources = ActiveSupport::OrderedHash.new sources = ActiveSupport::OrderedHash.new
sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy" sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
sources[:omg] = MIGRATIONS_ROOT + "/to_copy2" sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2"
ActiveRecord::Migration.copy(@migrations_path, sources)
assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") copied = ActiveRecord::Migration.copy(@migrations_path, sources)
assert File.exists?(@migrations_path + "/6_create_articles.omg.rb") assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/7_create_comments.omg.rb") assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101012_create_articles.omg.rb")
assert File.exists?(@migrations_path + "/20100726101013_create_comments.omg.rb")
assert_equal 4, copied.length
files_count = Dir[@migrations_path + "/*.rb"].length files_count = Dir[@migrations_path + "/*.rb"].length
ActiveRecord::Migration.copy(@migrations_path, sources) ActiveRecord::Migration.copy(@migrations_path, sources)
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
ensure
clear
end end
ensure
clear
end
def test_copying_migrations_with_timestamps def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_future
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"] @existing_migrations = Dir[@migrations_path + "/*.rb"]
Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb")
expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb",
@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"]
assert_equal expected, copied.map(&:filename)
files_count = Dir[@migrations_path + "/*.rb"].length files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty? assert copied.empty?
end
ensure
clear
end end
ensure
clear
end
def test_copying_migrations_with_timestamps_from_2_sources def test_skipping_migrations
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"] @existing_migrations = Dir[@migrations_path + "/*.rb"]
sources = ActiveSupport::OrderedHash.new sources = ActiveSupport::OrderedHash.new
sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2" sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_name_collision"
Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do skipped = []
copied = ActiveRecord::Migration.copy(@migrations_path, sources) on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert_equal 2, copied.length
assert File.exists?(@migrations_path + "/20100726101012_create_articles.omg.rb")
assert File.exists?(@migrations_path + "/20100726101013_create_comments.omg.rb")
assert_equal 4, copied.length
files_count = Dir[@migrations_path + "/*.rb"].length assert_equal 1, skipped.length
ActiveRecord::Migration.copy(@migrations_path, sources) assert_equal ["omg PeopleHaveHobbies"], skipped
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length ensure
end clear
ensure end
clear
end
def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_future def test_skip_is_not_called_if_migrations_are_from_the_same_plugin
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"] @existing_migrations = Dir[@migrations_path + "/*.rb"]
Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do sources = ActiveSupport::OrderedHash.new
ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb")
files_count = Dir[@migrations_path + "/*.rb"].length skipped = []
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
assert copied.empty? ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
end
ensure
clear
end
def test_skipping_migrations assert_equal 2, copied.length
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" assert_equal 0, skipped.length
@existing_migrations = Dir[@migrations_path + "/*.rb"] ensure
clear
end
sources = ActiveSupport::OrderedHash.new def test_copying_migrations_to_non_existing_directory
sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" @migrations_path = MIGRATIONS_ROOT + "/non_existing"
sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_name_collision" @existing_migrations = []
skipped = [] Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert_equal 2, copied.length assert_equal 2, copied.length
assert_equal 1, skipped.length
assert_equal ["omg PeopleHaveHobbies"], skipped
ensure
clear
end end
ensure
clear
Dir.delete(@migrations_path)
end
def test_skip_is_not_called_if_migrations_are_from_the_same_plugin def test_copying_migrations_to_empty_directory
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" @migrations_path = MIGRATIONS_ROOT + "/empty"
@existing_migrations = Dir[@migrations_path + "/*.rb"] @existing_migrations = []
sources = ActiveSupport::OrderedHash.new
sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
skipped = []
on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert_equal 2, copied.length assert_equal 2, copied.length
assert_equal 0, skipped.length
ensure
clear
end
def test_copying_migrations_to_non_existing_directory
@migrations_path = MIGRATIONS_ROOT + "/non_existing"
@existing_migrations = []
Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert_equal 2, copied.length
end
ensure
clear
Dir.delete(@migrations_path)
end
def test_copying_migrations_to_empty_directory
@migrations_path = MIGRATIONS_ROOT + "/empty"
@existing_migrations = []
Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert_equal 2, copied.length
end
ensure
clear
end end
ensure
clear
end end
end end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册