Skip to content

Commit

Permalink
Add test: check column DEFAULTs preserved on set NOT NULL (#235)
Browse files Browse the repository at this point in the history
Add a check to ensure that any `DEFAULT` on a column that is set to `NOT
NULL` is preserved by the set `NOT NULL` operation.

This already works as a consequence of earlier PRs for
#227 but it's worth explicitly
testing this behaviour.
  • Loading branch information
andrew-farries authored Jan 16, 2024
1 parent d803689 commit dde27eb
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions pkg/migrations/op_set_notnull_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
},
},
})
}

Expand Down

0 comments on commit dde27eb

Please sign in to comment.