/
per_structDB.go
1011 lines (786 loc) · 37.7 KB
/
per_structDB.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 orm
import (
"fmt"
"go/types"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/fullstack-lang/gong/go/models"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const BackRepoPerStructTemplateCode = `// generated by stacks/gong/go/models/orm_file_per_struct_back_repo.go
package orm
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
"gorm.io/gorm"
"github.com/tealeg/xlsx/v3"
"{{PkgPathRoot}}"
)
// dummy variable to have the import declaration wihthout compile failure (even if no code needing this import is generated)
var dummy_{{Structname}}_sql sql.NullBool
var dummy_{{Structname}}_time time.Duration
var dummy_{{Structname}}_sort sort.Float64Slice
// {{Structname}}API is the input in POST API
//
// for POST, API, one needs the fields of the model as well as the fields
// from associations ("Has One" and "Has Many") that are generated to
// fullfill the ORM requirements for associations
//
// swagger:model {{structname}}API
type {{Structname}}API struct {
gorm.Model
models.{{Structname}}_WOP
// encoding of pointers
// for API, it cannot be embedded
{{Structname}}PointersEncoding {{Structname}}PointersEncoding
}
// {{Structname}}PointersEncoding encodes pointers to Struct and
// reverse pointers of slice of poitners to Struct
type {{Structname}}PointersEncoding struct {
// insertion for pointer fields encoding declaration{{` + string(rune(BackRepoPointerEncodingFieldsDeclaration)) + `}}
}
// {{Structname}}DB describes a {{structname}} in the database
//
// It incorporates the GORM ID, basic fields from the model (because they can be serialized),
// the encoded version of pointers
//
// swagger:model {{structname}}DB
type {{Structname}}DB struct {
gorm.Model
// insertion for basic fields declaration{{` + string(rune(BackRepoBasicFieldsDeclaration)) + `}}
// encoding of pointers
// for GORM serialization, it is necessary to embed to Pointer Encoding declaration
{{Structname}}PointersEncoding
}
// {{Structname}}DBs arrays {{structname}}DBs
// swagger:response {{structname}}DBsResponse
type {{Structname}}DBs []{{Structname}}DB
// {{Structname}}DBResponse provides response
// swagger:response {{structname}}DBResponse
type {{Structname}}DBResponse struct {
{{Structname}}DB
}
// {{Structname}}WOP is a {{Structname}} without pointers (WOP is an acronym for "Without Pointers")
// it holds the same basic fields but pointers are encoded into uint
type {{Structname}}WOP struct {
ID int{{` + string(rune(BackRepoWOPInitialIndex)) + `}}
// insertion for WOP basic fields{{` + string(rune(BackRepoBasicAndTimeFieldsWOPDeclaration)) + `}}
// insertion for WOP pointer fields{{` + string(rune(BackRepoPointerEncodingFieldsWOPDeclaration)) + `}}
}
var {{Structname}}_Fields = []string{
// insertion for WOP basic fields{{` + string(rune(BackRepoBasicAndTimeFieldsName)) + `}}
}
type BackRepo{{Structname}}Struct struct {
// stores {{Structname}}DB according to their gorm ID
Map_{{Structname}}DBID_{{Structname}}DB map[uint]*{{Structname}}DB
// stores {{Structname}}DB ID according to {{Structname}} address
Map_{{Structname}}Ptr_{{Structname}}DBID map[*models.{{Structname}}]uint
// stores {{Structname}} according to their gorm ID
Map_{{Structname}}DBID_{{Structname}}Ptr map[uint]*models.{{Structname}}
db *gorm.DB
stage *models.StageStruct
}
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) GetStage() (stage *models.StageStruct) {
stage = backRepo{{Structname}}.stage
return
}
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) GetDB() *gorm.DB {
return backRepo{{Structname}}.db
}
// Get{{Structname}}DBFrom{{Structname}}Ptr is a handy function to access the back repo instance from the stage instance
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) Get{{Structname}}DBFrom{{Structname}}Ptr({{structname}} *models.{{Structname}}) ({{structname}}DB *{{Structname}}DB) {
id := backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}]
{{structname}}DB = backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[id]
return
}
// BackRepo{{Structname}}.CommitPhaseOne commits all staged instances of {{Structname}} to the BackRepo
// Phase One is the creation of instance in the database if it is not yet done to get the unique ID for each staged instance
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CommitPhaseOne(stage *models.StageStruct) (Error error) {
for {{structname}} := range stage.{{Structname}}s {
backRepo{{Structname}}.CommitPhaseOneInstance({{structname}})
}
// parse all backRepo instance and checks wether some instance have been unstaged
// in this case, remove them from the back repo
for id, {{structname}} := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr {
if _, ok := stage.{{Structname}}s[{{structname}}]; !ok {
backRepo{{Structname}}.CommitDeleteInstance(id)
}
}
return
}
// BackRepo{{Structname}}.CommitDeleteInstance commits deletion of {{Structname}} to the BackRepo
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CommitDeleteInstance(id uint) (Error error) {
{{structname}} := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr[id]
// {{structname}} is not staged anymore, remove {{structname}}DB
{{structname}}DB := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[id]
query := backRepo{{Structname}}.db.Unscoped().Delete(&{{structname}}DB)
if query.Error != nil {
log.Fatal(query.Error)
}
// update stores
delete(backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID, {{structname}})
delete(backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr, id)
delete(backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB, id)
return
}
// BackRepo{{Structname}}.CommitPhaseOneInstance commits {{structname}} staged instances of {{Structname}} to the BackRepo
// Phase One is the creation of instance in the database if it is not yet done to get the unique ID for each staged instance
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CommitPhaseOneInstance({{structname}} *models.{{Structname}}) (Error error) {
// check if the {{structname}} is not commited yet
if _, ok := backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}]; ok {
return
}
// initiate {{structname}}
var {{structname}}DB {{Structname}}DB
{{structname}}DB.CopyBasicFieldsFrom{{Structname}}({{structname}})
query := backRepo{{Structname}}.db.Create(&{{structname}}DB)
if query.Error != nil {
log.Fatal(query.Error)
}
// update stores
backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}] = {{structname}}DB.ID
backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr[{{structname}}DB.ID] = {{structname}}
backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[{{structname}}DB.ID] = &{{structname}}DB
return
}
// BackRepo{{Structname}}.CommitPhaseTwo commits all staged instances of {{Structname}} to the BackRepo
// Phase Two is the update of instance with the field in the database
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CommitPhaseTwo(backRepo *BackRepoStruct) (Error error) {
for idx, {{structname}} := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr {
backRepo{{Structname}}.CommitPhaseTwoInstance(backRepo, idx, {{structname}})
}
return
}
// BackRepo{{Structname}}.CommitPhaseTwoInstance commits {{structname }} of models.{{Structname}} to the BackRepo
// Phase Two is the update of instance with the field in the database
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CommitPhaseTwoInstance(backRepo *BackRepoStruct, idx uint, {{structname}} *models.{{Structname}}) (Error error) {
// fetch matching {{structname}}DB
if {{structname}}DB, ok := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[idx]; ok {
{{structname}}DB.CopyBasicFieldsFrom{{Structname}}({{structname}})
// insertion point for translating pointers encodings into actual pointers{{` + string(rune(BackRepoPointerEncodingFieldsCommit)) + `}}
query := backRepo{{Structname}}.db.Save(&{{structname}}DB)
if query.Error != nil {
log.Fatalln(query.Error)
}
} else {
err := errors.New(
fmt.Sprintf("Unkown {{Structname}} intance %s", {{structname}}.Name))
return err
}
return
}
// BackRepo{{Structname}}.CheckoutPhaseOne Checkouts all BackRepo instances to the Stage
//
// Phase One will result in having instances on the stage aligned with the back repo
// pointers are not initialized yet (this is for phase two)
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CheckoutPhaseOne() (Error error) {
{{structname}}DBArray := make([]{{Structname}}DB, 0)
query := backRepo{{Structname}}.db.Find(&{{structname}}DBArray)
if query.Error != nil {
return query.Error
}
// list of instances to be removed
// start from the initial map on the stage and remove instances that have been checked out
{{structname}}InstancesToBeRemovedFromTheStage := make(map[*models.{{Structname}}]any)
for key, value := range backRepo{{Structname}}.stage.{{Structname}}s {
{{structname}}InstancesToBeRemovedFromTheStage[key] = value
}
// copy orm objects to the the map
for _, {{structname}}DB := range {{structname}}DBArray {
backRepo{{Structname}}.CheckoutPhaseOneInstance(&{{structname}}DB)
// do not remove this instance from the stage, therefore
// remove instance from the list of instances to be be removed from the stage
{{structname}}, ok := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr[{{structname}}DB.ID]
if ok {
delete({{structname}}InstancesToBeRemovedFromTheStage, {{structname}})
}
}
// remove from stage and back repo's 3 maps all {{structname}}s that are not in the checkout
for {{structname}} := range {{structname}}InstancesToBeRemovedFromTheStage {
{{structname}}.Unstage(backRepo{{Structname}}.GetStage())
// remove instance from the back repo 3 maps
{{structname}}ID := backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}]
delete(backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID, {{structname}})
delete(backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB, {{structname}}ID)
delete(backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr, {{structname}}ID)
}
return
}
// CheckoutPhaseOneInstance takes a {{structname}}DB that has been found in the DB, updates the backRepo and stages the
// models version of the {{structname}}DB
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CheckoutPhaseOneInstance({{structname}}DB *{{Structname}}DB) (Error error) {
{{structname}}, ok := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr[{{structname}}DB.ID]
if !ok {
{{structname}} = new(models.{{Structname}})
backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr[{{structname}}DB.ID] = {{structname}}
backRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}] = {{structname}}DB.ID
// append model store with the new element
{{structname}}.Name = {{structname}}DB.Name_Data.String
{{structname}}.Stage(backRepo{{Structname}}.GetStage())
}
{{structname}}DB.CopyBasicFieldsTo{{Structname}}({{structname}})
// in some cases, the instance might have been unstaged. It is necessary to stage it again
{{structname}}.Stage(backRepo{{Structname}}.GetStage())
// preserve pointer to {{structname}}DB. Otherwise, pointer will is recycled and the map of pointers
// Map_{{Structname}}DBID_{{Structname}}DB)[{{structname}}DB hold variable pointers
{{structname}}DB_Data := *{{structname}}DB
preservedPtrTo{{Structname}} := &{{structname}}DB_Data
backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[{{structname}}DB.ID] = preservedPtrTo{{Structname}}
return
}
// BackRepo{{Structname}}.CheckoutPhaseTwo Checkouts all staged instances of {{Structname}} to the BackRepo
// Phase Two is the update of instance with the field in the database
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CheckoutPhaseTwo(backRepo *BackRepoStruct) (Error error) {
// parse all DB instance and update all pointer fields of the translated models instance
for _, {{structname}}DB := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB {
backRepo{{Structname}}.CheckoutPhaseTwoInstance(backRepo, {{structname}}DB)
}
return
}
// BackRepo{{Structname}}.CheckoutPhaseTwoInstance Checkouts staged instances of {{Structname}} to the BackRepo
// Phase Two is the update of instance with the field in the database
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) CheckoutPhaseTwoInstance(backRepo *BackRepoStruct, {{structname}}DB *{{Structname}}DB) (Error error) {
{{structname}} := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr[{{structname}}DB.ID]
{{structname}}DB.DecodePointers(backRepo, {{structname}})
return
}
func ({{structname}}DB *{{Structname}}DB) DecodePointers(backRepo *BackRepoStruct, {{structname}} *models.{{Structname}}) {
// insertion point for checkout of pointer encoding{{` + string(rune(BackRepoPointerEncodingFieldsCheckout)) + `}}
return
}
// Commit{{Structname}} allows commit of a single {{structname}} (if already staged)
func (backRepo *BackRepoStruct) Commit{{Structname}}({{structname}} *models.{{Structname}}) {
backRepo.BackRepo{{Structname}}.CommitPhaseOneInstance({{structname}})
if id, ok := backRepo.BackRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}]; ok {
backRepo.BackRepo{{Structname}}.CommitPhaseTwoInstance(backRepo, id, {{structname}})
}
backRepo.CommitFromBackNb = backRepo.CommitFromBackNb + 1
}
// Commit{{Structname}} allows checkout of a single {{structname}} (if already staged and with a BackRepo id)
func (backRepo *BackRepoStruct) Checkout{{Structname}}({{structname}} *models.{{Structname}}) {
// check if the {{structname}} is staged
if _, ok := backRepo.BackRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}]; ok {
if id, ok := backRepo.BackRepo{{Structname}}.Map_{{Structname}}Ptr_{{Structname}}DBID[{{structname}}]; ok {
var {{structname}}DB {{Structname}}DB
{{structname}}DB.ID = id
if err := backRepo.BackRepo{{Structname}}.db.First(&{{structname}}DB, id).Error; err != nil {
log.Fatalln("Checkout{{Structname}} : Problem with getting object with id:", id)
}
backRepo.BackRepo{{Structname}}.CheckoutPhaseOneInstance(&{{structname}}DB)
backRepo.BackRepo{{Structname}}.CheckoutPhaseTwoInstance(backRepo, &{{structname}}DB)
}
}
}
// CopyBasicFieldsFrom{{Structname}}
func ({{structname}}DB *{{Structname}}DB) CopyBasicFieldsFrom{{Structname}}({{structname}} *models.{{Structname}}) {
// insertion point for fields commit{{` + string(rune(BackRepoBasicFieldsCommit)) + `}}
}
// CopyBasicFieldsFrom{{Structname}}_WOP
func ({{structname}}DB *{{Structname}}DB) CopyBasicFieldsFrom{{Structname}}_WOP({{structname}} *models.{{Structname}}_WOP) {
// insertion point for fields commit{{` + string(rune(BackRepoBasicFieldsCommit)) + `}}
}
// CopyBasicFieldsFrom{{Structname}}WOP
func ({{structname}}DB *{{Structname}}DB) CopyBasicFieldsFrom{{Structname}}WOP({{structname}} *{{Structname}}WOP) {
// insertion point for fields commit{{` + string(rune(BackRepoBasicFieldsCommit)) + `}}
}
// CopyBasicFieldsTo{{Structname}}
func ({{structname}}DB *{{Structname}}DB) CopyBasicFieldsTo{{Structname}}({{structname}} *models.{{Structname}}) {
// insertion point for checkout of basic fields (back repo to stage){{` + string(rune(BackRepoBasicFieldsCheckout)) + `}}
}
// CopyBasicFieldsTo{{Structname}}_WOP
func ({{structname}}DB *{{Structname}}DB) CopyBasicFieldsTo{{Structname}}_WOP({{structname}} *models.{{Structname}}_WOP) {
// insertion point for checkout of basic fields (back repo to stage){{` + string(rune(BackRepoBasicFieldsCheckout)) + `}}
}
// CopyBasicFieldsTo{{Structname}}WOP
func ({{structname}}DB *{{Structname}}DB) CopyBasicFieldsTo{{Structname}}WOP({{structname}} *{{Structname}}WOP) {
{{structname}}.ID = int({{structname}}DB.ID)
// insertion point for checkout of basic fields (back repo to stage){{` + string(rune(BackRepoBasicFieldsCheckout)) + `}}
}
// Backup generates a json file from a slice of all {{Structname}}DB instances in the backrepo
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) Backup(dirPath string) {
filename := filepath.Join(dirPath, "{{Structname}}DB.json")
// organize the map into an array with increasing IDs, in order to have repoductible
// backup file
forBackup := make([]*{{Structname}}DB, 0)
for _, {{structname}}DB := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB {
forBackup = append(forBackup, {{structname}}DB)
}
sort.Slice(forBackup[:], func(i, j int) bool {
return forBackup[i].ID < forBackup[j].ID
})
file, err := json.MarshalIndent(forBackup, "", " ")
if err != nil {
log.Fatal("Cannot json {{Structname}} ", filename, " ", err.Error())
}
err = ioutil.WriteFile(filename, file, 0644)
if err != nil {
log.Fatal("Cannot write the json {{Structname}} file", err.Error())
}
}
// Backup generates a json file from a slice of all {{Structname}}DB instances in the backrepo
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) BackupXL(file *xlsx.File) {
// organize the map into an array with increasing IDs, in order to have repoductible
// backup file
forBackup := make([]*{{Structname}}DB, 0)
for _, {{structname}}DB := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB {
forBackup = append(forBackup, {{structname}}DB)
}
sort.Slice(forBackup[:], func(i, j int) bool {
return forBackup[i].ID < forBackup[j].ID
})
sh, err := file.AddSheet("{{Structname}}")
if err != nil {
log.Fatal("Cannot add XL file", err.Error())
}
_ = sh
row := sh.AddRow()
row.WriteSlice(&{{Structname}}_Fields, -1)
for _, {{structname}}DB := range forBackup {
var {{structname}}WOP {{Structname}}WOP
{{structname}}DB.CopyBasicFieldsTo{{Structname}}WOP(&{{structname}}WOP)
row := sh.AddRow()
row.WriteStruct(&{{structname}}WOP, -1)
}
}
// RestoreXL from the "{{Structname}}" sheet all {{Structname}}DB instances
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) RestoreXLPhaseOne(file *xlsx.File) {
// resets the map
BackRepo{{Structname}}id_atBckpTime_newID = make(map[uint]uint)
sh, ok := file.Sheet["{{Structname}}"]
_ = sh
if !ok {
log.Fatal(errors.New("sheet not found"))
}
// log.Println("Max row is", sh.MaxRow)
err := sh.ForEachRow(backRepo{{Structname}}.rowVisitor{{Structname}})
if err != nil {
log.Fatal("Err=", err)
}
}
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) rowVisitor{{Structname}}(row *xlsx.Row) error {
log.Printf("row line %d\n", row.GetCoordinate())
log.Println(row)
// skip first line
if row.GetCoordinate() > 0 {
var {{structname}}WOP {{Structname}}WOP
row.ReadStruct(&{{structname}}WOP)
// add the unmarshalled struct to the stage
{{structname}}DB := new({{Structname}}DB)
{{structname}}DB.CopyBasicFieldsFrom{{Structname}}WOP(&{{structname}}WOP)
{{structname}}DB_ID_atBackupTime := {{structname}}DB.ID
{{structname}}DB.ID = 0
query := backRepo{{Structname}}.db.Create({{structname}}DB)
if query.Error != nil {
log.Fatal(query.Error)
}
backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[{{structname}}DB.ID] = {{structname}}DB
BackRepo{{Structname}}id_atBckpTime_newID[{{structname}}DB_ID_atBackupTime] = {{structname}}DB.ID
}
return nil
}
// RestorePhaseOne read the file "{{Structname}}DB.json" in dirPath that stores an array
// of {{Structname}}DB and stores it in the database
// the map BackRepo{{Structname}}id_atBckpTime_newID is updated accordingly
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) RestorePhaseOne(dirPath string) {
// resets the map
BackRepo{{Structname}}id_atBckpTime_newID = make(map[uint]uint)
filename := filepath.Join(dirPath, "{{Structname}}DB.json")
jsonFile, err := os.Open(filename)
// if we os.Open returns an error then handle it
if err != nil {
log.Fatal("Cannot restore/open the json {{Structname}} file", filename, " ", err.Error())
}
// read our opened jsonFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
var forRestore []*{{Structname}}DB
err = json.Unmarshal(byteValue, &forRestore)
// fill up Map_{{Structname}}DBID_{{Structname}}DB
for _, {{structname}}DB := range forRestore {
{{structname}}DB_ID_atBackupTime := {{structname}}DB.ID
{{structname}}DB.ID = 0
query := backRepo{{Structname}}.db.Create({{structname}}DB)
if query.Error != nil {
log.Fatal(query.Error)
}
backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[{{structname}}DB.ID] = {{structname}}DB
BackRepo{{Structname}}id_atBckpTime_newID[{{structname}}DB_ID_atBackupTime] = {{structname}}DB.ID
}
if err != nil {
log.Fatal("Cannot restore/unmarshall json {{Structname}} file", err.Error())
}
}
// RestorePhaseTwo uses all map BackRepo<{{Structname}}>id_atBckpTime_newID
// to compute new index
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) RestorePhaseTwo() {
for _, {{structname}}DB := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB {
// next line of code is to avert unused variable compilation error
_ = {{structname}}DB
// insertion point for reindexing pointers encoding{{` + string(rune(BackRepoPointerEncodingFieldsReindexing)) + `}}
// update databse with new index encoding
query := backRepo{{Structname}}.db.Model({{structname}}DB).Updates(*{{structname}}DB)
if query.Error != nil {
log.Fatal(query.Error)
}
}
}
// BackRepo{{Structname}}.ResetReversePointers commits all staged instances of {{Structname}} to the BackRepo
// Phase Two is the update of instance with the field in the database
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) ResetReversePointers(backRepo *BackRepoStruct) (Error error) {
for idx, {{structname}} := range backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}Ptr {
backRepo{{Structname}}.ResetReversePointersInstance(backRepo, idx, {{structname}})
}
return
}
func (backRepo{{Structname}} *BackRepo{{Structname}}Struct) ResetReversePointersInstance(backRepo *BackRepoStruct, idx uint, {{structname}} *models.{{Structname}}) (Error error) {
// fetch matching {{structname}}DB
if {{structname}}DB, ok := backRepo{{Structname}}.Map_{{Structname}}DBID_{{Structname}}DB[idx]; ok {
_ = {{structname}}DB // to avoid unused variable error if there are no reverse to reset
// insertion point for reverse pointers reset{{` + string(rune(BackRepoPointerReversePointersReseting)) + `}}
// end of insertion point for reverse pointers reset
}
return
}
// this field is used during the restauration process.
// it stores the ID at the backup time and is used for renumbering
var BackRepo{{Structname}}id_atBckpTime_newID map[uint]uint
`
// insertion points
type BackRepoInsertionPoint int
const (
BackRepoBasicFieldsDeclaration BackRepoInsertionPoint = iota
BackRepoBasicAndTimeFieldsName
BackRepoWOPInitialIndex
BackRepoBasicAndTimeFieldsWOPDeclaration
BackRepoPointerEncodingFieldsDeclaration
BackRepoPointerEncodingFieldsWOPDeclaration
BackRepoBasicFieldsCommit
BackRepoPointerEncodingFieldsCommit
BackRepoBasicFieldsCheckout
BackRepoPointerEncodingFieldsCheckout
BackRepoPointerEncodingFieldsReindexing
BackRepoPointerReversePointersReseting
BackRepoNbInsertionPoints
)
// Sub Templates
type BackRepoPerStructSubTemplate int
const (
BackRepoDeclarationBasicField BackRepoPerStructSubTemplate = iota
BackRepoCommitBasicField
BackRepoCheckoutBasicField
BackRepoDeclarationTimeField
BackRepoCommitTimeField
BackRepoCheckoutTimeField
BackRepoCommitBasicFieldEnum
BackRepoCheckoutBasicFieldEnum
BackRepoCommitBasicFieldInt
BackRepoCheckoutBasicFieldInt
BackRepoCheckoutBasicFieldIntEnum
BackRepoDeclarationBasicBooleanField
BackRepoCommitBasicBooleanField
BackRepoCheckoutBasicFieldBoolean
BackRepoPointerEncoding
BackRepoSliceOfPointersEncoding
BackRepoCommitPointerToStructField
BackRepoCheckoutPointerToStructStageField
BackRepoReindexingPointerToStruct
BackRepoCommitSliceOfPointerToStructField
BackRepoCheckoutSliceOfPointerToStructStageField
)
var BackRepoFieldSubTemplateCode map[BackRepoPerStructSubTemplate]string = map[BackRepoPerStructSubTemplate]string{
//
// Declarations
//
BackRepoDeclarationBasicField: `
// Declation for basic field {{structname}}DB.{{FieldName}}
{{FieldName}}_Data sql.{{SqlNullType}}`,
BackRepoDeclarationTimeField: `
// Declation for basic field {{structname}}DB.{{FieldName}}
{{FieldName}}_Data sql.NullTime`,
BackRepoDeclarationBasicBooleanField: `
// Declation for basic field {{structname}}DB.{{FieldName}}
// provide the sql storage for the boolan
{{FieldName}}_Data sql.NullBool`,
BackRepoPointerEncoding: `
// field {{FieldName}} is a pointer to another Struct (optional or 0..1)
// This field is generated into another field to enable AS ONE association
{{FieldName}}ID sql.NullInt64`,
BackRepoSliceOfPointersEncoding: `
// field {{FieldName}} is a slice of pointers to another Struct (optional or 0..1)
{{FieldName}} IntSlice` + " `" + `gorm:"type:TEXT"` + "`",
//
// Commit sub templates
//
BackRepoCommitBasicField: `
{{structname}}DB.{{FieldName}}_Data.{{SqlNullType}} = {{structname}}.{{FieldName}}
{{structname}}DB.{{FieldName}}_Data.Valid = true`,
BackRepoCommitBasicFieldEnum: `
{{structname}}DB.{{FieldName}}_Data.String = {{structname}}.{{FieldName}}.ToString()
{{structname}}DB.{{FieldName}}_Data.Valid = true`,
BackRepoCommitBasicFieldInt: `
{{structname}}DB.{{FieldName}}_Data.Int64 = int64({{structname}}.{{FieldName}})
{{structname}}DB.{{FieldName}}_Data.Valid = true`,
BackRepoCommitTimeField: `
{{structname}}DB.{{FieldName}}_Data.Time = {{structname}}.{{FieldName}}
{{structname}}DB.{{FieldName}}_Data.Valid = true`,
BackRepoCommitBasicBooleanField: `
{{structname}}DB.{{FieldName}}_Data.Bool = {{structname}}.{{FieldName}}
{{structname}}DB.{{FieldName}}_Data.Valid = true`,
BackRepoCommitPointerToStructField: `
// commit pointer value {{structname}}.{{FieldName}} translates to updating the {{structname}}.{{FieldName}}ID
{{structname}}DB.{{FieldName}}ID.Valid = true // allow for a 0 value (nil association)
if {{structname}}.{{FieldName}} != nil {
if {{FieldName}}Id, ok := backRepo.BackRepo{{AssociationStructName}}.Map_{{AssociationStructName}}Ptr_{{AssociationStructName}}DBID[{{structname}}.{{FieldName}}]; ok {
{{structname}}DB.{{FieldName}}ID.Int64 = int64({{FieldName}}Id)
{{structname}}DB.{{FieldName}}ID.Valid = true
}
} else {
{{structname}}DB.{{FieldName}}ID.Int64 = 0
{{structname}}DB.{{FieldName}}ID.Valid = true
}
`,
BackRepoCommitSliceOfPointerToStructField: `
// 1. reset
{{structname}}DB.{{Structname}}PointersEncoding.{{FieldName}} = make([]int, 0)
// 2. encode
for _, {{associationStructName}}AssocEnd := range {{structname}}.{{FieldName}} {
{{associationStructName}}AssocEnd_DB :=
backRepo.BackRepo{{AssociationStructName}}.Get{{AssociationStructName}}DBFrom{{AssociationStructName}}Ptr({{associationStructName}}AssocEnd)
// the stage might be inconsistant, meaning that the {{associationStructName}}AssocEnd_DB might
// be missing from the stage. In this case, the commit operation is robust
// An alternative would be to crash here to reveal the missing element.
if {{associationStructName}}AssocEnd_DB == nil {
continue
}
{{structname}}DB.{{Structname}}PointersEncoding.{{FieldName}} =
append({{structname}}DB.{{Structname}}PointersEncoding.{{FieldName}}, int({{associationStructName}}AssocEnd_DB.ID))
}
`,
//
// sub template for checkouts
//
BackRepoCheckoutBasicField: `
{{structname}}.{{FieldName}} = {{structname}}DB.{{FieldName}}_Data.{{SqlNullType}}`,
BackRepoCheckoutTimeField: `
{{structname}}.{{FieldName}} = {{structname}}DB.{{FieldName}}_Data.Time`,
BackRepoCheckoutBasicFieldEnum: `
{{structname}}.{{FieldName}}.FromString({{structname}}DB.{{FieldName}}_Data.String)`,
BackRepoCheckoutBasicFieldInt: `
{{structname}}.{{FieldName}} = {{FieldType}}({{structname}}DB.{{FieldName}}_Data.Int64)`,
BackRepoCheckoutBasicFieldIntEnum: `
{{structname}}.{{FieldName}} = models.{{FieldType}}({{structname}}DB.{{FieldName}}_Data.Int64)`,
BackRepoCheckoutBasicFieldBoolean: `
{{structname}}.{{FieldName}} = {{structname}}DB.{{FieldName}}_Data.Bool`,
BackRepoCheckoutPointerToStructStageField: `
// {{FieldName}} field
{{structname}}.{{FieldName}} = nil
if {{structname}}DB.{{FieldName}}ID.Int64 != 0 {
{{structname}}.{{FieldName}} = backRepo.BackRepo{{AssociationStructName}}.Map_{{AssociationStructName}}DBID_{{AssociationStructName}}Ptr[uint({{structname}}DB.{{FieldName}}ID.Int64)]
}`,
BackRepoReindexingPointerToStruct: `
// reindexing {{FieldName}} field
if {{structname}}DB.{{FieldName}}ID.Int64 != 0 {
{{structname}}DB.{{FieldName}}ID.Int64 = int64(BackRepo{{AssociationStructName}}id_atBckpTime_newID[uint({{structname}}DB.{{FieldName}}ID.Int64)])
{{structname}}DB.{{FieldName}}ID.Valid = true
}
`,
BackRepoCheckoutSliceOfPointerToStructStageField: `
// This loop redeem {{structname}}.{{FieldName}} in the stage from the encode in the back repo
// It parses all {{AssociationStructName}}DB in the back repo and if the reverse pointer encoding matches the back repo ID
// it appends the stage instance
// 1. reset the slice
{{structname}}.{{FieldName}} = {{structname}}.{{FieldName}}[:0]
for _, _{{AssociationStructName}}id := range {{structname}}DB.{{Structname}}PointersEncoding.{{FieldName}} {
{{structname}}.{{FieldName}} = append({{structname}}.{{FieldName}}, backRepo.BackRepo{{AssociationStructName}}.Map_{{AssociationStructName}}DBID_{{AssociationStructName}}Ptr[uint(_{{AssociationStructName}}id)])
}
`,
}
// MultiCodeGeneratorBackRepo parses mdlPkg and generates the code for the
// back repository code
func MultiCodeGeneratorBackRepo(
modelPkg *models.ModelPkg,
pkgName string,
pkgGoPath string,
dirPath string) {
// have alphabetical order generation
structList := []*models.GongStruct{}
for _, _struct := range modelPkg.GongStructs {
if _struct.HasNameField() {
structList = append(structList, _struct)
}
}
sort.Slice(structList[:], func(i, j int) bool {
return structList[i].Name < structList[j].Name
})
for _, _struct := range structList {
codeGO := BackRepoPerStructTemplateCode
insertions := make(map[BackRepoInsertionPoint]string)
for insertion := BackRepoInsertionPoint(0); insertion < BackRepoNbInsertionPoints; insertion++ {
insertions[insertion] = ""
}
insertions[BackRepoBasicAndTimeFieldsName] += "\n\t\"ID\","
// for xlsx unmarshall, each field is with a magic code `xlsx:"N"` where N the the field ID
insertions[BackRepoWOPInitialIndex] = " `xlsx:\"0\"`"
fieldWOPindex := 1
for _, field := range _struct.Fields {
switch field := field.(type) {
case *models.GongBasicField:
insertions[BackRepoBasicAndTimeFieldsWOPDeclaration] +=
"\n\n\t" + field.Name + " " +
strings.ReplaceAll(field.DeclaredType, pkgGoPath+".", "models.") + fmt.Sprintf(" `xlsx:\"%d\"`", fieldWOPindex)
fieldWOPindex = fieldWOPindex + 1
insertions[BackRepoBasicAndTimeFieldsName] += "\n\t\"" + field.Name + "\","
if field.GetBasicKind() == types.Bool {
insertions[BackRepoBasicFieldsDeclaration] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoDeclarationBasicBooleanField],
"{{FieldName}}", field.Name)
insertions[BackRepoBasicFieldsCommit] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoCommitBasicBooleanField],
"{{FieldName}}", field.Name)
insertions[BackRepoBasicFieldsCheckout] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoCheckoutBasicFieldBoolean],
"{{FieldName}}", field.Name)
} else {
switch field.GetBasicKind() {
case types.String:
insertions[BackRepoBasicFieldsDeclaration] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoDeclarationBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "NullString")
if field.GongEnum != nil {
insertions[BackRepoBasicFieldsCommit] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoCommitBasicFieldEnum],
"{{FieldName}}", field.Name)
insertions[BackRepoBasicFieldsCheckout] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCheckoutBasicFieldEnum],
"{{FieldName}}", field.Name,
"{{EnumType}}", field.GongEnum.Name)
} else {
insertions[BackRepoBasicFieldsCommit] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCommitBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "String")
insertions[BackRepoBasicFieldsCheckout] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCheckoutBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "String")
}
case types.Float64:
insertions[BackRepoBasicFieldsDeclaration] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoDeclarationBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "NullFloat64")
insertions[BackRepoBasicFieldsCommit] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCommitBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "Float64")
insertions[BackRepoBasicFieldsCheckout] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCheckoutBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "Float64")
case types.Int, types.Int64:
insertions[BackRepoBasicFieldsDeclaration] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoDeclarationBasicField],
"{{FieldName}}", field.Name,
"{{SqlNullType}}", "NullInt64")
insertions[BackRepoBasicFieldsCommit] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoCommitBasicFieldInt],
"{{FieldName}}", field.Name)
if field.GongEnum != nil {
insertions[BackRepoBasicFieldsCheckout] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCheckoutBasicFieldIntEnum],
"{{FieldName}}", field.Name,
"{{FieldType}}", field.GongEnum.Name)
} else {
insertions[BackRepoBasicFieldsCheckout] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoCheckoutBasicFieldInt],
"{{FieldName}}", field.Name,
"{{FieldType}}", field.DeclaredType)
}
default:
}
}
case *models.GongTimeField:
insertions[BackRepoBasicAndTimeFieldsWOPDeclaration] +=
"\n\n\t" + field.Name + " " + "time.Time" + fmt.Sprintf(" `xlsx:\"%d\"`", fieldWOPindex)
fieldWOPindex = fieldWOPindex + 1
insertions[BackRepoBasicAndTimeFieldsName] += "\n\t\"" + field.Name + "\","
insertions[BackRepoBasicFieldsDeclaration] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoDeclarationTimeField],
"{{FieldName}}", field.Name)
insertions[BackRepoBasicFieldsCheckout] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoCheckoutTimeField],
"{{FieldName}}", field.Name)
insertions[BackRepoBasicFieldsCommit] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoCommitTimeField],
"{{FieldName}}", field.Name)
case *models.PointerToGongStructField:
insertions[BackRepoPointerEncodingFieldsDeclaration] += models.Replace1(
BackRepoFieldSubTemplateCode[BackRepoPointerEncoding],
"{{FieldName}}", field.Name)
insertions[BackRepoPointerEncodingFieldsCommit] += models.Replace3(
BackRepoFieldSubTemplateCode[BackRepoCommitPointerToStructField],
"{{AssociationStructName}}", field.GongStruct.Name,
"{{associationStructName}}", strings.ToLower(field.GongStruct.Name),
"{{FieldName}}", field.Name)
insertions[BackRepoPointerEncodingFieldsCheckout] += models.Replace3(
BackRepoFieldSubTemplateCode[BackRepoCheckoutPointerToStructStageField],
"{{AssociationStructName}}", field.GongStruct.Name,
"{{associationStructName}}", strings.ToLower(field.GongStruct.Name),
"{{FieldName}}", field.Name)
insertions[BackRepoPointerEncodingFieldsReindexing] += models.Replace3(
BackRepoFieldSubTemplateCode[BackRepoReindexingPointerToStruct],
"{{AssociationStructName}}", field.GongStruct.Name,
"{{associationStructName}}", strings.ToLower(field.GongStruct.Name),
"{{FieldName}}", field.Name)
case *models.SliceOfPointerToGongStructField:
insertions[BackRepoPointerEncodingFieldsDeclaration] += models.Replace2(
BackRepoFieldSubTemplateCode[BackRepoSliceOfPointersEncoding],
"{{FieldName}}", field.Name,
"{{AssociationStructName}}", field.GongStruct.Name,
)
insertions[BackRepoPointerEncodingFieldsCommit] += models.Replace3(
BackRepoFieldSubTemplateCode[BackRepoCommitSliceOfPointerToStructField],
"{{AssociationStructName}}", field.GongStruct.Name,
"{{associationStructName}}", strings.ToLower(field.GongStruct.Name),
"{{FieldName}}", field.Name)
insertions[BackRepoPointerEncodingFieldsCheckout] += models.Replace3(
BackRepoFieldSubTemplateCode[BackRepoCheckoutSliceOfPointerToStructStageField],
"{{AssociationStructName}}", field.GongStruct.Name,
"{{associationStructName}}", strings.ToLower(field.GongStruct.Name),
"{{FieldName}}", field.Name)
}
}
// substitutes {{<<insertion points>>}} stuff with generated code
for insertion := BackRepoInsertionPoint(0); insertion < BackRepoNbInsertionPoints; insertion++ {
toReplace := "{{" + string(rune(insertion)) + "}}"
codeGO = strings.ReplaceAll(codeGO, toReplace, insertions[insertion])
}
// substitutes struct level {{<...>}} stuff
caserEnglish := cases.Title(language.English)
codeGO = models.Replace6(codeGO,
"{{PkgName}}", pkgName,
"{{TitlePkgName}}", caserEnglish.String(pkgName),
"{{pkgname}}", strings.ToLower(pkgName),
"{{PkgPathRoot}}", strings.ReplaceAll(pkgGoPath, "/orm", ""),
"{{Structname}}", _struct.Name,