-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclient_impl.go
622 lines (568 loc) · 15.6 KB
/
client_impl.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
package neogo
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"github.com/goccy/go-json"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
"github.com/rlch/neogo/internal"
"github.com/rlch/neogo/query"
)
type (
clientImpl struct {
*session
cy *internal.CypherClient
query.Reader
query.Updater[query.Querier]
}
querierImpl struct {
*session
cy *internal.CypherQuerier
query.Reader
query.Runner
query.Updater[query.Querier]
}
readerImpl struct {
*session
cy *internal.CypherReader
}
yielderImpl struct {
*session
cy *internal.CypherYielder
query.Querier
}
updaterImpl[To, ToCypher any] struct {
*session
cy *internal.CypherUpdater[ToCypher]
to func(ToCypher) To
}
runnerImpl struct {
*session
cy *internal.CypherRunner
}
resultImpl struct {
*session
neo4j.ResultWithContext
compiled *internal.CompiledCypher
}
baseRunner interface {
GetRunner() *internal.CypherRunner
}
)
func (s *session) newClient(cy *internal.CypherClient) *clientImpl {
return &clientImpl{
session: s,
cy: cy,
Reader: s.newReader(cy.CypherReader),
Updater: newUpdater[query.Querier, *internal.CypherQuerier](
s,
cy.CypherUpdater,
func(c *internal.CypherQuerier) query.Querier {
return s.newQuerier(c)
},
),
}
}
func (s *session) newQuerier(cy *internal.CypherQuerier) *querierImpl {
return &querierImpl{
session: s,
cy: cy,
Reader: s.newReader(cy.CypherReader),
Runner: s.newRunner(cy.CypherRunner),
Updater: newUpdater[query.Querier, *internal.CypherQuerier](
s,
cy.CypherUpdater,
func(c *internal.CypherQuerier) query.Querier {
return s.newQuerier(c)
},
),
}
}
func (s *session) newReader(cy *internal.CypherReader) *readerImpl {
return &readerImpl{
session: s,
cy: cy,
}
}
func (s *session) newYielder(cy *internal.CypherYielder) *yielderImpl {
return &yielderImpl{
session: s,
cy: cy,
Querier: s.newQuerier(cy.CypherQuerier),
}
}
func newUpdater[To, ToCypher any](
s *session,
cy *internal.CypherUpdater[ToCypher],
to func(ToCypher) To,
) *updaterImpl[To, ToCypher] {
return &updaterImpl[To, ToCypher]{
session: s,
cy: cy,
to: to,
}
}
func (s *session) newRunner(cy *internal.CypherRunner) *runnerImpl {
return &runnerImpl{session: s, cy: cy}
}
func (c *clientImpl) Use(graphExpr string) query.Querier {
return c.newQuerier(c.cy.Use(graphExpr))
}
func (c *clientImpl) Union(unions ...func(c Query) query.Runner) query.Querier {
inUnions := make([]func(c *internal.CypherClient) *internal.CypherRunner, len(unions))
for i, union := range unions {
union := union
inUnions[i] = func(cc *internal.CypherClient) *internal.CypherRunner {
return union(c.newClient(cc)).(baseRunner).GetRunner()
}
}
return c.newQuerier(c.cy.Union(inUnions...))
}
func (c *clientImpl) UnionAll(unions ...func(c Query) query.Runner) query.Querier {
inUnions := make([]func(c *internal.CypherClient) *internal.CypherRunner, len(unions))
for i, union := range unions {
union := union
inUnions[i] = func(cc *internal.CypherClient) *internal.CypherRunner {
return union(c.newClient(cc)).(baseRunner).GetRunner()
}
}
return c.newQuerier(c.cy.UnionAll(inUnions...))
}
func (c *readerImpl) OptionalMatch(patterns internal.Patterns) query.Querier {
return c.newQuerier(c.cy.OptionalMatch(patterns))
}
func (c *readerImpl) Match(patterns internal.Patterns) query.Querier {
return c.newQuerier(c.cy.Match(patterns))
}
func (c *readerImpl) Subquery(subquery func(c Query) query.Runner) query.Querier {
inSubquery := func(cc *internal.CypherClient) *internal.CypherRunner {
runner := subquery(c.newClient(cc))
return runner.(baseRunner).GetRunner()
}
return c.newQuerier(c.cy.Subquery(inSubquery))
}
func (c *readerImpl) With(identifiers ...any) query.Querier {
return c.newQuerier(c.cy.With(identifiers...))
}
func (c *readerImpl) Unwind(expr any, as string) query.Querier {
return c.newQuerier(c.cy.Unwind(expr, as))
}
func (c *readerImpl) Call(procedure string) query.Yielder {
return c.newYielder(c.cy.Call(procedure))
}
func (c *readerImpl) Show(command string) query.Yielder {
return c.newYielder(c.cy.Show(command))
}
func (c *readerImpl) Return(identifiers ...any) query.Runner {
return c.newRunner(c.cy.Return(identifiers...))
}
func (c *readerImpl) Cypher(query string) query.Querier {
q := c.cy.Cypher(query)
return c.newQuerier(q)
}
func (c *readerImpl) Eval(expression query.Expression) query.Querier {
q := c.cy.Eval(func(s *internal.Scope, b *strings.Builder) {
expression.Compile(s, b)
})
return c.newQuerier(q)
}
func (c *querierImpl) Where(opts ...internal.WhereOption) query.Querier {
return c.newQuerier(c.cy.Where(opts...))
}
func (c *updaterImpl[To, ToCypher]) Create(pattern internal.Patterns) To {
return c.to(c.cy.Create(pattern))
}
func (c *updaterImpl[To, ToCypher]) Merge(pattern internal.Pattern, opts ...internal.MergeOption) To {
return c.to(c.cy.Merge(pattern, opts...))
}
func (c *updaterImpl[To, ToCypher]) DetachDelete(identifiers ...any) To {
return c.to(c.cy.DetachDelete(identifiers...))
}
func (c *updaterImpl[To, ToCypher]) Delete(identifiers ...any) To {
return c.to(c.cy.Delete(identifiers...))
}
func (c *updaterImpl[To, ToCypher]) Set(items ...internal.SetItem) To {
return c.to(c.cy.Set(items...))
}
func (c *updaterImpl[To, ToCypher]) Remove(items ...internal.RemoveItem) To {
return c.to(c.cy.Remove(items...))
}
func (c *updaterImpl[To, ToCypher]) ForEach(identifier, elementsExpr any, do func(c query.Updater[any])) To {
return c.to(c.cy.ForEach(identifier, elementsExpr, func(cu *internal.CypherUpdater[any]) {
u := &updaterImpl[any, any]{
session: c.session,
cy: cu,
to: func(tc any) any { return nil },
}
do(u)
}))
}
func (c *yielderImpl) Yield(identifiers ...any) query.Querier {
return c.newQuerier(c.cy.Yield(identifiers...))
}
func (c *yielderImpl) GetRunner() *internal.CypherRunner {
return c.cy.CypherRunner
}
func (c *querierImpl) GetRunner() *internal.CypherRunner {
return c.cy.CypherRunner
}
func (c *runnerImpl) GetRunner() *internal.CypherRunner {
return c.cy
}
func (c *runnerImpl) Print() query.Runner {
c.cy.Print()
return c
}
func (c *runnerImpl) run(
ctx context.Context,
params map[string]any,
mapResult func(r neo4j.ResultWithContext) (any, error),
) (out any, err error) {
cy, err := c.cy.CompileWithParams(params)
if err != nil {
return nil, fmt.Errorf("cannot compile cypher: %w", err)
}
canonicalizedParams, err := canonicalizeParams(cy.Parameters)
if err != nil {
return nil, fmt.Errorf("cannot serialize parameters: %w", err)
}
return c.executeTransaction(
ctx, cy,
func(tx neo4j.ManagedTransaction) (any, error) {
var result neo4j.ResultWithContext
result, err = tx.Run(ctx, cy.Cypher, canonicalizedParams)
if err != nil {
return nil, fmt.Errorf("cannot run cypher: %w", err)
}
err = c.unmarshalResult(ctx, cy, result)
if err != nil {
return nil, err
}
if mapResult == nil {
return nil, nil
}
return mapResult(result)
})
}
func (c *runnerImpl) RunWithParams(ctx context.Context, params map[string]any) (err error) {
_, err = c.run(ctx, params, nil)
return
}
func (c *runnerImpl) Run(ctx context.Context) (err error) {
_, err = c.run(ctx, nil, nil)
return
}
func (c *runnerImpl) RunSummary(ctx context.Context) (neo4j.ResultSummary, error) {
return c.RunSummaryWithParams(ctx, nil)
}
func (c *runnerImpl) RunSummaryWithParams(ctx context.Context, params map[string]any) (neo4j.ResultSummary, error) {
summary, err := c.run(ctx, params, func(r neo4j.ResultWithContext) (any, error) {
return r.Consume(ctx)
})
if err != nil {
return nil, err
}
return summary.(neo4j.ResultSummary), nil
}
func (c *runnerImpl) StreamWithParams(ctx context.Context, params map[string]any, sink func(r query.Result) error) (err error) {
cy, err := c.cy.CompileWithParams(params)
if err != nil {
return fmt.Errorf("cannot compile cypher: %w", err)
}
canonicalizedParams, err := canonicalizeParams(cy.Parameters)
if err != nil {
return fmt.Errorf("cannot serialize parameters: %w", err)
}
_, err = c.executeTransaction(ctx, cy, func(tx neo4j.ManagedTransaction) (any, error) {
var result neo4j.ResultWithContext
result, err = tx.Run(ctx, cy.Cypher, canonicalizedParams)
if err != nil {
return nil, fmt.Errorf("cannot run cypher: %w", err)
}
err := sink(&resultImpl{
session: c.session,
ResultWithContext: result,
compiled: cy,
})
if err != nil {
return nil, fmt.Errorf("cannot sink result: %w", err)
}
return nil, nil
})
return err
}
func (c *runnerImpl) Stream(ctx context.Context, sink func(r query.Result) error) (err error) {
return c.StreamWithParams(ctx, nil, sink)
}
func (c *resultImpl) Peek(ctx context.Context) bool {
return c.ResultWithContext.Peek(ctx)
}
func (c *resultImpl) Next(ctx context.Context) bool {
return c.ResultWithContext.Next(ctx)
}
func (c *resultImpl) Err() error {
return c.ResultWithContext.Err()
}
func (c *resultImpl) Read() error {
record := c.Record()
if record == nil {
return nil
}
if err := c.unmarshalRecord(c.compiled, record); err != nil {
return fmt.Errorf("cannot unmarshal record: %w", err)
}
return nil
}
func (s *session) unmarshalResult(
ctx context.Context,
cy *internal.CompiledCypher,
result neo4j.ResultWithContext,
) error {
if !result.Next(ctx) {
return nil
}
first := result.Record()
// If we have more than one record, we know we should be unmarshalling
// into slices. If we have a single record, we don't necessarily know if
// we want to marshal into slices or not.
//
// Compare the depth of nesting for the bindings and their corresponding
// record values:
// - If any of the bindings have a non-zero depth, i.e. non-slice, we
// assume single.
// - If any of the bindings have a different depth than the correpodning
// record-values, assume we have multiple records.
isRecords, err := (func() (bool, error) {
if result.Peek(ctx) {
return true, nil
}
allSlices := true
bindingTypes := map[string]reflect.Type{}
for k, binding := range cy.Bindings {
typ := binding.Type()
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
bindingTypes[k] = typ
if typ.Kind() == reflect.Slice ||
typ.Kind() == reflect.Array {
continue
}
allSlices = false
}
if !allSlices {
return false, nil
}
for k, bindingType := range bindingTypes {
recordV, ok := first.Get(k)
if !ok {
return false, fmt.Errorf("no value associated with key %q", k)
}
recordType := reflect.TypeOf(recordV)
for {
bindingNext := bindingType.Kind() == reflect.Array || bindingType.Kind() == reflect.Slice
recordNext := recordType.Kind() == reflect.Array || recordType.Kind() == reflect.Slice
if bindingNext && recordNext {
bindingType = bindingType.Elem()
recordType = recordType.Elem()
continue
} else if !bindingNext && !recordNext {
break
}
return true, nil
}
}
return false, nil
})()
if err != nil {
return err
}
if isRecords {
var records []*neo4j.Record
records, err = result.Collect(ctx)
if err != nil {
return fmt.Errorf("cannot collect records: %w", err)
}
records = append([]*neo4j.Record{first}, records...)
if err = s.unmarshalRecords(cy, records); err != nil {
return fmt.Errorf("cannot unmarshal records: %w", err)
}
} else {
single := result.Record()
if single == nil {
return nil
}
if err = s.unmarshalRecord(cy, single); err != nil {
return fmt.Errorf("cannot unmarshal record: %w", err)
}
}
return nil
}
func (s *session) unmarshalRecords(
cy *internal.CompiledCypher,
records []*neo4j.Record,
) error {
n := len(records)
slices := make(map[string]reflect.Value)
for name, binding := range cy.Bindings {
for binding.Kind() == reflect.Ptr {
binding = binding.Elem()
}
if binding.Kind() != reflect.Slice {
return fmt.Errorf("cannot allocate results a non-slice value, name: %q", name)
}
binding.Set(reflect.MakeSlice(
binding.Type(),
n, n,
))
slices[name] = binding
}
for i, record := range records {
for key, binding := range slices {
value, ok := record.Get(key)
if !ok {
return fmt.Errorf("no value associated with key %q", key)
}
to := binding.Index(i)
if to.Kind() == reflect.Ptr {
to.Set(reflect.New(to.Type().Elem()))
} else {
to.Set(reflect.New(to.Type()).Elem())
}
if to.CanAddr() {
to = to.Addr()
}
if err := s.bindValue(value, to); err != nil {
return fmt.Errorf(
"error binding key %s to type %T: %w",
key, binding.Interface(), err,
)
}
}
}
return nil
}
func (s *session) unmarshalRecord(
cy *internal.CompiledCypher,
record *neo4j.Record,
) error {
for key, binding := range cy.Bindings {
value, ok := record.Get(key)
if !ok {
return fmt.Errorf("no value associated with key %q", key)
}
if err := s.bindValue(value, binding); err != nil {
return fmt.Errorf(
"error binding key %q to type %T: %w",
key, binding.Interface(), err,
)
}
}
return nil
}
func (c *runnerImpl) executeTransaction(
ctx context.Context,
cy *internal.CompiledCypher,
exec neo4j.ManagedTransactionWork,
) (out any, err error) {
if c.currentTx == nil {
sess := c.Session()
sessConfig := neo4j.SessionConfig{
// We default to read mode and overwrite if:
// - the user explicitly requested write mode
// - the query is a write query
AccessMode: neo4j.AccessModeRead,
}
c.ensureCausalConsistency(ctx, &sessConfig)
if sess == nil {
if conf := c.execConfig.SessionConfig; conf != nil {
sessConfig = *conf
}
if cy.IsWrite || sessConfig.AccessMode == neo4j.AccessModeWrite {
sessConfig.AccessMode = neo4j.AccessModeWrite
} else {
sessConfig.AccessMode = neo4j.AccessModeRead
}
sess = c.db.NewSession(ctx, sessConfig)
defer func() {
if sessConfig.AccessMode == neo4j.AccessModeWrite {
bookmarks := sess.LastBookmarks()
key := c.causalConsistencyKey(ctx)
if cur, ok := causalConsistencyCache[key]; ok {
causalConsistencyCache[key] = neo4j.CombineBookmarks(cur, bookmarks)
} else {
causalConsistencyCache[key] = bookmarks
go func(key string) {
<-ctx.Done()
causalConsistencyCache[key] = nil
}(key)
}
}
if closeErr := sess.Close(ctx); closeErr != nil {
err = errors.Join(err, closeErr)
}
}()
}
config := func(tc *neo4j.TransactionConfig) {
if conf := c.execConfig.TransactionConfig; conf != nil {
*tc = *conf
}
}
if cy.IsWrite || sessConfig.AccessMode == neo4j.AccessModeWrite {
out, err = sess.ExecuteWrite(ctx, exec, config)
} else {
out, err = sess.ExecuteRead(ctx, exec, config)
}
if err != nil {
return nil, err
}
} else {
out, err = exec(c.currentTx)
if err != nil {
return nil, err
}
}
return
}
func canonicalizeParams(params map[string]any) (map[string]any, error) {
canon := make(map[string]any, len(params))
if len(params) == 0 {
return canon, nil
}
for k, v := range params {
if v == nil {
canon[k] = nil
}
vv := reflect.ValueOf(v)
for vv.Kind() == reflect.Ptr {
vv = vv.Elem()
}
switch vv.Kind() {
case reflect.Slice:
bytes, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("cannot marshal slice: %w", err)
}
var js []any
if err := json.Unmarshal(bytes, &js); err != nil {
return nil, fmt.Errorf("cannot unmarshal slice: %w", err)
}
canon[k] = js
case reflect.Map, reflect.Struct:
bytes, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("cannot marshal map: %w", err)
}
var js any
if err := json.Unmarshal(bytes, &js); err != nil {
return nil, fmt.Errorf("cannot unmarshal map: %w", err)
}
canon[k] = js
default:
canon[k] = v
}
}
return canon, nil
}