-
Notifications
You must be signed in to change notification settings - Fork 0
/
localDB.go
51 lines (41 loc) · 1011 Bytes
/
localDB.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
package localDB
import (
"database/sql"
"errors"
"fmt"
"log"
"sync"
"github.com/golang-migrate/migrate"
"github.com/golang-migrate/migrate/database/sqlite3"
_ "github.com/golang-migrate/migrate/source/file"
_ "github.com/mattn/go-sqlite3"
)
type DB struct {
sync.Mutex
db *sql.DB
}
func New(filePath string) *DB {
db, err := sql.Open("sqlite3", filePath)
if err != nil {
log.Fatal("sql.Open error: ", err)
}
return &DB{sync.Mutex{}, db}
}
func (db *DB) Close() {
db.db.Close()
}
func (db *DB) Migrate(migrations string) error {
driver, err := sqlite3.WithInstance(db.db, &sqlite3.Config{})
if err != nil {
return fmt.Errorf("sqlite3.WithInstance error: %w", err)
}
m, err := migrate.NewWithDatabaseInstance("file://"+migrations, "sqlite3", driver)
if err != nil {
return fmt.Errorf("migrate.NewWithDatabaseInstance error: %w", err)
}
err = m.Up()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return fmt.Errorf("migrate.Up() error: %w", err)
}
return nil
}