forked from saulmaldonado/agones-minecraft
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
63 lines (47 loc) · 1.05 KB
/
db.go
File metadata and controls
63 lines (47 loc) · 1.05 KB
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
package db
import (
"context"
"net"
"time"
"github.com/go-pg/pg/v10"
"go.uber.org/zap"
gormlogger "gorm.io/gorm/logger"
"moul.io/zapgorm2"
"agones-minecraft/config"
)
const (
DefaultThreshold time.Duration = time.Millisecond * 500
)
var db *pg.DB
func New() *pg.DB {
dbconfig := config.GetDBConfig()
return pg.Connect(&pg.Options{
Addr: net.JoinHostPort(dbconfig.Hostname, dbconfig.Port),
User: dbconfig.User,
Password: dbconfig.Password,
Database: dbconfig.Name,
})
}
func Init() {
logger := zapgorm2.New(zap.L())
logger.SlowThreshold = DefaultThreshold
if config.GetEnv() == config.Production {
logger.IgnoreRecordNotFoundError = true
} else {
logger.LogLevel = gormlogger.Info
}
pg := New()
if err := pg.Ping(context.Background()); err != nil {
zap.L().Fatal("error pinging database", zap.Error(err))
}
pg.AddQueryHook(NewLogger(zap.L()))
db = pg
}
func DB() *pg.DB {
return db
}
func Ping() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
return db.Ping(ctx)
}