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 }