forked from redis/go-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.go
647 lines (585 loc) · 15.9 KB
/
graph.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
package redis
import (
"context"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
)
type GraphCmdable interface {
GraphQuery(ctx context.Context, key, query string) *GraphCmd
}
// GraphQuery executes a query on a graph, exec: GRAPH.QUERY key query
func (c cmdable) GraphQuery(ctx context.Context, key, query string) *GraphCmd {
cmd := NewGraphCmd(ctx, "GRAPH.QUERY", key, query)
_ = c(ctx, cmd)
return cmd
}
// GraphIndexes show all graph indexes
//func (c cmdable) GraphIndexes(ctx context.Context, key string) {
// cmd := NewGraphCmd(ctx, "GRAPH.QUERY", key, query)
// _ = c(ctx, cmd)
// return cmd
//}
// ----------------------------------------------------------------------------
type (
graphDataType int
graphRowType int
)
const (
graphInteger graphDataType = iota + 1 // int (graph int)
graphNil // nil (graph nil/null)
graphString // string (graph string/boolean/double)
)
const (
graphResultBasic graphRowType = iota + 1 // int/nil/string
graphResultNode // node(3), id +labels +properties
graphResultEdge // edge(5), id + type + src_node + dest_node + properties
)
type GraphResult struct {
noResult bool // 是否是非结果集类响应,例如 CREATE 语句
text []string // 响应中的信息描述
field []string // 结果集类响应的字段,理论上字段数量等于rows每行字段数
rows [][]graphRow // 结果集列表
err error
}
// Message 获取执行描述信息
func (g *GraphResult) Message() []string {
return g.text
}
// IsResult 是否是结果集的响应,如果是非结果集响应返回 false,例如 CREATE 语句
// 如果是有结果集响应的查询,例如 MATCH ... RETURN x, 无论响应行数是否为0,都返回 true
func (g *GraphResult) IsResult() bool {
return !g.noResult
}
// Error 读取结果集中遇到的错误
func (g *GraphResult) Error() error {
return g.err
}
func (g *GraphResult) Field() []string {
return g.field
}
func (g *GraphResult) Len() int {
return len(g.rows)
}
// Row 读取一行数据
func (g *GraphResult) Row() map[string]any {
if g.noResult || len(g.field) == 0 || len(g.rows) == 0 || len(g.rows[0]) == 0 {
return nil
}
row := make(map[string]any, len(g.field))
for i := 0; i < len(g.field); i++ {
switch g.rows[0][i].typ {
case graphResultBasic:
row[g.field[i]] = g.rows[0][i].basic.String()
case graphResultNode:
row[g.field[i]] = g.rows[0][i].node.Map()
case graphResultEdge:
row[g.field[i]] = g.rows[0][i].edge.Map()
}
}
return row
}
// RowBasic 读取一行数据,但只处理基本数据类型
func (g *GraphResult) RowBasic() map[string]GraphData {
if g.noResult || len(g.field) == 0 || len(g.rows) == 0 || len(g.rows[0]) == 0 {
return nil
}
row := make(map[string]GraphData, len(g.field))
for i := 0; i < len(g.field); i++ {
if g.rows[0][i].typ == graphResultBasic {
row[g.field[i]] = *g.rows[0][i].basic
}
}
return row
}
// RowScan 将结果集的一行扫描到 dest 中,dest 必须是结构体指针
// 如果没有结果集,或非结果集响应,返回 Nil
func (g *GraphResult) RowScan(dest any) error {
if g.noResult || len(g.field) == 0 || len(g.rows) == 0 || len(g.rows[0]) == 0 {
return Nil
}
v, err := graphStruct(dest)
if err != nil {
return err
}
return g.scanStruct(v, g.rows[0])
}
// Rows 读取所有数据
func (g *GraphResult) Rows() []map[string]any {
if g.noResult || len(g.field) == 0 || len(g.rows) == 0 || len(g.rows[0]) == 0 {
return nil
}
rows := make([]map[string]any, 0, len(g.rows))
for i := 0; i < len(g.rows); i++ {
row := make(map[string]any, len(g.field))
for f := 0; f < len(g.field); f++ {
switch g.rows[i][f].typ {
case graphResultBasic:
row[g.field[f]] = g.rows[i][f].basic.String()
case graphResultNode:
row[g.field[f]] = g.rows[i][f].node.Map()
case graphResultEdge:
row[g.field[f]] = g.rows[i][f].edge.Map()
}
}
rows = append(rows, row)
}
return rows
}
// RowsBasic 读取所有数据,但只处理基本数据
func (g *GraphResult) RowsBasic() []map[string]GraphData {
if g.noResult || len(g.field) == 0 || len(g.rows) == 0 || len(g.rows[0]) == 0 {
return nil
}
rows := make([]map[string]GraphData, 0, len(g.rows))
for i := 0; i < len(g.rows); i++ {
row := make(map[string]GraphData, len(g.field))
for f := 0; f < len(g.field); f++ {
if g.rows[i][f].typ == graphResultBasic {
row[g.field[f]] = *g.rows[i][f].basic
}
}
rows = append(rows, row)
}
return rows
}
// RowsScan 将结果集的所有行扫描到 dest 中,dest 必须是结构体指针
// 如果没有结果集,或非结果集响应,返回 Nil
func (g *GraphResult) RowsScan(dest any) error {
if g.noResult || len(g.field) == 0 || len(g.rows) == 0 || len(g.rows[0]) == 0 {
return Nil
}
v, err := graphStructSlice(dest)
if err != nil {
return err
}
return g.scanStructSlice(v)
}
type graphRow struct {
typ graphRowType
basic *GraphData
node *GraphNode
edge *GraphEdge
}
type GraphData struct {
typ graphDataType
integerVal int64
stringVal string
}
func (d GraphData) IsNil() bool {
return d.typ == graphNil
}
func (d GraphData) String() string {
switch d.typ {
case graphInteger:
return strconv.FormatInt(d.integerVal, 10)
case graphNil:
return ""
case graphString:
return d.stringVal
default:
return ""
}
}
func (d GraphData) Int() int {
switch d.typ {
case graphInteger:
return int(d.integerVal)
case graphString:
n, _ := strconv.Atoi(d.stringVal)
return n
default:
return 0
}
}
func (d GraphData) Bool() bool {
switch d.typ {
case graphInteger:
return d.integerVal != 0
case graphNil:
return false
case graphString:
return d.stringVal == "true"
default:
return false
}
}
func (d GraphData) Float64() float64 {
if d.typ == graphInteger {
return float64(d.integerVal)
}
if d.typ == graphString {
v, _ := strconv.ParseFloat(d.stringVal, 64)
return v
}
return 0
}
type GraphNode struct {
ID int64
Labels []string
Properties map[string]GraphData
}
func (n *GraphNode) Map() map[string]any {
return map[string]any{
"id": n.ID,
"labels": n.Labels,
"properties": n.Properties,
}
}
type GraphEdge struct {
ID int64
Typ string
SrcNode int64
DstNode int64
Properties map[string]GraphData
}
func (e *GraphEdge) Map() map[string]any {
return map[string]any{
"id": e.ID,
"type": e.Typ,
"srcNode": e.SrcNode,
"dstNode": e.DstNode,
"properties": e.Properties,
}
}
// ----------------------------------------------------------------------------
// scan
var (
graphNodeType = reflect.TypeOf(GraphNode{})
graphEdgeType = reflect.TypeOf(GraphEdge{})
)
func (g *GraphResult) scanStructSlice(v graphStructValue) error {
if !v.isSlice {
return fmt.Errorf("redis.graph.Scan(non-slice %T)", v.value.Type())
}
gv := graphStructValue{
spec: v.spec,
}
elem := v.value.Type().Elem()
for i := 0; i < len(g.rows); i++ {
var item reflect.Value
if elem.Kind() == reflect.Ptr {
item = reflect.New(elem.Elem())
} else {
item = reflect.New(elem)
}
gv.value = item.Elem()
if err := g.scanStruct(gv, g.rows[i]); err != nil {
return err
}
if elem.Kind() == reflect.Ptr {
v.value.Set(reflect.Append(v.value, item))
} else {
v.value.Set(reflect.Append(v.value, item.Elem()))
}
}
return nil
}
func (g *GraphResult) scanStruct(v graphStructValue, row []graphRow) error {
for i := 0; i < len(g.field); i++ {
key := g.field[i]
idx, ok := v.spec.m[key]
if !ok {
continue
}
field := v.value.Field(idx)
isPtr := field.Kind() == reflect.Ptr
if isPtr && field.IsNil() {
field.Set(reflect.New(field.Type().Elem()))
}
if !isPtr && field.Type().Name() != "" && field.CanAddr() {
field = field.Addr()
isPtr = true
}
if isPtr {
field = field.Elem()
}
data := row[i]
if field.Type().Kind() != reflect.Struct && data.typ != graphResultBasic {
return fmt.Errorf("cannot scan redis.graph.result %v into struct field %s.%s of type %s",
data, v.value.Type().Name(), key, field.Type())
}
switch field.Type().Kind() {
case reflect.Bool:
field.SetBool(data.basic.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
field.SetInt(int64(data.basic.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
field.SetUint(uint64(data.basic.Int()))
case reflect.Float32, reflect.Float64:
field.SetFloat(data.basic.Float64())
case reflect.String:
field.SetString(data.basic.String())
case reflect.Struct:
// node
if field.Type() == graphNodeType {
if data.typ != graphResultNode {
return errors.New("cannot scan redis.graph.result into struct field, result not graph.node type")
}
node := field.Addr().Interface().(*GraphNode)
node.ID = data.node.ID
node.Labels = data.node.Labels
node.Properties = data.node.Properties
} else if field.Type() == graphEdgeType {
if data.typ != graphResultEdge {
return errors.New("cannot scan redis.graph.result into struct field, result not graph.edge type")
}
edge := field.Addr().Interface().(*GraphEdge)
edge.ID = data.edge.ID
edge.Typ = data.edge.Typ
edge.SrcNode = data.edge.SrcNode
edge.DstNode = data.edge.DstNode
edge.Properties = data.edge.Properties
} else {
// miss Anonymous
return fmt.Errorf("redis.graph.scan unsupported %s, not node,edge type", field.Type())
}
default:
// reflect.Complex64, reflect.Complex128, reflect.Array, reflect.Slice, reflect.Chan,
// reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.UnsafePointer:
return fmt.Errorf("redis.Scan(unsupported %s)", field.Type())
}
}
return nil
}
type graphStructValue struct {
spec *graphStructSpec
value reflect.Value
isSlice bool
}
type graphStructSpec struct {
m map[string]int
}
var graphStructMap sync.Map
func graphStructCache(t reflect.Type) *graphStructSpec {
if v, ok := graphStructMap.Load(t); ok {
return v.(*graphStructSpec)
}
spec := newStructSpec(t, "redis")
graphStructMap.Store(t, spec)
return spec
}
func graphStructSlice(dest any) (graphStructValue, error) {
v := reflect.ValueOf(dest)
if v.Kind() != reflect.Ptr {
return graphStructValue{}, fmt.Errorf("redis.graph.Scan(non-ptr1 %T)", dest)
}
v = v.Elem()
if v.Kind() != reflect.Slice {
return graphStructValue{}, fmt.Errorf("redis.graph.Scan(non-slice %T)", dest)
}
elem := v.Type().Elem()
if elem.Kind() == reflect.Ptr {
elem = v.Type().Elem().Elem()
}
if elem.Kind() != reflect.Struct {
return graphStructValue{}, fmt.Errorf("redis.graph.Scan(slice elem non-struct %T)", dest)
}
return graphStructValue{
spec: graphStructCache(elem),
value: v,
isSlice: true,
}, nil
}
func graphStruct(dest any) (graphStructValue, error) {
v := reflect.ValueOf(dest)
// The destination to scan into should be a struct pointer.
if v.Kind() != reflect.Ptr || v.IsNil() {
return graphStructValue{}, fmt.Errorf("redis.graph.Scan(non-pointer %T)", dest)
}
v = v.Elem()
if v.Kind() != reflect.Struct {
return graphStructValue{}, fmt.Errorf("redis.graph.Scan(non-struct %T)", dest)
}
return graphStructValue{
spec: graphStructCache(v.Type()),
value: v,
}, nil
}
func newStructSpec(t reflect.Type, fieldTag string) *graphStructSpec {
numField := t.NumField()
out := &graphStructSpec{
m: make(map[string]int, numField),
}
for i := 0; i < numField; i++ {
f := t.Field(i)
if f.Anonymous {
at := f.Type
if at.Kind() == reflect.Pointer {
at = at.Elem()
}
if !f.IsExported() && t.Kind() != reflect.Struct {
continue
}
} else if !f.IsExported() {
continue
}
tag := f.Tag.Get(fieldTag)
if tag == "" || tag == "-" {
continue
}
tag = strings.Split(tag, ",")[0]
if tag == "" {
continue
}
// Use the built-in decoder.
kind := f.Type.Kind()
if kind == reflect.Pointer {
kind = f.Type.Elem().Kind()
}
out.m[tag] = i
}
return out
}
// -------------------------------------------------------------------------------------
// index
//type (
// GraphIndexType string
// GraphIndexEntityType string
// GraphIndexStatus string
//)
//
//const (
// GraphIndexRange GraphIndexType = "RANGE"
// GraphIndexFulltext GraphIndexType = "FULLTEXT"
// GraphIndexVector GraphIndexType = "VECTOR"
// GraphIndexNode GraphIndexEntityType = "NODE"
// GraphIndexRelationship GraphIndexEntityType = "RELATIONSHIP"
// GraphIndexOperational GraphIndexStatus = "OPERATIONAL"
// GraphIndexFailed GraphIndexStatus = "FAILED"
// GraphIndexUnderConstruction GraphIndexStatus = "UNDER CONSTRUCTION"
//)
// -------------------------------------------------------------------------------------
//
//type Graph struct {
// Nodes map[string]*GraphNode
// Edges []*GraphEdge
// labels []string // List of node labels.
// relationshipTypes []string // List of relation types.
// properties []string // List of properties.
// mutex sync.Mutex // Lock, used for updating internal state.
//}
//
//// AddNode adds a node to the graph.
//func (g *Graph) AddNode(n *GraphNode) {
// g.mutex.Lock()
// g.Nodes[n.Alias] = n
// g.mutex.Unlock()
//}
//
//// AddEdge adds an edge to the graph.
//func (g *Graph) AddEdge(e *GraphEdge) error {
// // Verify that the edge has source and destination
// if e.Source == nil || e.Destination == nil {
// return fmt.Errorf("redis: both source and destination nodes should be defined")
// }
//
// // Verify that the edge's nodes have been previously added to the graph
// if _, ok := g.Nodes[e.Source.Alias]; !ok {
// return fmt.Errorf("redis: source node neeeds to be added to the graph first")
// }
// if _, ok := g.Nodes[e.Destination.Alias]; !ok {
// return fmt.Errorf("redis: destination node neeeds to be added to the graph first")
// }
//
// g.Edges = append(g.Edges, e)
// return nil
//}
//
//type GraphNode struct {
// ID uint64
// Labels []string
// Alias string
// Properties map[string]any
//}
//
//// Encode makes Node satisfy the Stringer interface
//func (n *GraphNode) Encode() string {
// buff := new(bytes.Buffer)
// buff.WriteByte('(')
//
// if n.Alias != "" {
// buff.WriteString(n.Alias)
// }
//
// for _, label := range n.Labels {
// buff.WriteByte(':')
// buff.WriteString(label)
// }
//
// writeGraphProperties(buff, n.Properties)
// buff.WriteByte(')')
// return buff.String()
//}
//
//type GraphEdge struct {
// ID uint64
// Relation string
// Source *GraphNode
// Destination *GraphNode
// Properties map[string]any
//}
//
//// Encode makes Edge satisfy the Stringer interface
//func (e *GraphEdge) Encode() string {
// buff := new(bytes.Buffer)
// buff.WriteByte('(')
// buff.WriteString(e.Source.Alias)
// buff.WriteByte(')')
//
// buff.WriteString("-[")
// if e.Relation != "" {
// buff.WriteString(e.Relation)
// }
// writeGraphProperties(buff, e.Properties)
// buff.WriteString("]->")
//
// buff.WriteByte('(')
// buff.WriteString(e.Destination.Alias)
// buff.WriteByte(')')
//
// return buff.String()
//}
//
//func writeGraphProperties(w *bytes.Buffer, p map[string]any) {
// if len(p) == 0 {
// return
// }
//
// w.WriteByte('{')
// for k, v := range p {
// w.WriteString(k)
// w.WriteByte(':')
// w.WriteString(graphPropertiesValue(v))
// }
// w.WriteByte('}')
//}
//
//func graphPropertiesValue(src any) string {
// if src == nil {
// return "null"
// }
//
// switch v := src.(type) {
// case string:
// return strconv.Quote(v)
// case int:
// return strconv.Itoa(v)
// case int64:
// return strconv.FormatInt(v, 10)
// case float64:
// return strconv.FormatFloat(v, 'f', -1, 64)
// case bool:
// return strconv.FormatBool(v)
// case time.Time:
// return v.Format(time.RFC3339Nano)
// case time.Duration:
// return strconv.FormatInt(v.Nanoseconds(), 10)
// default:
// internal.Logger.Printf(context.TODO(), "unrecognized type to convert to string")
// return ""
// }
//}