diff --git a/pkg/migrations/op_set_notnull_test.go b/pkg/migrations/op_set_notnull_test.go index eec21abc..0f37880f 100644 --- a/pkg/migrations/op_set_notnull_test.go +++ b/pkg/migrations/op_set_notnull_test.go @@ -299,6 +299,70 @@ func TestSetNotNull(t *testing.T) { ConstraintMustExist(t, db, "public", "employees", "fk_employee_department") }, }, + { + name: "setting a nullable column to not null retains any default defined on the column", + migrations: []migrations.Migration{ + { + Name: "01_add_table", + Operations: migrations.Operations{ + &migrations.OpCreateTable{ + Name: "users", + Columns: []migrations.Column{ + { + Name: "id", + Type: "integer", + Pk: true, + }, + { + Name: "name", + Type: "text", + Nullable: true, + Default: ptr("'anonymous'"), + }, + }, + }, + }, + }, + { + Name: "02_set_not_null", + Operations: migrations.Operations{ + &migrations.OpAlterColumn{ + Table: "users", + Column: "name", + Nullable: ptr(false), + Up: "(SELECT CASE WHEN name IS NULL THEN 'anonymous' ELSE name END)", + }, + }, + }, + }, + afterStart: func(t *testing.T, db *sql.DB) { + // A row can be inserted into the new version of the table. + MustInsert(t, db, "public", "02_set_not_null", "users", map[string]string{ + "id": "1", + }) + + // The newly inserted row respects the default value of the column. + rows := MustSelect(t, db, "public", "02_set_not_null", "users") + assert.Equal(t, []map[string]any{ + {"id": 1, "name": "anonymous"}, + }, rows) + }, + afterRollback: func(t *testing.T, db *sql.DB) { + }, + afterComplete: func(t *testing.T, db *sql.DB) { + // A row can be inserted into the new version of the table. + MustInsert(t, db, "public", "02_set_not_null", "users", map[string]string{ + "id": "2", + }) + + // The newly inserted row respects the default value of the column. + rows := MustSelect(t, db, "public", "02_set_not_null", "users") + assert.Equal(t, []map[string]any{ + {"id": 1, "name": "anonymous"}, + {"id": 2, "name": "anonymous"}, + }, rows) + }, + }, }) }