forked from z5labs/gogm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgogm.go
347 lines (289 loc) · 8.39 KB
/
gogm.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright (c) 2021 MindStand Technologies, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package gogm
import (
"context"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"reflect"
"strings"
"github.com/cornelk/hashmap"
"github.com/neo4j/neo4j-go-driver/v4/neo4j"
)
var globalGogm = &Gogm{isNoOp: true, logger: GetDefaultLogger()}
// SetGlobalGogm sets the global instance of gogm
func SetGlobalGogm(gogm *Gogm) {
globalGogm = gogm
}
// G returns the global instance of gogm
func G() *Gogm {
return globalGogm
}
type Gogm struct {
config *Config
pkStrategy *PrimaryKeyStrategy
logger Logger
boltMajorVersion int
mappedTypes *hashmap.HashMap
driver neo4j.Driver
mappedRelations *relationConfigs
ogmTypes []interface{}
// isNoOp specifies whether this instance of gogm can do anything
// is only used for the default global gogm
isNoOp bool
}
func New(config *Config, pkStrategy *PrimaryKeyStrategy, mapTypes ...interface{}) (*Gogm, error) {
return NewContext(context.Background(), config, pkStrategy, mapTypes...)
}
func NewContext(ctx context.Context, config *Config, pkStrategy *PrimaryKeyStrategy, mapTypes ...interface{}) (*Gogm, error) {
if config == nil {
return nil, errors.New("config can not be nil")
}
if pkStrategy == nil {
return nil, errors.New("pk strategy can not be nil")
}
if len(mapTypes) == 0 {
return nil, errors.New("no types to map")
}
g := &Gogm{
config: config,
logger: config.Logger,
boltMajorVersion: 0,
mappedTypes: &hashmap.HashMap{},
driver: nil,
mappedRelations: &relationConfigs{},
ogmTypes: mapTypes,
pkStrategy: pkStrategy,
}
err := g.init(ctx)
if err != nil {
return nil, fmt.Errorf("failed to init gogm instance, %w", err)
}
return g, nil
}
func (g *Gogm) init(ctx context.Context) error {
err := g.validate()
if err != nil {
return err
}
err = g.parseOgmTypes()
if err != nil {
return err
}
g.logger.Debug("establishing neo connection")
err = g.initDriver(ctx)
if err != nil {
return err
}
g.logger.Debug("initializing indices")
return g.initIndex(ctx)
}
func (g *Gogm) validate() error {
err := g.config.validate()
if err != nil {
return fmt.Errorf("config failed validation, %w", err)
}
g.logger = g.config.Logger
if g.config.TargetDbs == nil || len(g.config.TargetDbs) == 0 {
g.config.TargetDbs = []string{"neo4j"}
}
if g.pkStrategy == nil {
// setting to the default pk strategy
g.pkStrategy = DefaultPrimaryKeyStrategy
}
err = g.pkStrategy.validate()
if err != nil {
return fmt.Errorf("pk strategy failed validation, %w", err)
}
return nil
}
func (g *Gogm) parseOgmTypes() error {
g.logger.Debug("mapping types")
for _, t := range g.ogmTypes {
name := reflect.TypeOf(t).Elem().Name()
dc, err := getStructDecoratorConfig(g, t, g.mappedRelations)
if err != nil {
return err
}
g.logger.Debugf("mapped type %s", name)
g.mappedTypes.Set(name, *dc)
}
// validate relationships
g.logger.Debug("validating edges")
err := g.mappedRelations.Validate()
if err != nil {
g.logger.Debugf("failed to validate edges, %v", err)
return fmt.Errorf("failed to validate edges, %w", err)
}
return nil
}
func (g *Gogm) initDriver(ctx context.Context) error {
var certPool *x509.CertPool
isEncrypted := strings.Contains(g.config.Protocol, "+s")
if isEncrypted {
if g.config.UseSystemCertPool {
var err error
certPool, err = x509.SystemCertPool()
if err != nil {
return fmt.Errorf("failed to get system cert pool")
}
} else {
certPool = x509.NewCertPool()
}
if g.config.CAFileLocation != "" {
bytes, err := ioutil.ReadFile(g.config.CAFileLocation)
if err != nil {
return fmt.Errorf("failed to open ca file, %w", err)
}
certPool.AppendCertsFromPEM(bytes)
}
}
neoConfig := func(neoConf *neo4j.Config) {
if g.config.EnableDriverLogs {
neoConf.Log = wrapLogger(g.logger)
}
neoConf.MaxConnectionPoolSize = g.config.PoolSize
if isEncrypted {
neoConf.RootCAs = certPool
}
}
doneChan := make(chan error, 1)
_, hasDeadline := ctx.Deadline()
go g.initDriverRoutine(neoConfig, doneChan)
if hasDeadline {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
select {
case err := <-doneChan:
if err != nil {
return fmt.Errorf("failed to init driver, %w", err)
}
return nil
case <-ctx.Done():
return errors.New("timed out initializing driver")
}
} else {
err := <-doneChan
if err != nil {
return fmt.Errorf("failed to init driver, %w", err)
}
return nil
}
}
func (g *Gogm) initDriverRoutine(neoConfig func(neoConf *neo4j.Config), doneChan chan error) {
driver, err := neo4j.NewDriver(g.config.ConnectionString(), neo4j.BasicAuth(g.config.Username, g.config.Password, g.config.Realm), neoConfig)
if err != nil {
doneChan <- fmt.Errorf("failed to create driver, %w", err)
return
}
err = driver.VerifyConnectivity()
if err != nil {
doneChan <- fmt.Errorf("failed to verify connectivity, %w", err)
return
}
// set driver
g.driver = driver
// get neoversion
sess := driver.NewSession(neo4j.SessionConfig{
AccessMode: neo4j.AccessModeRead,
// DatabaseName: "neo4j",
})
res, err := sess.Run("return 1", nil)
if err != nil {
doneChan <- err
return
} else if err = res.Err(); err != nil {
doneChan <- err
return
}
sum, err := res.Consume()
if err != nil {
doneChan <- err
return
}
g.boltMajorVersion = sum.Server().ProtocolVersion().Major
doneChan <- nil
}
func (g *Gogm) initIndex(ctx context.Context) error {
switch g.config.IndexStrategy {
case ASSERT_INDEX:
g.logger.Debug("chose ASSERT_INDEX strategy")
g.logger.Debug("dropping all known indexes")
err := dropAllIndexesAndConstraints(ctx, g)
if err != nil {
return err
}
g.logger.Debug("creating all mapped indexes")
err = createAllIndexesAndConstraints(ctx, g, g.mappedTypes)
if err != nil {
return err
}
g.logger.Debug("verifying all indexes")
err = verifyAllIndexesAndConstraints(ctx, g, g.mappedTypes)
if err != nil {
return err
}
return nil
case VALIDATE_INDEX:
g.logger.Debug("chose VALIDATE_INDEX strategy")
g.logger.Debug("verifying all indexes")
err := verifyAllIndexesAndConstraints(ctx, g, g.mappedTypes)
if err != nil {
return err
}
return nil
case IGNORE_INDEX:
g.logger.Debug("ignoring indices")
return nil
default:
g.logger.Debugf("unknown index strategy, %v", g.config.IndexStrategy)
return fmt.Errorf("unknown index strategy, %v", g.config.IndexStrategy)
}
}
func (g *Gogm) Copy() *Gogm {
return &Gogm{
config: g.config,
logger: g.logger,
boltMajorVersion: g.boltMajorVersion,
mappedTypes: g.mappedTypes,
driver: g.driver,
mappedRelations: g.mappedRelations,
ogmTypes: g.ogmTypes,
}
}
func (g *Gogm) Close() error {
if g.driver == nil {
return errors.New("unable to close nil driver")
}
return g.driver.Close()
}
func (g *Gogm) NewSession(conf SessionConfig) (ISession, error) {
if g.isNoOp {
return nil, errors.New("gogm instance is no op. Please set global logger with SetGlobalLogger() or create a new gogm instance")
}
return newSessionWithConfig(g, conf)
}
func (g *Gogm) NewSessionV2(conf SessionConfig) (SessionV2, error) {
if g.isNoOp {
return nil, errors.New("gogm instance is no op. Please set global logger with SetGlobalLogger() or create a new gogm instance")
}
return newSessionWithConfigV2(g, conf)
}