-
Notifications
You must be signed in to change notification settings - Fork 26
/
databaseMigrations.go
53 lines (49 loc) · 1.01 KB
/
databaseMigrations.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
49
50
51
52
53
package main
import (
"database/sql"
"embed"
"fmt"
"io/fs"
"strings"
"github.com/lopezator/migrator"
)
//go:embed dbmigrations/*
var dbMigrations embed.FS
func (a *goBlog) migrateDb(db *sql.DB, logging bool) error {
var sqlMigrations []any
err := fs.WalkDir(dbMigrations, "dbmigrations", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.Type().IsDir() {
return err
}
mig := &migrator.Migration{}
mig.Name = strings.TrimSuffix(d.Name(), ".sql")
fd, fe := dbMigrations.ReadFile(path)
if fe != nil {
return fe
}
if len(fd) == 0 {
return nil
}
mig.Func = func(t *sql.Tx) error {
_, txe := t.Exec(string(fd))
return txe
}
sqlMigrations = append(sqlMigrations, mig)
return nil
})
if err != nil {
return err
}
m, err := migrator.New(
migrator.WithLogger(migrator.LoggerFunc(func(s string, i ...any) {
if logging {
a.info(fmt.Sprintf(s, i...))
}
})),
migrator.Migrations(sqlMigrations...),
)
if err != nil {
return err
}
return m.Migrate(db)
}