Skip to content

Commit

Permalink
Update schema during add column validation (#457)
Browse files Browse the repository at this point in the history
Update the schema during `add_column` operation validation so that
validation of subsequent operations in the same migration can see the
new column.

This means that migrations that add a new column and then perform some
other operation, like adding an index, on that column can be validated
because the new column is visible to the `create_index` operation during
it's validation phase.

This means that the following migration is now able to validate:

```json
{
  "name": "43_multiple_ops",
  "operations": [
    {
      "add_column": {
        "table": "players",
        "column": {
          "name": "rating",
          "type": "integer",
          "comment": "hello world",
          "check": {
            "name": "rating_check",
            "constraint": "rating > 0 AND rating < 100"
          },
          "nullable": false
        }
      }
    },
    {
      "create_index": {
        "name": "idx_player_rating",
        "table": "players",
        "columns": [
          "rating"
        ]
      }
    }
  ]
}
```

Previously, the new column would not have been visible to the
`create_index` operation and its validation would have failed.

This PR does for the `add_column` operation what #455 did for the
`create_table` operation.

Part of #239
andrew-farries authored Nov 8, 2024
1 parent d656387 commit 416fb7a
Showing 2 changed files with 7 additions and 2 deletions.
6 changes: 6 additions & 0 deletions pkg/migrations/op_add_column.go
Original file line number Diff line number Diff line change
@@ -184,6 +184,12 @@ func (o *OpAddColumn) Validate(ctx context.Context, s *schema.Schema) error {
return errors.New("adding primary key columns is not supported")
}

// Update the schema to ensure that the new column is visible to validation of
// subsequent operations.
table.AddColumn(o.Column.Name, schema.Column{
Name: TemporaryName(o.Column.Name),
})

return nil
}

3 changes: 1 addition & 2 deletions pkg/migrations/op_create_index_test.go
Original file line number Diff line number Diff line change
@@ -9,7 +9,6 @@ import (
"testing"

"github.com/xataio/pgroll/pkg/migrations"
"github.com/xataio/pgroll/pkg/roll"
)

func TestCreateIndex(t *testing.T) {
@@ -417,5 +416,5 @@ func TestCreateIndexOnObjectsCreatedInSameMigration(t *testing.T) {
IndexMustExist(t, db, schema, "users", "idx_users_age")
},
},
}, roll.WithSkipValidation(true)) // TODO: Remove once these migrations pass validation
})
}

0 comments on commit 416fb7a

Please sign in to comment.