-
Notifications
You must be signed in to change notification settings - Fork 1
/
migrate.go
45 lines (41 loc) · 1.01 KB
/
migrate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func AutoMigrate(_ context.Context, dbConn *sql.DB, up bool) error {
//nolint: contextcheck
driver, err := postgres.WithInstance(dbConn, &postgres.Config{})
if err != nil {
return err
}
viper.SetDefault("MIGRATIONS_DIR", "file://./internal/db/migrations")
viper.AutomaticEnv()
dir := viper.GetString("MIGRATIONS_DIR")
log.Infof("Migrations dir: %s", dir)
m, err := migrate.NewWithDatabaseInstance(
dir,
"postgres", driver)
if err != nil {
return fmt.Errorf("failed to initialize migrator: %w", err)
}
action := m.Down
if up {
action = m.Up
}
if err := action(); err != nil {
if !errors.Is(err, migrate.ErrNoChange) {
return fmt.Errorf("failed to migrate: %w", err)
}
} else {
log.Info("db: migrated")
}
return nil
}