-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrate.go
42 lines (34 loc) · 976 Bytes
/
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
package main
import (
"database/sql"
"embed"
"fmt"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/sqlite3"
"github.com/golang-migrate/migrate/v4/source/iofs"
"log"
)
//go:embed migrations
var migrations embed.FS
func CreateMigratedDb(dbPath string) (*sql.DB, error) {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, fmt.Errorf("failed to open database: %w", err)
}
driver, err := sqlite3.WithInstance(db, &sqlite3.Config{})
if err != nil {
return nil, fmt.Errorf("failed to initialize migration driver: %w", err)
}
source, err := iofs.New(migrations, "migrations")
if err != nil {
return nil, fmt.Errorf("failed to initialize migration source: %w", err)
}
m, err := migrate.NewWithInstance("iofs", source, "postgres", driver)
if err != nil {
return nil, fmt.Errorf("failed to initialize migrations: %w", err)
}
if err := m.Up(); err != nil {
log.Println(err)
}
return db, nil
}