generated from dalmarcogd/bpl-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
71 lines (62 loc) · 1.31 KB
/
database.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
package database
import (
"context"
"github.com/dalmarcogd/gbpl-go/internal/services"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"time"
)
type (
ServiceImpl struct {
serviceManager services.ServiceManager
ctx context.Context
client *gorm.DB
dsn string
}
)
func New() *ServiceImpl {
return &ServiceImpl{}
}
func (s *ServiceImpl) WithDsn(dsn string) *ServiceImpl {
s.dsn = dsn
return s
}
func (s *ServiceImpl) Init(ctx context.Context) error {
s.ctx = ctx
s.dsn = s.ServiceManager().Environment().DatabaseDsn()
c, err := gorm.Open(postgres.Open(s.dsn), &gorm.Config{
PrepareStmt: true,
})
if err != nil {
return err
}
s.client = c
db, err := s.client.DB()
if err != nil {
return err
}
if err := db.PingContext(s.ctx); err != nil {
return err
}
db.SetMaxIdleConns(1)
db.SetMaxOpenConns(10)
db.SetConnMaxLifetime(time.Hour)
return nil
}
func (s *ServiceImpl) Close() error {
db, err := s.client.DB()
if err != nil {
return err
}
return db.Close()
}
func (s *ServiceImpl) WithServiceManager(c services.ServiceManager) services.Database {
s.serviceManager = c
return s
}
func (s *ServiceImpl) ServiceManager() services.ServiceManager {
return s.serviceManager
}
func (s *ServiceImpl) DB(ctx context.Context) *gorm.DB {
return s.client.WithContext(ctx)
}