Add extra validation for the set NOT NULL op (#69)

Ensure that the column is not already marked as `NOT NULL`.
This commit is contained in:
Andrew Farries 2023-08-29 15:04:15 +01:00 committed by GitHub
parent 4983a6bd48
commit 2702343334
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 61 additions and 1 deletions

View File

@ -36,6 +36,15 @@ func (e ColumnDoesNotExistError) Error() string {
return fmt.Sprintf("column %q does not exist on table %q", e.Name, e.Table)
}
type ColumnIsNotNullableError struct {
Table string
Name string
}
func (e ColumnIsNotNullableError) Error() string {
return fmt.Sprintf("column %q on table %q is NOT NULL", e.Name, e.Table)
}
type IndexAlreadyExistsError struct {
Name string
}

View File

@ -171,10 +171,15 @@ func (o *OpSetNotNull) Validate(ctx context.Context, s *schema.Schema) error {
return TableDoesNotExistError{Name: o.Table}
}
if table.GetColumn(o.Column) == nil {
column := table.GetColumn(o.Column)
if column == nil {
return ColumnDoesNotExistError{Table: o.Table, Name: o.Column}
}
if !column.Nullable {
return ColumnIsNotNullableError{Table: o.Table, Name: o.Column}
}
if o.Up == nil {
return FieldRequiredError{Name: "up"}
}

View File

@ -239,5 +239,51 @@ func TestSetNotNullValidation(t *testing.T) {
},
wantStartErr: migrations.ColumnDoesNotExistError{Table: "reviews", Name: "doesntexist"},
},
{
name: "column is nullable",
migrations: []migrations.Migration{
{
Name: "01_add_table",
Operations: migrations.Operations{
&migrations.OpCreateTable{
Name: "reviews",
Columns: []migrations.Column{
{
Name: "id",
Type: "serial",
PrimaryKey: true,
},
{
Name: "username",
Type: "text",
Nullable: false,
},
{
Name: "product",
Type: "text",
Nullable: false,
},
{
Name: "review",
Type: "text",
Nullable: false,
},
},
},
},
},
{
Name: "02_set_not_null",
Operations: migrations.Operations{
&migrations.OpSetNotNull{
Table: "reviews",
Column: "review",
Up: ptr("product || ' is good'"),
},
},
},
},
wantStartErr: migrations.ColumnIsNotNullableError{Table: "reviews", Name: "review"},
},
})
}