-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
108 lines (83 loc) · 2.06 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package medialocker
import (
"fmt"
"sync"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/smook1980/medialocker/models"
)
const (
DB_URI_TEMPLATE = "%s.db"
// DB_URI_TEMPLATE = "file:%s.db?mode=rwc"
)
type DB interface {
VideoRepository() interface{}
}
type DBConnection struct {
*gorm.DB
}
func (db *DBConnection) Ping() error {
return db.DB.DB().Ping()
}
func (db *DBConnection) VideoRepository() interface{} {
return nil
}
type Closer func() error
type DBConnectionFactory func() (*DBConnection, error)
func NewDBConnectionFactory(log *Logger, c Config) (DBConnectionFactory, Closer) {
var connect sync.Once
var dbLock sync.Mutex
var db *gorm.DB
var dbUrl string
logSQL := c.LogSQL
if c.MemDB {
dbUrl = ":memory:"
} else {
dbUrl = fmt.Sprintf(DB_URI_TEMPLATE, c.DbPath)
}
logger := log.WithField("db", dbUrl)
logger = logger.WithField("module", "DBConnectionFactory")
logger.Debug("Initializing DB Connection Factory...")
closer := func() error {
var close sync.Once
var err error
close.Do(func() {
dbLock.Lock()
defer dbLock.Unlock()
if db != nil {
err = db.Close()
}
logger.Debug("DB connection closed!")
})
return err
}
factory := func() (*DBConnection, error) {
var err error
connect.Do(func() {
dbLock.Lock()
defer dbLock.Unlock()
logger.Debug("Connecting db...")
db, err = gorm.Open("sqlite3", dbUrl)
db.LogMode(logSQL)
logger.Debug("Migrating Schema...")
models.SchemaMigrate(db)
logger.Debug("DB Opened...")
})
if err != nil {
logger.Panicf("Failed to establish DB connection, this is a fatal error! %s", err)
}
dbLock.Lock()
defer dbLock.Unlock()
err = db.DB().Ping()
if err != nil {
logger.Debugf("Unable to ping connection, is it dead? Attempting to reopen! %s", err)
db.Close()
db, err = gorm.Open("sqlite3", fmt.Sprintf(DB_URI_TEMPLATE, c.DbPath))
if err != nil {
logger.Panicf("Failed to establish DB connection, this is a fatal error! %s", err)
}
}
return &DBConnection{DB: db}, nil
}
return factory, closer
}