Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: migrate/rollback to the target version #808

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion migrate/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ type MigrationFile struct {
//------------------------------------------------------------------------------

type migrationConfig struct {
nop bool
nop bool
targetVersion string
}

func newMigrationConfig(opts []MigrationOption) *migrationConfig {
Expand All @@ -276,6 +277,12 @@ func WithNopMigration() MigrationOption {
}
}

func WithTargetVersion(v string) MigrationOption {
return func(cfg *migrationConfig) {
cfg.targetVersion = v
}
}

//------------------------------------------------------------------------------

func sortAsc(ms MigrationSlice) {
Expand Down
34 changes: 34 additions & 0 deletions migrate/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,19 @@ func (m *Migrator) Migrate(ctx context.Context, opts ...MigrationOption) (*Migra
}
migrations = migrations.Unapplied()

if cfg.targetVersion != "" {
versionValid := false
for _, m := range migrations {
if m.Name == cfg.targetVersion {
versionValid = true
break
}
}
if !versionValid {
return nil, fmt.Errorf("version not found")
}
}

group := new(MigrationGroup)
if len(migrations) == 0 {
return group, nil
Expand Down Expand Up @@ -171,6 +184,10 @@ func (m *Migrator) Migrate(ctx context.Context, opts ...MigrationOption) (*Migra
return group, err
}
}

if cfg.targetVersion != "" && cfg.targetVersion == migration.Name {
return group, nil
}
}

return group, nil
Expand All @@ -188,6 +205,19 @@ func (m *Migrator) Rollback(ctx context.Context, opts ...MigrationOption) (*Migr
return nil, err
}

if cfg.targetVersion != "" {
versionValid := false
for _, m := range migrations {
if m.Name == cfg.targetVersion {
versionValid = true
break
}
}
if !versionValid {
return nil, fmt.Errorf("version not found")
}
}

lastGroup := migrations.LastGroup()

for i := len(lastGroup.Migrations) - 1; i >= 0; i-- {
Expand All @@ -210,6 +240,10 @@ func (m *Migrator) Rollback(ctx context.Context, opts ...MigrationOption) (*Migr
return lastGroup, err
}
}

if cfg.targetVersion != "" && cfg.targetVersion == migration.Name {
return lastGroup, nil
}
}

return lastGroup, nil
Expand Down