-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdgen.go
1040 lines (918 loc) · 25.1 KB
/
cmdgen.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 codegen
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"text/template"
"unicode"
"unicode/utf8"
"github.com/samber/lo"
"github.com/seambiz/codegen/config"
"github.com/seambiz/codegen/static"
"github.com/seambiz/strcase"
"github.com/valyala/bytebufferpool"
)
type Codegen interface {
Generate(conf *config.Config) string
GenerateTable(conf *config.Config, schema *config.Schema, table *config.Table) string
}
var (
codegenStart = []byte("// GENERATED BY CODEGEN.")
codegenEnd = []byte("// ^^ END OF GENERATED BY CODEGEN. ^^")
)
// GenBuffer type alias for shorter template functions
type GenBuffer struct {
buf *bytebufferpool.ByteBuffer
}
// NewGenBuffer factory
func NewGenBuffer(bb *bytebufferpool.ByteBuffer) *GenBuffer {
return &GenBuffer{buf: bb}
}
// NewLine write newline char to buffer
func (g *GenBuffer) NewLine() {
_, err := g.buf.Write([]byte{'\n'})
if err != nil {
panic(err)
}
}
// S shortcut for writing string to buffer and check error
func (g *GenBuffer) S(ss ...string) {
for _, s := range ss {
_, err := g.buf.WriteString(s)
if err != nil {
panic(err)
}
}
}
// Func shortcut for writing string to buffer and check error
func (g *GenBuffer) Func(Receiver, funcName string) {
g.S("func ")
if Receiver != "" {
g.S("(")
g.S(Receiver)
g.S(")")
}
g.S(" ")
g.S(funcName)
}
// FuncParams shortcut for writing string to buffer and check error
func (g *GenBuffer) FuncParams(ss ...string) {
g.S("(")
for i, s := range ss {
if i >= 1 {
g.S(",")
}
g.S(s)
}
g.S(")")
}
// FuncEnd shortcut for writing string to buffer and check error
func (g *GenBuffer) FuncEnd() {
g.S("}")
g.NewLine()
}
// FuncReturn shortcut for writing string to buffer and check error
func (g *GenBuffer) FuncReturn(ss ...string) {
if len(ss) == 0 {
g.S("{")
return
}
if len(ss) > 1 {
g.S("(")
}
for i, s := range ss {
if i >= 1 {
g.S(",")
}
g.S(s)
}
if len(ss) > 1 {
g.S(")")
}
g.S("{")
g.NewLine()
}
// Struct shortcut for writing string to buffer and check error
func (g *GenBuffer) Struct(name string) {
g.Line("type ", name, " struct {")
}
// StructEnd shortcut for writing string to buffer and check error
func (g *GenBuffer) StructEnd() {
g.Line("}")
}
// Line shortcut for writing string to buffer and check error
func (g *GenBuffer) Line(ss ...string) {
for _, s := range ss {
g.S(s)
}
g.NewLine()
}
// LogField generates zerolog logging instruction for single field
func (g *GenBuffer) LogField(f *config.Field, prefix string) {
switch f.GoType {
case "[]byte":
g.S("Bytes")
case "time.Time":
g.S("Time")
case "sql.NullString":
g.S("Str")
case "sql.NullInt64", "int64":
g.S("Int64")
case "sql.NullFloat64":
g.S("Float64")
case "string":
g.S("Str")
case "uint64":
g.S("Uint64")
default:
g.S(strings.Title(f.GoType))
}
g.S(`("`)
g.S(f.Title)
g.S(`", `)
if f.IsNullable {
switch f.GoType {
case "time.Time":
g.S("logTime(")
case "string":
g.S("logString(")
case "bool":
g.S("logBool(")
case "int":
g.S("logInt(")
case "uint":
g.S("logUInt(")
case "float32":
g.S("logFloat32(")
case "float64":
g.S("logFloat64(")
case "uint64":
g.S("logUInt64(")
case "int64":
g.S("logInt64(")
case "[]byte":
g.S("logBytes(")
default:
panic("unsupported pointer type: " + f.GoType)
}
}
if prefix != "" {
g.S(prefix)
g.S(".")
g.S(f.Title)
} else {
g.S(f.ParamName)
}
switch f.GoType {
case "sql.NullString":
g.S(".Str")
case "sql.NullInt64":
g.S(".Int64")
case "sql.NullFloat64":
g.S(".Float64")
}
g.S(")")
if f.IsNullable {
g.S(")")
}
}
// Log generates zerolog logging instruction for array of fields
func (g *GenBuffer) Log(fields []*config.Field, prefix string) {
for i, f := range fields {
if i > 0 {
g.S(".")
}
g.LogField(f, prefix)
}
}
// Bytes returns buffer contents
func (g *GenBuffer) Bytes() []byte {
return g.buf.Bytes()
}
// Free returns buffer to pool
func (g *GenBuffer) Free() {
bytebufferpool.Put(g.buf)
}
/*
Initials extracts the initial letters from each word in the string. The first letter of the string and all first
letters after the defined delimiters are returned as a new string. Their case is not changed. If the delimiters
parameter is excluded, then Whitespace is used. Whitespace is defined by unicode.IsSpacea(char). An empty delimiter array returns an empty string.
Parameters:
str - the string to get Initials from
delimiters - set of characters to determine words, exclusion of this parameter means whitespace would be delimeter
Returns:
string of initial letters
*/
func Initials(str string, delimiters ...rune) string {
if str == "" {
return str
}
if delimiters != nil && len(delimiters) == 0 {
return ""
}
strLen := len(str)
var buf bytes.Buffer
lastWasGap := true
for i := 0; i < strLen; i++ {
ch := rune(str[i])
if isDelimiter(ch, delimiters...) {
lastWasGap = true
} else if lastWasGap {
buf.WriteRune(ch)
lastWasGap = false
}
}
return buf.String()
}
// private function (lower case func name)
func isDelimiter(ch rune, delimiters ...rune) bool {
if delimiters == nil {
return unicode.IsSpace(ch)
}
for _, delimiter := range delimiters {
if ch == delimiter {
return true
}
}
return false
}
// ExecCommand wraps exec.Command
func ExecCommand(command string) {
parts := strings.Split(command, " ")
if len(parts) == 0 {
return
}
fmt.Println("command", parts)
cmd := exec.Command(parts[0], parts[1:]...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err := cmd.Run()
if err != nil {
fmt.Println("ERROR:", err)
}
}
func lowerFirst(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
}
var commonInitialisms = []string{
"ACL",
"API",
"ASCII",
"CPU",
"CSS",
"DNS",
"EOF",
"GUID",
"HTML",
"HTTP",
"HTTPS",
"ID",
"IP",
"JSON",
"LHS",
"QPS",
"RAM",
"RHS",
"RPC",
"SLA",
"SMTP",
"SQL",
"SSH",
"TCP",
"TLS",
"TTL",
"UDP",
"UI",
"UID",
"UUID",
"URI",
"URL",
"UTF8",
"VM",
"XML",
"XMPP",
"XSRF",
"XSS",
}
/*
Parse the config and add all filtered templates that should be processed to each schema and table.
This way the generation code will be much simpler.
And this function will be easier to test.
*/
func generateTemplatesConfig(conf *config.Config) {
// not the most performant approach, as templates will be rebuilt for each table, but much more readable than the old code
for _, schema := range conf.Schemas {
schema.PreparedTemplatefiles = make(map[string][]string)
for _, t := range schema.Tables {
t.PreparedTemplatefiles = make(map[string][]string)
}
var fileNames []string
if schema.TemplateFolder != "" {
files, err := ioutil.ReadDir(schema.TemplateFolder)
if err != nil {
panic(err)
}
for _, f := range files {
fileNames = append(fileNames, f.Name())
}
} else {
// use embedded templates
var err error
fileNames, err = static.WalkDirs("", false)
if err != nil {
panic(err)
}
sort.Strings(fileNames)
}
// first check all templates, that do not need to be concatenated
for _, fName := range fileNames {
if !strings.HasSuffix(fName, ".tmpl") {
continue
}
if schema.NoTests {
if strings.Contains(fName, "_test") {
continue
}
}
segments := strings.Split(fName, ".")
if len(segments) != 4 && len(segments) != 5 {
panic("filename segment length != 4,5: " + fName)
}
if len(segments) == 4 {
switch segments[0] {
case "once":
// 1. add all simple "once" templates to the schema
mapKey := strings.Join([]string{segments[0], segments[1], segments[2]}, ".")
schema.PreparedTemplatefiles[mapKey] = append(schema.PreparedTemplatefiles[mapKey], fName)
case "table":
// 2. add all simple "table" templates to the tables
for _, t := range schema.Tables {
if !t.Generate {
continue
}
mapKey := strings.Join([]string{segments[0], segments[1], segments[2]}, ".")
t.PreparedTemplatefiles[mapKey] = append(t.PreparedTemplatefiles[mapKey], fName)
}
}
}
}
// remove all templates, that were processed above
for i := 0; i < len(fileNames); i++ {
segments := strings.Split(fileNames[i], ".")
if len(segments) != 5 {
fileNames = append(fileNames[:i], fileNames[i+1:]...)
i--
}
}
// add all "once" files to be concatenated
for _, fName := range fileNames {
segments := strings.Split(fName, ".")
if len(segments) != 5 {
panic("wrong []segement length")
}
currentMapKey := strings.Join([]string{segments[0], segments[1], segments[2]}, ".")
if segments[0] == "once" {
schema.PreparedTemplatefiles[currentMapKey] = append(schema.PreparedTemplatefiles[currentMapKey], fName)
}
}
// generate general template files list for table
templateFiles := []string{}
for _, fName := range fileNames {
segments := strings.Split(fName, ".")
if len(segments) != 5 {
panic("wrong []segement length")
}
if segments[0] == "table" {
templateFiles = append(templateFiles, fName)
}
}
// add specific or global templates to each table
for _, t := range schema.Tables {
if !t.Generate {
continue
}
// choose files to process
tempFiles := templateFiles
if len(t.TemplateFiles) > 0 {
tempFiles = t.TemplateFiles
}
for _, tFile := range tempFiles {
segments := strings.Split(tFile, ".")
if len(segments) != 5 {
panic("wrong []segement length")
}
currentMapKey := strings.Join([]string{segments[0], segments[1], segments[2]}, ".")
t.PreparedTemplatefiles[currentMapKey] = append(t.PreparedTemplatefiles[currentMapKey], tFile)
}
}
}
}
func generateFile(conf *config.Config, schema *config.Schema, table *config.Table, fileprefix string, templateFiles map[string][]string) {
for key, fileNames := range templateFiles {
var buf bytes.Buffer
templateContents := []byte("")
for _, tFile := range fileNames {
var err error
var contents []byte
if schema.TemplateFolder != "" {
contents, err = ioutil.ReadFile(schema.TemplateFolder + tFile)
if err != nil {
panic(err)
}
} else {
contents, err = static.ReadFile(tFile)
if err != nil {
panic(err)
}
}
templateContents = append(templateContents, contents...)
}
tmpl, err := template.New(key).Funcs(getFuncMap()).Parse(string(templateContents))
if err != nil {
panic(err)
}
type GenData struct {
Conf *config.Config
Schema *config.Schema
Table *config.Table
}
d := GenData{}
d.Conf = conf
d.Schema = schema
d.Table = table
err = tmpl.Execute(&buf, d)
if err != nil {
panic(err)
}
segments := strings.Split(key, ".")
prefix := ""
if segments[0] == "table" {
prefix = strings.ReplaceAll(fileprefix, "_", "")
}
switch segments[1] {
case "subpackage":
fileName := filepath.Join(conf.DirOut, conf.SubPackage, fmt.Sprintf(conf.FilePattern, strings.ToLower(prefix+strings.Title(segments[2]))))
WriteToCodgenFile(conf, buf.Bytes(), fileName)
case "package":
fileName := filepath.Join(conf.DirOut, filepath.Join(conf.SubPackage, conf.Package), fmt.Sprintf(conf.FilePattern, strings.ToLower(prefix+strings.Title(segments[2]))))
WriteToCodgenFile(conf, buf.Bytes(), fileName)
case "root":
fileName := filepath.Join(conf.DirOut, "", fmt.Sprintf(conf.FilePattern, strings.ToLower(prefix+strings.Title(segments[2]))))
WriteToCodgenFile(conf, buf.Bytes(), fileName)
}
}
}
func generateCode(conf *config.Config) {
for _, schema := range conf.Schemas {
generateFile(conf, schema, nil, schema.Prefix, schema.PreparedTemplatefiles)
for _, table := range schema.Tables {
generateFile(conf, schema, table, schema.Prefix+table.Name, table.PreparedTemplatefiles)
}
}
if conf.GoFmtCmd != "" {
ExecCommand(conf.GoFmtCmd + " " + conf.DirOut)
}
if conf.LintPackage != "" {
ExecCommand("go vet " + conf.LintPackage)
}
if conf.MetaLinter != "" {
ExecCommand(conf.MetaLinter)
}
}
// Generate main call to start generation
func Generate(conf *config.Config) {
PrepareSchemaConfig(conf)
generateTemplatesConfig(conf)
generateCode(conf)
}
func Lint(dirOrFile string, lintCmd *string) {
linter := "golangci-lint run --enable-all -D ifshort -D scopelint -D exhaustivestruct -D golint -Dmaligned -D interfacer"
if lintCmd != nil {
linter = *lintCmd
}
fmt.Println("Linting:", dirOrFile, "...")
ExecCommand(linter + " " + dirOrFile)
}
func GenGo(conf *config.Config, generator Codegen, outfile string) {
uglyCode := generator.Generate(conf)
prettyCode, err := format.Source([]byte(uglyCode))
if err != nil {
fmt.Println(uglyCode)
f, err := os.CreateTemp("/tmp", "go")
if err != nil {
panic(err)
}
f.WriteString(uglyCode)
f.Close()
ExecCommand("go tool compile " + f.Name())
panic(err)
}
WriteToCodgenFile(conf, prettyCode, outfile)
}
func GenTable(conf *config.Config, generator Codegen, schema *config.Schema, table *config.Table, outfile string) {
uglyCode := generator.GenerateTable(conf, schema, table)
prettyCode, err := format.Source([]byte(uglyCode))
if err != nil {
fmt.Println(uglyCode)
f, err := os.CreateTemp("/tmp", "go")
if err != nil {
panic(err)
}
f.WriteString(uglyCode)
f.Close()
ExecCommand("go tool compile " + f.Name())
panic(err)
}
WriteTableToCodgenFile(conf, prettyCode, outfile, schema, table)
}
func fnTableJoinFields(baseTable *config.Table, conf *config.Config, table *config.Table, refAlias rune, tableAlias *rune, fks []*config.ForeignKey) {
for _, fk := range fks {
*tableAlias++
if fk.IsUnique {
fkRefTableTitle := strings.Title(fk.RefTable)
fkRefTable := strings.Title(fk.RefTable)
fkSchema := conf.GetSchema(fk.RefSchema)
pRefTable := fkSchema.GetTable(fk.RefTable)
if pRefTable != nil {
fkRefTableTitle = pRefTable.Title
fkRefTable = pRefTable.Name
}
t := config.Join{
Alias: string(*tableAlias),
Name: fkRefTable,
Title: fkRefTableTitle,
Initials: table.Initials,
Schema: fkSchema.Name,
Table: pRefTable,
}
for i := range fk.Fields {
t.Fields = append(t.Fields, config.JoinField{
Alias: string(refAlias),
Name: fk.Fields[i],
RefAlias: string(*tableAlias),
RefName: fk.RefFields[i],
})
}
baseTable.Joins = append(baseTable.Joins, t)
if len(fk.ForeignKeys) > 0 {
fnTableJoinFields(baseTable, conf, table, *tableAlias, tableAlias, fk.ForeignKeys)
}
}
}
}
func PrepareSchemaConfig(conf *config.Config) {
tableNr := 0
for _, schema := range conf.Schemas {
prefix := conf.Prefix
if schema.Prefix != "" {
prefix = schema.Prefix
}
// which templates should be used
if schema.TemplateFolder == "" {
schema.TemplateFolder = conf.TemplateFolder
}
tableNames := make([]string, len(schema.Tables))
for i := range schema.Tables {
tableNames[i] = schema.Tables[i].Name
}
if schema.Title == "" {
schema.Title = strcase.ToCamel(schema.Name)
}
for _, table := range schema.Tables {
if !table.Generate {
continue
}
table.ID = tableNr
tableNr++
// generate helper variables
// parts := strings.Split(table.Name, "_")
// for i := range parts {
// if strings.ToLower(parts[i]) == "id" {
// parts[i] = "ID"
// } else {
// parts[i] = strings.Title(parts[i])
// }
// }
table.Title = prefix + strcase.ToCamel(table.Name)
table.Lower = lowerFirst(table.Title)
// table.Initials = Initials(table.Name)
// table.Initials += Initials(table.Name[1:])
// table.Initials = strings.ToLower(table.Initials)
table.Initials = "s"
table.Receiver = table.Initials + " *" + table.Title
table.Store = table.Title + "Store"
table.StoreReceiver = table.Initials + " *" + table.Store
fieldNames := make([]string, len(table.Fields))
for i := range table.Fields {
fieldNames[i] = table.Fields[i].Name
}
// fill mapping for easy access to field properties
table.FieldMapping = make(map[string]int)
for i := range table.Fields {
// if table.Fields[i].Name == "id" {
// table.Fields[i].Title = "ID"
// } else {
// parts := strings.Split(table.Fields[i].Name, "_")
// for i := range parts {
// if strings.ToLower(parts[i]) == "id" {
// parts[i] = "ID"
// } else {
// parts[i] = strings.Title(parts[i])
// }
// }
// table.Fields[i].Title = strings.Join(parts, "")
// }
table.Fields[i].Title = strcase.ToCamel(table.Fields[i].Name)
table.Fields[i].Title = strings.ReplaceAll(table.Fields[i].Title, " ", "")
table.Fields[i].NoAudit = lo.Contains(schema.NoAudit, table.Fields[i].Name)
table.Fields[i].ParamName = strings.ToLower(table.Fields[i].Title)
table.FieldMapping[table.Fields[i].Name] = i
if table.Fields[i].IsPrimaryKey {
table.PkFields = append(table.PkFields, table.Fields[i])
} else {
table.OtherFields = append(table.OtherFields, table.Fields[i])
}
typename, ok := GoTypeMapping[table.Fields[i].DBType]
if !ok {
panic(fmt.Sprintf("%#v", table.Fields[i]))
}
table.Fields[i].GoType = typename
zero, ok := goZeroMapping[typename]
if !ok {
panic(typename)
}
table.Fields[i].GoZero = zero
jsonFunc, ok := goJSONMapping[typename]
if !ok {
panic(typename)
}
table.Fields[i].JsonFunc = jsonFunc
MappingFunc, ok := goDbMappingFunc[typename]
if !ok {
panic(typename)
}
table.Fields[i].MappingFunc = MappingFunc
table.NumFields = len(table.Fields)
}
}
for _, table := range schema.Tables {
if !table.Generate {
continue
}
fieldNames := make([]string, len(table.Fields))
for i := range table.Fields {
fieldNames[i] = table.Fields[i].Name
}
for k, fk := range table.ForeignKeys {
if fk.IsUnique {
table.NumUniqueFKs++
}
fk.GenTableName = strings.Title(fk.RefTable)
fkSchema := conf.GetSchema(fk.RefSchema)
if t := fkSchema.GetTable(fk.RefTable); t != nil {
fk.GenTableName = t.Title
fk.GenTable = t
}
if fk.IsUnique {
fk.GenFuncName = "OneBy"
} else {
fk.GenFuncName = "QueryBy"
}
for i := range fk.Fields {
if i > 0 {
fk.GenFuncName += "And"
}
fk.GenFuncName += fk.GenTable.Fields[fk.GenTable.FieldMapping[fk.RefFields[i]]].Title
}
table.ForeignKeys[k].RefTableTitle = fk.GenTableName
if fk.CustomName == "" {
table.ForeignKeys[k].CustomName = strcase.ToCamel(strings.Replace(fk.Name, "fk_", "", 1))
table.ForeignKeys[k].Name = strcase.ToSnake(strings.Replace(fk.Name, "fk_", "", 1))
}
if !fk.IsUnique && len(fk.RefFields) > 1 {
panic("FK: too many ref fields")
}
}
for _, fk := range table.ForeignKeys {
if fk.CustomName != "" {
fk.GenName = fk.CustomName
} else {
fk.GenName = fk.GenTable.Title + strings.Replace(fk.Name, "fk", "", 1)
}
}
table.Alias = "A"
tableAlias := 'A'
fnTableJoinFields(table, conf, table, tableAlias, &tableAlias, table.ForeignKeys)
// Index func name
// only unique names allowed, filter duplicates
uniqueFuncs := map[string]bool{}
for _, index := range table.Indices {
funcName := ""
if index.IsUnique {
funcName = "OneBy"
} else {
funcName = "QueryBy"
}
for i, f := range index.Fields {
if i > 0 {
funcName += "And"
}
funcName += table.Fields[table.FieldMapping[f]].Title
}
// unique check
if _, contains := uniqueFuncs[funcName]; contains {
index.Generate = false
}
uniqueFuncs[funcName] = true
index.FuncName = funcName
}
}
}
}
func writeBufferToCodgenFile(bb *GenBuffer, conf *config.Config, filename string) {
fileName := filepath.Join(conf.DirOut, fmt.Sprintf(conf.FilePattern, strings.ToLower(strings.Replace(filename, "_", "", -1))))
fmt.Println("Writing to", fileName)
if conf.GenTests == false {
if strings.Contains(fileName, "_test") {
return
}
}
// check if file exists and if it already has codegen comments
// if not, just write everything to the file
if _, err := os.Stat(fileName); os.IsNotExist(err) {
err := ioutil.WriteFile(fileName, bb.Bytes(), os.ModePerm)
bb.Free()
if err != nil {
panic(err)
}
} else {
fileContents, err := ioutil.ReadFile(fileName)
if err != nil {
panic(err)
}
if bytes.Contains(fileContents, codegenStart) && bytes.Contains(fileContents, codegenEnd) {
start := bytes.Index(fileContents, codegenStart)
if start == -1 {
panic("start == -1")
}
end := bytes.LastIndex(fileContents, codegenEnd)
if end == -1 {
panic("end == -1")
}
newStart := bytes.Index(bb.Bytes(), codegenStart)
if newStart == -1 {
panic("newStart == -1")
}
newEnd := bytes.LastIndex(bb.Bytes(), codegenEnd)
if newEnd == -1 {
panic("newEnd == -1")
}
var newContent []byte
newContent = append(newContent, fileContents[:start]...)
newContent = append(newContent, bb.Bytes()[newStart:newEnd]...)
newContent = append(newContent, fileContents[end:]...)
err := ioutil.WriteFile(fileName, newContent, os.ModePerm)
bb.Free()
if err != nil {
panic(err)
}
} else {
fmt.Println("ERR: existing file (" + fileName + ") does not contain codegen comment.")
fmt.Println("ERR: exiting now, so content does not get overwritten.")
os.Exit(1)
}
}
}
func WriteToCodgenFile(conf *config.Config, code []byte, outfile string) {
fmt.Println("Writing to", outfile)
// check if file exists and if it already has codegen comments
// if not, just write everything to the file
if _, err := os.Stat(outfile); os.IsNotExist(err) {
fmt.Println(err)
err := ioutil.WriteFile(outfile, code, os.ModePerm)
if err != nil {
panic(err)
}
} else {
fileContents, err := ioutil.ReadFile(outfile)
if err != nil {
panic(err)
}
/**********************************************************************
* default comments
**********************************************************************/
startComment := codegenStart
if conf.CommentStart != "" {
startComment = []byte(conf.CommentStart)
}
endComment := codegenEnd
if conf.CommentEnd != "" {
endComment = []byte(conf.CommentEnd)
}
if bytes.Contains(fileContents, startComment) && bytes.Contains(fileContents, endComment) {
start := bytes.Index(fileContents, startComment)
if start == -1 {
panic("start == -1")
}
end := bytes.LastIndex(fileContents, endComment)
if end == -1 {
panic("end == -1")
}
newStart := bytes.Index(code, startComment)
if newStart == -1 {
panic("newStart == -1")
}
newEnd := bytes.LastIndex(code, endComment)
if newEnd == -1 {
panic("newEnd == -1")
}
var newContent []byte
newContent = append(newContent, fileContents[:start]...)
newContent = append(newContent, code[newStart:newEnd]...)
newContent = append(newContent, fileContents[end:]...)
err := ioutil.WriteFile(outfile, newContent, os.ModePerm)
if err != nil {
panic(err)
}
} else {
fmt.Println("ERR: existing file (" + outfile + ") does not contain codegen comment.")
fmt.Println("ERR: exiting now, so content does not get overwritten.")
os.Exit(1)
}
}
}
func WriteTableToCodgenFile(conf *config.Config, code []byte, outfile string, schema *config.Schema, table *config.Table) {
fmt.Println("Writing Table to", outfile)
// check if file exists and if it already has codegen comments
// if not, just write everything to the file
if _, err := os.Stat(outfile); os.IsNotExist(err) {
fmt.Println(err)
err := ioutil.WriteFile(outfile, code, os.ModePerm)
if err != nil {
panic(err)
}
} else {
f, err := ioutil.ReadFile(outfile)
if err != nil {
panic(err)
}
fileContents := string(f)
/**********************************************************************
* special table comments
**********************************************************************/
startCommentTable := ""
endCommentTable := ""
if table.CommentStart != "" {
startCommentTable = table.CommentStart
}
if table.CommentEnd != "" {
endCommentTable = table.CommentEnd
}
if startCommentTable == "" || endCommentTable == "" {
WriteToCodgenFile(conf, code, outfile)
return
}