/
get_kind_class.go
378 lines (328 loc) · 11.5 KB
/
get_kind_class.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
/* _ _
*__ _____ __ ___ ___ __ _| |_ ___
*\ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
* \ V V / __/ (_| |\ V /| | (_| | || __/
* \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
*
* Copyright © 2016 - 2019 Weaviate. All rights reserved.
* LICENSE: https://github.com/creativesoftwarefdn/weaviate/blob/develop/LICENSE.md
* DESIGN & CONCEPT: Bob van Luijt (@bobvanluijt)
* CONTACT: hello@creativesoftwarefdn.org
*/
package get
import (
"fmt"
"regexp"
"strings"
"github.com/creativesoftwarefdn/weaviate/database/schema"
"github.com/creativesoftwarefdn/weaviate/database/schema/kind"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/common"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/descriptions"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/local/common_filters"
"github.com/creativesoftwarefdn/weaviate/graphqlapi/local/get/refclasses"
"github.com/creativesoftwarefdn/weaviate/models"
"github.com/creativesoftwarefdn/weaviate/network/common/peers"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/language/ast"
)
// Build a single class in Local -> Get -> (k kind.Kind) -> (models.SemanticSchemaClass)
func buildGetClass(dbSchema *schema.Schema, k kind.Kind, class *models.SemanticSchemaClass,
knownClasses *map[string]*graphql.Object, knownRefClasses refclasses.ByNetworkClass,
peers peers.Peers) (*graphql.Field, error) {
classObject := buildGetClassObject(k.Name(), class, dbSchema, knownClasses, knownRefClasses, peers)
(*knownClasses)[class.Class] = classObject
classField := buildGetClassField(classObject, k, class)
return &classField, nil
}
func buildGetClassObject(kindName string, class *models.SemanticSchemaClass, dbSchema *schema.Schema,
knownClasses *map[string]*graphql.Object, knownRefClasses refclasses.ByNetworkClass,
peers peers.Peers) *graphql.Object {
return graphql.NewObject(graphql.ObjectConfig{
Name: class.Class,
Fields: (graphql.FieldsThunk)(func() graphql.Fields {
classProperties := graphql.Fields{}
classProperties["uuid"] = &graphql.Field{
Description: descriptions.LocalGetClassUUID,
Type: graphql.String,
}
for _, property := range class.Properties {
propertyType, err := dbSchema.FindPropertyDataType(property.AtDataType)
if err != nil {
// We can't return an error in this FieldsThunk function, so we need to panic
panic(fmt.Sprintf("buildGetClass: wrong propertyType for %s.%s.%s; %s",
kindName, class.Class, property.Name, err.Error()))
}
var field *graphql.Field
var fieldName string
if propertyType.IsPrimitive() {
fieldName = property.Name
field = buildPrimitiveField(propertyType, property, kindName, class.Class)
} else {
// uppercase key because it's a reference
fieldName = strings.Title(property.Name)
field = buildReferenceField(propertyType, property, kindName, class.Class, knownClasses, knownRefClasses, peers)
}
classProperties[fieldName] = field
}
return classProperties
}),
Description: class.Description,
})
}
func buildPrimitiveField(propertyType schema.PropertyDataType,
property *models.SemanticSchemaClassProperty, kindName, className string) *graphql.Field {
switch propertyType.AsPrimitive() {
case schema.DataTypeString:
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source.(map[string]interface{})[p.Info.FieldName], nil
},
}
case schema.DataTypeText:
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: graphql.String,
}
case schema.DataTypeInt:
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: graphql.Int,
}
case schema.DataTypeNumber:
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: graphql.Float,
}
case schema.DataTypeBoolean:
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: graphql.Boolean,
}
case schema.DataTypeDate:
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: graphql.String, // String since no graphql date datatype exists
}
case schema.DataTypeGeoCoordinates:
obj := newGeoCoordinatesObject(className, property.Name)
return &graphql.Field{
Description: property.Description,
Name: property.Name,
Type: obj,
Resolve: resolveGeoCoordinates,
}
default:
panic(fmt.Sprintf("buildGetClass: unknown primitive type for %s.%s.%s; %s",
kindName, className, property.Name, propertyType.AsPrimitive()))
}
}
func newGeoCoordinatesObject(className string, propertyName string) *graphql.Object {
return graphql.NewObject(graphql.ObjectConfig{
Description: "GeoCoordinates as latitude and longitude in decimal form",
Name: fmt.Sprintf("%s%sGeoCoordinatesObj", className, propertyName),
Fields: graphql.Fields{
"latitude": &graphql.Field{
Name: "Latitude",
Description: "The Latitude of the point in decimal form.",
Type: graphql.Float,
},
"longitude": &graphql.Field{
Name: "Longitude",
Description: "The Longitude of the point in decimal form.",
Type: graphql.Float,
},
},
})
}
func resolveGeoCoordinates(p graphql.ResolveParams) (interface{}, error) {
field := p.Source.(map[string]interface{})[p.Info.FieldName]
if field == nil {
return nil, nil
}
geo, ok := field.(*models.GeoCoordinates)
if !ok {
return nil, fmt.Errorf("expected a *models.GeoCoordinates, but got: %T", field)
}
return map[string]interface{}{
"latitude": geo.Latitude,
"longitude": geo.Longitude,
}, nil
}
func buildGetClassField(classObject *graphql.Object, k kind.Kind,
class *models.SemanticSchemaClass) graphql.Field {
kindName := strings.Title(k.Name())
return graphql.Field{
Type: graphql.NewList(classObject),
Description: class.Description,
Args: graphql.FieldConfigArgument{
"first": &graphql.ArgumentConfig{
Description: descriptions.First,
Type: graphql.Int,
},
"after": &graphql.ArgumentConfig{
Description: descriptions.After,
Type: graphql.Int,
},
"where": &graphql.ArgumentConfig{
Description: descriptions.LocalGetWhere,
Type: graphql.NewInputObject(
graphql.InputObjectConfig{
Name: fmt.Sprintf("WeaviateLocalGet%ss%sWhereInpObj", kindName, class.Class),
Fields: common_filters.BuildNew(fmt.Sprintf("WeaviateLocalGet%ss%s", kindName, class.Class)),
Description: descriptions.LocalGetWhereInpObj,
},
),
},
},
Resolve: makeResolveGetClass(k, class.Class),
}
}
func makeResolveGetClass(k kind.Kind, className string) graphql.FieldResolveFn {
return func(p graphql.ResolveParams) (interface{}, error) {
filtersAndResolver := p.Source.(*filtersAndResolver)
pagination, err := common.ExtractPaginationFromArgs(p.Args)
if err != nil {
return nil, err
}
// There can only be exactly one ast.Field; it is the class name.
if len(p.Info.FieldASTs) != 1 {
panic("Only one Field expected here")
}
selectionsOfClass := p.Info.FieldASTs[0].SelectionSet
properties, err := extractProperties(selectionsOfClass, p.Info.Fragments)
if err != nil {
return nil, err
}
filters, err := common_filters.ExtractFilters(p.Args, p.Info.FieldName)
if err != nil {
return nil, fmt.Errorf("could not extract filters: %s", err)
}
params := Params{
Filters: filters,
Kind: k,
ClassName: className,
Pagination: pagination,
Properties: properties,
}
return func() (interface{}, error) {
return filtersAndResolver.resolver.LocalGetClass(¶ms)
}, nil
}
}
func isPrimitive(selectionSet *ast.SelectionSet) bool {
if selectionSet == nil {
return true
}
// if there is a selection set it could either be a cross-ref or a map-type
// field like GeoCoordinates
for _, subSelection := range selectionSet.Selections {
if subsectionField, ok := subSelection.(*ast.Field); ok {
if subsectionField.Name.Value == "latitude" || subsectionField.Name.Value == "longitude" {
return true
}
}
}
// must be a ref field
return false
}
func extractProperties(selections *ast.SelectionSet, fragments map[string]ast.Definition) ([]SelectProperty, error) {
var properties []SelectProperty
for _, selection := range selections.Selections {
field := selection.(*ast.Field)
name := field.Name.Value
property := SelectProperty{Name: name}
property.IsPrimitive = isPrimitive(field.SelectionSet)
if !property.IsPrimitive {
// We can interpret this property in different ways
for _, subSelection := range field.SelectionSet.Selections {
switch s := subSelection.(type) {
case *ast.Field:
// Is it a field with the name __typename?
if s.Name.Value == "__typename" {
property.IncludeTypeName = true
continue
} else {
return nil, fmt.Errorf("Expected a InlineFragment, not a '%s' field ", s.Name.Value)
}
case *ast.FragmentSpread:
ref, err := extractFragmentSpread(s, fragments)
if err != nil {
return nil, err
}
property.Refs = append(property.Refs, ref)
case *ast.InlineFragment:
ref, err := extractInlineFragment(s, fragments)
if err != nil {
return nil, err
}
property.Refs = append(property.Refs, ref)
default:
return nil, fmt.Errorf("unrecoginzed type in subs-selection: %T", subSelection)
}
}
}
properties = append(properties, property)
}
return properties, nil
}
func extractInlineFragment(fragment *ast.InlineFragment, fragments map[string]ast.Definition) (SelectClass, error) {
var className schema.ClassName
var err error
var result SelectClass
if strings.Contains(fragment.TypeCondition.Name.Value, "__") {
// is a helper type for a network ref
// don't validate anything as of now
className = schema.ClassName(fragment.TypeCondition.Name.Value)
} else {
err, className = schema.ValidateClassName(fragment.TypeCondition.Name.Value)
if err != nil {
return result, fmt.Errorf("the inline fragment type name '%s' is not a valid class name", fragment.TypeCondition.Name.Value)
}
}
subProperties, err := extractProperties(fragment.SelectionSet, fragments)
if err != nil {
return result, err
}
result.ClassName = string(className)
result.RefProperties = subProperties
return result, nil
}
func extractFragmentSpread(spread *ast.FragmentSpread, fragments map[string]ast.Definition) (SelectClass, error) {
var result SelectClass
name := spread.Name.Value
def, ok := fragments[name]
if !ok {
return result, fmt.Errorf("spread fragment '%s' refers to unknown fragment", name)
}
className, err := hackyWorkaroundToExtractClassName(def, name)
if err != nil {
return result, err
}
subProperties, err := extractProperties(def.GetSelectionSet(), fragments)
if err != nil {
return result, err
}
result.ClassName = string(className)
result.RefProperties = subProperties
return result, nil
}
// It seems there's no proper way to extract this info unfortunately:
// https://github.com/graphql-go/graphql/issues/455
func hackyWorkaroundToExtractClassName(def ast.Definition, name string) (string, error) {
loc := def.GetLoc()
raw := loc.Source.Body[loc.Start:loc.End]
r := regexp.MustCompile(fmt.Sprintf(`fragment\s*%s\s*on\s*(\w*)\s*{`, name))
matches := r.FindSubmatch(raw)
if len(matches) < 2 {
return "", fmt.Errorf("could not extract a className from fragment")
}
return string(matches[1]), nil
}