serve: run migrations on startup
Some checks failed
/ push (push) Has been cancelled

This commit is contained in:
Tigor Hutasuhut 2024-05-23 22:31:09 +07:00
parent cd1959d824
commit 32fea20476
2 changed files with 28 additions and 0 deletions

View file

@ -28,6 +28,11 @@ var serveCmd = &cobra.Command{
} }
defer tele.Close() defer tele.Close()
if err := db.RunMigrations(cfg); err != nil {
log.New(cmd.Context()).Err(err).Error("failed to run migrations")
os.Exit(1)
}
database, err := db.NewComfy(cfg) database, err := db.NewComfy(cfg)
if err != nil { if err != nil {
log.New(cmd.Context()).Err(err).Error("failed to open database") log.New(cmd.Context()).Err(err).Error("failed to open database")

View file

@ -69,3 +69,26 @@ func ApplyLogger(cfg *config.Config, db *sql.DB) *sql.DB {
sqldblogger.WithSQLQueryAsMessage(true), sqldblogger.WithSQLQueryAsMessage(true),
) )
} }
func RunMigrations(cfg *config.Config) error {
if cfg.Bool("db.automigrate") {
driver := cfg.String("db.driver")
dsn := cfg.String("db.string")
db, err := sql.Open(driver, dsn)
if err != nil {
return errs.Wrapw(err, "migration: failed to open database", "driver", driver, "db.string", dsn)
}
defer db.Close()
goose.SetLogger(goose.NopLogger())
goose.SetBaseFS(Migrations)
if err := goose.SetDialect(driver); err != nil {
return errs.Wrapw(err, "failed to set goose dialect", "dialect", driver, "dsn", dsn)
}
if err := goose.Up(db, "db/migrations"); err != nil {
return errs.Wrapw(err, "failed to migrate database", "dialect", driver, "dsn", dsn)
}
}
return nil
}