diff --git a/cmd/migrate/migrate.go b/cmd/migrate/migrate.go index f930e9c..a7fb720 100644 --- a/cmd/migrate/migrate.go +++ b/cmd/migrate/migrate.go @@ -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 { @@ -59,9 +81,3 @@ func dir(action string) string { return "migrations" } - -func checkErr(err error) { - if err != nil { - panic(err) - } -}