-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
introspec.go
689 lines (600 loc) · 19 KB
/
introspec.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
package core
import (
"fmt"
"strings"
"github.com/chirino/graphql"
"github.com/chirino/graphql/resolvers"
"github.com/chirino/graphql/schema"
"github.com/dosco/graphjin/core/internal/sdata"
"github.com/dosco/graphjin/core/internal/util"
)
var typeMap map[string]string = map[string]string{
"smallint": "Int",
"integer": "Int",
"bigint": "Int",
"smallserial": "Int",
"serial": "Int",
"bigserial": "Int",
"decimal": "Float",
"numeric": "Float",
"real": "Float",
"double precision": "Float",
"money": "Float",
"boolean": "Boolean",
}
type expInfo struct {
name, vtype string
list bool
desc, db string
}
const (
likeDesc = "Value matching pattern where '%' represents zero or more characters and '_' represents a single character. Eg. '_r%' finds values having 'r' in second position"
notLikeDesc = "Value not matching pattern where '%' represents zero or more characters and '_' represents a single character. Eg. '_r%' finds values not having 'r' in second position"
iLikeDesc = "Value matching (case-insensitive) pattern where '%' represents zero or more characters and '_' represents a single character. Eg. '_r%' finds values having 'r' in second position"
notILikeDesc = "Value not matching (case-insensitive) pattern where '%' represents zero or more characters and '_' represents a single character. Eg. '_r%' finds values not having 'r' in second position"
similarDesc = "Value matching regex pattern. Similar to the 'like' operator but with support for regex. Pattern must match entire value."
notSimilarDesc = "Value not matching regex pattern. Similar to the 'like' operator but with support for regex. Pattern must not match entire value."
)
var expList []expInfo = []expInfo{
{"eq", "", false, "Equals value", ""},
{"equals", "", false, "Equals value", ""},
{"neq", "", false, "Does not equal value", ""},
{"not_equals", "", false, "Does not equal value", ""},
{"gt", "", false, "Is greater than value", ""},
{"greater_than", "", false, "Is greater than value", ""},
{"lt", "", false, "Is lesser than value", ""},
{"lesser_than", "", false, "Is lesser than value", ""},
{"gte", "", false, "Is greater than or equals value", ""},
{"greater_or_equals", "", false, "Is greater than or equals value", ""},
{"lte", "", false, "Is lesser than or equals value", ""},
{"lesser_or_equals", "", false, "Is lesser than or equals value", ""},
{"in", "", true, "Is in list of values", ""},
{"nin", "", true, "Is not in list of values", ""},
{"not_in", "", true, "Is not in list of values", ""},
{"like", "String", false, likeDesc, ""},
{"nlike", "String", false, notLikeDesc, ""},
{"not_like", "String", false, notLikeDesc, ""},
{"ilike", "String", false, iLikeDesc, ""},
{"nilike", "String", false, notILikeDesc, ""},
{"not_ilike", "String", false, notILikeDesc, ""},
{"similar", "String", false, similarDesc, ""},
{"nsimilar", "String", false, notSimilarDesc, ""},
{"not_similar", "String", false, notSimilarDesc, ""},
{"regex", "String", false, "Value matches regex pattern", ""},
{"nregex", "String", false, "Value not matching regex pattern", ""},
{"not_regex", "String", false, "Value not matching regex pattern", ""},
{"iregex", "String", false, "Value matches (case-insensitive) regex pattern", ""},
{"niregex", "String", false, "Value not matching (case-insensitive) regex pattern", ""},
{"not_iregex", "String", false, "Value not matching (case-insensitive) regex pattern", ""},
{"has_key", "", false, "JSON value contains this key", ""},
{"has_key_any", "", true, "JSON value contains any of these keys", ""},
{"has_key_all", "", true, "JSON value contains all of these keys", ""},
{"contains", "", false, "JSON value matches any of they key/value pairs", ""},
{"contained_in", "", false, "JSON value contains all of they key/value pairs", ""},
{"is_null", "Boolean", false, "Is value null (true) or not null (false)", ""},
}
type funcInfo struct {
name, desc, db string
}
var funcCount = funcInfo{"count", "Count the number of rows", ""}
var funcListNum []funcInfo = []funcInfo{
{"avg", "Calculate an average %s", ""},
{"max", "Find the maximum %s", ""},
{"min", "Find the minimum %s", ""},
{"stddev", "Calculate the standard deviation of %s values", ""},
{"stddev_pop", "Calculate the population standard deviation of %s values", ""},
{"stddev_samp", "Calculate the sample standard deviation of %s values", ""},
{"variance", "Calculate the sample variance of %s values", ""},
{"var_samp", "Calculate the sample variance of %s values", ""},
{"var_pop", "Calculate the population sample variance of %s values", ""},
}
var funcListString []funcInfo = []funcInfo{
{"length", "Calculate the length of %s", ""},
{"lower", "Convert %s to lowercase", ""},
{"upper", "Convert %s to uppercase", ""},
}
type intro struct {
*schema.Schema
*sdata.DBSchema
gj *GraphJin
query *schema.Object
mutation *schema.Object
subscription *schema.Object
exptNeeded map[string]bool
}
func (gj *GraphJin) initGraphQLEgine() error {
if gj.prod {
return nil
}
engine := graphql.New()
in := &intro{
Schema: engine.Schema,
DBSchema: gj.schema,
gj: gj,
query: &schema.Object{Name: "Query", Fields: schema.FieldList{}},
mutation: &schema.Object{Name: "Mutation", Fields: schema.FieldList{}},
subscription: &schema.Object{Name: "Subscribe", Fields: schema.FieldList{}},
exptNeeded: map[string]bool{},
}
in.Types[in.query.Name] = in.query
in.Types[in.mutation.Name] = in.mutation
in.Types[in.subscription.Name] = in.subscription
in.EntryPoints[schema.Query] = in.query
in.EntryPoints[schema.Mutation] = in.mutation
in.EntryPoints[schema.Subscription] = in.subscription
in.Types["OrderDirection"] = &schema.Enum{Name: "OrderDirection", Values: []*schema.EnumValue{
{
Name: "asc",
Desc: schema.NewDescription("Ascending"),
}, {
Name: "desc",
Desc: schema.NewDescription("Descending"),
},
}}
in.Types["Cursor"] = &schema.Scalar{
Name: "Cursor",
Desc: schema.NewDescription("A cursor is an encoded string use for pagination"),
}
if err := in.addTables(); err != nil {
return err
}
in.addExpressions()
in.addDirectives()
if err := in.ResolveTypes(); err != nil {
return err
}
engine.Resolver = resolvers.Func(revolverFunc)
gj.ge = engine
return nil
}
func revolverFunc(request *resolvers.ResolveRequest, next resolvers.Resolution) resolvers.Resolution {
resolver := resolvers.MetadataResolver.Resolve(request, next)
if resolver != nil {
return resolver
}
resolver = resolvers.MethodResolver.Resolve(request, next) // needed by the MetadataResolver
if resolver != nil {
return resolver
}
return nil
}
func (in *intro) addTables() error {
for _, t := range in.GetTables() {
if err := in.addTable(t.Name, t, false); err != nil {
return err
}
if err := in.addTable(t.Name, t, true); err != nil {
return err
}
}
for name, t := range in.GetAliases() {
if err := in.addTable(name, t, false); err != nil {
return err
}
}
return nil
}
// func (in *intro) addToTable(name, desc string, ti sdata.DBTable) {
// k := name + "Output"
// var ot *schema.Object = in.Types[k].(*schema.Object)
// ot.Fields = append(ot.Fields, &schema.Field{
// Name: ti.Name,
// Type: &schema.TypeName{Name: ti.Name + "Output"},
// Desc: schema.NewDescription(desc),
// })
// }
func (in *intro) addTable(name string, ti sdata.DBTable, singular bool) error {
if ti.Blocked {
return nil
}
if len(ti.Columns) == 0 {
return nil
}
if singular {
name = name + in.SingularSuffix
}
if in.gj.conf.EnableCamelcase {
name = util.ToCamel(name)
}
// outputType
ot := &schema.Object{
Name: name + "Output", Fields: schema.FieldList{},
}
in.Types[ot.Name] = ot
// inputType
it := &schema.InputObject{
Name: name + "Input", Fields: schema.InputValueList{},
}
in.Types[it.Name] = it
// orderByType
obt := &schema.InputObject{
Name: name + "OrderBy", Fields: schema.InputValueList{},
}
in.Types[obt.Name] = obt
ot.Fields = append(ot.Fields, &schema.Field{
Name: name,
Type: &schema.NonNull{OfType: &schema.List{OfType: &schema.NonNull{OfType: &schema.TypeName{Name: name + "Output"}}}},
})
// expressionType
exptName := name + "Expression"
expt := &schema.InputObject{
Name: exptName,
Fields: schema.InputValueList{
&schema.InputValue{
Name: "and",
Type: &schema.TypeName{Name: exptName},
},
&schema.InputValue{
Name: "or",
Type: &schema.TypeName{Name: exptName},
},
&schema.InputValue{
Name: "not",
Type: &schema.TypeName{Name: exptName},
},
},
}
in.Types[expt.Name] = expt
for _, col := range ti.Columns {
in.addColumn(name, ti, col, it, obt, expt, ot, singular)
}
relTables1, err := in.GetFirstDegree(ti.Schema, ti.Name)
if err != nil {
return err
}
for k, t := range relTables1 {
k1 := t.Name + "Output"
if _, ok := in.Types[k1]; !ok {
continue
}
if t.Blocked {
continue
}
ot.Fields = append(ot.Fields, &schema.Field{
Name: k,
Type: &schema.TypeName{Name: k1},
})
}
relTables2, err := in.GetSecondDegree(ti.Schema, ti.Name)
if err != nil {
return err
}
for k, t := range relTables2 {
k1 := t.Name + "Output"
if _, ok := in.Types[k1]; !ok {
continue
}
if t.Blocked {
continue
}
ot.Fields = append(ot.Fields, &schema.Field{
Name: k,
Type: &schema.TypeName{Name: k1},
})
}
return nil
}
func (in *intro) addDirectives() {
in.DeclaredDirectives["object"] = &schema.DirectiveDecl{
Name: "object",
Desc: schema.NewDescription("Directs the executor to change the return type from a list to a object. All but the first entry of the list will be truncated"),
Locs: []string{"FIELD"},
}
in.DeclaredDirectives["through"] = &schema.DirectiveDecl{
Name: "through",
Desc: schema.NewDescription("Directs the executor to use the specified table as a join-table to connect this field and it's parent"),
Locs: []string{"FIELD"},
Args: schema.InputValueList{
{
Name: "table",
Desc: schema.NewDescription("Table name"),
Type: &schema.TypeName{Name: "String"},
},
},
}
in.DeclaredDirectives["script"] = &schema.DirectiveDecl{
Name: "script",
Desc: schema.NewDescription("Script the executor to use run specified script against this GraphQL request"),
Locs: []string{"QUERY", "MUTATION", "SUBSCRIPTION"},
Args: schema.InputValueList{
{
Name: "name",
Desc: schema.NewDescription("Script name"),
Type: &schema.TypeName{Name: "String"},
},
},
}
in.DeclaredDirectives["notRelated"] = &schema.DirectiveDecl{
Name: "notRelated",
Desc: schema.NewDescription("Directs the executor to treat this selector as if it were the top-level selector with no relation to its parent"),
Locs: []string{"FIELD"},
}
in.DeclaredDirectives["cacheControl"] = &schema.DirectiveDecl{
Name: "cacheControl",
Desc: schema.NewDescription("Directs the executor to set the cache-control header when GET (APQ) requests are used for the query"),
Locs: []string{"QUERY", "MUTATION", "SUBSCRIPTION"},
Args: schema.InputValueList{
{
Name: "maxAge",
Desc: schema.NewDescription("The maximum amount of time (in seconds) a resource is considered fresh"),
Type: &schema.TypeName{Name: "Int"},
},
{
Name: "scope",
Desc: schema.NewDescription("Set to 'public' when any cache can store the data and 'private' when only the browser cache should"),
Type: &schema.TypeName{Name: "String"},
},
},
}
}
func (in *intro) addColumn(
tableName string,
ti sdata.DBTable, col sdata.DBColumn,
it, obt, expt *schema.InputObject, ot *schema.Object, singular bool) {
colName := col.Name
if col.Blocked {
return
}
if in.gj.conf.EnableCamelcase {
colName = util.ToCamel(colName)
}
colType, typeName := getGQLType(col)
ot.Fields = append(ot.Fields, &schema.Field{
Name: colName,
Type: colType,
})
in.addFuncs(colName, typeName, colType, ti, col, it, obt, expt, ot, singular)
in.addArgs(tableName, ti, col, it, obt, expt, ot, singular)
it.Fields = append(it.Fields, &schema.InputValue{
Name: colName,
Type: colType,
})
obt.Fields = append(obt.Fields, &schema.InputValue{
Name: colName,
Type: &schema.TypeName{Name: "OrderDirection"},
})
in.exptNeeded[typeName] = true
expt.Fields = append(expt.Fields, &schema.InputValue{
Name: colName,
Type: &schema.TypeName{Name: typeName + "Expression"},
})
}
func (in *intro) addFuncs(
colName string,
typeName string,
colType schema.Type,
ti sdata.DBTable, col sdata.DBColumn,
it, obt, expt *schema.InputObject, ot *schema.Object, singular bool) {
var fn string
if in.gj.conf.DisableFuncs {
return
}
if col.PrimaryKey && !in.gj.conf.DisableAgg {
fn = funcCount.name + "_" + colName
if in.gj.conf.EnableCamelcase {
fn = util.ToCamel(fn)
}
ot.Fields = append(ot.Fields, &schema.Field{
Name: fn,
Type: colType,
Desc: schema.NewDescription(funcCount.desc),
})
}
// No functions on foreign key columns
if col.FKeyCol == "" {
// If it's a numeric type...
if !in.gj.conf.DisableAgg {
if typeName == "Float" || typeName == "Int" {
for _, v := range funcListNum {
fn = funcCount.name + "_" + colName
if in.gj.conf.EnableCamelcase {
fn = util.ToCamel(fn)
}
desc := fmt.Sprintf(v.desc, colName)
ot.Fields = append(ot.Fields, &schema.Field{
Name: fn,
Type: colType,
Desc: schema.NewDescription(desc),
})
}
}
}
if typeName == "String" {
for _, v := range funcListString {
fn = funcCount.name + "_" + colName
if in.gj.conf.EnableCamelcase {
fn = util.ToCamel(fn)
}
desc := fmt.Sprintf(v.desc, colName)
ot.Fields = append(ot.Fields, &schema.Field{
Name: fn,
Type: colType,
Desc: schema.NewDescription(desc),
})
}
}
for _, f := range in.GetFunctions() {
if col.Type != f.Params[0].Type {
continue
}
fn = funcCount.name + "_" + colName
if in.gj.conf.EnableCamelcase {
fn = util.ToCamel(fn)
}
ot.Fields = append(ot.Fields, &schema.Field{
Name: fn,
Type: colType,
})
}
}
}
func (in *intro) addArgs(
name string,
ti sdata.DBTable, col sdata.DBColumn,
it, obt, expt *schema.InputObject, ot *schema.Object, singular bool) {
otName := &schema.TypeName{Name: ot.Name}
itName := &schema.TypeName{Name: it.Name}
potName := &schema.List{OfType: &schema.NonNull{OfType: &schema.TypeName{Name: ot.Name}}}
pitName := &schema.List{OfType: &schema.NonNull{OfType: &schema.TypeName{Name: it.Name}}}
var args schema.InputValueList
if !singular {
args = schema.InputValueList{
&schema.InputValue{
Desc: schema.NewDescription("Sort or order results. Use key 'asc' for ascending and 'desc' for descending"),
Name: "order_by",
Type: &schema.TypeName{Name: obt.Name},
},
&schema.InputValue{
Desc: schema.NewDescription("Filter results based on column values or values of columns in related tables"),
Name: "where",
Type: &schema.TypeName{Name: expt.Name},
},
&schema.InputValue{
Desc: schema.NewDescription("Limit the number of returned rows"),
Name: "limit",
Type: &schema.TypeName{Name: "Int"},
},
&schema.InputValue{
Desc: schema.NewDescription("Offset the number of returned rows (Not efficient for pagination, please use a cursor for that)"),
Name: "offset",
Type: &schema.TypeName{Name: "Int"},
},
&schema.InputValue{
Desc: schema.NewDescription("Number of rows to return from the top. Combine with 'after' or 'before' arguments for cursor pagination"),
Name: "first",
Type: &schema.TypeName{Name: "Int"},
},
&schema.InputValue{
Desc: schema.NewDescription("Number of rows to return from the bottom. Combine with 'after' or 'before' arguments for cursor pagination"),
Name: "last",
Type: &schema.TypeName{Name: "Int"},
},
&schema.InputValue{
Desc: schema.NewDescription("Pass the cursor to this argument for backward pagination"),
Name: "before",
Type: &schema.TypeName{Name: "Cursor"},
},
&schema.InputValue{
Desc: schema.NewDescription("Pass the cursor to this argument for forward pagination"),
Name: "after",
Type: &schema.TypeName{Name: "Cursor"},
},
}
if len(ti.FullText) == 0 {
args = append(args, &schema.InputValue{
Desc: schema.NewDescription("Performs a full text search"),
Name: "search",
Type: &schema.TypeName{Name: "String"},
})
}
}
if ti.PrimaryCol.Name != "" && singular {
colType, _ := getGQLType(ti.PrimaryCol)
args = append(args, &schema.InputValue{
Desc: schema.NewDescription("Finds the record by the primary key"),
Name: "id",
Type: colType,
})
}
if singular {
in.query.Fields = append(in.query.Fields, &schema.Field{
//Desc: schema.NewDescription(""),
Name: name,
Type: otName,
Args: args,
})
in.subscription.Fields = append(in.subscription.Fields, &schema.Field{
//Desc: schema.NewDescription(""),
Name: name,
Type: otName,
Args: args,
})
} else {
in.query.Fields = append(in.query.Fields, &schema.Field{
//Desc: schema.NewDescription(""),
Name: name,
Type: potName,
Args: args,
})
in.subscription.Fields = append(in.subscription.Fields, &schema.Field{
//Desc: schema.NewDescription(""),
Name: name,
Type: potName,
Args: args,
})
}
mutationArgs := append(args, schema.InputValueList{
&schema.InputValue{
Desc: schema.NewDescription(fmt.Sprintf("Insert row into table %s", name)),
Name: "insert",
Type: pitName,
},
&schema.InputValue{
Desc: schema.NewDescription(fmt.Sprintf("Update row in table %s", name)),
Name: "update",
Type: itName,
},
&schema.InputValue{
Desc: schema.NewDescription(fmt.Sprintf("Update or Insert row in table %s", name)),
Name: "upsert",
Type: itName,
},
&schema.InputValue{
Desc: schema.NewDescription(fmt.Sprintf("Delete row from table %s", name)),
Name: "delete",
Type: &schema.NonNull{OfType: &schema.TypeName{Name: "Boolean"}},
},
}...)
in.mutation.Fields = append(in.mutation.Fields, &schema.Field{
Name: name,
Args: mutationArgs,
Type: potName,
})
}
func (in *intro) addExpressions() {
// scalarExpressionTypesNeeded
for typeName := range in.exptNeeded {
var fields schema.InputValueList
for _, v := range expList {
vtype := v.vtype
if v.vtype == "" {
vtype = typeName
}
iv := &schema.InputValue{
Name: v.name,
Desc: schema.NewDescription(v.desc),
Type: &schema.TypeName{Name: vtype},
}
if v.list {
iv.Type = &schema.List{OfType: iv.Type}
}
fields = append(fields, iv)
}
ext := &schema.InputObject{
Name: typeName + "Expression",
Fields: fields,
}
in.Types[ext.Name] = ext
}
}
func getGQLType(col sdata.DBColumn) (schema.Type, string) {
var typeName string
var ok bool
k := strings.ToLower(col.Type)
if i := strings.IndexAny(k, "(["); i != -1 {
k = k[:i]
}
if col.PrimaryKey {
typeName = "ID"
} else if typeName, ok = typeMap[k]; !ok {
typeName = "String"
}
var t schema.Type = &schema.TypeName{Name: typeName}
if col.Array {
t = &schema.List{OfType: t}
}
// if col.NotNull {
// t = &schema.NonNull{OfType: t}
// }
return t, typeName
}