Skip to content

Commit

Permalink
refactor: migration cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
joaofnds committed Nov 21, 2024
1 parent 1a5e68d commit bec4139
Showing 1 changed file with 38 additions and 22 deletions.
60 changes: 38 additions & 22 deletions cmd/migrate/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,34 +22,56 @@ var migrations embed.FS
func main() {
if len(os.Args) < 2 {
fmt.Println(`usage:
go run cmd/migrate/migrate.go up
go run cmd/migrate/migrate.go down
go run cmd/migrate/migrate.go down-to 20170506082527
go run cmd/migrate/migrate.go status
go run cmd/migrate/migrate.go redo
go run cmd/migrate/migrate.go up
go run cmd/migrate/migrate.go down
go run cmd/migrate/migrate.go down-to 20170506082527
go run cmd/migrate/migrate.go status
go run cmd/migrate/migrate.go redo
go run cmd/migrate/migrate.go create`)
os.Exit(1)
}

ctx := context.Background()

db, dbErr := dbInstance(ctx)
if dbErr != nil {
fmt.Println(dbErr)
os.Exit(1)
}

goose.SetBaseFS(migrations)

action, args := os.Args[1], os.Args[2:]
gooseErr := goose.RunContext(ctx, action, db, dir(action), args...)
if gooseErr != nil {
fmt.Println(strings.ReplaceAll(gooseErr.Error(), `\n`, "\n"))
os.Exit(1)
}
}

func dbInstance(ctx context.Context) (*sql.DB, error) {
var db *sql.DB

app := fx.New(
logger.NopLoggerProvider,
config.Module,
postgres.Module,
fx.Invoke(func(db *sql.DB, config postgres.Config) error {
goose.SetBaseFS(migrations)
action, args := os.Args[1], os.Args[2:]
err := goose.RunContext(ctx, action, db, dir(action), args...)
if err != nil {
fmt.Println(strings.ReplaceAll(err.Error(), `\n`, "\n"))
}
return err
}),
fx.Populate(&db),
)

defer func() { checkErr(app.Stop(ctx)) }()
checkErr(app.Start(ctx))
if err := app.Err(); err != nil {
return nil, fmt.Errorf("app.Err: %w", err)
}

if err := app.Stop(ctx); err != nil {
return nil, fmt.Errorf("app.Stop: %w", err)
}

if db == nil {
return nil, fmt.Errorf("db is nil")
}

return db, nil
}

func dir(action string) string {
Expand All @@ -59,9 +81,3 @@ func dir(action string) string {

return "migrations"
}

func checkErr(err error) {
if err != nil {
panic(err)
}
}

0 comments on commit bec4139

Please sign in to comment.