@@ -196,14 +196,16 @@ def change_column(table_name, column_name, type, options = {})
196196 end
197197
198198 column_object = schema_cache . columns ( table_name ) . find { |c | c . name . to_s == column_name . to_s }
199- without_constraints = options . key? ( :default ) || options . key? ( :limit )
199+ changing_type = column_object && column_object . type != type . to_sym
200+ no_constraint_options = options . key? ( :default ) || options . key? ( :limit )
201+
200202 default = if !options . key? ( :default ) && column_object
201203 column_object . default
202204 else
203205 options [ :default ]
204206 end
205207
206- if without_constraints || ( column_object && column_object . type != type . to_sym )
208+ if no_constraint_options || changing_type
207209 remove_default_constraint ( table_name , column_name )
208210 indexes = indexes ( table_name ) . select { |index | index . columns . include? ( column_name . to_s ) }
209211 remove_indexes ( table_name , column_name )
@@ -212,10 +214,14 @@ def change_column(table_name, column_name, type, options = {})
212214 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?
213215 alter_command = "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 ] ) } "
214216 alter_command += " COLLATE #{ options [ :collation ] } " if options [ :collation ] . present?
215- alter_command += " NOT NULL" if !options [ :null ] . nil? && options [ :null ] == false
217+ if !options [ :null ] . nil?
218+ alter_command += " NOT NULL" if options [ :null ] == false
219+ elsif column_object && !column_object . null
220+ alter_command += " NOT NULL"
221+ end
216222 sql_commands << alter_command
217223
218- if without_constraints
224+ if no_constraint_options || ( changing_type && default . present? )
219225 default = quote_default_expression ( default , column_object || column_for ( table_name , column_name ) )
220226 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 ) } "
221227 end
0 commit comments