-
Notifications
You must be signed in to change notification settings - Fork 9
/
collection_handlers.go
1210 lines (1136 loc) · 43.4 KB
/
collection_handlers.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
/*
* Copyright 2018. bigpigeon. All rights reserved.
* Use of this source code is governed by a MIT style
* license that can be found in the LICENSE file.
*/
package toyorm
import (
"errors"
"fmt"
"reflect"
"time"
)
func CollectionHandlerPreloadInsertOrSave(option string) func(*CollectionContext) error {
return func(ctx *CollectionContext) error {
for fieldName, preload := range ctx.Brick.BelongToPreload {
mainField, subField := preload.RelationField, preload.SubModel.GetOnePrimary()
preloadBrick := ctx.Brick.MapPreloadBrick[fieldName]
subRecords := MakeRecordsWithElem(preload.SubModel, ctx.Result.Records.GetFieldAddressType(fieldName))
// map[i]=>j [i]record.SubData -> [j]subRecord
bindMap := map[int]int{}
for i, record := range ctx.Result.Records.GetRecords() {
if ctx.Brick.ignoreModeSelector[ModePreload].Ignore(record.Field(fieldName)) == false {
bindMap[i] = subRecords.Len()
subRecords.Add(record.FieldAddress(fieldName))
}
}
subCtx := preloadBrick.GetContext(option, subRecords)
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
// set model relation field
ctx.Result.SimpleRelation[fieldName] = map[int]int{}
for i, record := range ctx.Result.Records.GetRecords() {
if j, ok := bindMap[i]; ok {
subRecord := subRecords.GetRecord(j)
record.SetField(mainField.Name(), subRecord.Field(subField.Name()))
ctx.Result.SimpleRelation[fieldName][j] = i
}
}
}
if err := ctx.Next(); err != nil {
return err
}
for fieldName, preload := range ctx.Brick.OneToOnePreload {
preloadBrick := ctx.Brick.MapPreloadBrick[fieldName]
mainPos, subPos := preload.Model.GetOnePrimary(), preload.RelationField
subRecords := MakeRecordsWithElem(preload.SubModel, ctx.Result.Records.GetFieldAddressType(fieldName))
// set sub model relation field
ctx.Result.SimpleRelation[fieldName] = map[int]int{}
for i, record := range ctx.Result.Records.GetRecords() {
if ctx.Brick.ignoreModeSelector[ModePreload].Ignore(record.Field(fieldName)) == false {
// it means relation field, result[j].LastInsertId() is id value
subRecord := subRecords.Add(record.FieldAddress(fieldName))
ctx.Result.SimpleRelation[fieldName][subRecords.Len()-1] = i
if primary := record.Field(mainPos.Name()); primary.IsValid() {
subRecord.SetField(subPos.Name(), primary)
} else {
panic("relation field not set")
}
}
}
subCtx := preloadBrick.GetContext(option, subRecords)
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
// one to many
for fieldName, preload := range ctx.Brick.OneToManyPreload {
preloadBrick := ctx.Brick.MapPreloadBrick[fieldName]
mainField, subField := preload.Model.GetOnePrimary(), preload.RelationField
elemAddressType := reflect.PtrTo(LoopTypeIndirect(ctx.Result.Records.GetFieldType(fieldName)).Elem())
subRecords := MakeRecordsWithElem(preload.SubModel, elemAddressType)
// set sub model relation field
ctx.Result.MultipleRelation[fieldName] = map[int]Pair{}
for i, record := range ctx.Result.Records.GetRecords() {
if primary := record.Field(mainField.Name()); primary.IsValid() {
rField := LoopIndirect(record.Field(fieldName))
for subi := 0; subi < rField.Len(); subi++ {
subRecord := subRecords.Add(rField.Index(subi).Addr())
ctx.Result.MultipleRelation[fieldName][subRecords.Len()-1] = Pair{i, subi}
subRecord.SetField(subField.Name(), primary)
}
} else {
return errors.New("some records have not primary")
}
}
subCtx := preloadBrick.GetContext(option, subRecords)
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
// many to many
for fieldName, preload := range ctx.Brick.ManyToManyPreload {
subBrick := ctx.Brick.MapPreloadBrick[fieldName]
middleBrick := NewCollectionBrick(ctx.Brick.Toy, preload.MiddleModel).CopyStatus(ctx.Brick)
mainField, subField := preload.Model.GetOnePrimary(), preload.SubModel.GetOnePrimary()
elemAddressType := reflect.PtrTo(LoopTypeIndirect(ctx.Result.Records.GetFieldType(fieldName)).Elem())
subRecords := MakeRecordsWithElem(preload.SubModel, elemAddressType)
ctx.Result.MultipleRelation[fieldName] = map[int]Pair{}
for i, record := range ctx.Result.Records.GetRecords() {
rField := LoopIndirect(record.Field(fieldName))
for subi := 0; subi < rField.Len(); subi++ {
subRecords.Add(rField.Index(subi).Addr())
ctx.Result.MultipleRelation[fieldName][subRecords.Len()-1] = Pair{i, subi}
}
}
subCtx := subBrick.GetContext(option, subRecords)
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
middleRecords := MakeRecordsWithElem(middleBrick.Model, middleBrick.Model.ReflectType)
// use to calculate what sub records belong for
offset := 0
for _, record := range ctx.Result.Records.GetRecords() {
primary := record.Field(mainField.Name())
primary.IsValid()
if primary.IsValid() == false {
return errors.New("some records have not primary")
}
rField := LoopIndirect(record.Field(fieldName))
for subi := 0; subi < rField.Len(); subi++ {
subRecord := subRecords.GetRecord(subi + offset)
subPrimary := subRecord.Field(subField.Name())
if subPrimary.IsValid() == false {
return errors.New("some records have not primary")
}
middleRecord := NewRecord(middleBrick.Model, reflect.New(middleBrick.Model.ReflectType).Elem())
middleRecord.SetField(preload.RelationField.Name(), primary)
middleRecord.SetField(preload.SubRelationField.Name(), subPrimary)
middleRecords.Add(middleRecord.Source())
}
offset += rField.Len()
}
middleCtx := middleBrick.GetContext(option, middleRecords)
ctx.Result.MiddleModelPreload[fieldName] = middleCtx.Result
if err := middleCtx.Next(); err != nil {
return err
}
}
return nil
}
}
func CollectionHandlerInsertTimeGenerate(ctx *CollectionContext) error {
records := ctx.Result.Records
createField := ctx.Brick.Model.GetFieldWithName("CreatedAt")
updateField := ctx.Brick.Model.GetFieldWithName("UpdatedAt")
if createField != nil || updateField != nil {
current := time.Now()
if createField != nil {
for _, record := range records.GetRecords() {
record.SetField(createField.Name(), reflect.ValueOf(current))
}
}
if updateField != nil {
for _, record := range records.GetRecords() {
record.SetField(updateField.Name(), reflect.ValueOf(current))
}
}
}
return nil
}
func CollectionHandlerInsertAssignDbIndex(ctx *CollectionContext) error {
if ctx.Brick.dbIndex != -1 {
return nil
}
primaryKeyField := ctx.Brick.Model.GetPrimary()
var getDBIndex func(r ModelRecord) (int, error)
notPtrElemType := LoopTypeIndirect(ctx.Result.Records.ElemType())
if _, ok := reflect.Zero(reflect.PtrTo(notPtrElemType)).Interface().(DBValSelector); ok {
getDBIndex = func(r ModelRecord) (int, error) {
iface := r.Source().Addr().Interface().(DBValSelector)
return iface.Select(len(ctx.Brick.Toy.dbs)), nil
}
} else if selector := ctx.Brick.selector; selector != nil {
getDBIndex = func(r ModelRecord) (int, error) {
var ifaces []interface{}
for _, field := range primaryKeyField {
if fieldVal := r.Field(field.Name()); !fieldVal.IsValid() || IsZero(fieldVal) {
return 0, ErrZeroPrimaryKey{ctx.Brick.Model}
} else {
ifaces = append(ifaces, fieldVal.Interface())
}
}
return selector(len(ctx.Brick.Toy.dbs), ifaces...), nil
}
} else {
return ErrCollectionDBSelectorNotFound{}
}
dbRecordsMap := map[int]ModelRecords{}
// dbRecordsMap dbIndexMap[i] means the position in Records
dbIndexMap := make([][]int, len(ctx.Brick.Toy.dbs))
for i, record := range ctx.Result.Records.GetRecords() {
dbIndex, err := getDBIndex(record)
if err != nil {
return err
}
if dbRecordsMap[dbIndex] == nil {
dbRecordsMap[dbIndex] = MakeRecordsWithElem(ctx.Brick.Model, record.Source().Addr().Type())
}
dbRecordsMap[dbIndex].Add(record.Source().Addr())
dbIndexMap[dbIndex] = append(dbIndexMap[dbIndex], i)
}
for i, records := range dbRecordsMap {
dbCtx := NewCollectionContext(ctx.handlers[ctx.index+1:], ctx.Brick.DBIndex(i), records)
err := dbCtx.Next()
if err != nil {
return err
}
for _, action := range dbCtx.Result.ActionFlow {
affectData := action.AffectData()
for j := 0; j < len(affectData); j++ {
affectData[j] = dbIndexMap[i][affectData[j]]
}
action.SetAffectData(affectData)
ctx.Result.AddRecord(action)
}
//
}
ctx.Abort()
return nil
}
func CollectionHandlerInsert(ctx *CollectionContext) error {
// current insert
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
//setInsertId := len(ctx.Brick.Model.GetPrimary()) == 1 && ctx.Brick.Model.GetOnePrimary().AutoIncrement() == true
for i, record := range ctx.Result.Records.GetRecords() {
action := CollectionExecAction{affectData: []int{i}, dbIndex: ctx.Brick.dbIndex}
var err error
if ctx.Brick.template == nil {
action.Exec = ctx.Brick.InsertExec(record)
} else {
tempMap := DefaultCollectionTemplateExec(ctx.Brick)
values := ctx.Brick.getFieldValuePairWithRecord(ModeInsert, record).ToValueList()
tempMap["Columns"] = getColumnExec(columnsValueToColumn(values))
tempMap["Values"] = getValuesExec(values)
action.Exec, err = ctx.Brick.Toy.Dialect.TemplateExec(*ctx.Brick.template, tempMap)
if err != nil {
return err
}
}
action.Result, action.Error = ctx.Brick.Toy.Dialect.InsertExecutor(
ctx.Brick.Toy.dbs[action.dbIndex],
action.Exec,
ctx.Brick.debugPrint(action.dbIndex),
)
if action.Error == nil {
// set primary field value if model has one primary key
if len(ctx.Brick.Model.GetPrimary()) == 1 {
primaryKey := ctx.Brick.Model.GetOnePrimary()
primaryKeyName := primaryKey.Name()
if IntKind(primaryKey.StructField().Type.Kind()) {
// just set not zero primary key
if fieldValue := record.Field(primaryKeyName); !fieldValue.IsValid() || IsZero(fieldValue) {
if lastId, err := action.Result.LastInsertId(); err == nil {
ctx.Result.Records.GetRecord(i).SetField(primaryKeyName, reflect.ValueOf(lastId))
} else {
return errors.New(fmt.Sprintf("get (%s) auto increment failure reason(%s)", ctx.Brick.Model.Name, err))
}
}
}
}
}
ctx.Result.AddRecord(action)
}
return nil
}
// preload schedule belongTo -> Next() -> oneToOne -> oneToMany -> manyToMany(sub -> middle)
func CollectionHandlerSimplePreload(option string) func(ctx *CollectionContext) error {
return func(ctx *CollectionContext) (err error) {
for fieldName := range ctx.Brick.BelongToPreload {
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
err = ctx.Next()
if err != nil {
return err
}
for fieldName := range ctx.Brick.OneToOnePreload {
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
for fieldName := range ctx.Brick.OneToManyPreload {
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
for fieldName, preload := range ctx.Brick.ManyToManyPreload {
{
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
// process middle model
{
middleModel := preload.MiddleModel
brick := NewCollectionBrick(ctx.Brick.Toy, middleModel).CopyStatus(ctx.Brick)
middleCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.MiddleModelPreload[fieldName] = middleCtx.Result
if err := middleCtx.Next(); err != nil {
return err
}
}
}
return nil
}
}
// preload schedule oneToOne -> oneToMany -> current model -> manyToMany(sub -> middle) -> Next() -> belongTo
func CollectionHandlerDropTablePreload(option string) func(ctx *CollectionContext) error {
return func(ctx *CollectionContext) (err error) {
for fieldName := range ctx.Brick.OneToOnePreload {
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
for fieldName := range ctx.Brick.OneToManyPreload {
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
for fieldName, preload := range ctx.Brick.ManyToManyPreload {
// process middle model
{
middleModel := preload.MiddleModel
brick := NewCollectionBrick(ctx.Brick.Toy, middleModel).CopyStatus(ctx.Brick)
middleCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.MiddleModelPreload[fieldName] = middleCtx.Result
if err := middleCtx.Next(); err != nil {
return err
}
}
// process sub model
{
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
}
err = ctx.Next()
if err != nil {
return err
}
for fieldName := range ctx.Brick.BelongToPreload {
brick := ctx.Brick.MapPreloadBrick[fieldName]
subCtx := brick.GetContext(option, MakeRecordsWithElem(brick.Model, brick.Model.ReflectType))
ctx.Result.Preload[fieldName] = subCtx.Result
if err := subCtx.Next(); err != nil {
return err
}
}
return nil
}
}
// assign after handlers to all db
func CollectionHandlerAssignToAllDb(ctx *CollectionContext) error {
if ctx.Brick.dbIndex != -1 {
return nil
}
for i := range ctx.Brick.Toy.dbs {
dbCtx := NewCollectionContext(ctx.handlers[ctx.index+1:], ctx.Brick.DBIndex(i), ctx.Result.Records)
err := dbCtx.Next()
if err != nil {
return err
}
ctx.Result.ActionFlow = append(ctx.Result.ActionFlow, dbCtx.Result.ActionFlow...)
}
ctx.Abort()
return nil
}
func CollectionHandlerCreateTable(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
execs := ctx.Brick.Toy.Dialect.CreateTable(ctx.Brick.Model, map[string]ForeignKey{})
for _, exec := range execs {
action := CollectionExecAction{Exec: exec, dbIndex: ctx.Brick.dbIndex}
action.Result, action.Error = ctx.Brick.Exec(exec, action.dbIndex)
ctx.Result.AddRecord(action)
}
return nil
}
func CollectionHandlerExistTableAbort(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
action := CollectionQueryAction{dbIndex: ctx.Brick.dbIndex}
action.Exec = ctx.Brick.Toy.Dialect.HasTable(ctx.Brick.Model)
var hasTable bool
err := ctx.Brick.QueryRow(action.Exec, ctx.Brick.dbIndex).Scan(&hasTable)
if err != nil {
action.Error = append(action.Error, err)
}
ctx.Result.AddRecord(action)
if err != nil || hasTable == true {
ctx.Abort()
}
return nil
}
func CollectionHandlerDropTable(ctx *CollectionContext) (err error) {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
exec := ctx.Brick.Toy.Dialect.DropTable(ctx.Brick.Model)
action := CollectionExecAction{Exec: exec, dbIndex: ctx.Brick.dbIndex}
action.Result, action.Error = ctx.Brick.Exec(exec, action.dbIndex)
ctx.Result.AddRecord(action)
return nil
}
func CollectionHandlerNotExistTableAbort(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
action := CollectionQueryAction{}
action.Exec = ctx.Brick.Toy.Dialect.HasTable(ctx.Brick.Model)
var hasTable bool
err := ctx.Brick.QueryRow(action.Exec, ctx.Brick.dbIndex).Scan(&hasTable)
if err != nil {
action.Error = append(action.Error, err)
}
ctx.Result.AddRecord(action)
if err != nil || hasTable == false {
ctx.Abort()
}
return nil
}
func CollectionHandlerPreloadContainerCheck(ctx *CollectionContext) error {
for fieldName, preload := range ctx.Brick.BelongToPreload {
if fieldType := ctx.Result.Records.GetFieldType(fieldName); fieldType == nil {
return errors.New(fmt.Sprintf("struct missing %s field", fieldName))
} else {
subRecords := MakeRecordsWithElem(preload.SubModel, fieldType)
subPrimaryFieldName := preload.SubModel.GetOnePrimary().Name()
if relationFieldType := subRecords.GetFieldType(subPrimaryFieldName); relationFieldType == nil {
return errors.New(fmt.Sprintf("struct of the %s field missing %s field", fieldName, subPrimaryFieldName))
}
}
if fieldType := ctx.Result.Records.GetFieldType(preload.RelationField.Name()); fieldType == nil {
return errors.New(fmt.Sprintf("struct missing %s field", preload.RelationField.Name()))
}
}
var needPrimaryKey bool
for fieldName, preload := range ctx.Brick.OneToOnePreload {
needPrimaryKey = true
if fieldType := ctx.Result.Records.GetFieldType(fieldName); fieldType == nil {
return errors.New(fmt.Sprintf("struct missing %s field", fieldName))
} else {
subRecords := MakeRecordsWithElem(preload.SubModel, fieldType)
if relationFieldType := subRecords.GetFieldType(preload.RelationField.Name()); relationFieldType == nil {
return errors.New(fmt.Sprintf("struct of the %s field missing %s field", fieldName, preload.RelationField.Name()))
}
}
}
for fieldName, preload := range ctx.Brick.OneToManyPreload {
needPrimaryKey = true
if fieldType := ctx.Result.Records.GetFieldType(fieldName); fieldType == nil {
return errors.New(fmt.Sprintf("struct missing %s field", fieldName))
} else {
subRecords := MakeRecordsWithElem(preload.SubModel, fieldType)
if relationFieldType := subRecords.GetFieldType(preload.RelationField.Name()); relationFieldType == nil {
return errors.New(fmt.Sprintf("struct of the %s field missing %s field", fieldName, preload.RelationField.Name()))
}
}
}
for fieldName, preload := range ctx.Brick.ManyToManyPreload {
needPrimaryKey = true
if fieldType := ctx.Result.Records.GetFieldType(fieldName); fieldType == nil {
return errors.New(fmt.Sprintf("struct missing %s field", fieldName))
} else {
subRecords := MakeRecordsWithElem(preload.SubModel, fieldType)
subPrimaryFieldName := preload.SubModel.GetOnePrimary().Name()
if relationFieldType := subRecords.GetFieldType(subPrimaryFieldName); relationFieldType == nil {
return errors.New(fmt.Sprintf("struct of the %s field missing %s field", fieldName, subPrimaryFieldName))
}
}
}
if needPrimaryKey {
primaryName := ctx.Brick.Model.GetOnePrimary().Name()
if primaryType := ctx.Result.Records.GetFieldType(primaryName); primaryType == nil {
return errors.New(fmt.Sprintf("struct missing %s field", primaryName))
}
}
return nil
}
func CollectionHandlerSaveTimeGenerate(ctx *CollectionContext) error {
now := reflect.ValueOf(time.Now())
if createAtField := ctx.Brick.Model.GetFieldWithName("CreatedAt"); createAtField != nil {
for _, record := range ctx.Result.Records.GetRecords() {
if fieldValue := record.Field(createAtField.Name()); fieldValue.IsValid() == false || IsZero(fieldValue) {
record.SetField(createAtField.Name(), now)
}
}
}
if updateField := ctx.Brick.Model.GetFieldWithName("UpdatedAt"); updateField != nil {
for _, record := range ctx.Result.Records.GetRecords() {
record.SetField(updateField.Name(), now)
}
}
return nil
}
func CollectionHandlerSave(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
//setInsertId := len(ctx.Brick.Model.GetPrimary()) == 1 && ctx.Brick.Model.GetOnePrimary().AutoIncrement() == true
for i, record := range ctx.Result.Records.GetRecords() {
var action CollectionExecAction
var err error
action = CollectionExecAction{affectData: []int{i}, dbIndex: ctx.Brick.dbIndex}
var useInsert bool
// if have any primary key, use insert ,other use update
for _, key := range ctx.Brick.Model.PrimaryFields {
if field := record.Field(key.Name()); field.IsValid() == false || IsZero(field) {
useInsert = true
}
}
if ctx.Brick.template == nil {
if useInsert {
action.Exec = ctx.Brick.InsertExec(record)
action.Result, action.Error = ctx.Brick.Toy.Dialect.InsertExecutor(
ctx.Brick.Toy.dbs[action.dbIndex],
action.Exec,
ctx.Brick.debugPrint(action.dbIndex),
)
if action.Error == nil {
// set primary field value if model has one primary key
if len(ctx.Brick.Model.GetPrimary()) == 1 {
primaryKey := ctx.Brick.Model.GetOnePrimary()
primaryKeyName := primaryKey.Name()
if IntKind(primaryKey.StructField().Type.Kind()) {
// just set not zero primary key
if fieldValue := record.Field(primaryKeyName); !fieldValue.IsValid() || IsZero(fieldValue) {
if lastId, err := action.Result.LastInsertId(); err == nil {
ctx.Result.Records.GetRecord(i).SetField(primaryKeyName, reflect.ValueOf(lastId))
} else {
return errors.New(fmt.Sprintf("get (%s) auto increment failure reason(%s)", ctx.Brick.Model.Name, err))
}
}
}
}
}
} else {
action.Exec = ctx.Brick.SaveExec(record)
action.Result, action.Error = ctx.Brick.Toy.Dialect.SaveExecutor(
ctx.Brick.Toy.dbs[action.dbIndex],
action.Exec,
ctx.Brick.debugPrint(action.dbIndex),
)
}
} else {
tempMap := DefaultCollectionTemplateExec(ctx.Brick)
values := ctx.Brick.getFieldValuePairWithRecord(ModeSave, record).ToValueList()
tempMap["Columns"] = getColumnExec(columnsValueToColumn(values))
tempMap["Values"] = getValuesExec(values)
tempMap["UpdateValues"] = getUpdateValuesExec(values)
action.Exec, err = ctx.Brick.Toy.Dialect.TemplateExec(*ctx.Brick.template, tempMap)
if err != nil {
return err
}
}
ctx.Result.AddRecord(action)
}
return nil
}
func CollectionHandlerUSave(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
notIgnoreBrick := ctx.Brick.IgnoreMode(ModeDefault, IgnoreNo)
for i, record := range ctx.Result.Records.GetRecords() {
var action CollectionExecAction
var err error
action = CollectionExecAction{affectData: []int{i}}
var useInsert bool
ConditionKeyVal := map[string]interface{}{}
// if have any zero primary key,, return error ,otherwise use update
for _, field := range ctx.Brick.Model.PrimaryFields {
if fieldVal := record.Field(field.Name()); fieldVal.IsValid() == false || IsZero(fieldVal) {
useInsert = true
} else {
ConditionKeyVal[field.Name()] = fieldVal.Interface()
}
}
if useInsert {
action.Exec = DefaultExec{"nil sql", nil}
action.Error = ErrNilPrimaryKey{}
} else {
// cas process
if casField := ctx.Brick.Model.GetFieldWithName("Cas"); casField != nil {
ConditionKeyVal[casField.Name()] = record.Field(casField.Name()).Int() - 1
}
brick := notIgnoreBrick.WhereGroup(ExprAnd, ConditionKeyVal)
if ctx.Brick.template == nil {
action.Exec = brick.UpdateExec(record)
action.Result, action.Error = ctx.Brick.Exec(action.Exec, brick.dbIndex)
} else {
tempMap := DefaultCollectionTemplateExec(brick)
values := ctx.Brick.getFieldValuePairWithRecord(ModeSave, record).ToValueList()
tempMap["UpdateValues"] = getUpdateValuesExec(values)
action.Exec, err = ctx.Brick.Toy.Dialect.TemplateExec(*ctx.Brick.template, tempMap)
if err != nil {
return err
}
}
}
ctx.Result.AddRecord(action)
}
return nil
}
func CollectionHandlerPreloadFind(ctx *CollectionContext) error {
ctx.Next()
for fieldName, preload := range ctx.Brick.BelongToPreload {
mainField, subField := preload.RelationField, preload.SubModel.GetOnePrimary()
brick := ctx.Brick.MapPreloadBrick[fieldName]
mainGroup := ctx.Result.Records.GroupBy(mainField.Name())
delete(mainGroup, reflect.Zero(mainField.StructField().Type))
if keys := mainGroup.Keys(); len(keys) != 0 {
// the relation condition should have lowest priority
brick = brick.Where(ExprIn, subField, keys).And().Conditions(brick.Search)
containerList := reflect.New(reflect.SliceOf(ctx.Result.Records.GetFieldType(fieldName))).Elem()
//var preloadRecords ModelRecords
subCtx, err := brick.find(LoopIndirectAndNew(containerList))
ctx.Result.Preload[fieldName] = subCtx.Result
if err != nil {
return err
}
// set sub data to container field
subGroup := subCtx.Result.Records.GroupBy(subField.Name())
ctx.Result.SimpleRelation[fieldName] = map[int]int{}
for key, records := range mainGroup {
if subRecords := subGroup[key]; len(subRecords) != 0 {
for _, record := range records {
record.SetField(preload.ContainerField.Name(), subRecords[0].Source())
ctx.Result.SimpleRelation[fieldName][subRecords[0].Index] = record.Index
}
}
}
}
}
for fieldName, preload := range ctx.Brick.OneToOnePreload {
var mainField, subField Field
mainField, subField = preload.Model.GetOnePrimary(), preload.RelationField
brick := ctx.Brick.MapPreloadBrick[fieldName]
mainGroup := ctx.Result.Records.GroupBy(mainField.Name())
delete(mainGroup, reflect.Zero(mainField.StructField().Type))
if keys := mainGroup.Keys(); len(keys) != 0 {
// the relation condition should have lowest priority
brick = brick.Where(ExprIn, subField, keys).And().Conditions(brick.Search)
containerList := reflect.New(reflect.SliceOf(ctx.Result.Records.GetFieldType(fieldName))).Elem()
//var preloadRecords ModelRecords
subCtx, err := brick.find(LoopIndirectAndNew(containerList))
ctx.Result.Preload[fieldName] = subCtx.Result
if err != nil {
return err
}
// set sub data to container field
ctx.Result.SimpleRelation[fieldName] = map[int]int{}
subGroup := subCtx.Result.Records.GroupBy(subField.Name())
for key, records := range mainGroup {
if subRecords := subGroup[key]; len(subRecords) != 0 {
for _, record := range records {
record.SetField(preload.ContainerField.Name(), subRecords[0].Source())
ctx.Result.SimpleRelation[fieldName][subRecords[0].Index] = record.Index
}
}
}
}
}
// one to many
for fieldName, preload := range ctx.Brick.OneToManyPreload {
mainField, subField := preload.Model.GetOnePrimary(), preload.RelationField
brick := ctx.Brick.MapPreloadBrick[fieldName]
mainGroup := ctx.Result.Records.GroupBy(mainField.Name())
delete(mainGroup, reflect.Zero(mainField.StructField().Type))
if keys := mainGroup.Keys(); len(keys) != 0 {
// the relation condition should have lowest priority
brick = brick.Where(ExprIn, subField, keys).And().Conditions(brick.Search)
containerList := reflect.New(ctx.Result.Records.GetFieldType(fieldName)).Elem()
subCtx, err := brick.find(LoopIndirectAndNew(containerList))
ctx.Result.Preload[fieldName] = subCtx.Result
if err != nil {
return err
}
subGroup := subCtx.Result.Records.GroupBy(subField.Name())
ctx.Result.MultipleRelation[fieldName] = map[int]Pair{}
for key, records := range mainGroup {
if subRecords := subGroup[key]; len(subRecords) != 0 {
for _, record := range records {
container := record.Field(preload.ContainerField.Name())
containerIndirect := LoopIndirectAndNew(container)
for j, subRecord := range subRecords {
containerIndirect.Set(SafeAppend(containerIndirect, subRecord.Source()))
ctx.Result.MultipleRelation[fieldName][subRecord.Index] = Pair{record.Index, j}
}
}
}
}
}
}
// many to many
for fieldName, preload := range ctx.Brick.ManyToManyPreload {
mainPrimary, subPrimary := preload.Model.GetOnePrimary(), preload.SubModel.GetOnePrimary()
middleBrick := NewCollectionBrick(ctx.Brick.Toy, preload.MiddleModel).CopyStatus(ctx.Brick)
// primaryMap: map[model.id]->the model's ModelRecord
//primaryMap := map[interface{}]ModelRecord{}
mainGroup := ctx.Result.Records.GroupBy(mainPrimary.Name())
if keys := mainGroup.Keys(); len(keys) != 0 {
// the relation condition should have lowest priority
middleBrick = middleBrick.Where(ExprIn, preload.RelationField, keys).And().Conditions(middleBrick.Search)
middleModelElemList := reflect.New(reflect.SliceOf(preload.MiddleModel.ReflectType)).Elem()
//var middleModelRecords ModelRecords
middleCtx, err := middleBrick.find(middleModelElemList)
ctx.Result.MiddleModelPreload[fieldName] = middleCtx.Result
if err != nil {
return err
}
middleGroup := middleCtx.Result.Records.GroupBy(preload.SubRelationField.Name())
if subKeys := middleGroup.Keys(); len(subKeys) != 0 {
brick := ctx.Brick.MapPreloadBrick[fieldName]
// the relation condition should have lowest priority
brick = brick.Where(ExprIn, subPrimary, subKeys).And().Conditions(brick.Search)
containerField := reflect.New(ctx.Result.Records.GetFieldType(fieldName)).Elem()
//var subRecords ModelRecords
subCtx, err := brick.find(LoopIndirectAndNew(containerField))
ctx.Result.Preload[fieldName] = subCtx.Result
if err != nil {
return err
}
ctx.Result.MultipleRelation[fieldName] = map[int]Pair{}
for j, subRecord := range subCtx.Result.Records.GetRecords() {
if middleRecords := middleGroup[subRecord.Field(subPrimary.Name()).Interface()]; len(middleRecords) != 0 {
for _, middleRecord := range middleRecords {
mainRecord := mainGroup[middleRecord.Field(preload.RelationField.Name()).Interface()][0]
name := preload.ContainerField.Name()
container := mainRecord.Field(name)
containerIndirect := LoopIndirectAndNew(container)
subi := containerIndirect.Len()
containerIndirect.Set(SafeAppend(containerIndirect, subRecord.Source()))
ctx.Result.MultipleRelation[fieldName][j] = Pair{mainRecord.Index, subi}
}
}
}
}
}
}
return nil
}
func CollectionHandlerFind(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
action := CollectionQueryAction{
dbIndex: ctx.Brick.dbIndex,
}
var err error
// use template or use default exec
if ctx.Brick.template == nil {
action.Exec = ctx.Brick.FindExec(ctx.Result.Records)
} else {
tempMap := DefaultCollectionTemplateExec(ctx.Brick)
tempMap["Columns"] = getColumnExec(ctx.Brick.getSelectFields(ctx.Result.Records).ToColumnList())
action.Exec, err = ctx.Brick.Toy.Dialect.TemplateExec(*ctx.Brick.template, tempMap)
if err != nil {
return err
}
}
rows, err := ctx.Brick.Query(action.Exec, action.dbIndex)
if err != nil {
action.Error = append(action.Error, err)
ctx.Result.AddRecord(action)
return err
}
defer rows.Close()
// find current data
min := ctx.Result.Records.Len()
for rows.Next() {
elem := reflect.New(ctx.Result.Records.ElemType()).Elem()
ctx.Result.Records.Len()
record := ctx.Result.Records.Add(elem)
var scanners []interface{}
for _, field := range ctx.Brick.getScanFields(ctx.Result.Records) {
value := record.Field(field.Name())
scanners = append(scanners, value.Addr().Interface())
}
err := rows.Scan(scanners...)
action.Error = append(action.Error, err)
}
if err := rows.Err(); err != nil {
action.Error = append(action.Error, err)
}
max := ctx.Result.Records.Len()
action.affectData = makeRange(min, max)
ctx.Result.AddRecord(action)
return nil
}
func CollectionHandlerFindOneAssignDbIndex(ctx *CollectionContext) error {
if ctx.Brick.dbIndex != -1 {
return nil
}
for i := range ctx.Brick.Toy.dbs {
currentLen := ctx.Result.Records.Len()
dbCtx := NewCollectionContext(ctx.handlers[ctx.index+1:], ctx.Brick.DBIndex(i), ctx.Result.Records)
err := dbCtx.Next()
if err != nil {
fmt.Printf("not row %v\n", err)
return err
}
ctx.Result.ActionFlow = append(ctx.Result.ActionFlow, dbCtx.Result.ActionFlow...)
if ctx.Result.Records.Len() > currentLen {
break
}
}
ctx.Abort()
return nil
}
func CollectionHandlerFindOne(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
action := CollectionQueryAction{
dbIndex: ctx.Brick.dbIndex,
}
var err error
// use template or use default exec
if ctx.Brick.template == nil {
action.Exec = ctx.Brick.FindExec(ctx.Result.Records)
} else {
tempMap := DefaultCollectionTemplateExec(ctx.Brick)
tempMap["Columns"] = getColumnExec(ctx.Brick.getSelectFields(ctx.Result.Records).ToColumnList())
action.Exec, err = ctx.Brick.Toy.Dialect.TemplateExec(*ctx.Brick.template, tempMap)
if err != nil {
return err
}
}
rows, err := ctx.Brick.Query(action.Exec, action.dbIndex)
if err != nil {
action.Error = append(action.Error, err)
ctx.Result.AddRecord(action)
return err
}
defer rows.Close()
// find current data
min := ctx.Result.Records.Len()
if rows.Next() {
elem := reflect.New(ctx.Result.Records.ElemType()).Elem()
ctx.Result.Records.Len()
record := ctx.Result.Records.Add(elem)
var scanners []interface{}
for _, field := range ctx.Brick.getScanFields(ctx.Result.Records) {
value := record.Field(field.Name())
scanners = append(scanners, value.Addr().Interface())
}
err := rows.Scan(scanners...)
action.Error = append(action.Error, err)
}
max := ctx.Result.Records.Len()
action.affectData = makeRange(min, max)
ctx.Result.AddRecord(action)
return nil
}
func CollectionHandlerSoftDeleteCheck(ctx *CollectionContext) error {
deletedField := ctx.Brick.Model.GetFieldWithName("DeletedAt")
if deletedField != nil {
ctx.Brick = ctx.Brick.Where(ExprNull, deletedField).And().Conditions(ctx.Brick.Search)
}
return nil
}
func CollectionHandlerUpdateTimeGenerate(ctx *CollectionContext) error {
records := ctx.Result.Records
if updateField := ctx.Brick.Model.GetFieldWithName("UpdatedAt"); updateField != nil {
current := reflect.ValueOf(time.Now())
for _, record := range records.GetRecords() {
record.SetField(updateField.Name(), current)
}
}
return nil
}
func CollectionHandlerUpdate(ctx *CollectionContext) error {
if ctx.Brick.dbIndex == -1 {
return ErrDbIndexNotSet{}
}
for i, record := range ctx.Result.Records.GetRecords() {
action := CollectionExecAction{affectData: []int{i}, dbIndex: ctx.Brick.dbIndex}
var err error
if ctx.Brick.template == nil {
action.Exec = ctx.Brick.UpdateExec(record)
} else {
tempMap := DefaultCollectionTemplateExec(ctx.Brick)
values := ctx.Brick.getFieldValuePairWithRecord(ModeUpdate, record).ToValueList()
tempMap["Columns"] = getColumnExec(columnsValueToColumn(values))
tempMap["Values"] = getUpdateValuesExec(values)
action.Exec, err = ctx.Brick.Toy.Dialect.TemplateExec(*ctx.Brick.template, tempMap)
if err != nil {
return err
}
}
action.Result, action.Error = ctx.Brick.Exec(action.Exec, action.dbIndex)
ctx.Result.AddRecord(action)
}
return nil
}
func HandlerCollectionPreloadDelete(ctx *CollectionContext) error {
for fieldName, preload := range ctx.Brick.OneToOnePreload {
preloadBrick := ctx.Brick.MapPreloadBrick[fieldName]
subRecords := MakeRecordsWithElem(preload.SubModel, ctx.Result.Records.GetFieldAddressType(fieldName))
mainSoftDelete := preload.Model.GetFieldWithName("DeletedAt") != nil
subSoftDelete := preload.SubModel.GetFieldWithName("DeletedAt") != nil
// set sub model relation field
for _, record := range ctx.Result.Records.GetRecords() {
// it means relation field, result[j].LastInsertId() is id value
subRecords.Add(record.FieldAddress(fieldName))
}
// if main model is hard delete need set relationship field set zero if sub model is soft delete
if mainSoftDelete == false && subSoftDelete == true {
deletedAtField := preloadBrick.Model.GetFieldWithName("DeletedAt")
preloadBrick = preloadBrick.bindDefaultFields(preload.RelationField, deletedAtField)