This adds the ability to define hooks that will run prior to a schema migration. The hooks should only be used when a migration would fail due to data being in an invalid state, likely due to a bug in the previous schema definition. For example if a column was missing a constraint, and a new migration is attempting to add the constraint, there might already be values that violate the new constraint. In such cases, we would want the user to make a decision to address the data, and need to provide them with details about what data is problematic in case they want to manually address the problem. To help the user, if there is a sane way to address the data, we should provide an option to automatically "repair" the data, allowing the migration to continue. However, this still should be an explicit opt-in from the user, and we need to clearly describe what the repair option would do to the user so they understand the consequences of opting in. To accomplish this each migration can be provided a hook that contains a CheckFunc, RepairFunc, and RepairDescription. These functions must operate at the point-in-time of the migration immediately preceding the current migration, as as such they should not use and domain packages or repositories, instead they should use direct sql with the sql library. The description is used to explain what the RepairFunc will do. Hooks should be defined in `internal/db/schema/migrations/oss/oss.go` and registered with the schema edition. See the example in `internal/db/schema/manager_example_test.go` for more details.
41 lines
1018 B
Go
41 lines
1018 B
Go
package schema
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/hashicorp/boundary/internal/db/common"
|
|
"github.com/hashicorp/boundary/internal/errors"
|
|
)
|
|
|
|
// MigrateStore executes the migrations needed to initialize the store. It
|
|
// returns true if migrations actually ran; false if the database is already current
|
|
// or if there was an error. Supports the WithEditions(...) option.
|
|
func MigrateStore(ctx context.Context, dialect Dialect, url string, opt ...Option) (bool, error) {
|
|
const op = "schema.MigrateStore"
|
|
|
|
d, err := common.SqlOpen(dialect.String(), url)
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
sMan, err := NewManager(ctx, dialect, d, opt...)
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
st, err := sMan.CurrentState(ctx)
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
if st.Initialized && st.MigrationsApplied() {
|
|
return false, nil
|
|
}
|
|
|
|
if _, err := sMan.ApplyMigrations(ctx); err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
return true, nil
|
|
}
|