-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
59 lines (50 loc) · 1.01 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
package db
import (
"sync"
"github.com/caesium-cloud/caesium/internal/models"
"github.com/caesium-cloud/caesium/pkg/dqlite"
"github.com/caesium-cloud/caesium/pkg/env"
"github.com/caesium-cloud/caesium/pkg/log"
_ "github.com/jackc/pgx/v4"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var (
once sync.Once
gdb *gorm.DB
err error
)
func Connection() *gorm.DB {
once.Do(func() {
dbType := env.Variables().DatabaseType
log.Info("establishing db connection", "type", dbType)
switch dbType {
case "postgres":
gdb, err = gorm.Open(
postgres.Open(env.Variables().DatabaseDSN),
&gorm.Config{},
)
case "internal":
fallthrough
case dqlite.DriverName:
fallthrough
default:
gdb, err = gorm.Open(
dqlite.Open(""),
&gorm.Config{},
)
}
if err != nil {
log.Fatal("failed to connect to database", "error", err)
}
})
return gdb
}
func Migrate() (err error) {
for _, model := range models.All {
if err = Connection().AutoMigrate(model); err != nil {
return
}
}
return
}