-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
migrate.go
48 lines (39 loc) · 1.03 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
46
47
48
package migrate
import (
"context"
"embed"
"fmt"
"strings"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/mongodb"
"github.com/johejo/golang-migrate-extra/source/iofs"
"go.mongodb.org/mongo-driver/mongo"
"github.com/shortlink-org/shortlink/pkg/db"
)
// Migration - apply migration to db
func Migration(_ context.Context, store db.DB, fs embed.FS, tableName string) error {
client, ok := store.GetConn().(*mongo.Client)
if !ok {
return db.ErrGetConnection
}
driverMigrations, err := iofs.New(fs, "migrations")
if err != nil {
return err
}
driverDB, err := mongodb.WithInstance(client, &mongodb.Config{
DatabaseName: "shortlink",
MigrationsCollection: fmt.Sprintf("schema_migrations_%s", strings.ReplaceAll(tableName, "-", "_")),
})
if err != nil {
return err
}
m, err := migrate.NewWithInstance("iofs", driverMigrations, "mongodb", driverDB)
if err != nil {
return err
}
err = m.Up()
if err != nil && err.Error() != "no change" {
return err
}
return nil
}