forked from web-ridge/gqlgen-sqlboiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_plugin.go
executable file
·1013 lines (877 loc) · 28.6 KB
/
convert_plugin.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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gbgen
import (
"fmt"
"go/types"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"unicode"
"github.com/web-ridge/gqlgen-sqlboiler/v3/customization"
"github.com/99designs/gqlgen/codegen/config"
gqlgenTemplates "github.com/99designs/gqlgen/codegen/templates"
"github.com/99designs/gqlgen/plugin"
"github.com/iancoleman/strcase"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/vektah/gqlparser/v2/ast"
"github.com/volatiletech/strmangle"
"github.com/web-ridge/gqlgen-sqlboiler/v3/templates"
)
var pathRegex *regexp.Regexp //nolint:gochecknoglobals
func init() { //nolint:gochecknoinits
fmt.Println(" _ _____ _ _ \n | | | __ \\(_) | | \n __ _____| |__ | |__) |_ __| | __ _ ___ \n \\ \\ /\\ / / _ \\ '_ \\| _ /| |/ _` |/ _` |/ _ \\\n \\ V V / __/ |_) | | \\ \\| | (_| | (_| | __/\n \\_/\\_/ \\___|_.__/|_| \\_\\_|\\__,_|\\__, |\\___|\n __/ | \n |___/ ") //nolint:lll
fmt.Println("")
fmt.Println(" Please help us with feedback, stars and PR's to improve this plugin.")
fmt.Println(" If you don't have time for that, please donate if you like this project.")
fmt.Println(" Click the sponsor button (PayPal) on https://github.com/web-ridge/gqlgen-sqlboiler")
fmt.Println("")
pathRegex = regexp.MustCompile(`src/(.*)`)
// Default level for this example is info, unless debug flag is present
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
type Import struct {
Alias string
ImportPath string
}
type ModelBuild struct {
Backend Config
Frontend Config
PluginConfig ConvertPluginConfig
PackageName string
Interfaces []*Interface
Models []*Model
Enums []*Enum
Scalars []string
}
func (t ModelBuild) Imports() []Import {
return []Import{
{
Alias: t.Frontend.PackageName,
ImportPath: t.Frontend.Directory,
},
{
Alias: t.Backend.PackageName,
ImportPath: t.Backend.Directory,
},
}
}
type Interface struct {
Description string
Name string
}
type Preload struct {
Key string
ColumnSetting ColumnSetting
}
type Model struct { //nolint:maligned
Name string
PluralName string
BoilerModel *BoilerModel
PrimaryKeyType string
Fields []*Field
IsNormal bool
IsInput bool
IsCreateInput bool
IsUpdateInput bool
IsNormalInput bool
IsPayload bool
IsConnection bool
IsEdge bool
IsOrdering bool
IsWhere bool
IsFilter bool
IsPreloadable bool
PreloadArray []Preload
HasPrimaryStringID bool
// other stuff
Description string
PureFields []*ast.FieldDefinition
Implements []string
}
type ColumnSetting struct {
Name string
RelationshipModelName string
IDAvailable bool
}
type Field struct { //nolint:maligned
Name string
JSONName string
PluralName string
Type string
TypeWithoutPointer string
IsNumberID bool
IsPrimaryNumberID bool
IsPrimaryStringID bool
IsPrimaryID bool
IsRequired bool
IsPlural bool
ConvertConfig ConvertConfig
Enum *Enum
// relation stuff
IsRelation bool
IsObject bool
// boiler relation stuff is inside this field
BoilerField BoilerField
// graphql relation ship can be found here
Relationship *Model
IsOr bool
IsAnd bool
// Some stuff
Description string
OriginalType types.Type
}
type Enum struct {
Description string
Name string
PluralName string
Values []*EnumValue
HasBoilerEnum bool
BoilerEnum *BoilerEnum
}
type EnumValue struct {
Description string
Name string
NameLower string
BoilerEnumValue *BoilerEnumValue
}
func NewConvertPlugin(output, backend, frontend Config, pluginConfig ConvertPluginConfig) plugin.Plugin {
return &ConvertPlugin{
Output: output,
Backend: backend,
Frontend: frontend,
PluginConfig: pluginConfig,
rootImportPath: getRootImportPath(),
}
}
type ConvertPlugin struct {
Output Config
Backend Config
Frontend Config
PluginConfig ConvertPluginConfig
rootImportPath string
}
type Config struct {
Directory string
PackageName string
}
type ConvertPluginConfig struct {
UseReflectWorkaroundForSubModelFilteringInPostgresIssue25 bool
}
var _ plugin.ConfigMutator = &ConvertPlugin{}
func (m *ConvertPlugin) Name() string {
return "convert-generator"
}
func copyConfig(cfg config.Config) *config.Config {
return &cfg
}
func GetModelsWithInformation(
backend Config,
enums []*Enum,
cfg *config.Config,
boilerModels []*BoilerModel,
ignoreTypePrefixes []string) []*Model {
// get models based on the schema and sqlboiler structs
models := getModelsFromSchema(cfg.Schema, boilerModels)
// Now we have all model's let enhance them with fields
enhanceModelsWithFields(enums, cfg.Schema, cfg, models, ignoreTypePrefixes)
// Add preload maps
enhanceModelsWithPreloadArray(backend, models)
// Sort in same order
sort.Slice(models, func(i, j int) bool { return models[i].Name < models[j].Name })
for _, m := range models {
cfg.Models.Add(m.Name, cfg.Model.ImportPath()+"."+gqlgenTemplates.ToGo(m.Name))
}
return models
}
func (m *ConvertPlugin) MutateConfig(originalCfg *config.Config) error {
b := &ModelBuild{
PackageName: m.Output.PackageName,
Backend: Config{
Directory: path.Join(m.rootImportPath, m.Backend.Directory),
PackageName: m.Backend.PackageName,
},
Frontend: Config{
Directory: path.Join(m.rootImportPath, m.Frontend.Directory),
PackageName: m.Frontend.PackageName,
},
PluginConfig: m.PluginConfig,
}
cfg := copyConfig(*originalCfg)
if err := os.MkdirAll(m.Output.Directory, os.ModePerm); err != nil {
log.Error().Err(err).Str("directory", m.Output.Directory).Msg("could not create directories")
}
// log.Debug().Msg("[customization] looking for *_customized files")
log.Debug().Msg("[convert] get boiler models")
boilerModels, boilerEnums := GetBoilerModels(m.Backend.Directory)
log.Debug().Msg("[convert] get extra's from schema")
interfaces, enums, scalars := getExtrasFromSchema(cfg.Schema, boilerEnums)
log.Debug().Msg("[convert] get model with information")
models := GetModelsWithInformation(b.Backend, enums, originalCfg, boilerModels, []string{m.Frontend.PackageName, m.Backend.PackageName, "boilergql"})
b.Models = models
b.Interfaces = interfaces
b.Enums = enumsWithout(enums, []string{"SortDirection", "Sort"})
b.Scalars = scalars
if len(b.Models) == 0 {
log.Warn().Msg("no models found in graphql so skipping generation")
return nil
}
// for _, model := range models {
// fmt.Println(model.Name, "->", model.BoilerModel.Name)
// for _, field := range model.Fields {
// fmt.Println(" ", field.Name, field.Type)
// fmt.Println(" ", field.BoilerField.Name, field.BoilerField.Type)
// }
// }
filesToGenerate := []string{
"generated_convert.go",
"generated_convert_batch.go",
"generated_convert_input.go",
"generated_filter.go",
"generated_preload.go",
"generated_sort.go",
}
// We get all function names from helper repository to check if any customizations are available
// we ignore the files we generated by this plugin
userDefinedFunctions, err := customization.GetFunctionNamesFromDir(m.Output.PackageName, filesToGenerate)
if err != nil {
log.Err(err).Msg("could not parse user defined functions")
}
for _, fileName := range filesToGenerate {
templateName := fileName + "tpl"
log.Debug().Msg("[convert] render " + templateName)
templateContent, err := getTemplateContent(templateName)
if err != nil {
log.Err(err).Msg("error when reading " + templateName)
continue
}
if renderError := templates.WriteTemplateFile(
m.Output.Directory+"/"+fileName,
templates.Options{
Template: templateContent,
PackageName: m.Output.PackageName,
Data: b,
UserDefinedFunctions: userDefinedFunctions,
}); renderError != nil {
log.Err(renderError).Msg("error while rendering " + templateName)
}
log.Debug().Msg("[convert] rendered " + templateName)
}
return nil
}
//// take a string in the form github.com/package/blah.Type and split it into package and type
//func PkgAndType(name string) (string, string) {
// parts := strings.Split(name, ".")
// if len(parts) == 1 {
// return "", name
// }
//
// return strings.Join(parts[:len(parts)-1], "."), parts[len(parts)-1]
//}
func enumsWithout(enums []*Enum, skip []string) []*Enum {
// lol: cleanup xD
var a []*Enum
for _, e := range enums {
var skipped bool
for _, skip := range skip {
if strings.HasSuffix(e.Name, skip) {
skipped = true
}
}
if !skipped {
a = append(a, e)
}
}
return a
}
func getTemplateContent(filename string) (string, error) {
// load path relative to calling source file
_, callerFile, _, _ := runtime.Caller(1) //nolint:dogsled
rootDir := filepath.Dir(callerFile)
content, err := ioutil.ReadFile(path.Join(rootDir, "template_files", filename))
if err != nil {
return "", fmt.Errorf("could not read template file: %v", err)
}
return string(content), nil
}
// getAstFieldType check's if user has defined a
func getAstFieldType(binder *config.Binder, schema *ast.Schema, cfg *config.Config, field *ast.FieldDefinition) (
types.Type, error) {
var typ types.Type
var err error
fieldDef := schema.Types[field.Type.Name()]
if cfg.Models.UserDefined(field.Type.Name()) {
typ, err = binder.FindTypeFromName(cfg.Models[field.Type.Name()].Model[0])
if err != nil {
return typ, err
}
} else {
switch fieldDef.Kind {
case ast.Scalar:
// no user defined model, referencing a default scalar
typ = types.NewNamed(
types.NewTypeName(0, cfg.Model.Pkg(), "string", nil),
nil,
nil,
)
case ast.Interface, ast.Union:
// no user defined model, referencing a generated interface type
typ = types.NewNamed(
types.NewTypeName(0, cfg.Model.Pkg(), gqlgenTemplates.ToGo(field.Type.Name()), nil),
types.NewInterfaceType([]*types.Func{}, []types.Type{}),
nil,
)
case ast.Enum:
// no user defined model, must reference a generated enum
typ = types.NewNamed(
types.NewTypeName(0, cfg.Model.Pkg(), gqlgenTemplates.ToGo(field.Type.Name()), nil),
nil,
nil,
)
case ast.Object, ast.InputObject:
// no user defined model, must reference a generated struct
typ = types.NewNamed(
types.NewTypeName(0, cfg.Model.Pkg(), gqlgenTemplates.ToGo(field.Type.Name()), nil),
types.NewStruct(nil, nil),
nil,
)
default:
panic(fmt.Errorf("unknown ast type %s", fieldDef.Kind))
}
}
return typ, err
}
func getGraphqlFieldName(cfg *config.Config, modelName string, field *ast.FieldDefinition) string {
name := field.Name
if nameOveride := cfg.Models[modelName].Fields[field.Name].FieldName; nameOveride != "" {
// TODO: map overrides to sqlboiler the other way around?
name = nameOveride
}
return name
}
//nolint:gocognit,gocyclo
func enhanceModelsWithFields(enums []*Enum, schema *ast.Schema, cfg *config.Config,
models []*Model, ignoreTypePrefixes []string) {
binder := cfg.NewBinder()
// Generate the basic of the fields
for _, m := range models {
// Let's convert the pure ast fields to something usable for our templates
for _, field := range m.PureFields {
fieldDef := schema.Types[field.Type.Name()]
// This calls some qglgen boilerType which gets the gqlgen type
typ, err := getAstFieldType(binder, schema, cfg, field)
if err != nil {
log.Err(err).Msg("could not get field type from graphql schema")
}
jsonName := getGraphqlFieldName(cfg, m.Name, field)
name := gqlgenTemplates.ToGo(jsonName)
// just some (old) Relay clutter which is not needed anymore + we won't do anything with it
// in our database converts.
if strings.EqualFold(name, "clientMutationId") {
continue
}
// override type struct with qqlgen code
typ = binder.CopyModifiersFromAst(field.Type, typ)
if isStruct(typ) && (fieldDef.Kind == ast.Object || fieldDef.Kind == ast.InputObject) {
typ = types.NewPointer(typ)
}
// generate some booleans because these checks will be used a lot
isObject := fieldDef.Kind == ast.Object || fieldDef.Kind == ast.InputObject
shortType := getShortType(typ.String(), ignoreTypePrefixes)
isPrimaryID := strings.EqualFold(name, "id")
// get sqlboiler information of the field
boilerField := findBoilerFieldOrForeignKey(m.BoilerModel.Fields, name, isObject)
isString := strings.Contains(strings.ToLower(boilerField.Type), "string")
isNumberID := strings.HasSuffix(name, "ID") && !isString
isPrimaryNumberID := isPrimaryID && !isString
isPrimaryStringID := isPrimaryID && isString
// enable simpler code in resolvers
if isPrimaryStringID {
m.HasPrimaryStringID = isPrimaryStringID
}
if isPrimaryNumberID || isPrimaryStringID {
m.PrimaryKeyType = boilerField.Type
}
isEdges := strings.HasSuffix(m.Name, "Connection") && name == "Edges"
isPageInfo := strings.HasSuffix(m.Name, "Connection") && name == "PageInfo"
isSort := strings.HasSuffix(m.Name, "Ordering") && name == "Sort"
isSortDirection := strings.HasSuffix(m.Name, "Ordering") && name == "Direction"
isCursor := strings.HasSuffix(m.Name, "Edge") && name == "Cursor"
isNode := strings.HasSuffix(m.Name, "Edge") && name == "Node"
// log some warnings when fields could not be converted
if boilerField.Type == "" {
// TODO: add filter + where here
switch {
case m.IsPayload:
case IsPlural(name):
case (m.IsFilter || m.IsWhere) && (strings.EqualFold(name, "and") ||
strings.EqualFold(name, "or") ||
strings.EqualFold(name, "search") ||
strings.EqualFold(name, "where")) ||
isEdges ||
isSort ||
isSortDirection ||
isPageInfo ||
isCursor ||
isNode:
// ignore
default:
log.Warn().Str("model.field", m.Name+"."+name).Msg("boiler type not available (empty type)")
}
}
if boilerField.Name == "" {
if m.IsPayload || m.IsFilter || m.IsWhere || m.IsOrdering || m.IsEdge || isPageInfo || isEdges {
} else {
log.Warn().Str("model.field", m.Name+"."+name).Msg("boiler type not available")
continue
}
}
enum := findEnum(enums, shortType)
field := &Field{
Name: name,
JSONName: jsonName,
Type: shortType,
TypeWithoutPointer: strings.Replace(strings.TrimPrefix(shortType, "*"), ".", "Dot", -1),
BoilerField: boilerField,
IsNumberID: isNumberID,
IsPrimaryID: isPrimaryID,
IsPrimaryNumberID: isPrimaryNumberID,
IsPrimaryStringID: isPrimaryStringID,
IsRelation: boilerField.IsRelation,
IsObject: isObject,
IsOr: strings.EqualFold(name, "or"),
IsAnd: strings.EqualFold(name, "and"),
IsPlural: IsPlural(name),
PluralName: Plural(name),
OriginalType: typ,
Description: field.Description,
Enum: enum,
}
field.ConvertConfig = getConvertConfig(enums, m, field)
m.Fields = append(m.Fields, field)
}
}
for _, m := range models {
for _, f := range m.Fields {
if f.BoilerField.Relationship != nil {
f.Relationship = findModel(models, f.BoilerField.Relationship.Name)
}
}
}
}
// TaskBlockedBies -> TaskBlockedBy
// People -> Person
func Singular(s string) string {
singular := strmangle.Singular(strcase.ToSnake(s))
singularTitle := strmangle.TitleCase(singular)
if isFirstCharacterLowerCase(s) {
a := []rune(singularTitle)
a[0] = unicode.ToLower(a[0])
return string(a)
}
return singularTitle
}
// TaskBlockedBy -> TaskBlockedBies
// Person -> Persons
// Person -> People
func Plural(s string) string {
plural := strmangle.Plural(strcase.ToSnake(s))
pluralTitle := strmangle.TitleCase(plural)
if isFirstCharacterLowerCase(s) {
a := []rune(pluralTitle)
a[0] = unicode.ToLower(a[0])
return string(a)
}
return pluralTitle
}
func IsPlural(s string) bool {
return s == Plural(s)
}
func IsSingular(s string) bool {
return s == Singular(s)
}
func getShortType(longType string, ignoreTypePrefixes []string) string {
// longType e.g = gitlab.com/decicify/app/backend/graphql_models.FlowWhere
splittedBySlash := strings.Split(longType, "/")
// gitlab.com, decicify, app, backend, graphql_models.FlowWhere
lastPart := splittedBySlash[len(splittedBySlash)-1]
isPointer := strings.HasPrefix(longType, "*")
isStructInPackage := strings.Count(lastPart, ".") > 0
if isStructInPackage {
// if packages are deeper they don't have pointers but *time.Time will since it's not deep
returnType := strings.TrimPrefix(lastPart, "*")
for _, ignoreType := range ignoreTypePrefixes {
fullIgnoreType := ignoreType + "."
returnType = strings.TrimPrefix(returnType, fullIgnoreType)
}
if isPointer {
return "*" + returnType
}
return returnType
}
return longType
}
func findModel(models []*Model, search string) *Model {
for _, m := range models {
if m.Name == search {
return m
}
}
return nil
}
//func findField(fields []*Field, search string) *Field {
// for _, f := range fields {
// if f.Name == search {
// return f
// }
// }
// return nil
//}
func findBoilerFieldOrForeignKey(fields []*BoilerField, golangGraphQLName string, isObject bool) BoilerField {
// get database friendly struct for this model
for _, field := range fields {
if isObject {
// If it a relation check to see if a foreign key is available
if strings.EqualFold(field.Name, golangGraphQLName+"ID") {
return *field
}
}
if strings.EqualFold(field.Name, golangGraphQLName) {
return *field
}
}
return BoilerField{}
}
func getExtrasFromSchema(schema *ast.Schema, boilerEnums []*BoilerEnum) (interfaces []*Interface, enums []*Enum, scalars []string) {
for _, schemaType := range schema.Types {
switch schemaType.Kind {
case ast.Interface, ast.Union:
interfaces = append(interfaces, &Interface{
Description: schemaType.Description,
Name: schemaType.Name,
})
case ast.Enum:
boilerEnum := findBoilerEnum(boilerEnums, schemaType.Name)
it := &Enum{
Name: schemaType.Name,
PluralName: Plural(schemaType.Name),
Description: schemaType.Description,
HasBoilerEnum: boilerEnum != nil,
BoilerEnum: boilerEnum,
}
for _, v := range schemaType.EnumValues {
it.Values = append(it.Values, &EnumValue{
Name: v.Name,
NameLower: strcase.ToLowerCamel(strings.ToLower(v.Name)),
Description: v.Description,
BoilerEnumValue: findBoilerEnumValue(boilerEnum, v.Name),
})
}
if strings.HasPrefix(it.Name, "_") {
continue
}
enums = append(enums, it)
case ast.Scalar:
scalars = append(scalars, schemaType.Name)
}
}
return
}
func getModelsFromSchema(schema *ast.Schema, boilerModels []*BoilerModel) (models []*Model) { //nolint:gocognit,gocyclo
for _, schemaType := range schema.Types {
// skip boiler plate from ggqlgen, we only want the models
if strings.HasPrefix(schemaType.Name, "_") {
continue
}
// if cfg.Models.UserDefined(schemaType.Name) {
// fmt.Println("continue")
// continue
// }
switch schemaType.Kind {
case ast.Object, ast.InputObject:
{
if schemaType == schema.Query ||
schemaType == schema.Mutation ||
schemaType == schema.Subscription {
continue
}
modelName := schemaType.Name
// fmt.Println("GRAPHQL MODEL ::::", m.Name)
if strings.HasPrefix(modelName, "_") {
continue
}
// We will try to find a corresponding boiler struct
boilerModel := FindBoilerModel(boilerModels, getBaseModelFromName(modelName))
isInput := doesEndWith(modelName, "Input")
isCreateInput := doesEndWith(modelName, "CreateInput")
isUpdateInput := doesEndWith(modelName, "UpdateInput")
isFilter := doesEndWith(modelName, "Filter")
isWhere := doesEndWith(modelName, "Where")
isPayload := doesEndWith(modelName, "Payload")
isEdge := doesEndWith(modelName, "Edge")
isConnection := doesEndWith(modelName, "Connection")
isPageInfo := modelName == "PageInfo"
isOrdering := doesEndWith(modelName, "Ordering")
var isPagination bool
paginationTriggers := []string{
"ConnectionBackwardPagination",
"ConnectionPagination",
"ConnectionForwardPagination",
}
for _, p := range paginationTriggers {
if modelName == p {
isPagination = true
}
}
// if no boiler model is found
if boilerModel == nil || boilerModel.Name == "" {
if isInput || isWhere || isFilter || isPayload || isPageInfo || isPagination {
// silent continue
continue
}
log.Warn().Str("model", modelName).Msg("skipped because no database model found")
continue
}
isNormalInput := isInput && !isCreateInput && !isUpdateInput
isNormal := !isInput && !isWhere && !isFilter && !isPayload && !isEdge && !isConnection && !isOrdering
m := &Model{
Name: modelName,
Description: schemaType.Description,
PluralName: Plural(modelName),
BoilerModel: boilerModel,
IsInput: isInput,
IsFilter: isFilter,
IsWhere: isWhere,
IsUpdateInput: isUpdateInput,
IsCreateInput: isCreateInput,
IsNormalInput: isNormalInput,
IsConnection: isConnection,
IsEdge: isEdge,
IsPayload: isPayload,
IsOrdering: isOrdering,
IsNormal: isNormal,
IsPreloadable: isNormal,
}
for _, implementor := range schema.GetImplements(schemaType) {
m.Implements = append(m.Implements, implementor.Name)
}
m.PureFields = append(m.PureFields, schemaType.Fields...)
models = append(models, m)
}
}
}
return //nolint:nakedret
}
func doesEndWith(s string, suffix string) bool {
return strings.HasSuffix(s, suffix) && s != suffix
}
func getPreloadMapForModel(backend Config, model *Model) map[string]ColumnSetting {
preloadMap := map[string]ColumnSetting{}
for _, field := range model.Fields {
// only relations are preloadable
if !field.IsObject || !field.BoilerField.IsRelation {
continue
}
// var key string
// if field.IsPlural {
key := field.JSONName
// } else {
// key = field.PluralName
// }
name := fmt.Sprintf("%v.%vRels.%v", backend.PackageName, model.Name, foreignKeyToRel(field.BoilerField.Name))
setting := ColumnSetting{
Name: name,
IDAvailable: !field.IsPlural,
RelationshipModelName: field.BoilerField.Relationship.TableName,
}
preloadMap[key] = setting
}
return preloadMap
}
func enhanceModelsWithPreloadArray(backend Config, models []*Model) {
// first adding basic first level relations
for _, model := range models {
if !model.IsPreloadable {
continue
}
modelPreloadMap := getPreloadMapForModel(backend, model)
sortedPreloadKeys := make([]string, 0, len(modelPreloadMap))
for k := range modelPreloadMap {
sortedPreloadKeys = append(sortedPreloadKeys, k)
}
sort.Strings(sortedPreloadKeys)
model.PreloadArray = make([]Preload, len(sortedPreloadKeys))
for i, k := range sortedPreloadKeys {
columnSetting := modelPreloadMap[k]
model.PreloadArray[i] = Preload{
Key: k,
ColumnSetting: columnSetting,
}
}
}
}
// The relationship is defined in the normal model but not in the input, where etc structs
// So just find the normal model and get the relationship type :)
func getBaseModelFromName(v string) string {
v = safeTrim(v, "CreateInput")
v = safeTrim(v, "UpdateInput")
v = safeTrim(v, "Input")
v = safeTrim(v, "Payload")
v = safeTrim(v, "Where")
v = safeTrim(v, "Filter")
v = safeTrim(v, "Ordering")
v = safeTrim(v, "Edge")
v = safeTrim(v, "Connection")
return v
}
func safeTrim(v string, trimSuffix string) string {
// let user still choose Payload as model names
// not recommended but could be done theoretically :-)
if v != trimSuffix {
v = strings.TrimSuffix(v, trimSuffix)
}
return v
}
func foreignKeyToRel(v string) string {
return strings.TrimSuffix(strcase.ToCamel(v), "ID")
}
func isStruct(t types.Type) bool {
_, is := t.Underlying().(*types.Struct)
return is
}
type ConvertConfig struct {
IsCustom bool
ToBoiler string
ToGraphQL string
GraphTypeAsText string
BoilerTypeAsText string
}
func findBoilerEnum(enums []*BoilerEnum, graphType string) *BoilerEnum {
for _, enum := range enums {
if enum.Name == graphType {
return enum
}
}
return nil
}
func findBoilerEnumValue(enum *BoilerEnum, name string) *BoilerEnumValue {
if enum != nil {
for _, v := range enum.Values {
if strings.EqualFold(strings.TrimPrefix(v.Name, enum.Name), name) {
return v
}
}
log.Error().Str(enum.Name, name).Msg("could sqlboiler enum value")
}
return nil
}
func findEnum(enums []*Enum, graphType string) *Enum {
for _, enum := range enums {
if enum.Name == graphType {
return enum
}
}
return nil
}
func getConvertConfig(enums []*Enum, model *Model, field *Field) (cc ConvertConfig) { //nolint:gocognit,gocyclo
graphType := field.Type
boilType := field.BoilerField.Type
enum := findEnum(enums, field.TypeWithoutPointer)
if enum != nil { //nolint:nestif
cc.IsCustom = true
cc.ToBoiler = strings.TrimPrefix(
getToBoiler(
getBoilerTypeAsText(boilType),
getGraphTypeAsText(graphType),
), boilerPackage)
cc.ToGraphQL = strings.TrimPrefix(
getToGraphQL(
getBoilerTypeAsText(boilType),
getGraphTypeAsText(graphType),
), boilerPackage)
} else if graphType != boilType {
cc.IsCustom = true
if field.IsPrimaryID || field.IsNumberID && field.BoilerField.IsRelation {
// TODO: more dynamic and universal
cc.ToGraphQL = "VALUE"
cc.ToBoiler = "VALUE"
// first unpointer json type if is pointer
if strings.HasPrefix(graphType, "*") {
cc.ToBoiler = boilerPackage + "PointerStringToString(VALUE)"
}
goToUint := getBoilerTypeAsText(boilType) + "ToUint"
if goToUint == "IntToUint" {
cc.ToGraphQL = "uint(VALUE)"
} else if goToUint != "UintToUint" {
cc.ToGraphQL = boilerPackage + goToUint + "(VALUE)"
}
if field.IsPrimaryID {
cc.ToGraphQL = model.Name + "IDToGraphQL(" + cc.ToGraphQL + ")"
} else if field.IsNumberID {
cc.ToGraphQL = field.BoilerField.Relationship.Name + "IDToGraphQL(" + cc.ToGraphQL + ")"
}
isInt := strings.HasPrefix(strings.ToLower(boilType), "int") && !strings.HasPrefix(strings.ToLower(boilType), "uint")
if strings.HasPrefix(boilType, "null") {
cc.ToBoiler = fmt.Sprintf("boilergql.IDToNullBoiler(%v)", cc.ToBoiler)
if isInt {
cc.ToBoiler = fmt.Sprintf("boilergql.NullUintToNullInt(%v)", cc.ToBoiler)
}
} else {
cc.ToBoiler = fmt.Sprintf("boilergql.IDToBoiler(%v)", cc.ToBoiler)
if isInt {
cc.ToBoiler = fmt.Sprintf("int(%v)", cc.ToBoiler)
}
}
cc.ToGraphQL = strings.Replace(cc.ToGraphQL, "VALUE", "m."+field.BoilerField.Name, -1)
cc.ToBoiler = strings.Replace(cc.ToBoiler, "VALUE", "m."+field.Name, -1)
} else {
// Make these go-friendly for the helper/convert_plugin.go package
cc.ToBoiler = getToBoiler(getBoilerTypeAsText(boilType), getGraphTypeAsText(graphType))
cc.ToGraphQL = getToGraphQL(getBoilerTypeAsText(boilType), getGraphTypeAsText(graphType))
}
}
// fmt.Println("boilType for", field.Name, ":", boilType)
// JSON let the user convert how it looks in a custom file
if strings.Contains(boilType, "JSON") {
cc.ToBoiler = strings.TrimPrefix(cc.ToBoiler, boilerPackage)
cc.ToGraphQL = strings.TrimPrefix(cc.ToGraphQL, boilerPackage)
}
cc.GraphTypeAsText = getGraphTypeAsText(graphType)
cc.BoilerTypeAsText = getBoilerTypeAsText(boilType)
return //nolint:nakedret
}
const boilerPackage = "boilergql."
func getToBoiler(boilType, graphType string) string {
return boilerPackage + getGraphTypeAsText(graphType) + "To" + getBoilerTypeAsText(boilType)
}
func getToGraphQL(boilType, graphType string) string {
return boilerPackage + getBoilerTypeAsText(boilType) + "To" + getGraphTypeAsText(graphType)
}
func getBoilerTypeAsText(boilType string) string {
// backward compatible missed Dot
if strings.HasPrefix(boilType, "types.") {
boilType = strings.TrimPrefix(boilType, "types.")
boilType = strcase.ToCamel(boilType)
boilType = "Types" + boilType
}
// if strings.HasPrefix(boilType, "null.") {
// boilType = strings.TrimPrefix(boilType, "null.")
// boilType = strcase.ToCamel(boilType)
// boilType = "NullDot" + boilType
// }