/
datastore.go
221 lines (181 loc) · 5.11 KB
/
datastore.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package frame
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"gocloud.dev/server/health/sqlhealth"
"gorm.io/datatypes"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
"math/rand"
"strconv"
"strings"
)
type store struct {
writeDatabase []*gorm.DB
readDatabase []*gorm.DB
}
func tenantPartition(ctx context.Context) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
authClaim := ClaimsFromContext(ctx)
if authClaim != nil &&
authClaim.TenantId() != "" &&
authClaim.PartitionId() != "" &&
!authClaim.isSystem() {
return db.Where("tenant_id = ? AND partition_id = ?", authClaim.TenantId(), authClaim.PartitionId())
}
return db
}
}
// DBPropertiesToMap converts the supplied db json content into a golang map
func DBPropertiesToMap(props datatypes.JSONMap) map[string]string {
if props == nil {
return make(map[string]string, len(props))
}
payload := make(map[string]string, len(props))
for k, val := range props {
switch v := val.(type) {
case nil:
payload[k] = ""
case string:
payload[k] = v
case bool:
payload[k] = strconv.FormatBool(v)
case int, int64, int32, int16, int8:
payload[k] = strconv.FormatInt(int64(val.(int)), 10)
case float32, float64:
payload[k] = strconv.FormatFloat(val.(float64), 'g', -1, 64)
default:
marVal, err1 := json.Marshal(val)
if err1 != nil {
payload[k] = fmt.Sprintf("%v", val)
continue
}
payload[k] = string(marVal)
}
}
return payload
}
// DBPropertiesFromMap converts a map into a JSONMap object
func DBPropertiesFromMap(propsMap map[string]string) datatypes.JSONMap {
jsonMap := make(datatypes.JSONMap)
if propsMap == nil {
return jsonMap
}
for k, val := range propsMap {
jsonMap[k] = val
if !strings.HasPrefix(val, "{") && !strings.HasPrefix(val, "[") {
continue
}
var prop any
// Determine if the JSON is an object or an array and unmarshal accordingly
if err := json.Unmarshal([]byte(val), &prop); err != nil {
continue
}
jsonMap[k] = prop
}
return jsonMap
}
// DBErrorIsRecordNotFound validate if supplied error is because of record missing in DB
func DBErrorIsRecordNotFound(err error) bool {
return errors.Is(err, gorm.ErrRecordNotFound)
}
// DB obtains an already instantiated db connection with the option
// to specify if you want write or read only db connection
func (s *Service) DB(ctx context.Context, readOnly bool) *gorm.DB {
var db *gorm.DB
if readOnly {
replicaCount := len(s.dataStore.readDatabase)
if replicaCount > 0 {
randomIndex := 0
if replicaCount > 1 {
randomIndex = rand.Intn(replicaCount)
}
db = s.dataStore.readDatabase[randomIndex]
}
}
if db == nil {
writeCount := len(s.dataStore.writeDatabase)
if writeCount == 0 {
log.Printf("DB -- attempting use a database when none is setup")
return nil
}
randomIndex := 0
if writeCount > 1 {
randomIndex = rand.Intn(writeCount)
}
db = s.dataStore.writeDatabase[randomIndex]
}
partitionedDb := db.WithContext(ctx).Scopes(tenantPartition(ctx))
config, ok := s.Config().(ConfigurationLogLevel)
if ok && config.LoggingLevelIsDebug() {
return partitionedDb.Debug()
}
return partitionedDb
}
// DatastoreCon Option method to store a connection that will be utilized when connecting to the database
func DatastoreCon(postgresqlConnection string, readOnly bool) Option {
return func(s *Service) {
if s.dataStore == nil {
s.dataStore = &store{
writeDatabase: []*gorm.DB{},
readDatabase: []*gorm.DB{},
}
}
if s.dataStore.writeDatabase == nil {
s.dataStore.writeDatabase = []*gorm.DB{}
}
if s.dataStore.readDatabase == nil {
s.dataStore.readDatabase = []*gorm.DB{}
}
config, err := pgx.ParseConfig(postgresqlConnection)
if err != nil {
log.Printf("Datastore -- problem parsing database connection : %s", err)
}
db := stdlib.OpenDB(*config)
gormDB, _ := gorm.Open(
postgres.New(postgres.Config{Conn: db, PreferSimpleProtocol: true}),
&gorm.Config{SkipDefaultTransaction: true},
)
//_ = gormDB.Use(tracing.NewPlugin())
s.AddCleanupMethod(func(ctx context.Context) {
_ = db.Close()
})
if readOnly {
s.dataStore.readDatabase = append(s.dataStore.readDatabase, gormDB)
} else {
s.dataStore.writeDatabase = append(s.dataStore.writeDatabase, gormDB)
}
addSQLHealthChecker(s, db)
}
}
func Datastore(ctx context.Context) Option {
return func(s *Service) {
config, ok := s.Config().(ConfigurationDatabase)
if !ok {
s.L().Warn("configuration object not of type : ConfigurationDatabase")
return
}
primaryDatabase := DatastoreCon(config.GetDatabasePrimaryHostURL(), false)
primaryDatabase(s)
replicaURL := config.GetDatabaseReplicaHostURL()
if replicaURL == "" {
replicaURL = config.GetDatabasePrimaryHostURL()
}
replicaDatabase := DatastoreCon(replicaURL, true)
replicaDatabase(s)
}
}
// addSqlHealthChecker returns a health check for the database.
func addSQLHealthChecker(s *Service, db *sql.DB) {
dbCheck := sqlhealth.New(db)
s.AddHealthCheck(dbCheck)
s.AddCleanupMethod(func(ctx context.Context) {
dbCheck.Stop()
})
}