github.com/goravel/framework@v1.13.9/database/console/migrate_rollback_command.go (about) 1 package console 2 3 import ( 4 "strconv" 5 6 _ "github.com/go-sql-driver/mysql" 7 "github.com/golang-migrate/migrate/v4" 8 _ "github.com/golang-migrate/migrate/v4/source/file" 9 "github.com/gookit/color" 10 11 "github.com/goravel/framework/contracts/config" 12 "github.com/goravel/framework/contracts/console" 13 "github.com/goravel/framework/contracts/console/command" 14 ) 15 16 type MigrateRollbackCommand struct { 17 config config.Config 18 } 19 20 func NewMigrateRollbackCommand(config config.Config) *MigrateRollbackCommand { 21 return &MigrateRollbackCommand{ 22 config: config, 23 } 24 } 25 26 // Signature The name and signature of the console command. 27 func (receiver *MigrateRollbackCommand) Signature() string { 28 return "migrate:rollback" 29 } 30 31 // Description The console command description. 32 func (receiver *MigrateRollbackCommand) Description() string { 33 return "Rollback the database migrations" 34 } 35 36 // Extend The console command extend. 37 func (receiver *MigrateRollbackCommand) Extend() command.Extend { 38 return command.Extend{ 39 Category: "migrate", 40 Flags: []command.Flag{ 41 &command.StringFlag{ 42 Name: "step", 43 Value: "1", 44 Usage: "rollback steps", 45 }, 46 }, 47 } 48 } 49 50 // Handle Execute the console command. 51 func (receiver *MigrateRollbackCommand) Handle(ctx console.Context) error { 52 m, err := getMigrate(receiver.config) 53 if err != nil { 54 return err 55 } 56 if m == nil { 57 color.Yellowln("Please fill database config first") 58 59 return nil 60 } 61 62 stepString := "-" + ctx.Option("step") 63 step, err := strconv.Atoi(stepString) 64 if err != nil { 65 color.Redln("Migration rollback failed: invalid step", ctx.Option("step")) 66 67 return nil 68 } 69 70 if err = m.Steps(step); err != nil && err != migrate.ErrNoChange && err != migrate.ErrNilVersion { 71 switch err.(type) { 72 case migrate.ErrShortLimit: 73 default: 74 color.Redln("Migration rollback failed:", err.Error()) 75 76 return nil 77 } 78 } 79 80 color.Greenln("Migration rollback success") 81 82 return nil 83 }