Newer
Older
Manish R Jain
committed
/*
* Copyright 2015 Manish R Jain <manishrjain@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package query
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/task"
"github.com/dgraph-io/dgraph/uid"
"github.com/dgraph-io/dgraph/x"
Manish R Jain
committed
"github.com/google/flatbuffers/go"
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
/*
* QUERY:
* Let's take this query from GraphQL as example:
* {
* me {
* id
* firstName
* lastName
* birthday {
* month
* day
* }
* friends {
* name
* }
* }
* }
*
* REPRESENTATION:
* This would be represented in SubGraph format internally, as such:
* SubGraph [result uid = me]
* |
* Children
* |
* --> SubGraph [Attr = "xid"]
* --> SubGraph [Attr = "firstName"]
* --> SubGraph [Attr = "lastName"]
* --> SubGraph [Attr = "birthday"]
* |
* Children
* |
* --> SubGraph [Attr = "month"]
* --> SubGraph [Attr = "day"]
* --> SubGraph [Attr = "friends"]
* |
* Children
* |
* --> SubGraph [Attr = "name"]
*
* ALGORITHM:
* This is a rough and simple algorithm of how to process this SubGraph query
* and populate the results:
*
* For a given entity, a new SubGraph can be started off with NewGraph(id).
* Given a SubGraph, is the Query field empty? [Step a]
* - If no, run (or send it to server serving the attribute) query
* and populate result.
* Iterate over children and copy Result Uids to child Query Uids.
* Set Attr. Then for each child, use goroutine to run Step:a.
* Wait for goroutines to finish.
* Return errors, if any.
*/
var log = x.Log("query")
// SubGraph is the way to represent data internally. It contains both the
// query and the response. Once generated, this can then be encoded to other
// client convenient formats, like GraphQL / JSON.
type SubGraph struct {
Attr string
Children []*SubGraph
query []byte
result []byte
}
Manish R Jain
committed
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
func getChildren(r *task.Result, sg *SubGraph) (result interface{}, rerr error) {
var l []interface{}
for i := 0; i < r.UidsLength(); i++ {
m := make(map[string]interface{})
uid := r.Uids(i)
m["uid"] = uid
if len(sg.Children) > 0 {
for _, cg := range sg.Children {
}
// do something.
}
var v task.Value
if ok := r.Values(&v, i); !ok {
return nil, fmt.Errorf("While reading value at index: %v", i)
}
var i interface{}
if err := posting.ParseValue(i, v.ValBytes()); err != nil {
return nil, err
}
if r.UidsLength() == 0 {
}
}
}
func processChild(result *[]map[string]interface{}, g *SubGraph) error {
ro := flatbuffers.GetUOffsetT(g.result)
r := new(task.Result)
r.Init(g.result, ro)
if r.ValuesLength() > 0 {
var v task.Value
for i := 0; i < r.ValuesLength(); i++ {
if ok := r.Values(&v, i); !ok {
glog.WithField("idx", i).Error("While loading value")
return fmt.Errorf("While parsing value at index: %v", i)
}
var i interface{}
if err := posting.ParseValue(i, v.ValBytes()); err != nil {
x.Log(glog, err).Error("While parsing value")
return err
}
result[i][g.Attr] = i
}
}
if r.UidsLength() > 0 {
rlist := make([]map[string]interface{}, r.UidsLength())
for i := 0; i < r.UidsLength(); i++ {
rlist[i]["uid"] = r.Uids(i)
for _, cg := range g.Children {
if err := processChild(&rlist, cg); err != nil {
x.Log(glog, err).Error("While processing child with attr: %v", cg.Attr)
return err
}
}
}
}
}
func (sg SubGraph) ToJson() (result []byte, rerr error) {
ro := flatbuffers.GetUOffsetT(sg.result)
r := new(task.Result)
r.Init(sg.result, ro)
rlist := make([]map[string]interface{}, r.UidsLength())
for i := 0; i < r.UidsLength(); i++ {
rlist[i]["uid"] = r.Uids(i)
}
}
func NewGraph(euid uint64, exid string) (*SubGraph, error) {
// This would set the Result field in SubGraph,
// and populate the children for attributes.
if len(exid) > 0 {
u, err := uid.GetOrAssign(exid)
x.Err(log, err).WithField("xid", exid).Error(
"While GetOrAssign uid from external id")
return nil, err
log.WithField("xid", exid).WithField("uid", u).Debug("GetOrAssign")
euid = u
if euid == 0 {
err := fmt.Errorf("Query internal id is zero")
x.Err(log, err).Error("Invalid query")
return nil, err
// Encode uid into result flatbuffer.
b := flatbuffers.NewBuilder(0)
task.ResultStartUidsVector(b, 1)
b.PrependUint64(euid)
vend := b.EndVector(1)
task.ResultStart(b)
task.ResultAddUids(b, vend)
rend := task.ResultEnd(b)
b.Finish(rend)
sg := new(SubGraph)
sg.result = b.Bytes[b.Head():]
return sg, nil
Manish R Jain
committed
}
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
func createTaskQuery(attr string, r *task.Result) []byte {
b := flatbuffers.NewBuilder(0)
ao := b.CreateString(attr)
task.QueryStartUidsVector(b, r.UidsLength())
for i := r.UidsLength() - 1; i >= 0; i-- {
uid := r.Uids(i)
b.PrependUint64(uid)
}
vend := b.EndVector(r.UidsLength())
task.QueryStart(b)
task.QueryAddAttr(b, ao)
task.QueryAddUids(b, vend)
qend := task.QueryEnd(b)
b.Finish(qend)
return b.Bytes[b.Head():]
}
func ProcessGraph(sg *SubGraph, rch chan error) {
var err error
if len(sg.query) > 0 {
// This task execution would go over the wire in later versions.
sg.result, err = posting.ProcessTask(sg.query)
if err != nil {
rch <- err
return
}
}
uo := flatbuffers.GetUOffsetT(sg.result)
r := new(task.Result)
r.Init(sg.result, uo)
if r.UidsLength() == 0 {
// Looks like we're done here.
if len(sg.Children) > 0 {
log.Debug("Have some children but no results. Life got cut short early.")
}
rch <- nil
return
}
// Let's execute it in a tree fashion. Each SubGraph would break off
// as many goroutines as it's children; which would then recursively
// do the same thing.
// Buffered channel to ensure no-blockage.
childchan := make(chan error, len(sg.Children))
for i := 0; i < len(sg.Children); i++ {
child := sg.Children[i]
child.query = createTaskQuery(child.Attr, r)
go ProcessGraph(child, childchan)
}
// Now get all the results back.
for i := 0; i < len(sg.Children); i++ {
err = <-childchan
if err != nil {
rch <- err
return
}
}
rch <- nil
}