@@ -1181,6 +1181,23 @@ func (csg *columnSQLVertexGenerator) Alter(diff columnDiff) ([]Statement, error)
11811181 })
11821182 }
11831183
1184+ // Drop the default before type conversion. This will allow type conversions
1185+ // between incompatible types if the previous column has a default and the new column is dropping its default.
1186+ // It also must be dropped before an identity is added to the column, otherwise adding the identity errors
1187+ // with "a default already exists."
1188+ //
1189+ // To keep the code simpler, put dropping the default before updating the column identity AND dropping the default.
1190+ // There is an argument to drop the default after removing the not null constraint, since writes will continue to succeed
1191+ // on columns migrating from not-null and a default to nullable with no default; however, this would not work
1192+ // for the case where an identity is being added to the column.
1193+ if len (oldColumn .Default ) > 0 && len (newColumn .Default ) == 0 {
1194+ stmts = append (stmts , Statement {
1195+ DDL : fmt .Sprintf ("%s DROP DEFAULT" , alterColumnPrefix ),
1196+ Timeout : statementTimeoutDefault ,
1197+ LockTimeout : lockTimeoutDefault ,
1198+ })
1199+ }
1200+
11841201 updateIdentityStmts , err := csg .buildUpdateIdentityStatements (oldColumn , newColumn )
11851202 if err != nil {
11861203 return nil , fmt .Errorf ("building update identity statements: %w" , err )
@@ -1197,16 +1214,6 @@ func (csg *columnSQLVertexGenerator) Alter(diff columnDiff) ([]Statement, error)
11971214 })
11981215 }
11991216
1200- if len (oldColumn .Default ) > 0 && len (newColumn .Default ) == 0 {
1201- // Drop the default before type conversion. This will allow type conversions
1202- // between incompatible types if the previous column has a default and the new column is dropping its default
1203- stmts = append (stmts , Statement {
1204- DDL : fmt .Sprintf ("%s DROP DEFAULT" , alterColumnPrefix ),
1205- Timeout : statementTimeoutDefault ,
1206- LockTimeout : lockTimeoutDefault ,
1207- })
1208- }
1209-
12101217 if ! strings .EqualFold (oldColumn .Type , newColumn .Type ) ||
12111218 ! strings .EqualFold (oldColumn .Collation .GetFQEscapedName (), newColumn .Collation .GetFQEscapedName ()) {
12121219 stmts = append (stmts ,
0 commit comments