From 000d79e1faf849e576e7ab440f7284351c6174c0 Mon Sep 17 00:00:00 2001 From: Andrew Farries Date: Thu, 18 Jan 2024 11:36:44 +0000 Subject: [PATCH] Test: set not null preserves `CHECK` constraints Ensure that altering a column to make it `NOT NULL` retains any check constraints that were defined on the column. --- pkg/migrations/op_set_notnull_test.go | 58 ++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/pkg/migrations/op_set_notnull_test.go b/pkg/migrations/op_set_notnull_test.go index d619386c..b8098924 100644 --- a/pkg/migrations/op_set_notnull_test.go +++ b/pkg/migrations/op_set_notnull_test.go @@ -301,7 +301,7 @@ func TestSetNotNull(t *testing.T) { }, }, { - name: "setting a nullable column to not null retains any default defined on the column", + name: "setting a column to not null retains any default defined on the column", migrations: []migrations.Migration{ { Name: "01_add_table", @@ -364,6 +364,62 @@ func TestSetNotNull(t *testing.T) { }, rows) }, }, + { + name: "setting a column to not null retains any check constraints 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, + Check: &migrations.CheckConstraint{ + Name: "name_length", + Constraint: "length(name) > 3", + }, + }, + }, + }, + }, + }, + { + 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) { + // Inserting a row that violates the check constraint should fail. + MustNotInsert(t, db, "public", "02_set_not_null", "users", map[string]string{ + "id": "1", + "name": "a", + }, testutils.CheckViolationErrorCode) + }, + afterRollback: func(t *testing.T, db *sql.DB) { + }, + afterComplete: func(t *testing.T, db *sql.DB) { + // Inserting a row that violates the check constraint should fail. + MustNotInsert(t, db, "public", "02_set_not_null", "users", map[string]string{ + "id": "2", + "name": "b", + }, testutils.CheckViolationErrorCode) + }, + }, }) }