/
reverse_query.go
123 lines (104 loc) · 2.57 KB
/
reverse_query.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
package memdb
import (
"context"
"fmt"
"runtime"
"time"
"github.com/hashicorp/go-memdb"
"github.com/authzed/spicedb/internal/datastore"
)
type memdbReverseTupleQuery struct {
db *memdb.MemDB
revision datastore.Revision
objNamespaceName string
objRelationName string
subNamespaceName string
subRelationName string
subObjectID string
limit *uint64
simulatedLatency time.Duration
}
func (mtq memdbReverseTupleQuery) Limit(limit uint64) datastore.CommonTupleQuery {
mtq.limit = &limit
return mtq
}
func (mtq memdbReverseTupleQuery) WithObjectRelation(namespaceName string, relationName string) datastore.ReverseTupleQuery {
mtq.objNamespaceName = namespaceName
mtq.objRelationName = relationName
return mtq
}
func (mtq memdbReverseTupleQuery) Execute(ctx context.Context) (datastore.TupleIterator, error) {
db := mtq.db
if db == nil {
return nil, fmt.Errorf("memdb closed")
}
txn := db.Txn(false)
time.Sleep(mtq.simulatedLatency)
var err error
var bestIterator memdb.ResultIterator
if mtq.objNamespaceName != "" {
if mtq.subObjectID != "" {
bestIterator, err = txn.Get(
tableRelationship,
indexRelationAndSubject,
mtq.subNamespaceName,
mtq.subObjectID,
mtq.subRelationName,
mtq.objNamespaceName,
mtq.objRelationName,
)
} else {
bestIterator, err = txn.Get(
tableRelationship,
indexRelationAndRelation,
mtq.subNamespaceName,
mtq.subRelationName,
mtq.objNamespaceName,
mtq.objRelationName,
)
}
} else if mtq.subObjectID != "" {
bestIterator, err = txn.Get(
tableRelationship,
indexSubject,
mtq.subNamespaceName,
mtq.subObjectID,
mtq.subRelationName,
)
} else if mtq.subRelationName != "" {
bestIterator, err = txn.Get(
tableRelationship,
indexSubjectRelation,
mtq.subNamespaceName,
mtq.subRelationName,
)
} else {
bestIterator, err = txn.Get(
tableRelationship,
indexSubjectNamespace,
mtq.subNamespaceName,
)
}
if err != nil {
txn.Abort()
return nil, fmt.Errorf(errUnableToQueryTuples, err)
}
filteredIterator := memdb.NewFilterIterator(bestIterator, func(tupleRaw interface{}) bool {
tuple := tupleRaw.(*relationship)
if uint64(mtq.revision.IntPart()) < tuple.createdTxn || uint64(mtq.revision.IntPart()) >= tuple.deletedTxn {
return true
}
return false
})
iter := &memdbTupleIterator{
txn: txn,
it: filteredIterator,
limit: mtq.limit,
}
runtime.SetFinalizer(iter, func(iter *memdbTupleIterator) {
if iter.txn != nil {
panic("Tuple iterator garbage collected before Close() was called")
}
})
return iter, nil
}