2019-03-21 17:07:09 +03:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2023-12-27 12:35:24 +03:00
|
|
|
"embed"
|
2021-04-12 14:03:10 +03:00
|
|
|
|
2023-12-27 12:35:24 +03:00
|
|
|
"github.com/golang-migrate/migrate/v4"
|
|
|
|
"github.com/golang-migrate/migrate/v4/database/postgres"
|
|
|
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
2019-03-21 17:07:09 +03:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2023-12-27 12:35:24 +03:00
|
|
|
//go:embed migrations/*.sql
|
|
|
|
var migrations embed.FS
|
|
|
|
|
2019-03-21 17:07:09 +03:00
|
|
|
type PostgresAccessor struct {
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
2023-12-27 12:35:24 +03:00
|
|
|
func (a *PostgresAccessor) Migrate() error {
|
|
|
|
driver, err := postgres.WithInstance(a.db, &postgres.Config{})
|
2019-03-21 17:07:09 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-04-12 14:03:10 +03:00
|
|
|
|
2023-12-27 12:35:24 +03:00
|
|
|
d, err := iofs.New(migrations, "migrations")
|
2021-04-12 14:03:10 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-12-27 12:35:24 +03:00
|
|
|
m, err := migrate.NewWithInstance("iofs", d, "postgres", driver)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = m.Up()
|
|
|
|
if err != nil && err != migrate.ErrNoChange {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
v, _, _ := m.Version()
|
|
|
|
logrus.WithFields(logrus.Fields{"version": v}).Info("DB Migrated")
|
2019-03-21 17:07:09 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|