/
sql.go
91 lines (69 loc) · 1.98 KB
/
sql.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
package db
import (
"context"
"sync"
"github.com/scrapnode/kanthor/database"
"github.com/scrapnode/kanthor/logging"
"gorm.io/gorm"
)
func NewSql(logger logging.Logger, db database.Database) Database {
logger = logger.With("repositories", "db.sql")
return &sql{logger: logger, db: db}
}
type sql struct {
logger logging.Logger
db database.Database
workspace *SqlWorkspace
workspaceCredentials *SqlWorkspaceCredentials
application *SqlApplication
endpoint *SqlEndpoint
endpointRule *SqlEndpointRule
mu sync.Mutex
}
func (repo *sql) Transaction(ctx context.Context, handler func(txctx context.Context) (interface{}, error)) (res interface{}, err error) {
err = repo.db.Client().(*gorm.DB).Transaction(func(tx *gorm.DB) error {
res, err = handler(context.WithValue(ctx, database.CtxTransaction, tx))
return err
})
return
}
func (repo *sql) Workspace() Workspace {
repo.mu.Lock()
defer repo.mu.Unlock()
if repo.workspace == nil {
repo.workspace = &SqlWorkspace{client: repo.db.Client().(*gorm.DB)}
}
return repo.workspace
}
func (repo *sql) WorkspaceCredentials() WorkspaceCredentials {
repo.mu.Lock()
defer repo.mu.Unlock()
if repo.workspaceCredentials == nil {
repo.workspaceCredentials = &SqlWorkspaceCredentials{client: repo.db.Client().(*gorm.DB)}
}
return repo.workspaceCredentials
}
func (repo *sql) Application() Application {
repo.mu.Lock()
defer repo.mu.Unlock()
if repo.application == nil {
repo.application = &SqlApplication{client: repo.db.Client().(*gorm.DB)}
}
return repo.application
}
func (repo *sql) Endpoint() Endpoint {
repo.mu.Lock()
defer repo.mu.Unlock()
if repo.endpoint == nil {
repo.endpoint = &SqlEndpoint{client: repo.db.Client().(*gorm.DB)}
}
return repo.endpoint
}
func (repo *sql) EndpointRule() EndpointRule {
repo.mu.Lock()
defer repo.mu.Unlock()
if repo.endpointRule == nil {
repo.endpointRule = &SqlEndpointRule{client: repo.db.Client().(*gorm.DB)}
}
return repo.endpointRule
}