@@ -141,18 +141,17 @@ def change_column(table_name, column_name, type, options = {})
141
141
sql_commands = [ ]
142
142
indexes = [ ]
143
143
column_object = schema_cache . columns ( table_name ) . find { |c | c . name . to_s == column_name . to_s }
144
- if options_include_default ?( options ) || ( column_object && column_object . type != type . to_sym )
144
+ if without_constraints ?( options ) || ( column_object && column_object . type != type . to_sym )
145
145
remove_default_constraint ( table_name , column_name )
146
146
indexes = indexes ( table_name ) . select { |index | index . columns . include? ( column_name . to_s ) }
147
147
remove_indexes ( table_name , column_name )
148
148
end
149
149
sql_commands << "UPDATE #{ quote_table_name ( table_name ) } SET #{ quote_column_name ( column_name ) } =#{ quote_default_expression ( options [ :default ] , column_object ) } WHERE #{ quote_column_name ( column_name ) } IS NULL" if !options [ :null ] . nil? && options [ :null ] == false && !options [ :default ] . nil?
150
150
sql_commands << "ALTER TABLE #{ quote_table_name ( table_name ) } ALTER COLUMN #{ quote_column_name ( column_name ) } #{ type_to_sql ( type , limit : options [ :limit ] , precision : options [ :precision ] , scale : options [ :scale ] ) } "
151
151
sql_commands . last << ' NOT NULL' if !options [ :null ] . nil? && options [ :null ] == false
152
- if options . key? ( :default ) && default_constraint_name ( table_name , column_name ) . present?
153
- change_column_default ( table_name , column_name , options [ :default ] )
154
- elsif options_include_default? ( options )
155
- sql_commands << "ALTER TABLE #{ quote_table_name ( table_name ) } ADD CONSTRAINT #{ default_constraint_name ( table_name , column_name ) } DEFAULT #{ quote_default_expression ( options [ :default ] , column_object ) } FOR #{ quote_column_name ( column_name ) } "
152
+ if without_constraints? ( options )
153
+ default = quote_default_expression ( options [ :default ] , column_object || column_for ( table_name , column_name ) )
154
+ sql_commands << "ALTER TABLE #{ quote_table_name ( table_name ) } ADD CONSTRAINT #{ default_constraint_name ( table_name , column_name ) } DEFAULT #{ default } FOR #{ quote_column_name ( column_name ) } "
156
155
end
157
156
# Add any removed indexes back
158
157
indexes . each do |index |
@@ -492,6 +491,10 @@ def default_constraint_name(table_name, column_name)
492
491
"DF_#{ table_name } _#{ column_name } "
493
492
end
494
493
494
+ def without_constraints? ( options )
495
+ options . key? ( :default ) || ( options . key? ( :limit ) && options . key? ( :default ) )
496
+ end
497
+
495
498
def lowercase_schema_reflection_sql ( node )
496
499
lowercase_schema_reflection ? "LOWER(#{ node } )" : node
497
500
end
0 commit comments