Permalink
Browse files

MySQL: rename_column preserves default values. [#466 state:resolved]

  • Loading branch information...
1 parent a02d672 commit 2e1b56c93745bf0513e449e95830edd390abfaf2 @oboxodo oboxodo committed with jeremy Jun 21, 2008
View
@@ -1,5 +1,7 @@
*Edge*
+* MySQL: rename_column preserves column defaults. #466 [Diego Algorta]
+
* Add :from option to calculations. #397 [Ben Munat]
* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. [Jan De Poorter]
@@ -450,8 +450,16 @@ def change_column(table_name, column_name, type, options = {}) #:nodoc:
end
def rename_column(table_name, column_name, new_column_name) #:nodoc:
+ options = {}
+ if column = columns(table_name).find { |c| c.name == column_name.to_s }
+ options[:default] = column.default
+ else
+ raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
+ end
current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
- execute "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
+ rename_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
+ add_column_options!(rename_column_sql, options)
+ execute(rename_column_sql)
end
# Maps logical Rails types to MySQL-specific data types.
@@ -483,6 +483,32 @@ def test_rename_column
end
end
+ def test_rename_column_preserves_default_value_not_null
+ 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
+
+ def test_rename_nonexistent_column
+ ActiveRecord::Base.connection.create_table(:hats) do |table|
+ table.column :hat_name, :string, :default => nil
+ end
+ assert_raises(ActiveRecord::ActiveRecordError) do
+ Person.connection.rename_column "hats", "nonexistent", "should_fail"
+ end
+ ensure
+ ActiveRecord::Base.connection.drop_table(:hats)
+ end
+
def test_rename_column_with_sql_reserved_word
begin
assert_nothing_raised { Person.connection.rename_column "people", "first_name", "group" }

0 comments on commit 2e1b56c

Please sign in to comment.