Files
softplayer-backend/cmd/migrate.go
Nikolai Rodionov 8c5f88cb46
All checks were successful
ci/woodpecker/push/build Pipeline was successful
Add linter and a little bit more tests
Signed-off-by: Nikolai Rodionov <iam@allanger.xyz>
2026-05-18 11:02:10 +02:00

62 lines
1.6 KiB
Go

package cmd
import (
"context"
"errors"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/logger"
postgres_helper "gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/postgres"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/jackc/pgx/v5/stdlib"
)
// 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 := postgres_helper.Open(ctx, 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
}