Skip to content

Commit 2925af5

Browse files
committed
Using change_column will leave default if the type does not change or a new default is not included. Fixes issue #22.
1 parent f555a00 commit 2925af5

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

CHANGELOG

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11

22
MASTER
33

4+
* Using change_column will leave default if the type does not change or a new default
5+
is not included. Fixes issue #22. [Ransom Briggs]
6+
47
* Use correct SP name for sp_MSforeachtable so any collation can get to it. [7to3]
58

69
* Qualify INFORMATION_SCHEMA.COLUMNS with a correct period DB name if present.

lib/active_record/connection_adapters/sqlserver_adapter.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -653,10 +653,13 @@ def remove_column(table_name, *column_names)
653653

654654
def change_column(table_name, column_name, type, options = {})
655655
sql_commands = []
656-
remove_default_constraint(table_name, column_name)
656+
column_object = columns(table_name).detect { |c| c.name.to_s == column_name.to_s }
657657
change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
658658
change_column_sql << " NOT NULL" if options[:null] == false
659659
sql_commands << change_column_sql
660+
if options_include_default?(options) || (column_object && column_object.type != type.to_sym)
661+
remove_default_constraint(table_name,column_name)
662+
end
660663
if options_include_default?(options)
661664
remove_sqlserver_columns_cache_for(table_name)
662665
sql_commands << "ALTER TABLE #{quote_table_name(table_name)} ADD CONSTRAINT #{default_name(table_name,column_name)} DEFAULT #{quote(options[:default])} FOR #{quote_column_name(column_name)}"

test/cases/migration_test_sqlserver.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,21 @@ def setup
4646
assert lock_version_column.default.nil?
4747
end
4848

49+
should 'not drop the default contraint if just renaming' do
50+
find_default = lambda do
51+
@connection.select_all("EXEC sp_helpconstraint 'defaults','nomsg'").select do |row|
52+
row['constraint_type'] == "DEFAULT on column decimal_number"
53+
end.last
54+
end
55+
default_before = find_default.call
56+
@connection.change_column :defaults, :decimal_number, :decimal, :precision => 4
57+
default_after = find_default.call
58+
assert default_after
59+
assert_equal default_before['constraint_keys'], default_after['constraint_keys']
60+
end
61+
4962
end
5063

51-
5264
end
5365

5466

0 commit comments

Comments
 (0)