@@ -141,18 +141,23 @@ 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
+ without_constraints = options . key? ( :default ) || options . key? ( :limit )
145
+ default = if !options . key? ( :default ) && column_object
146
+ column_object . default
147
+ else
148
+ options [ :default ]
149
+ end
150
+ if without_constraints || ( column_object && column_object . type != type . to_sym )
145
151
remove_default_constraint ( table_name , column_name )
146
152
indexes = indexes ( table_name ) . select { |index | index . columns . include? ( column_name . to_s ) }
147
153
remove_indexes ( table_name , column_name )
148
154
end
149
155
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
156
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
157
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 ) } "
158
+ if without_constraints
159
+ default = quote_default_expression ( default , column_object || column_for ( table_name , column_name ) )
160
+ 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
161
end
157
162
# Add any removed indexes back
158
163
indexes . each do |index |
0 commit comments