-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresult.go
1551 lines (1411 loc) · 33.3 KB
/
result.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 mx
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"sort"
"strconv"
"strings"
"unsafe"
)
// SQLRows 查询后的返回结果
type SQLRows struct {
driver string
rows *sql.Rows
err error
}
type SQLResult struct {
result sql.Result
err error
}
func (r *SQLResult) LastInsertId() (int64, error) {
if r.err != nil {
return 0, r.err
}
return r.result.LastInsertId()
}
func (r *SQLResult) RowsAffected() (int64, error) {
if r.err != nil {
return 0, r.err
}
return r.result.RowsAffected()
}
type (
//RowsMap 多行
RowsMap []RowMap
//RowMap 单行
RowMap map[string]string
//RowsMapInterface 多行
RowsMapInterface []RowMapInterface
//RowMapInterface 单行
RowMapInterface map[string]any
)
// Pluck 获取某一列的interface类型
func (r *SQLRows) Pluck(cn string) []any {
if r.err != nil {
return []any{}
}
rs := r.RowsMapInterface()
out := make([]any, 0, len(rs))
for _, v := range rs {
out = append(out, v[cn])
}
return out
}
// PluckInt 获取某一列的int类型
func (r *SQLRows) PluckInt(cn string) []int {
if r.err != nil {
return []int{}
}
rs := r.RowsMapInterface()
out := make([]int, 0, len(rs))
for _, v := range rs {
i, ok := v[cn].(int)
if ok {
out = append(out, i)
} else {
out = append(out, Int(v[cn]))
}
}
return out
}
// PluckString 获取某一列的string类型
func (r *SQLRows) PluckString(cn string) []string {
if r.err != nil {
return []string{}
}
out := []string{}
rs := r.RowsMapInterface()
for _, v := range rs {
i, ok := v[cn].(string)
if ok {
out = append(out, i)
} else {
out = append(out, String(v[cn]))
}
}
return out
}
// RowMapInterface 返回map[string]interface{} 只有一列
func (r *SQLRows) RowMapInterface() RowMapInterface {
rows := r.RowsMapInterface()
if len(rows) >= 1 {
return rows[0]
}
return make(RowMapInterface)
}
// RowsMapInterface 返回[]map[string]interface{},每个数组对应一列。
/*
如果是无符号的tinyint能存0-255
这里有浪费tinyint->int8[-128,127] unsigned tinyint uint8[0,255],这里直接用int16[-32768,32767]
*/
func (r *SQLRows) RowsMapInterface() RowsMapInterface {
// _st := time.Now()
// defer func() {
// fmt.Println(time.Now().Sub(_st))
// }()
rs := RowsMapInterface{}
if r.err != nil {
return rs
}
// ct, err := r.rows.ColumnTypes()
// fmt.Println(err)
// for _, v := range ct {
// fmt.Println(wtf.JSONStringify(v))
// }
// fmt.Println(wtf.JSONStringify(r.rows))
// fmt.Println(r.rows)
// https://segmentfault.com/a/1190000003036452
cols, err := r.rows.Columns()
if err != nil {
return rs
}
for r.rows.Next() {
rowMap := make(map[string]any)
containers := make([]any, 0, len(cols))
for i := 0; i < cap(containers); i++ {
containers = append(containers, &sql.RawBytes{})
}
r.rows.Scan(containers...)
for i := 0; i < len(cols); i++ {
for i := 0; i < cap(containers); i++ {
rowMap[cols[i]] = string(*containers[i].(*sql.RawBytes))
}
}
rs = append(rs, rowMap)
}
return rs
}
// MarshalJSON 实现MarshalJSON
// func (rm RowMap) MarshalJSON() ([]byte, error) {
// sb := bytes.NewBuffer(make([]byte, 0, 1024))
// sb.WriteByte('{')
// l := len(rm)
// n := 0
// for k, v := range rm {
// sb.WriteByte('"')
// sb.Write(stringByte(k))
// sb.Write([]byte{'"', ':', '"'})
// if strings.Contains(v, "\\") {
// v = strings.Replace(v, "\\", "\\\\", -1)
// }
// if strings.Contains(v, `"`) {
// sb.Write([]byte(strings.Replace(v, `"`, `\"`, -1)))
// } else {
// sb.Write([]byte(v))
// }
// sb.WriteByte('"')
// n++
// if n < l {
// sb.WriteByte(',')
// }
// }
// sb.WriteByte('}')
// return sb.Bytes(), nil
// }
// Bool return single bool
func (rm RowMap) Bool(field ...string) bool {
if rm.NotFound() {
return false
}
if len(field) > 0 {
if rm[field[0]] == "1" {
return true
}
return false
}
for _, v := range rm {
if v == "1" {
return true
}
return false
}
return false
}
// FieldDefault get field if not reture the def value
func (rm RowMap) FieldDefault(field, def string) string {
val, ok := rm[field]
if !ok {
val = def
}
return val
}
// Interface conver RowMap to RowMapInterface
func (rm RowMap) Interface() RowMapInterface {
rmi := make(RowMapInterface, len(rm))
for k, v := range rm {
rmi[k] = v
}
return rmi
}
// HaveRecord return it's have record
func (rm RowMap) HaveRecord() bool {
if len(rm) > 0 {
return true
}
return false
}
// NotFound return it's not found
func (rm RowMap) NotFound() bool {
if len(rm) == 0 {
return true
}
return false
}
// Copy return a Copy RowMap
func (rm RowMap) Copy() RowMap {
r := make(RowMap, len(rm))
for k, v := range rm {
r[k] = v
}
return r
}
// Int return int field
func (rm RowMap) Int(field string, def ...int) int {
val, ok := rm[field]
if ok {
i, err := strconv.Atoi(val)
if err == nil {
return i
}
}
if len(def) > 0 {
return def[0]
}
return 0
}
// Int32 return int32 field
func (rm RowMap) Int32(field string, def ...int32) int32 {
val, ok := rm[field]
if ok {
i, err := strconv.Atoi(val)
if err == nil {
return int32(i)
}
}
if len(def) > 0 {
return def[0]
}
return 0
}
// Incr
func (rm RowMap) Incr(field string, num ...int) int {
val := 1
if len(num) > 0 {
val = num[0]
}
next := rm.Int(field) + val
rm[field] = String(next)
return next
}
// Strings return []string field
func (rm RowMap) Strings(field string) []string {
s := make([]string, 0)
json.Unmarshal([]byte(rm[field]), &s)
return s
}
// Float64 return float64
func (rm RowMap) Float64(field string, def ...float64) float64 {
val, ok := rm[field]
if ok {
f, err := strconv.ParseFloat(val, 64)
if err == nil {
return f
}
}
if len(def) > 0 {
return def[0]
}
return 0
}
// Unmarshal json unmarshal
func (r RowMap) Unmarshal(field string, v any) error {
return json.Unmarshal([]byte(r[field]), v)
}
// RowsMap 旧代码适配
func (rm RowsMap) RowsMap() RowsMap {
return rm
}
// Copy 复制一份
func (rm RowsMap) Copy() RowsMap {
nrm := make(RowsMap, len(rm))
for _, r := range rm {
nr := make(RowMap, len(r))
for k, v := range r {
nr[k] = v
}
nrm = append(nrm, nr)
}
return nrm
}
// Sum Sum
func (rm RowsMap) Sum(field string) int {
sum := 0
for _, v := range rm {
sum += v.Int(field)
}
return sum
}
// SumFloat SumFloat
// 8.7 * 100.0 = 869.9999999999999 -> Round
func (rm RowsMap) SumFloat(field string, multiple int) int {
sum := 0
for _, v := range rm {
sum += int(math.Round(v.Float64(field) * float64(multiple)))
}
return sum
}
// SumFloat64 SumFloat64
func (rm RowsMap) SumFloat64(field string, multiple int) float64 {
sum := 0
for _, v := range rm {
sum += int(math.Round(v.Float64(field) * float64(multiple)))
}
return float64(sum) / float64(multiple)
}
// SumFloatString SumFloatString
func (rm RowsMap) SumFloatString(field string) string {
return String(float64(rm.SumFloat(field, 100)) / 100.0)
}
// SumByFieldEq SumByFieldEq
func (rm RowsMap) SumByFieldEq(field, eqField, eq string) int {
sum := 0
for _, v := range rm {
if v[eqField] == eq {
sum += v.Int(field)
}
}
return sum
}
// Max return max field
func (rm RowsMap) Max(field string) string {
max := ""
for _, r := range rm {
if r[field] > max {
max = r[field]
}
}
return max
}
// String return map[string]string
func (rm RowsMap) String() []map[string]string {
ms := []map[string]string{}
for _, r := range rm {
ms = append(ms, map[string]string(r))
}
return ms
}
// Interface conver RowsMap to RowsMapInterface
func (rm RowsMap) Interface() RowsMapInterface {
rmi := RowsMapInterface{}
for _, v := range rm {
rmi = append(rmi, v.Interface())
}
return rmi
}
// MapIndex 按照指定field划分成map[string]RowMap
// MapIndex 默认是 MapIndexStringRow
// 当key为string的时候可以省略String
// 当value为对应(Index->RowMap)(Indexs->RowsMap)时,可省略Row(s)Map。
// 当key为string,value为特殊命名时(Exist)可省略String
func (rm RowsMap) MapIndex(field string) map[string]RowMap {
sr := make(map[string]RowMap, len(rm))
for _, r := range rm {
sr[r[field]] = r
}
return sr
}
// MapIndexExist 按照指定field划分成map[string]bool
// MapIndexStringBool -> MapIndexExist
func (rm RowsMap) MapIndexExist(field string) map[string]bool {
sr := make(map[string]bool, len(rm))
for _, r := range rm {
sr[r[field]] = true
}
return sr
}
// MapIndexExistInt 按照指定field划分成map[int]bool
// Deprecated: 请用 MapIndexIntExist
func (rm RowsMap) MapIndexExistInt(field string) map[int]bool {
sr := make(map[int]bool, len(rm))
for _, r := range rm {
sr[r.Int(field)] = true
}
return sr
}
// MapIndexIntExist 按照指定field划分成map[int]bool
// alias MapIndexIntBool
func (rm RowsMap) MapIndexIntExist(field string) map[int]bool {
sr := make(map[int]bool, len(rm))
for _, r := range rm {
sr[r.Int(field)] = true
}
return sr
}
// MapIndexInt 按照指定field划分成map[int]RowMap
func (rm RowsMap) MapIndexInt(field string) map[int]RowMap {
sr := make(map[int]RowMap, len(rm))
for _, r := range rm {
sr[r.Int(field)] = r
}
return sr
}
// MapIndexKV 按照key,val 转换成 map[string]string
// alias MapIndexStringString
// KV为特殊命名,表示StringString
func (rm RowsMap) MapIndexKV(key, val string) map[string]string {
ss := make(map[string]string, len(rm))
for _, r := range rm {
ss[r[key]] = r[val]
}
return ss
}
// MapIndexIntKV 按照key,val 转换成 map[int]string
// Deprecated: 请用 MapIndexIntString
func (rm RowsMap) MapIndexIntKV(key, val string) map[int]string {
ss := make(map[int]string, len(rm))
for _, r := range rm {
ss[r.Int(key)] = r[val]
}
return ss
}
func (rm RowsMap) MapIndexIntString(key, val string) map[int]string {
ss := make(map[int]string, len(rm))
for _, r := range rm {
ss[r.Int(key)] = r[val]
}
return ss
}
func (rm RowsMap) MapIndexStringInt(key, val string) map[string]int {
ss := make(map[string]int, len(rm))
for _, r := range rm {
ss[key] = r.Int(val)
}
return ss
}
// MapIndexIntKVInt 按照key,val 转换成 map[int]int
// Deprecated: 请用 MapIndexIntInt
func (rm RowsMap) MapIndexIntKVInt(key, val string) map[int]int {
ss := make(map[int]int, len(rm))
for _, r := range rm {
ss[r.Int(key)] = r.Int(val)
}
return ss
}
func (rm RowsMap) MapIndexIntInt(key, val string) map[int]int {
ss := make(map[int]int, len(rm))
for _, r := range rm {
ss[r.Int(key)] = r.Int(val)
}
return ss
}
// MapIndexIntFloat 按照key,val 转换成 map[int]float64
func (rm RowsMap) MapIndexIntFloat(key, val string) map[int]float64 {
ss := make(map[int]float64, len(rm))
for _, r := range rm {
ss[r.Int(key)] = r.Float64(val)
}
return ss
}
// MapIndexKVSum 按照key,val 转换成 map[string]string 值为叠加
func (rm RowsMap) MapIndexKVSum(key, val string) map[string]string {
ss := make(map[string]string)
idx := rm.MapIndexs(key)
for k, rs := range idx {
ss[k] = rs.SumFloatString(val)
}
return ss
}
// MapIndexs 按照指定field划分成map[string]RowsMap
func (rm RowsMap) MapIndexs(field string) map[string]RowsMap {
sr := make(map[string]RowsMap, len(rm))
for _, r := range rm {
sr[r[field]] = append(sr[r[field]], r)
}
return sr
}
func (rm RowsMap) MapIndexsInt(field string) map[int]RowsMap {
sr := make(map[int]RowsMap, len(rm))
for _, r := range rm {
sr[r.Int(field)] = append(sr[r.Int(field)], r)
}
return sr
}
// Vals vals
type Vals []string
// Contains vals weather contains s
func (vs Vals) Contains(s string) bool {
for _, v := range vs {
if v == s {
return true
}
}
return false
}
// MapIndexsKV 按k,v划分成map[string]Vals
func (rm RowsMap) MapIndexsKV(key, val string) map[string]Vals {
sv := make(map[string]Vals)
for _, r := range rm {
sv[r[key]] = append(sv[r[key]], r[val])
}
return sv
}
// Filter 过滤指定字段
func (rm RowsMap) Filter(field, equal string) RowsMap {
frm := RowsMap{}
for _, v := range rm {
if v[field] == equal {
frm = append(frm, v)
}
}
return frm
}
// Filter 过滤指定字段
func (rm RowsMap) FilterContains(fields []string, equal string) RowsMap {
if equal == "" {
return rm
}
frm := RowsMap{}
for _, v := range rm {
isMatch := false
for _, field := range fields {
if strings.Contains(v[field], equal) {
isMatch = true
break
}
}
if isMatch {
frm = append(frm, v)
}
}
return frm
}
// FilterIn 指定字段在数组里面皆会被挑选出来
func (rm RowsMap) FilterIn(field string, equals []string) RowsMap {
em := make(map[string]bool, len(equals))
for _, e := range equals {
em[e] = true
}
frm := RowsMap{}
for _, v := range rm {
if em[v[field]] {
frm = append(frm, v)
}
}
return frm
}
// FilterNotIn 指定字段在数组里面皆不会被挑选出来
func (rm RowsMap) FilterNotIn(field string, equals []string) RowsMap {
em := make(map[string]bool, len(equals))
for _, e := range equals {
em[e] = true
}
frm := RowsMap{}
for _, v := range rm {
if !em[v[field]] {
frm = append(frm, v)
}
}
return frm
}
// FilterFunc fileter by func (like jq)
// return true will be append
func (rm RowsMap) FilterFunc(equalF func(RowMap) bool) RowsMap {
frm := RowsMap{}
for _, v := range rm {
if equalF(v) {
frm = append(frm, v)
}
}
return frm
}
// Len 返回RowsMap的长度
func (rm RowsMap) Len() int {
return len(rm)
}
// First 返回RowsMap的第一个元素,如果没有则返回空RowMap
func (rm RowsMap) First() RowMap {
if len(rm) > 0 {
return rm[0]
}
return RowMap{}
}
// EachAddTableString 根据一个字段查找
// https://github.com/shesuyo/crud/issues/11
// 第一个是原来的,第二个是新的。
// rowmapfield tablefield tablefield rowmapfield
func (rm *RowsMap) EachAddTableString(table *Table, args ...string) {
argsLen := len(args)
if argsLen < 4 || argsLen%2 != 0 {
return
}
fiels := []string{args[1]}
for i := 2; i < argsLen; i += 2 {
fiels = append(fiels, args[i])
}
datas := table.Fields(fiels...).In(args[1], rm.Pluck(args[0])...).RowsMap()
rmLen := len(*rm)
datasLen := len(datas)
for i := 0; i < rmLen; i++ {
isFound := false
for j := 0; j < datasLen; j++ {
if (*rm)[i][args[0]] == datas[j][args[1]] {
isFound = true
for k := 2; k < argsLen; k += 2 {
(*rm)[i][args[k+1]] = datas[j][args[k]]
}
break
}
}
if !isFound {
for k := 2; k < argsLen; k += 2 {
(*rm)[i][args[k+1]] = ""
}
}
}
}
// EachMod mod each rowmap
func (rm RowsMap) EachMod(f func(RowMap)) RowsMap {
l := len(rm)
for i := 0; i < l; i++ {
f(rm[i])
}
return rm
}
// RowsMapGroup 用于对一个字段进行分组
type RowsMapGroup struct {
Key string `json:"key"`
Len int `json:"len"`
Vals RowsMap `json:"vals"`
}
// GroupByField 用field字段进行分组
func (rm RowsMap) GroupByField(field string) []RowsMapGroup {
gm := map[string][]RowMap{}
orders := []string{}
for _, v := range rm {
_, ok := gm[v[field]]
if !ok {
orders = append(orders, v[field])
}
gm[v[field]] = append(gm[v[field]], v)
}
rmg := make([]RowsMapGroup, 0, len(orders))
for _, key := range orders {
tmp := RowsMapGroup{
Key: key,
Vals: gm[key],
}
tmp.Len = len(tmp.Vals)
rmg = append(rmg, tmp)
}
return rmg
}
// GroupBySQL group like sql
func (rm RowsMap) GroupBySQL(field string, sumFields ...string) RowsMap {
keyMaps := rm.MapIndexs(field)
group := make(RowsMap, 0, len(keyMaps))
for _, rm := range keyMaps {
r := rm.First().Copy()
for _, field := range sumFields {
r[field] = rm.SumFloatString(field)
}
group = append(group, r)
}
return group
}
// RowsWrap WarpByField
type RowsWrap struct {
Key string `json:"key"`
Val RowsMap `json:"val"`
}
// RowsWraps []RowsWrap
type RowsWraps []RowsWrap
type RowsWrapsSortFunc func(rm *RowsWraps, i, j int) bool
// RowsWrapsSort sort for RowsWraps
type RowsWrapsSort struct {
rm *RowsWraps
f RowsWrapsSortFunc
}
// Len len
func (rs RowsWrapsSort) Len() int {
return len(*(rs.rm))
}
// Swap swap
func (rs RowsWrapsSort) Swap(i, j int) {
(*(rs.rm))[i], (*(rs.rm))[j] = (*(rs.rm))[j], (*(rs.rm))[i]
}
// Less Less
func (rs RowsWrapsSort) Less(i, j int) bool {
return rs.f(rs.rm, i, j)
}
// Sort Sort
func (rw *RowsWraps) Sort(f RowsWrapsSortFunc) {
rf := RowsWrapsSort{rm: rw, f: f}
sort.Sort(rf)
}
// HaveKey return weather have this key
func (rw RowsWraps) HaveKey(key string) bool {
for _, v := range rw {
if v.Key == key {
return true
}
}
return false
}
// Set auto judge & set key
func (rw *RowsWraps) Set(key string, val RowMap) {
if rw.HaveKey(key) {
l := len(*rw)
for i := 0; i < l; i++ {
if (*rw)[i].Key == key {
(*rw)[i].Val = append((*rw)[i].Val, val)
}
}
} else {
if val == nil {
(*rw) = append((*rw), RowsWrap{Key: key, Val: make(RowsMap, 0, 1)})
} else {
(*rw) = append((*rw), RowsWrap{Key: key, Val: []RowMap{val}})
}
}
}
// WarpByField WarpByField
func (rm RowsMap) WarpByField(field string) RowsWraps {
rw := RowsWraps{}
for _, v := range rm {
rw.Set(v[field], v)
}
return rw
}
// MultiWarp multi warp
type MultiWarp struct {
ID string `json:"id"`
Name string `json:"name"`
Vals []MultiWarp `json:"vals"`
preID string
tailID string
}
type MultiWarps []MultiWarp
// MultiWarpByField multi level warp by field
// fields id1,key1,id2,key2,id3,key3
// 先传id再传字段
// if RowMap[key] == "" , abandon key+n(n>=0)
// 方案1:一层一层的进行拼接
// 方案2: 所有层次一起拼接
// 方案3: 从最后一层向前拼接
// 方案4: 所有节点一起算出来,然后再进行首尾拼接。
// 同头同尾也会有问题
/*
3 2 1
3 2 2
4 2 3
*/
func (rm RowsMap) MultiWarpByField(fields ...string) MultiWarps {
length := len(fields)
if length == 0 || length%2 == 1 {
return []MultiWarp{}
}
fields = append(fields, "", "")
fields = append([]string{"", ""}, fields...)
levels := make([][]MultiWarp, length/2)
for _, r := range rm {
levelIdx := len(levels) - 1
for i := len(fields) - 4; i >= 2; i -= 2 {
// fmt.Println("i,levelIdx:", i, levelIdx)
isAppend := false
// 不需要ID为0的项,认为不存在。
if r[fields[i]] == "0" || r[fields[i]] == "" {
// 这里没有减层,所以之前有BUG
// 以后需要注意在continue的时候没有处理for最后面的loop处理
levelIdx--
continue
}
ps := []string{}
for j := 2; j < i; j += 2 {
ps = append(ps, r[fields[j]])
}
var pre string //preID: r[fields[i-2]],
pre = strings.Join(ps, "-")
var tail string
if pre == "" {
tail = r[fields[i]]
} else {
tail = pre + "-" + r[fields[i]]
}
newWarp := MultiWarp{
ID: r[fields[i]],
Name: r[fields[i+1]],
preID: pre,
tailID: tail,
Vals: make([]MultiWarp, 0),
}
// fmt.Println(levelIdx, pre, tail, fmt.Sprintf("i:%d", i), fields[i])
// newWarp := MultiWarp{ID: r[fields[i]], Name: r[fields[i+1]], preID: r[fields[i-2]], tailID: r[fields[i+2]], Vals: make([]MultiWarp, 0)}
// fmt.Println(r, stringify(newWarp))
// newWarp := MultiWarp{ID: r[fields[i]], Name: r[fields[i+1]], preID: r[fields[i-2]], tailID: r[fields[i+2]]}
for _, level := range levels[levelIdx] {
if pre == tail {
isAppend = true
break
}
if level.ID == newWarp.ID && level.preID == newWarp.preID {
// 只要父节点和本身节点是一样的话,就是重复的了。
// 因为这棵树是从前面(idx=0)开始的,所以不能以同一个尾判断是同一个,同级下也可能有相同的尾。
// if level.ID == newWarp.ID && level.preID == newWarp.preID && level.tailID == newWarp.tailID {
isAppend = true
break
}
}
if !isAppend {
levels[levelIdx] = append(levels[levelIdx], newWarp)
}
levelIdx--
}
}
// for i := 0; i < len(levels); i++ {
// fmt.Println(i, len(levels[i]), stringify(levels[i]))
// }
// 从倒数第二个level开始向前合并
for i := len(levels) - 2; i >= 0; i-- {
for lIdx := 0; lIdx < len(levels[i]); lIdx++ {
for cIdx := 0; cIdx < len(levels[i+1]); cIdx++ {
// 如果前面的尾巴是
// tailID其实在这里是没有用的,因为不同的tailID,可能已经被除重了。
if levels[i][lIdx].tailID == levels[i+1][cIdx].preID {
levels[i][lIdx].Vals = append(levels[i][lIdx].Vals, levels[i+1][cIdx])
} else {
// not match
// fmt.Println(levels[i][lIdx].Name, levels[i][lIdx].tailID, levels[i+1][cIdx].Name, levels[i+1][cIdx].ID)
}
}
}
}
if levels[0] == nil {
return []MultiWarp{}
}
return levels[0]
}
// HaveID 是否有这个ID
func (rm RowsMap) HaveID(id string) bool {
for _, v := range rm {
if v["id"] == id {
return true
}
}
return false
}
// RowID 根据id获取所在行
func (rm RowsMap) RowID(id string) RowMap {
for _, v := range rm {
if v["id"] == id {
return v
}
}
return nil
}
// RowField 根据字段获取所在行
func (rm RowsMap) RowField(val, field string) RowMap {
for _, v := range rm {
if v[field] == val {
return v
}
}
return RowMap{}
}
// RowsField 根据字段找出多列
func (rm RowsMap) RowsField(val, field string) RowsMap {
rows := RowsMap{}
for _, v := range rm {
if v[field] == val {
rows = append(rows, v)
}
}
return rows
}
// Pluck 取出中间的一列
func (rm RowsMap) Pluck(key string) []any {
var vs = make([]any, 0)
for _, v := range rm {
vs = append(vs, v[key])
}
return vs
}
// PluckString pluck field with string
func (rm RowsMap) PluckString(key string) []string {
var vs = make([]string, 0)
for _, v := range rm {
vs = append(vs, v[key])
}
return vs
}