-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathschemagen.go
424 lines (376 loc) · 11.7 KB
/
schemagen.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
/*
* Copyright 2019 Dgraph Labs, Inc. and Contributors
*
* 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 schema
import (
"fmt"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
"github.com/vektah/gqlparser/v2/parser"
"github.com/vektah/gqlparser/v2/validator"
)
// A Handler can produce valid GraphQL and Dgraph schemas given an input of
// types and relationships
type Handler interface {
DGSchema() string
GQLSchema() string
}
type handler struct {
input string
originalDefs []string
completeSchema *ast.Schema
dgraphSchema string
}
// FromString builds a GraphQL Schema from input string, or returns any parsing
// or validation errors.
func FromString(schema string) (Schema, error) {
// validator.Prelude includes a bunch of predefined types which help with schema introspection
// queries, hence we include it as part of the schema.
doc, gqlErr := parser.ParseSchemas(validator.Prelude, &ast.Source{Input: schema})
if gqlErr != nil {
return nil, errors.Wrap(gqlErr, "while parsing GraphQL schema")
}
gqlSchema, gqlErr := validator.ValidateSchemaDocument(doc)
if gqlErr != nil {
return nil, errors.Wrap(gqlErr, "while validating GraphQL schema")
}
return AsSchema(gqlSchema), nil
}
func (s *handler) GQLSchema() string {
return Stringify(s.completeSchema, s.originalDefs)
}
func (s *handler) DGSchema() string {
return s.dgraphSchema
}
// NewHandler processes the input schema. If there are no errors, it returns
// a valid Handler, otherwise it returns nil and an error.
func NewHandler(input string) (Handler, error) {
if input == "" {
return nil, gqlerror.Errorf("No schema specified")
}
// The input schema contains just what's required to describe the types,
// relationships and searchability - but that's not enough to define a
// valid GraphQL schema: e.g. we allow an input schema file like
//
// type T {
// f: Int @search
// }
//
// But, that's not valid GraphQL unless there's also definitions of scalars
// (Int, String, etc) and definitions of the directives (@search, etc).
// We don't want to make the user have those in their file and then we have
// to check that they've made the right definitions, etc, etc.
//
// So we parse the original input of just types and relationships and
// run a validation to make sure it only contains things that it should.
// To that we add all the scalars and other definitions we always require.
//
// Then, we GraphQL validate to make sure their definitions plus our additions
// is GraphQL valid. At this point we know the definitions are GraphQL valid,
// but we need to check if it makes sense to our layer.
//
// The next final validation ensures that the definitions are made
// in such a way that our GraphQL API will be able to interpret the schema
// correctly.
//
// Then we can complete the process by adding in queries and mutations etc. to
// make the final full GraphQL schema.
doc, gqlErr := parser.ParseSchemas(validator.Prelude, &ast.Source{Input: input})
if gqlErr != nil {
return nil, gqlerror.List{gqlErr}
}
gqlErrList := preGQLValidation(doc)
if gqlErrList != nil {
return nil, gqlErrList
}
defns := make([]string, 0, len(doc.Definitions))
for _, defn := range doc.Definitions {
if defn.BuiltIn {
continue
}
defns = append(defns, defn.Name)
}
expandSchema(doc)
sch, gqlErr := validator.ValidateSchemaDocument(doc)
if gqlErr != nil {
return nil, gqlerror.List{gqlErr}
}
gqlErrList = postGQLValidation(sch, defns)
if gqlErrList != nil {
return nil, gqlErrList
}
dgSchema, gqlErrList := genDgSchema(sch, defns)
if gqlErrList != nil {
return nil, gqlErrList
}
completeSchema(sch, defns)
return &handler{
input: input,
dgraphSchema: dgSchema,
completeSchema: sch,
originalDefs: defns,
}, nil
}
func getAllSearchIndexes(val *ast.Value) []string {
res := make([]string, len(val.Children))
for i, child := range val.Children {
res[i] = supportedSearches[child.Value.Raw].dgIndex
}
return res
}
func typeName(def *ast.Definition) string {
name := def.Name
dir := def.Directives.ForName(dgraphDirective)
if dir == nil {
return name
}
typeArg := dir.Arguments.ForName(dgraphTypeArg)
if typeArg == nil {
return name
}
return typeArg.Value.Raw
}
// fieldName returns the dgraph predicate corresponding to a field.
// If the field had a dgraph directive, then it returns the value of the name field otherwise
// it returns typeName + "." + fieldName.
func fieldName(def *ast.FieldDefinition, typName string) string {
name := typName + "." + def.Name
dir := def.Directives.ForName(dgraphDirective)
if dir == nil {
return name
}
predArg := dir.Arguments.ForName(dgraphPredArg)
if predArg == nil {
return name
}
return predArg.Value.Raw
}
func getDgraphTypeError(f *ast.FieldDefinition, defName, typStr string) *gqlerror.Error {
return gqlerror.ErrorPosf(f.Position,
"Type: %s; Field: %s has its dgraph Type: %s; which is different from a previous field"+
" with same dgraph predicate.", defName, f.Name, typStr)
}
// genDgSchema generates Dgraph schema from a valid graphql schema.
func genDgSchema(gqlSch *ast.Schema, definitions []string) (string, gqlerror.List) {
var typeStrings []string
var errs []*gqlerror.Error
type dgPred struct {
typ string
gqlType string
indexes map[string]bool
upsert string
reverse string
}
type field struct {
name string
// true if the field was inherited from an interface, we don't add the predicate schema
// for it then as the it would already have been added with the interface.
inherited bool
}
type dgType struct {
name string
fields []field
}
dgTypes := make([]dgType, 0, len(definitions))
dgPreds := make(map[string]dgPred)
for _, key := range definitions {
def := gqlSch.Types[key]
switch def.Kind {
case ast.Object, ast.Interface:
typName := typeName(def)
typ := dgType{name: typName}
fd := getPasswordField(def)
for _, f := range def.Fields {
if f.Type.Name() == "ID" {
continue
}
typName = typeName(def)
// This field could have originally been defined in an interface that this type
// implements. If we get a parent interface, then we should prefix the field name
// with it instead of def.Name.
parentInt := parentInterface(gqlSch, def, f.Name)
if parentInt != nil {
typName = typeName(parentInt)
}
fname := fieldName(f, typName)
if edge, ok := dgPreds[fname]; ok && edge.gqlType != f.Type.Name() && edge.
reverse == "" {
errs = append(errs, gqlerror.ErrorPosf(f.Position,
"Type: %s; Field: %s has its GraphQL Type: %s; which is different from a"+
" previous field with same dgraph predicate.", def.Name, f.Name,
f.Type.Name()))
continue
}
var prefix, suffix string
if f.Type.Elem != nil {
prefix = "["
suffix = "]"
}
var typStr string
switch gqlSch.Types[f.Type.Name()].Kind {
case ast.Object:
typStr = fmt.Sprintf("%suid%s", prefix, suffix)
if parentInt == nil {
if strings.HasPrefix(fname, "~") {
// remove ~
forwardEdge := fname[1:]
forwardPred := dgPreds[forwardEdge]
forwardPred.reverse = "@reverse "
dgPreds[forwardEdge] = forwardPred
} else {
edge, ok := dgPreds[fname]
if ok && edge.typ != "" && edge.typ != typStr {
errs = append(errs, getDgraphTypeError(f, def.Name, typStr))
continue
} else {
edge.typ = typStr
edge.gqlType = f.Type.Name()
dgPreds[fname] = edge
}
}
}
typ.fields = append(typ.fields, field{fname, parentInt != nil})
case ast.Scalar:
typStr = fmt.Sprintf(
"%s%s%s",
prefix, scalarToDgraph[f.Type.Name()], suffix,
)
indexes := make([]string, 0)
upsertStr := ""
search := f.Directives.ForName(searchDirective)
id := f.Directives.ForName(idDirective)
if id != nil {
upsertStr = "@upsert "
indexes = []string{"hash"}
}
if search != nil {
arg := search.Arguments.ForName(searchArgs)
if arg != nil {
indexes = append(getAllSearchIndexes(arg.Value), indexes...)
} else {
indexes = append(indexes, defaultSearches[f.Type.Name()])
}
}
if parentInt == nil {
edge, ok := dgPreds[fname]
if ok && edge.typ != typStr {
errs = append(errs, getDgraphTypeError(f, def.Name, typStr))
continue
} else if !ok {
edge = dgPred{
typ: typStr,
gqlType: f.Type.Name(),
indexes: make(map[string]bool),
}
}
if edge.upsert == "" {
edge.upsert = upsertStr
}
for _, index := range indexes {
edge.indexes[index] = true
}
dgPreds[fname] = edge
}
typ.fields = append(typ.fields, field{fname, parentInt != nil})
case ast.Enum:
typStr = fmt.Sprintf("%s%s%s", prefix, "string", suffix)
indexes := []string{"hash"}
search := f.Directives.ForName(searchDirective)
if search != nil {
arg := search.Arguments.ForName(searchArgs)
if arg != nil {
indexes = getAllSearchIndexes(arg.Value)
}
}
if parentInt == nil {
edge, ok := dgPreds[fname]
if ok && edge.typ != typStr {
errs = append(errs, getDgraphTypeError(f, def.Name, typStr))
continue
} else if !ok {
edge = dgPred{
typ: typStr,
gqlType: f.Type.Name(),
indexes: make(map[string]bool),
}
}
for _, index := range indexes {
edge.indexes[index] = true
}
dgPreds[fname] = edge
}
typ.fields = append(typ.fields, field{fname, parentInt != nil})
}
}
if fd != nil {
parentInt := parentInterface(gqlSch, def, fd.Name)
if parentInt != nil {
typName = typeName(parentInt)
}
fname := fieldName(fd, typName)
typStr := "password"
if parentInt == nil {
if edge, ok := dgPreds[fname]; ok && edge.typ != typStr {
errs = append(errs, getDgraphTypeError(fd, def.Name, typStr))
continue
} else {
edge = dgPred{
typ: typStr,
gqlType: fd.Type.Name(),
}
dgPreds[fname] = edge
}
}
typ.fields = append(typ.fields, field{fname, parentInt != nil})
}
dgTypes = append(dgTypes, typ)
}
}
predWritten := make(map[string]bool, len(dgPreds))
for _, typ := range dgTypes {
var typeDef, preds strings.Builder
fmt.Fprintf(&typeDef, "type %s {\n", typ.name)
for _, fld := range typ.fields {
f, ok := dgPreds[fld.name]
if !ok {
continue
}
fmt.Fprintf(&typeDef, " %s\n", fld.name)
if !fld.inherited && !predWritten[fld.name] {
indexStr := ""
if len(f.indexes) > 0 {
indexes := make([]string, 0)
for index := range f.indexes {
indexes = append(indexes, index)
}
sort.Strings(indexes)
indexStr = fmt.Sprintf(" @index(%s)", strings.Join(indexes, ", "))
}
fmt.Fprintf(&preds, "%s: %s%s %s%s.\n", fld.name, f.typ, indexStr, f.upsert,
f.reverse)
predWritten[fld.name] = true
}
}
fmt.Fprintf(&typeDef, "}\n")
typeStrings = append(
typeStrings,
fmt.Sprintf("%s%s", typeDef.String(), preds.String()),
)
}
return strings.Join(typeStrings, ""), errs
}