-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
46 lines (36 loc) · 1.11 KB
/
db.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
package db
import (
"context"
"embed"
"github.com/cockroachdb/errors"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/sqlite3"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
const Memory = ":memory:?_foreign_keys=1"
//go:embed migrations/*.sql
var fs embed.FS
func NewDB(ctx context.Context, dataSourceName string) (*sqlx.DB, error) {
db, err := sqlx.ConnectContext(ctx, "sqlite3", dataSourceName)
if err != nil {
return nil, errors.Wrap(err, "db: connect to db")
}
srcDriver, err := iofs.New(fs, "migrations")
if err != nil {
return nil, errors.Wrap(err, "db: setup source driver for migration")
}
dbDriver, err := sqlite3.WithInstance(db.DB, &sqlite3.Config{})
if err != nil {
return nil, errors.Wrap(err, "db: setup database driver for migration")
}
m, err := migrate.NewWithInstance("iofs", srcDriver, "", dbDriver)
if err != nil {
return nil, errors.Wrap(err, "db: setup migration")
}
if err := m.Up(); err != nil {
return db, errors.Wrap(err, "db: run migration")
}
return db, err
}