-
Notifications
You must be signed in to change notification settings - Fork 18
/
tarantool_orm_generator.go
812 lines (719 loc) · 30.5 KB
/
tarantool_orm_generator.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
package Tt
import (
"bytes"
"fmt"
"os"
"sort"
"strings"
"github.com/kokizzu/gotro/I"
"github.com/kokizzu/gotro/L"
"github.com/kokizzu/gotro/S"
"github.com/kokizzu/gotro/X"
)
// quote import
func qi(importPath string) string {
return `
` + S.BT(importPath)
}
// double quote
func dq(str string) string {
return `"` + str + `"`
}
var typeGraphql = map[DataType]string{
Unsigned: `Int`,
//Number: `Float`,
String: `String`,
Double: `Float`,
Integer: `Int`,
Boolean: `Boolean`,
}
func TypeGraphql(field Field) string {
typ := typeGraphql[field.Type]
if typ == `Int` {
if S.EndsWith(field.Name, `By`) || S.EndsWith(field.Name, `Id`) {
return `ID`
}
}
return typ
}
const connStruct = `Tt.Adapter`
const connImport = "\n\n\t`github.com/tarantool/go-tarantool/v2`"
const iterEq = `tarantool.IterEq`
const iterAll = `tarantool.IterAll`
const iterNeighbor = `tarantool.IterNeighbor`
var _ = iterNeighbor
const NL = "\n"
const warning = "// DO NOT EDIT, will be overwritten by github.com/kokizzu/D/Tt/tarantool_orm_generator.go\n\n"
func GenerateOrm(tables map[TableName]*TableProp, withGraphql ...bool) {
ci := L.CallerInfo(2)
this := L.CallerInfo()
pkgName := S.RightOfLast(ci.PackageName, `/`)
wcPkgName := `wc` + pkgName[1:] // write/command (mutator)
rqPkgName := `rq` + pkgName[1:] // read/query (reader)
mPkgName := `m` + pkgName[1:]
L.Print(rqPkgName, wcPkgName)
//var maxMap = map[string]string{
// Unsigned: `math.MaxInt32`,
// Number: `math.MaxFloat32`,
// String: "``",
//}
//var minMap = map[string]string{
// Unsigned: `0`,
// Number: `-math.MaxFloat32`,
// String: "``",
//}
//// do not generate when no table files changed
//maxModTime := int64(0)
//stat, err := os.Stat(genDir + genRqFilename)
//if err == nil {
// err = filepath.Walk(genDir, func(path string, info os.FileInfo, err error) error {
// if strings.Contains(path, `_table_`) || strings.Contains(path, `_schema.go`) {
// modTime := info.ModTime().UnixNano()
// if maxModTime < modTime {
// maxModTime = modTime
// }
// }
// return nil
// })
// if L.IsError(err, `filepath.Walk failed: `+genDir) {
// return
// }
// // no table file changed
// if stat.ModTime().UnixNano() >= maxModTime {
// return
// }
//}
// generate
rqBuf := bytes.Buffer{}
wcBuf := bytes.Buffer{}
RQ := func(str string) {
_, err := rqBuf.WriteString(str)
L.PanicIf(err, `failed rqBuf.WriteString`)
}
WC := func(str string) {
_, err := wcBuf.WriteString(str)
L.PanicIf(err, `failed wcBuf.WriteString`)
}
BOTH := func(str string) {
RQ(str)
WC(str)
}
//BOTH(`// generated: ` + time.Now().String() + NL)
RQ(`package ` + rqPkgName)
WC(`package ` + wcPkgName)
BOTH("\n\n")
BOTH(warning)
haveString, haveAutoIncrementId := false, false
useGraphql := len(withGraphql) > 0
// sort by table name to keep the order when regenerating structs
tableNames := make([]string, 0, len(tables))
for k, v := range tables {
tableNames = append(tableNames, string(k))
useGraphql = useGraphql || v.GenGraphqlType // if one of them use graphql, import anyway
for _, prop := range v.Fields {
if prop.Type == String {
haveString = true
}
}
if v.AutoIncrementId {
haveAutoIncrementId = true
}
}
sort.Strings(tableNames)
// import reader
BOTH(`import (`)
RQ(qi(ci.PackageName))
WC(qi(ci.PackageName + `/` + rqPkgName))
BOTH(connImport)
BOTH(NL)
if useGraphql {
//RQ(qi(`github.com/ graphql-go/graphql`))
}
BOTH(qi(`github.com/kokizzu/gotro/A`))
BOTH(qi(this.PackageName)) // github.com/kokizzu/gotro/D/Tt
BOTH(qi(`github.com/kokizzu/gotro/L`))
WC(qi(`github.com/kokizzu/gotro/M`))
if haveString {
WC(qi(`github.com/kokizzu/gotro/S`))
}
if haveAutoIncrementId {
BOTH(qi(`github.com/kokizzu/gotro/X`))
}
BOTH(`
)` + "\n\n")
RQ(`//go:generate gomodifytags -all -add-tags json,form,query,long,msg -transform camelcase --skip-unexported -w -file ` + rqPkgName + "__ORM.GEN.go\n")
RQ(`//go:generate replacer -afterprefix "Id\" form" "Id,string\" form" type ` + rqPkgName + "__ORM.GEN.go\n")
RQ(`//go:generate replacer -afterprefix "json:\"id\"" "json:\"id,string\"" type ` + rqPkgName + "__ORM.GEN.go\n")
RQ(`//go:generate replacer -afterprefix "By\" form" "By,string\" form" type ` + rqPkgName + "__ORM.GEN.go\n")
//RQ(`//go:generate msgp -tests=false -file ` + rqPkgName + `__ORM.GEN.go -o ` + rqPkgName + `__MSG.GEN.go` + "\n\n")
WC(`//go:generate gomodifytags -all -add-tags json,form,query,long,msg -transform camelcase --skip-unexported -w -file ` + wcPkgName + "__ORM.GEN.go\n")
WC(`//go:generate replacer -afterprefix "Id\" form" "Id,string\" form" type ` + wcPkgName + "__ORM.GEN.go\n")
WC(`//go:generate replacer -afterprefix "json:\"id\"" "json:\"id,string\"" type ` + wcPkgName + "__ORM.GEN.go\n")
WC(`//go:generate replacer -afterprefix "By\" form" "By,string\" form" type ` + wcPkgName + "__ORM.GEN.go\n")
//WC(` //go:generate msgp -tests=false -file ` + wcPkgName + `__ORM.GEN.go -o ` + wcPkgName + `__MSG.GEN.go` + "\n\n")
// for each table generate in order
for _, tableName := range tableNames {
props := tables[TableName(tableName)]
structName := S.PascalCase(tableName)
maxLen := 1
propByName := map[string]Field{}
censoredFieldsByName := map[string]bool{}
for _, prop := range props.Fields {
l := len(prop.Name) + 1
if maxLen < l {
maxLen = l
}
propByName[prop.Name] = prop
}
for _, propName := range props.AutoCensorFields {
censoredFieldsByName[propName] = true
}
// mutator struct
WC("// " + structName + "Mutator DAO writer/command struct\n")
WC(`type ` + structName + "Mutator struct {\n")
WC(` ` + rqPkgName + `.` + structName + NL)
WC(" mutations *tarantool.Operations\n")
WC(" logs []A.X\n")
WC("}\n\n")
// mutator struct constructor
WC("// New" + structName + "Mutator create new ORM writer/command object\n")
WC(`func New` + structName + `Mutator(adapter *` + connStruct + `) (res *` + structName + "Mutator) {\n")
WC(` res = &` + structName + `Mutator{` + structName + `: ` + rqPkgName + `.` + structName + "{Adapter: adapter}}\n")
WC(" res.mutations = tarantool.NewOperations()\n")
for _, prop := range props.Fields {
if prop.Type == Array {
WC(` res.` + S.PascalCase(prop.Name) + ` = ` + TypeToGoType[prop.Type] + "{}\n")
}
}
WC(" return\n")
WC("}\n\n")
// reader struct
RQ("// " + structName + " DAO reader/query struct\n")
RQ(`type ` + structName + " struct {\n")
const none = `"-"`
RQ(" Adapter *" + connStruct + " " + S.BT("json:"+none+" msg:"+none+" query:"+none+" form:"+none) + NL)
for _, prop := range props.Fields {
camel := S.PascalCase(prop.Name)
RQ(" " + camel + strings.Repeat(` `, maxLen-len(camel)) + TypeToGoType[prop.Type] + NL)
}
RQ("}\n\n")
// reader struct constructor
RQ("// New" + structName + " create new ORM reader/query object\n")
RQ(`func New` + structName + `(adapter *` + connStruct + `) *` + structName + " {\n")
RQ(` return &` + structName + "{Adapter: adapter}\n")
RQ("}\n\n")
// table name
receiverName := strings.ToLower(string(structName[0]))
RQ("// SpaceName returns full package and table name\n")
RQ(`func (` + receiverName + ` *` + structName + ") SpaceName() string { //nolint:dupl false positive\n")
RQ(" return string(" + mPkgName + `.Table` + structName + ") // casting required to string from Tt.TableName\n")
RQ("}\n\n")
// Sql table name
RQ("// SqlTableName returns quoted table name\n")
RQ(`func (` + receiverName + ` *` + structName + ") SqlTableName() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(S.QQ(tableName)) + NL)
RQ("}\n\n")
// have mutation
WC("// Logs get array of logs [field, old, new]\n")
WC(`func (` + receiverName + ` *` + structName + "Mutator) Logs() []A.X { //nolint:dupl false positive\n")
WC(` return ` + receiverName + ".logs\n")
WC("}\n\n")
// have mutation
WC("// HaveMutation check whether Set* methods ever called\n")
WC(`func (` + receiverName + ` *` + structName + "Mutator) HaveMutation() bool { //nolint:dupl false positive\n")
WC(` return len(` + receiverName + ".logs) > 0\n")
WC("}\n\n")
// clear mutation
WC("// ClearMutations clear all previously called Set* methods\n")
WC(`func (` + receiverName + ` *` + structName + "Mutator) ClearMutations() { //nolint:dupl false positive\n")
WC(` ` + receiverName + ".mutations = tarantool.NewOperations()\n")
WC(` ` + receiverName + ".logs = []A.X{}\n")
WC("}\n\n")
// auto increment id
if props.AutoIncrementId {
uniquePropCamel := S.PascalCase(IdCol)
structProp := receiverName + `.` + uniquePropCamel
RQ(`func (` + receiverName + ` *` + structName + `) UniqueIndex` + uniquePropCamel + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(IdCol) + NL)
RQ("}\n\n")
keyFunc := Field{Type: Unsigned}.KeyRenderer()
generateMutationByUniqueIndex(uniquePropCamel, structProp, receiverName, structName, keyFunc, RQ, WC)
if props.GenGraphqlType {
generateGraphqlQueryField(structName, uniquePropCamel, propByName[IdCol], RQ)
}
}
// spatial index
if props.Spatial != `` {
uniquePropCamel := S.PascalCase(props.Spatial)
RQ("// SpatialIndex" + uniquePropCamel + " return spatial index name\n")
RQ(`func (` + receiverName + ` *` + structName + `) SpatialIndex` + uniquePropCamel + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(props.Spatial) + NL)
RQ("}\n\n")
}
// unique index1
if props.Unique1 != `` && !(props.AutoIncrementId && props.Unique1 == IdCol) {
uniquePropCamel := S.PascalCase(props.Unique1)
structProp := receiverName + `.` + uniquePropCamel
RQ("// UniqueIndex" + uniquePropCamel + " return unique index name\n")
RQ(`func (` + receiverName + ` *` + structName + `) UniqueIndex` + uniquePropCamel + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(props.Unique1) + NL)
RQ("}\n\n")
keyType := propByName[props.Unique1].KeyRenderer()
generateMutationByUniqueIndex(uniquePropCamel, structProp, receiverName, structName, keyType, RQ, WC)
if props.GenGraphqlType {
generateGraphqlQueryField(structName, uniquePropCamel, propByName[props.Unique1], RQ)
}
}
// unique index2
if props.Unique2 != `` && !(props.AutoIncrementId && props.Unique2 == IdCol) {
uniquePropCamel := S.PascalCase(props.Unique2)
structProp := receiverName + `.` + uniquePropCamel
RQ("// UniqueIndex" + uniquePropCamel + " return unique index name\n")
RQ(`func (` + receiverName + ` *` + structName + `) UniqueIndex` + uniquePropCamel + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(props.Unique2) + NL)
RQ("}\n\n")
keyType := propByName[props.Unique2].KeyRenderer()
generateMutationByUniqueIndex(uniquePropCamel, structProp, receiverName, structName, keyType, RQ, WC)
}
// unique index3
if props.Unique3 != `` && !(props.AutoIncrementId && props.Unique3 == IdCol) {
uniquePropCamel := S.PascalCase(props.Unique3)
structProp := receiverName + `.` + uniquePropCamel
RQ("// UniqueIndex" + uniquePropCamel + " return unique index name\n")
RQ(`func (` + receiverName + ` *` + structName + `) UniqueIndex` + uniquePropCamel + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(props.Unique3) + NL)
RQ("}\n\n")
keyType := propByName[props.Unique3].KeyRenderer()
generateMutationByUniqueIndex(uniquePropCamel, structProp, receiverName, structName, keyType, RQ, WC)
}
// unique indexes
if len(props.Uniques) > 0 {
uniquePropCamel := ``
structProps := ``
for _, uniq := range props.Uniques {
uniquePropCamel += S.PascalCase(uniq)
structProps += `, ` + receiverName + `.` + S.PascalCase(uniq)
}
if len(structProps) > 2 {
structProps = structProps[2:]
}
RQ("// UniqueIndex" + uniquePropCamel + " return unique index name\n")
RQ(`func (` + receiverName + ` *` + structName + `) UniqueIndex` + uniquePropCamel + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(strings.Join(props.Uniques, `__`)) + NL)
RQ("}\n\n")
keyFunc := func(structProp string) string { return "TodoWhatToUseForMultipleKey:" + structProp }
generateMutationByUniqueIndex(uniquePropCamel, structProps, receiverName, structName, keyFunc, RQ, WC)
}
// insert, error if exists
WC("// DoInsert insert, error if already exists\n")
WC(`func (` + receiverName + ` *` + structName + "Mutator) DoInsert() bool { //nolint:dupl false positive\n")
ret1 := S.IfElse(props.AutoIncrementId, `row`, `_`)
WC(" arr := " + receiverName + ".ToArray()\n")
WC(" " + ret1 + ", err := " + receiverName + ".Adapter.RetryDo(\n")
WC(" tarantool.NewInsertRequest(" + receiverName + ".SpaceName()).\n")
WC(" Tuple(arr),\n")
WC(" )\n")
if props.AutoIncrementId {
WC(" if err == nil {\n")
WC(" if len(row) > 0 {\n")
WC(" if cells, ok := row[0].([]any); ok && len(cells) > 0 {\n")
WC(" " + receiverName + ".Id = X.ToU(cells[0])\n")
WC(" }\n")
WC(" }\n")
WC(" }\n")
}
WC(" return !L.IsError(err, `" + structName + ".DoInsert failed: `+" + receiverName + ".SpaceName() + `\\n%#v`, arr)\n")
WC("}\n\n")
// replace = upsert, only error when there's unique secondary key
// https://github.com/tarantool/tarantool/issues/5732
if props.AutoIncrementId {
WC("// DoUpsert upsert, insert or overwrite, will error only when there's unique secondary key being violated\n")
WC("// tarantool's replace/upsert can only match by primary key\n")
WC("// previous name: DoReplace\n")
WC(`func (` + receiverName + ` *` + structName + "Mutator) DoUpsertById() bool { //nolint:dupl false positive\n")
WC(" if " + receiverName + ".Id > 0 {\n")
WC(" return " + receiverName + ".DoUpdateById()\n")
WC(" }\n")
WC(" return " + receiverName + ".DoInsert()\n")
WC("}\n\n")
}
// Sql select all fields, used when need to mutate or show every fields
RQ("// SqlSelectAllFields generate Sql select fields\n")
RQ(`func (` + receiverName + ` *` + structName + ") SqlSelectAllFields() string { //nolint:dupl false positive\n")
sqlFields := ``
for _, prop := range props.Fields {
sqlFields += `, ` + dq(prop.Name) + "\n\t"
}
RQ(` return ` + S.BT(sqlFields[1:]) + NL)
RQ("}\n\n")
// Sql select all fields, used when need to mutate or show only uncensored fields
RQ("// SqlSelectAllUncensoredFields generate Sql select fields\n")
RQ(`func (` + receiverName + ` *` + structName + ") SqlSelectAllUncensoredFields() string { //nolint:dupl false positive\n")
sqlUncenFields := ``
for _, prop := range props.Fields {
if !censoredFieldsByName[prop.Name] {
sqlUncenFields += `, ` + dq(prop.Name) + "\n\t"
}
}
RQ(` return ` + S.BT(sqlFields[1:]) + NL)
RQ("}\n\n")
// to Update AX
RQ("// ToUpdateArray generate slice of update command\n")
RQ(`func (` + receiverName + ` *` + structName + ") ToUpdateArray() *tarantool.Operations { //nolint:dupl false positive\n")
RQ(" return tarantool.NewOperations().\n")
last := len(props.Fields) - 1
for idx, prop := range props.Fields {
RQ(" Assign(" + I.ToStr(idx) + ", " + receiverName + "." + S.PascalCase(prop.Name) + ")" +
S.If(idx != last, ".") + "\n")
}
RQ("}\n\n")
for idx, prop := range props.Fields {
propName := S.PascalCase(prop.Name)
// index functions
RQ("// Idx" + propName + " return name of the index\n")
RQ(`func (` + receiverName + ` *` + structName + ") Idx" + propName + "() int { //nolint:dupl false positive\n")
RQ(" return " + X.ToS(idx) + NL)
RQ("}\n\n")
// column name functions
//RQ(`func (` + receiverName + ` *` + structName + ") col" + propName + "() string { //nolint:dupl false positive\n")
//RQ(" return " + S.BT(prop.Name) + NL)
//RQ("}\n\n")
// Sql column name functions
RQ("// Sql" + propName + " return name of the column being indexed\n")
RQ(`func (` + receiverName + ` *` + structName + ") Sql" + propName + "() string { //nolint:dupl false positive\n")
RQ(" return " + S.BT(S.QQ(prop.Name)) + NL)
RQ("}\n\n")
// mutator methods
WC("// Set" + propName + " create mutations, should not duplicate\n")
propType := TypeToGoType[prop.Type]
WC(`func (` + receiverName + ` *` + structName + "Mutator) Set" + propName + "(val " + propType + ") bool { //nolint:dupl false positive\n")
if prop.Type != Array {
WC(" if val != " + receiverName + `.` + propName + " {\n")
WC(" " + receiverName + ".mutations.Assign(" + I.ToStr(idx) + ", val)\n")
if !censoredFieldsByName[prop.Name] {
WC(" " + receiverName + ".logs = append(" + receiverName + ".logs, A.X{`" + prop.Name + "`, " + receiverName + `.` + propName + ", val})\n")
}
WC(" " + receiverName + `.` + propName + " = val\n")
WC(" return true\n")
WC(" }\n")
WC(" return false\n")
} else { // always overwrite for array
WC(" " + receiverName + ".mutations.Assign(" + I.ToStr(idx) + ", val)\n")
WC(" " + receiverName + ".logs = append(" + receiverName + ".logs, A.X{`" + prop.Name + "`, " + receiverName + `.` + propName + ", val})\n")
if !censoredFieldsByName[prop.Name] {
WC(" " + receiverName + `.` + propName + " = val\n")
}
WC(" return true\n")
}
WC("}\n\n")
}
// SetAll
WC("// SetAll set all from another source, only if another property is not empty/nil/zero or in forceMap\n")
WC(`func (` + receiverName + ` *` + structName + "Mutator) SetAll(from " + rqPkgName + `.` + structName + ", excludeMap, forceMap M.SB) (changed bool) { //nolint:dupl false positive\n")
WC(" if excludeMap == nil { // list of fields to exclude\n")
WC(" excludeMap = M.SB{}\n")
WC(" }\n")
WC(" if forceMap == nil { // list of fields to force overwrite\n")
WC(" forceMap = M.SB{}\n")
WC(" }\n")
for _, prop := range props.Fields {
pascalPropName := S.PascalCase(prop.Name)
// index functions
WC(" if !excludeMap[`" + prop.Name + "`] && (forceMap[`" + prop.Name + "`] || from." + pascalPropName + ` != ` + TypeToGoNilValue[prop.Type] + ") {\n")
if propByName[prop.Name].Type == String {
WC(` ` + receiverName + `.` + pascalPropName + ` = S.Trim(from.` + pascalPropName + ")\n")
} else {
WC(` ` + receiverName + `.` + pascalPropName + ` = from.` + pascalPropName + "\n")
}
WC(" changed = true\n")
WC(" }\n")
}
WC(" return\n")
WC("}\n\n")
// CensorFields
if len(props.AutoCensorFields) > 0 {
RQ("// CensorFields remove sensitive fields for output\n")
RQ(`func (` + receiverName + ` *` + structName + ") CensorFields() { //nolint:dupl false positive\n")
for _, propName := range props.AutoCensorFields {
propType := propByName[propName].Type
RQ(" " + receiverName + "." + S.PascalCase(propName) + " = " + TypeToGoEmptyValue[propType] + "\n")
}
RQ(" }\n")
}
// to AX
RQ("// ToArray receiver fields to slice\n")
RQ(`func (` + receiverName + ` *` + structName + ") ToArray() A.X { //nolint:dupl false positive\n")
if props.AutoIncrementId {
RQ(" var " + IdCol + " any = nil\n")
idProp := receiverName + "." + S.PascalCase(IdCol)
RQ(" if " + idProp + " != 0 {\n")
RQ(" " + IdCol + " = " + idProp + "\n")
RQ(" }\n")
}
RQ(" return A.X{\n")
for idx, prop := range props.Fields {
camel := S.PascalCase(prop.Name)
if props.AutoIncrementId && IdCol == prop.Name {
RQ(" " + IdCol + ",\n")
} else {
RQ(" " + receiverName + "." + camel + `,` + strings.Repeat(` `, maxLen-len(camel)) + `// ` + X.ToS(idx) + NL)
}
}
RQ(" }\n")
RQ("}\n\n")
// from AX
RQ("// FromArray convert slice to receiver fields\n")
RQ(`func (` + receiverName + ` *` + structName + `) FromArray(a A.X) *` + structName + " { //nolint:dupl false positive\n")
for idx, prop := range props.Fields {
RQ(" " + receiverName + "." + S.PascalCase(prop.Name) + ` = ` + TypeToConvertFunc[prop.Type] + "(a[" + X.ToS(idx) + "])\n")
}
RQ(" return " + receiverName + NL)
RQ("}\n\n")
// from AX but uncensored
RQ("// FromUncensoredArray convert slice to receiver fields\n")
RQ(`func (` + receiverName + ` *` + structName + `) FromUncensoredArray(a A.X) *` + structName + " { //nolint:dupl false positive\n")
for idx, prop := range props.Fields {
if !censoredFieldsByName[prop.Name] {
RQ(" " + receiverName + "." + S.PascalCase(prop.Name) + ` = ` + TypeToConvertFunc[prop.Type] + "(a[" + X.ToS(idx) + "])\n")
}
}
RQ(" return " + receiverName + NL)
RQ("}\n\n")
// find many
RQ("// FindOffsetLimit returns slice of struct, order by idx, eg. .UniqueIndex*()\n")
RQ(`func (` + receiverName + ` *` + structName + ") FindOffsetLimit(offset, limit uint32, idx string) []" + structName + " { //nolint:dupl false positive\n")
RQ(" var rows []" + structName + NL)
RQ(" res, err := " + receiverName + ".Adapter.RetryDo(\n")
RQ(" tarantool.NewSelectRequest(" + receiverName + ".SpaceName()).\n")
RQ(" Index(idx).\n")
RQ(" Offset(offset).\n")
RQ(" Limit(limit).\n")
RQ(" Iterator(" + iterAll + "),\n")
RQ(" )\n")
RQ(" if L.IsError(err, `" + structName + ".FindOffsetLimit failed: `+" + receiverName + ".SpaceName()) {\n")
RQ(" return rows\n")
RQ(" }\n")
RQ(" for _, row := range res {\n")
RQ(" item := " + structName + "{}\n")
RQ(" row, ok := row.([]any)\n")
RQ(" if ok {\n")
RQ(" rows = append(rows, *item.FromArray(row))\n")
RQ(" }\n")
RQ(" }\n")
RQ(" return rows\n")
RQ("}\n\n")
// find many
RQ("// FindArrOffsetLimit returns as slice of slice order by idx eg. .UniqueIndex*()\n")
RQ(`func (` + receiverName + ` *` + structName + ") FindArrOffsetLimit(offset, limit uint32, idx string) ([]A.X, Tt.QueryMeta) { //nolint:dupl false positive\n")
RQ(" var rows []A.X" + NL)
RQ(" resp, err := " + receiverName + ".Adapter.RetryDoResp(\n")
RQ(" tarantool.NewSelectRequest(" + receiverName + ".SpaceName()).\n")
RQ(" Index(idx).\n")
RQ(" Offset(offset).\n")
RQ(" Limit(limit).\n")
RQ(" Iterator(" + iterAll + "),\n")
RQ(" )\n")
RQ(" if L.IsError(err, `" + structName + ".FindOffsetLimit failed: `+" + receiverName + ".SpaceName()) {\n")
RQ(" return rows, Tt.QueryMetaFrom(resp, err)\n")
RQ(" }\n")
RQ(" res, err := resp.Decode()\n")
RQ(" if L.IsError(err, `" + structName + ".FindOffsetLimit failed: `+" + receiverName + ".SpaceName()) {\n")
RQ(" return rows, Tt.QueryMetaFrom(resp, err)\n")
RQ(" }\n")
RQ(" rows = make([]A.X, len(res))\n")
RQ(" for _, row := range res {\n")
RQ(" row, ok := row.([]any)\n")
RQ(" if ok {\n")
RQ(" rows = append(rows, row)\n")
RQ(" }\n")
RQ(" }\n")
RQ(" return rows, Tt.QueryMetaFrom(resp, nil)\n")
RQ("}\n\n")
// total records
RQ("// Total count number of rows\n")
RQ(`func (` + receiverName + ` *` + structName + ") Total() int64 { //nolint:dupl false positive\n")
RQ(" rows := " + receiverName + ".Adapter.CallBoxSpace(" + receiverName + ".SpaceName() + `:count`, A.X{})\n")
RQ(" if len(rows) > 0 && len(rows[0]) > 0 {\n")
RQ(" return X.ToI(rows[0][0])\n")
RQ(" }\n")
RQ(" return 0\n")
RQ("}\n\n")
//// set to min value
//WC(`func (`+receiverName+` *` + structName + ") ResetToMax() { //nolint:dupl false positive\n")
//for _, prop := range props.Fields {
// WC(" "+receiverName+"." + S.PascalCase(prop.Name) + " = " + maxMap[prop.Type] + NL)
//}
//WC("}\n\n")
//
//// set to min value
//WC(`func (`+receiverName+` *` + structName + ") ResetToMin() { //nolint:dupl false positive\n")
//for _, prop := range props.Fields {
// WC(" "+receiverName+"." + S.PascalCase(prop.Name) + " = " + minMap[prop.Type] + NL)
//}
//WC("}\n\n")
//
//// set if greater
//WC(`func (`+receiverName+` *` + structName + ") SetIfLesser(l *"+structName+") { //nolint:dupl false positive\n")
//for _, prop := range props.Fields {
// propName := S.PascalCase(prop.Name)
// WC(" if "+receiverName+"." + propName + " > l." + propName + " {\n")
// WC(" "+receiverName+"." + propName + " = l." + propName + NL)
// WC(" }\n")
//}
//WC("}\n\n")
//
//// set if greater
//WC(`func (`+receiverName+` *` + structName + ") SetIfGreater(l *"+structName+") { //nolint:dupl false positive\n")
//for _, prop := range props.Fields {
// propName := S.PascalCase(prop.Name)
// WC(" if "+receiverName+"." + propName + " < l." + propName + " {\n")
// WC(" "+receiverName+"." + propName + " = l." + propName + NL)
// WC(" }\n")
//}
//WC("}\n\n")
// field type map
RQ("// " + structName + "FieldTypeMap returns key value of field name and key\n")
RQ("var " + structName + "FieldTypeMap = map[string]Tt.DataType { //nolint:dupl false positive\n")
for _, field := range props.Fields {
RQ(" " + S.BT(field.Name) + `:` + strings.Repeat(` `, maxLen-len(field.Name)) + TypeToConst[field.Type] + ",\n")
}
RQ("}\n\n")
// graphql type
if props.GenGraphqlType {
RQ(`var GraphqlType` + structName + " = graphql.NewObject(\n")
RQ(" graphql.ObjectConfig{\n")
RQ(" Name: " + S.BT(tableName) + ",\n")
RQ(" Fields: graphql.Fields{\n")
hiddenFields := map[string]bool{}
for _, fieldName := range props.HiddenFields {
hiddenFields[fieldName] = true
}
for _, field := range props.Fields {
if hiddenFields[field.Name] {
continue
}
RQ(" " + S.BT(field.Name) + ": &graphql.Field{\n")
RQ(" Type: graphql." + TypeGraphql(field) + ",\n")
RQ(" },\n")
}
RQ(" },\n")
RQ(" },\n")
RQ(")\n\n")
//// graphql field list
//RQ(`var GraphqlField` + structName + "List = &graphql.Field{\n")
//RQ(" Type: GraphqlType" + structName + ",\n")
//RQ(" Description: " + S.BT(`list of `+structName) + ",\n")
//
//RQ("}\n\n")
}
BOTH(warning)
}
err := os.MkdirAll(`./`+rqPkgName, os.ModePerm)
if L.IsError(err, `os.MkDir failed: `+rqPkgName) {
return
}
rqFname := fmt.Sprintf(`./%s/%s__ORM.GEN.go`, rqPkgName, rqPkgName)
err = os.WriteFile(rqFname, rqBuf.Bytes(), os.ModePerm)
if L.IsError(err, `os.WriteFile failed: `+rqFname) {
return
}
err = os.MkdirAll(`./`+wcPkgName, os.ModePerm)
if L.IsError(err, `os.MkDir failed: `+wcPkgName) {
return
}
wcFname := fmt.Sprintf(`./%s/%s__ORM.GEN.go`, wcPkgName, wcPkgName)
err = os.WriteFile(wcFname, wcBuf.Bytes(), os.ModePerm)
if L.IsError(err, `os.WriteFile failed: `+wcFname) {
return
}
}
func generateGraphqlQueryField(structName string, uniqueFieldName string, field Field, RQ func(str string)) {
// graphql field
RQ(`var GraphqlField` + structName + "By" + uniqueFieldName + " = &graphql.Field{\n")
RQ(" Type: GraphqlType" + structName + ",\n")
RQ(" Description: " + S.BT(`list of `+structName) + ",\n")
RQ(" Args: graphql.FieldConfigArgument{\n")
RQ(" " + S.BT(uniqueFieldName) + ": &graphql.ArgumentConfig{\n")
RQ(" Type: graphql." + TypeGraphql(field) + ",\n")
RQ(" },\n")
RQ(" },\n")
RQ("}\n\n")
// graphql field resolver
RQ(`func (g *` + structName + `) GraphqlField` + structName + "By" + uniqueFieldName + "WithResolver() *graphql.Field {\n")
RQ(" field := *GraphqlField" + structName + "By" + uniqueFieldName + "\n")
RQ(" field.Resolve = func(p graphql.ResolveParams) (any, error) {\n")
RQ(" q := g\n")
RQ(" v, ok := p.Args[" + S.BT(S.LowerFirst(uniqueFieldName)) + "]\n")
RQ(" if !ok {\n")
RQ(" v, _ = p.Args[" + S.BT(uniqueFieldName) + "]\n")
RQ(" }\n")
RQ(" q." + uniqueFieldName + " = " + TypeToConvertFunc[field.Type] + "(v)\n")
RQ(" if q.FindBy" + uniqueFieldName + "() {\n")
RQ(" return q, nil\n")
RQ(" }\n")
RQ(" return nil, nil\n")
RQ(" }\n")
RQ(" return &field\n")
RQ("}\n\n")
}
func generateMutationByUniqueIndex(uniqueCamel, structProp, receiverName, structName string, keyFunc func(string) string, RQ, WC func(str string)) {
//// primary fields
//RQ(`func (` + receiverName + ` *` + structName + ") PrimaryIndex() A.X { //nolint:dupl false positive\n")
//RQ(` return A.X{` + structProp + "}\n")
//RQ("}\n\n")
// find by unique, used when need to mutate the object
RQ("// FindBy" + uniqueCamel + " Find one by " + uniqueCamel + "\n")
RQ(`func (` + receiverName + ` *` + structName + `) FindBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
RQ(" res, err := " + receiverName + ".Adapter.RetryDo(\n")
RQ(" tarantool.NewSelectRequest(" + receiverName + ".SpaceName()).\n")
RQ(" Index(" + receiverName + ".UniqueIndex" + uniqueCamel + "()).\n")
RQ(" Limit(1).\n")
RQ(" Iterator(" + iterEq + ").\n")
RQ(" Key(" + keyFunc(structProp) + "),\n")
RQ(" )\n")
RQ(" if L.IsError(err, `" + structName + `.FindBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName()) {\n")
RQ(" return false\n")
RQ(" }\n")
RQ(" if len(res) == 1 {\n")
RQ(" if row, ok := res[0].([]any); ok {\n")
RQ(" " + receiverName + ".FromArray(row)\n")
RQ(" return true\n")
RQ(" }\n")
RQ(" }\n")
RQ(" return false\n")
RQ("}\n\n")
// Overwrite all columns, error if not exists
WC("// DoOverwriteBy" + uniqueCamel + " update all columns, error if not exists, not using mutations/Set*\n")
WC(`func (` + receiverName + ` *` + structName + `Mutator) DoOverwriteBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
WC(" _, err := " + receiverName + ".Adapter.RetryDo(tarantool.NewUpdateRequest(" + receiverName + ".SpaceName()).\n")
WC(" Index(" + receiverName + ".UniqueIndex" + uniqueCamel + "()).\n")
WC(" Key(" + keyFunc(structProp) + ").\n")
WC(" Operations(" + receiverName + ".ToUpdateArray()),\n")
WC(" )\n")
WC(" return !L.IsError(err, `" + structName + `.DoOverwriteBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName())\n")
WC("}\n\n")
// Update only mutated, error if not exists
WC("// DoUpdateBy" + uniqueCamel + " update only mutated fields, error if not exists, use Find* and Set* methods instead of direct assignment\n")
WC(`func (` + receiverName + ` *` + structName + `Mutator) DoUpdateBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
WC(` if !` + receiverName + ".HaveMutation() {\n")
WC(" return true\n")
WC(" }\n")
WC(" _, err := " + receiverName + ".Adapter.RetryDo(\n")
WC(" tarantool.NewUpdateRequest(" + receiverName + ".SpaceName()).\n")
WC(" Index(" + receiverName + ".UniqueIndex" + uniqueCamel + "()).\n")
WC(" Key(" + keyFunc(structProp) + ").\n")
WC(" Operations(" + receiverName + ".mutations),\n")
WC(" )\n")
WC(" return !L.IsError(err, `" + structName + `.DoUpdateBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName())\n")
WC("}\n\n")
// permanent delete
WC("// DoDeletePermanentBy" + uniqueCamel + " permanent delete\n")
WC(`func (` + receiverName + ` *` + structName + `Mutator) DoDeletePermanentBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
WC(" _, err := " + receiverName + ".Adapter.RetryDo(\n")
WC(" tarantool.NewDeleteRequest(" + receiverName + ".SpaceName()).\n")
WC(" Index(" + receiverName + ".UniqueIndex" + uniqueCamel + "()).\n")
WC(" Key(" + keyFunc(structProp) + "),\n")
WC(" )\n")
WC(" return !L.IsError(err, `" + structName + `.DoDeletePermanentBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName())\n")
WC("}\n\n")
}