Files
softplayer-backend/cmd/migrate.go
Nikolai Rodionov 99f9bb462f
All checks were successful
ci/woodpecker/push/build Pipeline was successful
A bit of refactoring and updates
Signed-off-by: Nikolai Rodionov <iam@allanger.xyz>
2026-05-11 11:57:17 +02:00

60 lines
1.5 KiB
Go

package cmd
import (
"context"
"database/sql"
"errors"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/logger"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
// Migrate the database to the latest state
type Migrate struct {
// Postgres connection string
DBConnectionString string `env:"SOFTPLAYER_DB_CONNECTION_STRING"`
// Path to the directory with migrations
MigrationsPath string `env:"SOFTPLAYER_DB_MIGRATIOON_PATH" default:"file://migrations"`
}
func (cmd *Migrate) Run(ctx context.Context) error {
log := logger.FromContext(ctx)
log.Info("Starting a database migration driver")
db, err := sql.Open("postgres", cmd.DBConnectionString)
if err != nil {
log.Error(err, "Couldn't start a database driver")
return err
}
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
log.Error(err, "Couldn't start a database migration driver")
return err
}
log.Info("Preparing database migrations")
m, err := migrate.NewWithDatabaseInstance(
cmd.MigrationsPath,
"postgres", driver)
if err != nil {
log.Error(err, "Couldn't perform database migrations")
return err
}
log.Info("Starting database migrations")
err = m.Up()
if err != nil {
if errors.Is(err, migrate.ErrNoChange) {
log.Info("Database is already up-to-date")
} else {
log.Error(err, "Couldn't migrate the database")
return err
}
}
return nil
}