-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdag.go
759 lines (675 loc) · 22.8 KB
/
dag.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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
// Package arangodag implements directed acyclic graphs (DAGs) on top of ArangoDB.
package arangodag
import (
"context"
"encoding/json"
"fmt"
"github.com/arangodb/go-driver"
"github.com/emicklei/dot"
"github.com/rs/zerolog/log"
"net/http"
)
const (
maxDepth = 10000
)
// DAG implements the data structure of the DAG.
type DAG struct {
DB driver.Database
Vertices driver.Collection
Edges driver.Collection
queryLogging bool
}
// Info contains basic information about the DAG.
type Info struct {
Nodes int64 `json:"nodes"`
Relations int64 `json:"relations"`
}
type dagEdge struct {
From driver.DocumentID `json:"_from"`
To driver.DocumentID `json:"_to"`
Data interface{} `json:"data,omitempty"`
}
type dagVertex struct {
Key string `json:"_key,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// KeyInterface describes the interface a type must implement in order to
// explicitly specify the vertex key.
type KeyInterface interface {
Key() string
}
// ConnectDAG returns a DAG instance from the given DB and collection name.
// ConnectDAG returns an error if the DB does not exist or does not contain
// collections that provide for a valid DAG.
func ConnectDAG(ctx context.Context, dbName, collectionName string, client driver.Client) (*DAG, error) {
return newDAG(ctx, dbName, collectionName, client, false)
}
// CreateDAG creates and returns a new DAG. CreateDAG returns an error, if the given DB
// already exists.
func CreateDAG(ctx context.Context, dbName, collectionName string, client driver.Client) (*DAG, error) {
return newDAG(ctx, dbName, collectionName, client, true)
}
func newDAG(ctx context.Context, dbName, collectionName string, client driver.Client, create bool) (*DAG, error) {
d := DAG{}
// use an existing DB or create it, if requested
exists, err := client.DatabaseExists(ctx, dbName)
if err != nil {
return nil, fmt.Errorf("failed to check, if DB '%s' exists: %w", dbName, err)
}
if !exists {
if !create {
return nil, fmt.Errorf("DB '%s' does not exist", dbName)
} else {
if d.DB, err = client.CreateDatabase(ctx, dbName, nil); err != nil {
return nil, fmt.Errorf("failed to create DB '%s': %w", dbName, err)
}
}
} else {
d.DB, err = client.Database(ctx, dbName)
if err != nil {
return nil, fmt.Errorf("failed to connnect to DB '%s': %w", dbName, err)
}
}
// use an existing vertex collection or create it, if requested
vertexCollName := fmt.Sprintf("%s-%s", "v", collectionName)
if exists, err = d.DB.CollectionExists(ctx, vertexCollName); err != nil {
return nil, fmt.Errorf("failed to check, if vertex collection '%s' exists: %w", vertexCollName, err)
}
if !exists {
if !create {
return nil, fmt.Errorf("vertex collection '%s' does not exist", vertexCollName)
} else {
d.Vertices, err = d.DB.CreateCollection(ctx, vertexCollName, nil)
if err != nil {
return nil, fmt.Errorf("failed to create vertex collection '%s': %w", vertexCollName, err)
}
}
} else {
d.Vertices, err = d.DB.Collection(ctx, vertexCollName)
if err != nil {
return nil, fmt.Errorf("failed to connnect to vertex collection '%s': %w", vertexCollName, err)
}
}
// use an existing edge collection or create it, if requested
edgeCollName := fmt.Sprintf("%s-%s", "e", collectionName)
if exists, err = d.DB.CollectionExists(ctx, edgeCollName); err != nil {
return nil, fmt.Errorf("failed to check, if edge collection '%s' exists: %w", edgeCollName, err)
}
if !exists {
if !create {
return nil, fmt.Errorf("edge collection '%s' does not exist", edgeCollName)
} else {
collectionOptions := &driver.CreateCollectionOptions{
Type: driver.CollectionTypeEdge,
}
d.Edges, err = d.DB.CreateCollection(ctx, edgeCollName, collectionOptions)
if err != nil {
return nil, fmt.Errorf("failed to create edge collection '%s': %w", edgeCollName, err)
}
// ensure unique edges (from->to) (see: https://stackoverflow.com/a/43006762)
if _, _, err = d.Edges.EnsureHashIndex(
ctx,
[]string{"_from", "_to"},
&driver.EnsureHashIndexOptions{Unique: true},
); err != nil {
return nil, fmt.Errorf("failed to set unique edge constraint: %w", err)
}
}
} else {
d.Edges, err = d.DB.Collection(ctx, edgeCollName)
if err != nil {
return nil, fmt.Errorf("failed to connnect to edge collection '%s': %w", edgeCollName, err)
}
}
return &d, nil
}
// SetQueryLogging enables or disables query logging.
func (d *DAG) SetQueryLogging(queryLogging bool) {
d.queryLogging = queryLogging
}
// AddVertex adds a new vertex to the DAG with the given data.
//
// If the given data implements the KeyInterface, then the key for the new vertex
// will be taken from the data. If not, a key will be generated.
//
// Note, only exported fields in data (i.e. capital first letter), will be stored.
//
// AddVertex prevents duplicate keys.
func (d *DAG) AddVertex(ctx context.Context, data interface{}) (meta driver.DocumentMeta, err error) {
var key string
if i, ok := data.(KeyInterface); ok {
key = i.Key()
}
v := dagVertex{
Key: key,
Data: data,
}
return d.Vertices.CreateDocument(ctx, v)
}
// AddNamedVertex adds a vertex with the given key and data to the DAG.
//
// Use the type json.RawMessage for data (i.e. []byte) to add "raw" JSON strings /
// byte slices.
//
// AddVertex prevents duplicate keys.
func (d *DAG) AddNamedVertex(ctx context.Context, key string, data interface{}) (meta driver.DocumentMeta, err error) {
v := dagVertex{
Key: key,
Data: data,
}
return d.Vertices.CreateDocument(ctx, v)
}
// UpdateVertex updates the data of the vertex with the given key.
func (d *DAG) UpdateVertex(ctx context.Context, key string, data interface{}) (meta driver.DocumentMeta, err error) {
v := dagVertex{
Data: data,
}
return d.Vertices.UpdateDocument(ctx, key, v)
}
// ReplaceVertex replaces the data of the vertex with the given key.
func (d *DAG) ReplaceVertex(ctx context.Context, key string, data interface{}) (meta driver.DocumentMeta, err error) {
v := dagVertex{
Data: data,
}
return d.Vertices.ReplaceDocument(ctx, key, v)
}
// GetVertex returns the vertex with the key srcKey.
//
// If src doesn't exist, GetVertex returns an error.
func (d *DAG) GetVertex(ctx context.Context, srcKey string, data interface{}) (driver.DocumentMeta, error) {
v := dagVertex{
Data: data,
}
return d.Vertices.ReadDocument(ctx, srcKey, &v)
}
// DelVertex removes the vertex with the key srcKey (src). DelVertex also removes
// any inbound and outbound edges. In case of success, DelVertex returns the
// Number of edges that were removed.
//
// If src doesn't exist, DelVertex returns an error.
func (d *DAG) DelVertex(ctx context.Context, srcKey string) (count int64, err error) {
// delete edges
id := driver.NewDocumentID(d.Vertices.Name(), srcKey)
query := "FOR e IN @@edgeCollection " +
"FILTER e._from == @from || e._to == @from " +
"REMOVE { _key: e._key } IN @@edgeCollection " +
"RETURN e"
bindVars := map[string]interface{}{
"from": id,
"@edgeCollection": d.Edges.Name(),
}
d.LogQuery(query, bindVars)
var cursor driver.Cursor
if cursor, err = d.DB.Query(driver.WithQueryCount(ctx), query, bindVars); err != nil {
return
}
count = cursor.Count()
if err = cursor.Close(); err != nil {
return
}
// remove vertex
_, err = d.Vertices.RemoveDocument(ctx, srcKey)
return
}
// GetOrder returns the Number of vertices in the graph.
func (d *DAG) GetOrder(ctx context.Context) (int64, error) {
return d.Vertices.Count(ctx)
}
// GetAllVertices executes the query to retrieve all vertices of the DAG.
// GetAllVertices returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetAllVertices(ctx context.Context) (driver.Cursor, error) {
query := "FOR v IN @@vertexCollection RETURN v"
bindVars := map[string]interface{}{
"@vertexCollection": d.Vertices.Name(),
}
d.LogQuery(query, bindVars)
return d.DB.Query(ctx, query, bindVars)
}
// GetLeaves executes the query to retrieve all leaves of the DAG.
// GetLeaves returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetLeaves(ctx context.Context) (driver.Cursor, error) {
query := "FOR v IN @@vertexCollection " +
"FILTER LENGTH(FOR vv IN 1..1 OUTBOUND v @@edgeCollection LIMIT 1 RETURN 1) == 0 " +
"RETURN v"
bindVars := map[string]interface{}{
"@vertexCollection": d.Vertices.Name(),
"@edgeCollection": d.Edges.Name(),
}
d.LogQuery(query, bindVars)
return d.DB.Query(ctx, query, bindVars)
}
// GetRoots executes the query to retrieve all roots of the DAG.
// GetRoots returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetRoots(ctx context.Context) (driver.Cursor, error) {
query := "FOR v IN @@vertexCollection " +
"FILTER LENGTH(FOR vv IN 1..1 INBOUND v @@edgeCollection LIMIT 1 RETURN 1) == 0 " +
"RETURN v"
bindVars := map[string]interface{}{
"@vertexCollection": d.Vertices.Name(),
"@edgeCollection": d.Edges.Name(),
}
d.LogQuery(query, bindVars)
return d.DB.Query(ctx, query, bindVars)
}
// AddEdge adds an edge from the vertex with the key srcKey (src) to the vertex with
// the key dstKey (dst) and returns the key of the new edge.
//
// If createVertices is true, AddEdge creates missing vertices. Otherwise, it
// raises an error.
//
// AddEdge prevents duplicate edges and loops (and thereby maintains a valid
// DAG).
func (d *DAG) AddEdge(ctx context.Context, srcKey, dstKey string, data interface{}, createVertices bool) (meta driver.DocumentMeta, err error) {
// ensure vertices exist
var src driver.DocumentMeta
if src, err = d.Vertices.ReadDocument(ctx, srcKey, nil); err != nil {
// if not found and createVertices, try to create a vertex with no data
if driver.IsNotFound(err) && createVertices {
if src, err = d.AddNamedVertex(ctx, srcKey, nil); err != nil {
return
}
} else {
return
}
}
// ensure vertices exist
var dst driver.DocumentMeta
if dst, err = d.Vertices.ReadDocument(ctx, dstKey, nil); err != nil {
// if not found and createVertices, try to create a vertex with no data
if driver.IsNotFound(err) && createVertices {
if dst, err = d.AddNamedVertex(ctx, dstKey, nil); err != nil {
return
}
} else {
return
}
}
return d.addEdge(ctx, src.ID, dst.ID, data)
}
// DelEdge removes the edge from the vertex with the key srcKey (src) to the vertex with
// the key dstKey (dst).
//
// DelEdge returns an error, if such an edge doesn't exist.
func (d *DAG) DelEdge(ctx context.Context, srcKey, dstKey string) (meta driver.DocumentMeta, err error) {
if meta, err = d.getEdge(ctx, srcKey, dstKey, nil); err != nil {
return
}
return d.Edges.RemoveDocument(ctx, meta.Key)
}
// EdgeExists returns true, if an edge between the vertex with the key srcKey
// (src) and the vertex with the key dstKey (dst) exists. If src, dst or an edge
// between the two doesn't exist, GetEdge returns an error.
func (d *DAG) EdgeExists(ctx context.Context, srcKey, dstKey string) (bool, error) {
_, err := d.getEdge(ctx, srcKey, dstKey, nil)
if err != nil {
if IsDAGErrorWithNumber(err, DAGErrNotFound) {
return false, nil
}
return false, err
}
return true, nil
}
// GetEdge returns the edge between the vertex with the key srcKey (src) and the
// vertex with the key dstKey (dst), if such exists. If src, dst or an edge
// between the two doesn't exist, GetEdge returns an error.
func (d *DAG) GetEdge(ctx context.Context, srcKey, dstKey string, data interface{}) (driver.DocumentMeta, error) {
return d.getEdge(ctx, srcKey, dstKey, data)
}
// GetSize returns the Number of edges in the DAG.
func (d *DAG) GetSize(ctx context.Context) (int64, error) {
return d.Edges.Count(ctx)
}
// GetEdges executes the query to retrieve all edges of the DAG. GetEdges returns
// a cursor that may be used retrieve the edges one-by-one.
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetEdges(ctx context.Context) (driver.Cursor, error) {
query := "FOR v IN @@collection RETURN v"
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
}
d.LogQuery(query, bindVars)
return d.DB.Query(ctx, query, bindVars)
}
// GetShortestPath executes the query to retrieve the vertices on the shortest
// path between the vertex with the key srcKey (src) and the vertex with the key
// dstKey (dst). GetShortestPath returns a cursor that may be used retrieve the
// vertices one-by-one. The result includes the src and dst.
//
// If src and dst are equal, the cursor will return a single vertex.
//
// If src or dst don't exist, the cursor doesn't return any vertex (i.e. no error
// is returned).
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetShortestPath(ctx context.Context, srcKey, dstKey string) (driver.Cursor, error) {
srcID := driver.NewDocumentID(d.Vertices.Name(), srcKey).String()
dstID := driver.NewDocumentID(d.Vertices.Name(), dstKey).String()
query := "FOR v IN OUTBOUND SHORTEST_PATH @from TO @to @@collection RETURN v"
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
"from": srcID,
"to": dstID,
}
d.LogQuery(query, bindVars)
return d.DB.Query(ctx, query, bindVars)
}
// GetParents executes the query to retrieve all parents of the vertex with the key
// srcKey (src). GetParents returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// If src doesn't exist, the cursor doesn't return any vertex (i.e. no error
// is returned).
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetParents(ctx context.Context, srcKey string) (driver.Cursor, error) {
return d.getRelatives(ctx, srcKey, false, 1, false)
}
// GetParentCount returns the Number parent-vertices of the vertex with the key
// srcKey (src).
//
// If src doesn't exist, GetParentCount returns 0.
func (d *DAG) GetParentCount(ctx context.Context, srcKey string) (count int64, err error) {
srcID := driver.NewDocumentID(d.Vertices.Name(), srcKey).String()
query := "FOR v IN 1..1 INBOUND @from @@collection RETURN v"
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
"from": srcID,
}
count, err = d.count(ctx, query, bindVars)
if err != nil {
return
}
return
}
// GetAncestors executes the query to retrieve all ancestors of the vertex with the key
// srcKey (src). GetAncestors returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// By default, GetAncestors returns vertices in BFS order, if dfs is set to true,
// it will be in DFS order.
//
// If src doesn't exist, the cursor doesn't return any vertex (i.e. no error
// is returned).
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetAncestors(ctx context.Context, srcKey string, dfs bool) (driver.Cursor, error) {
return d.getRelatives(ctx, srcKey, false, maxDepth, dfs)
}
// GetChildren executes the query to retrieve all children of the vertex with the key
// srcKey. GetChildren returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// If src doesn't exist, the cursor doesn't return any vertex (i.e. no error
// is returned).
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetChildren(ctx context.Context, srcKey string) (driver.Cursor, error) {
return d.getRelatives(ctx, srcKey, true, 1, false)
}
// GetChildCount returns the Number child-vertices of the vertex with the key
// srcKey.
//
// If src doesn't exist, GetChildCount returns 0.
func (d *DAG) GetChildCount(ctx context.Context, srcKey string) (count int64, err error) {
srcID := driver.NewDocumentID(d.Vertices.Name(), srcKey).String()
query := "FOR v IN 1..1 OUTBOUND @from @@collection RETURN v"
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
"from": srcID,
}
count, err = d.count(ctx, query, bindVars)
if err != nil {
return
}
return
}
// GetDescendants executes the query to retrieve all descendants of the vertex with the key
// srcKey. GetDescendants returns a cursor that may be used retrieve the vertices
// one-by-one.
//
// By default, GetDescendants returns vertices in BFS order, if dfs is set to
// true, it will be in DFS order.
//
// If src doesn't exist, the cursor doesn't return any vertex (i.e. no error
// is returned).
//
// It is up to the caller to close the cursor, if no longer needed.
func (d *DAG) GetDescendants(ctx context.Context, srcKey string, dfs bool) (driver.Cursor, error) {
return d.getRelatives(ctx, srcKey, true, maxDepth, dfs)
}
// DotGraph returns a (dot-) graph of the DAG.
func (d *DAG) DotGraph(ctx context.Context, g *dot.Graph) (nodeMapping map[driver.DocumentID]dot.Node, err error) {
// mapping between arangoDB-vertex keys and dot nodes
nodeMapping = make(map[driver.DocumentID]dot.Node)
var cursor driver.Cursor
// read all vertices
if cursor, err = d.GetAllVertices(ctx); err != nil {
return
}
var vertex driver.DocumentMeta
for {
_, errRead := cursor.ReadDocument(ctx, &vertex)
if driver.IsNoMoreDocuments(errRead) {
break
}
if errRead != nil {
err = errRead
return
}
node := g.Node(vertex.Key).Label(vertex.Key)
nodeMapping[vertex.ID] = node
}
if err = cursor.Close(); err != nil {
return
}
// read all vertices
if cursor, err = d.GetEdges(ctx); err != nil {
return
}
var edge dagEdge
for {
_, errRead := cursor.ReadDocument(ctx, &edge)
if driver.IsNoMoreDocuments(errRead) {
break
}
if errRead != nil {
err = errRead
return
}
g.Edge(nodeMapping[edge.From], nodeMapping[edge.To])
}
if err = cursor.Close(); err != nil {
return
}
return
}
// String returns a (graphviz) dot representation of the DAG.
func (d *DAG) String(ctx context.Context) (result string, err error) {
// transform to dot graph
g := dot.NewGraph(dot.Directed)
if _, err = d.DotGraph(ctx, g); err != nil {
return
}
// get the dot string
result = g.String()
return
}
// Info returns information about the DAG.
func (d *DAG) Info(ctx context.Context) (Info, error) {
info := Info{}
nodeCount, errorVertexCount := d.Vertices.Count(ctx)
if errorVertexCount != nil {
return Info{}, errorVertexCount
}
info.Nodes = nodeCount
relationCount, errorRelationCount := d.Edges.Count(ctx)
if errorRelationCount != nil {
return Info{}, errorRelationCount
}
info.Relations = relationCount
return info, nil
}
func (d *DAG) getRelatives(ctx context.Context, srcKey string, outbound bool, depth int, dfs bool) (driver.Cursor, error) {
id := driver.NewDocumentID(d.Vertices.Name(), srcKey).String()
// compute query options / parameters
uniqueVertices := "global"
order := "bfs"
if dfs {
order = "dfs"
uniqueVertices = "none"
}
direction := "INBOUND"
if outbound {
direction = "OUTBOUND"
}
// compute the query
// (somehow INBOUND/OUTBOUND can't be set via bindVars)
query := fmt.Sprintf("FOR v IN 1..@depth %s @from @@collection "+
"OPTIONS {order: @order, uniqueVertices: @uniqueVertices} RETURN DISTINCT v", direction)
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
"from": id,
"order": order,
"uniqueVertices": uniqueVertices,
"depth": depth,
}
d.LogQuery(query, bindVars)
return d.DB.Query(ctx, query, bindVars)
}
func (d *DAG) addEdge(ctx context.Context, srcID, dstID driver.DocumentID, data interface{}) (meta driver.DocumentMeta, err error) {
// prevent loops
var pathExists bool
if pathExists, err = d.pathExists(ctx, dstID, srcID); err != nil {
return
}
if pathExists {
return meta, DAGError{
Code: http.StatusConflict,
Number: DAGErrLoop,
Message: fmt.Sprintf("adding an edge from %s to %s would create a loop", srcID.Key(), dstID.Key()),
}
}
// add edge
edge := dagEdge{srcID, dstID, data}
return d.Edges.CreateDocument(ctx, edge)
}
func (d *DAG) getEdge(ctx context.Context, srcKey, dstKey string, data interface{}) (meta driver.DocumentMeta, err error) {
srcID := driver.NewDocumentID(d.Vertices.Name(), srcKey).String()
dstID := driver.NewDocumentID(d.Vertices.Name(), dstKey).String()
query := "FOR e IN @@collection FILTER e._from == @from && e._to == @to LIMIT 1 RETURN e"
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
"from": srcID,
"to": dstID,
}
d.LogQuery(query, bindVars)
var cursor driver.Cursor
if cursor, err = d.DB.Query(ctx, query, bindVars); err != nil {
return
}
if data == nil {
meta, err = cursor.ReadDocument(ctx, &struct{}{})
} else {
edge := struct {
Data interface{} `json:"data,omitempty"`
}{
Data: data,
}
meta, err = cursor.ReadDocument(ctx, &edge)
}
if driver.IsNoMoreDocuments(err) {
return meta, DAGError{
Code: http.StatusNotFound,
Number: DAGErrNotFound,
Message: fmt.Sprintf("an edge from %s to %s doesn't exist", srcKey, dstKey),
}
}
if err != nil {
return driver.DocumentMeta{}, err
}
return meta, nil
}
func (d *DAG) pathExists(ctx context.Context, srcID, dstID driver.DocumentID) (bool, error) {
query := "FOR p IN OUTBOUND SHORTEST_PATH @from TO @to @@collection LIMIT 1 RETURN p"
bindVars := map[string]interface{}{
"@collection": d.Edges.Name(),
"from": srcID,
"to": dstID,
}
return d.exists(ctx, query, bindVars)
}
func (d *DAG) exists(ctx context.Context, query string, bindVars map[string]interface{}) (exists bool, err error) {
var count int64
count, err = d.count(ctx, query, bindVars)
if err != nil {
return
}
exists = count > 0
return
}
func (d *DAG) count(ctx context.Context, query string, bindVars map[string]interface{}) (count int64, err error) {
ctx = driver.WithQueryCount(ctx)
var cursor driver.Cursor
d.LogQuery(query, bindVars)
cursor, err = d.DB.Query(ctx, query, bindVars)
if err != nil {
return
}
count = cursor.Count()
err = cursor.Close()
return
}
func (d *DAG) LogQuery(query string, bindVars map[string]interface{}) {
if !d.queryLogging {
return
}
event := log.Debug().Str("query", query)
jsonBytes, err := json.Marshal(bindVars)
if err != nil {
event.Str("bindVars", fmt.Sprintf("%v", bindVars))
} else {
event.RawJSON("bindVars", jsonBytes)
}
event.Msg("query")
}
/**** Errors ***/
const (
DAGErrLoop = 1000
DAGErrNotFound = 1001
)
type DAGError struct {
Code int
Number int
Message string
}
// Error returns the error Message of an ArangoError.
func (e DAGError) Error() string {
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("DAGError: Code %d, Number %d, Message %s", e.Code, e.Number, e.Message)
}
var Cause = func(err error) error { return err }
// IsDAGError returns true when the given error is an DAGError.
func IsDAGError(err error) bool {
_, ok := Cause(err).(DAGError)
return ok
}
func IsDAGErrorWithNumber(err error, number int) bool {
e, ok := Cause(err).(DAGError)
return ok && e.Number == number
}
func IsDAGErrorWithCode(err error, status int) bool {
e, ok := Cause(err).(DAGError)
return ok && e.Code == status
}