/
helper-reflect.go
803 lines (746 loc) · 18.4 KB
/
helper-reflect.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
package helper
import (
"database/sql"
"fmt"
"log"
"reflect"
"time"
)
/*
* Copyright 2020-2023 Aldelo, LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ================================================================================================================
// Custom Type Registry
// ================================================================================================================
var customTypeRegistry map[string]reflect.Type
// ReflectTypeRegistryAdd will accept a custom struct object, and add its type into custom type registry,
// if customFullTypeName is not specified, the type name is inferred from the type itself,
// custom type registry is used by reflect unmarshal helpers to construct custom type for undefined interface targets
func ReflectTypeRegistryAdd(customStructObj interface{}, customFullTypeName ...string) bool {
if customStructObj == nil {
return false
}
o := reflect.TypeOf(customStructObj)
if o.Kind() == reflect.Ptr {
o = o.Elem()
}
if o.Kind() != reflect.Struct {
return false
}
typeName := o.Name()
log.Println(typeName)
if len(customFullTypeName) > 0 {
if LenTrim(customFullTypeName[0]) > 0 {
typeName = Trim(customFullTypeName[0])
}
}
if customTypeRegistry == nil {
customTypeRegistry = make(map[string]reflect.Type)
}
customTypeRegistry[typeName] = o
return true
}
// ReflectTypeRegistryRemove will remove a pre-registered custom type from type registry for the given type name
func ReflectTypeRegistryRemove(customFullTypeName string) {
if customTypeRegistry != nil {
delete(customTypeRegistry, customFullTypeName)
}
}
// ReflectTypeRegistryRemoveAll will clear all previously registered custom types from type registry
func ReflectTypeRegistryRemoveAll() {
if customTypeRegistry != nil {
customTypeRegistry = make(map[string]reflect.Type)
}
}
// ReflectTypeRegistryCount returns count of custom types registered in the type registry
func ReflectTypeRegistryCount() int {
if customTypeRegistry != nil {
return len(customTypeRegistry)
} else {
return 0
}
}
// ReflectTypeRegistryGet returns a previously registered custom type in the type registry, based on the given type name string
func ReflectTypeRegistryGet(customFullTypeName string) reflect.Type {
if customTypeRegistry != nil {
if t, ok := customTypeRegistry[customFullTypeName]; ok {
return t
} else {
return nil
}
} else {
return nil
}
}
// ================================================================================================================
// Custom Struct Tag Reflect Helpers
// ================================================================================================================
// GetStructTagValueByObject will accept a struct object, struct field name, and struct tag name,
// and return the found tag value and reflect type,
// if reflect type or struct tag is not found, a notFound is returned
// [ Parameters ]
//
// structObj = struct object variable
// structFieldName = struct's field name (CASE SENSITIVE)
// structTagName = struct's tag name (the left side of struct tag - the key portion) (CASE SENSITIVE)
func GetStructTagValueByObject(structObj interface{}, structFieldName string, structTagName string) (notFound bool, tagValue string, t reflect.Type) {
// get reflect type from struct object
t = reflect.TypeOf(structObj)
if t == nil {
// no reflect type found
return true, "", nil
}
// get field
field, ok := t.FieldByName(structFieldName)
if !ok {
// struct field not found
return true, "", t
} else {
// struct field found
return false, field.Tag.Get(structTagName), t
}
}
// GetStructTagValueByType will accept a prior obtained reflect type, struct field name, and struct tag name,
// and return the found tag value,
// if struct tag value is not found, a notFound is returned,
// if the reflect type is nil, then not found is returned too
// [ Parameters ]
//
// t = reflect type of a struct object (obtained via GetStructTagValueByObject)
// structFieldName = struct's field name (CASE SENSITIVE)
// structTagName = struct's tag name (the left side of struct tag - the key portion) (CASE SENSITIVE)
func GetStructTagValueByType(t reflect.Type, structFieldName string, structTagName string) (notFound bool, tagValue string) {
// check if reflect type is valid
if t == nil {
return true, ""
}
// get field
field, ok := t.FieldByName(structFieldName)
if !ok {
// struct field not found
return true, ""
} else {
// struct field found
return false, field.Tag.Get(structTagName)
}
}
// GetStructTagsValueSlice returns named struct tag values from field, in the order queried
func GetStructTagsValueSlice(field reflect.StructField, tagName ...string) (tagValues []string) {
for _, t := range tagName {
tagValues = append(tagValues, field.Tag.Get(t))
}
return
}
// ================================================================================================================
// Reflection Helpers
// ================================================================================================================
// ReflectCall uses reflection to invoke a method by name, and pass in param values if any,
// result is returned via reflect.Value object slice
func ReflectCall(o reflect.Value, methodName string, paramValue ...interface{}) (resultSlice []reflect.Value, notFound bool) {
method := o.MethodByName(methodName)
if method.Kind() == reflect.Invalid {
return nil, true
}
if !method.IsZero() {
var params []reflect.Value
if len(paramValue) > 0 {
for _, p := range paramValue {
params = append(params, reflect.ValueOf(p))
}
}
resultSlice = method.Call(params)
if len(resultSlice) == 0 {
return nil, false
} else {
return resultSlice, false
}
} else {
return nil, true
}
}
// ReflectValueToString accepts reflect.Value and returns its underlying field value in string data type
// boolTrue is the literal value to use for bool true condition, boolFalse is the false condition literal,
// if boolTrue or boolFalse is not defined, then default 'true' or 'false' is used,
// skipBlank and skipZero if true indicates if field value is blank (string) or Zero (int, float, time, pointer, bool) then skip render,
// zeroBlank = will blank the value if it is 0, 0.00, or time.IsZero
//
// timeFormat:
//
// 2006, 06 = year,
// 01, 1, Jan, January = month,
// 02, 2, _2 = day (_2 = width two, right justified)
// 03, 3, 15 = hour (15 = 24 hour format)
// 04, 4 = minute
// 05, 5 = second
// PM pm = AM PM
func ReflectValueToString(o reflect.Value, boolTrue string, boolFalse string, skipBlank bool, skipZero bool, timeFormat string, zeroBlank bool) (valueStr string, skip bool, err error) {
buf := ""
switch o.Kind() {
case reflect.String:
buf = o.String()
if skipBlank && LenTrim(buf) == 0 {
return "", true, nil
}
case reflect.Bool:
if o.Bool() {
if len(boolTrue) == 0 {
buf = "true"
} else {
buf = Trim(boolTrue)
}
} else {
if skipZero {
return "", true, nil
} else {
if len(boolFalse) == 0 {
buf = "false"
} else {
if Trim(boolTrue) == Trim(boolFalse) {
buf = "false"
} else {
buf = Trim(boolFalse)
}
}
}
}
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
if skipZero && o.Int() == 0 {
return "", true, nil
} else {
if zeroBlank && o.Int() == 0 {
buf = ""
} else {
buf = Int64ToString(o.Int())
}
}
case reflect.Float32:
fallthrough
case reflect.Float64:
if skipZero && o.Float() == 0.00 {
return "", true, nil
} else {
if zeroBlank && o.Float() == 0.00 {
buf = ""
} else {
buf = FloatToString(o.Float())
}
}
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
if skipZero && o.Uint() == 0 {
return "", true, nil
} else {
if zeroBlank && o.Uint() == 0 {
buf = ""
} else {
buf = UInt64ToString(o.Uint())
}
}
case reflect.Ptr:
if o.IsZero() || o.IsNil() {
if skipZero || skipBlank {
return "", true, nil
} else {
if rt, _, _ := DerefPointersZero(o); rt.Kind() == reflect.Bool {
if Trim(boolTrue) == Trim(boolFalse) {
return "false", false, nil
} else {
if LenTrim(boolFalse) > 0 {
return boolFalse, false, nil
} else {
return "", false, nil
}
}
} else {
return "", false, nil
}
}
}
o2 := o.Elem()
if o2.IsZero() {
if skipZero || skipBlank {
return "", true, nil
}
}
switch f := o2.Interface().(type) {
case int8:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0 {
buf = ""
} else {
buf = Itoa(int(f))
}
}
case int16:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0 {
buf = ""
} else {
buf = Itoa(int(f))
}
}
case int32:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0 {
buf = ""
} else {
buf = Itoa(int(f))
}
}
case int64:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0 {
buf = ""
} else {
buf = Int64ToString(f)
}
}
case int:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0 {
buf = ""
} else {
buf = Itoa(f)
}
}
case bool:
if f {
if len(boolTrue) == 0 {
buf = "true"
} else {
buf = Trim(boolTrue)
}
} else {
if skipZero {
return "", true, nil
} else {
if len(boolFalse) == 0 {
buf = "false"
} else {
if Trim(boolTrue) == Trim(boolFalse) {
buf = "false"
} else {
buf = Trim(boolFalse)
}
}
}
}
case string:
if skipBlank && LenTrim(f) == 0 {
return "", true, nil
} else {
buf = f
}
case float32:
if skipZero && f == 0.00 {
return "", true, nil
} else {
if zeroBlank && f == 0.00 {
buf = ""
} else {
buf = Float32ToString(f)
}
}
case float64:
if skipZero && f == 0.00 {
return "", true, nil
} else {
if zeroBlank && f == 0.00 {
buf = ""
} else {
buf = Float64ToString(f)
}
}
case uint:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0.00 {
buf = ""
} else {
buf = UintToStr(f)
}
}
case uint64:
if skipZero && f == 0 {
return "", true, nil
} else {
if zeroBlank && f == 0.00 {
buf = ""
} else {
buf = UInt64ToString(f)
}
}
case time.Time:
if skipZero && f.IsZero() {
return "", true, nil
} else {
if LenTrim(timeFormat) == 0 {
if zeroBlank && f.IsZero() {
buf = ""
} else {
buf = FormatDateTime(f)
}
} else {
if zeroBlank && f.IsZero() {
buf = ""
} else {
buf = f.Format(timeFormat)
}
}
}
default:
return "", false, fmt.Errorf("%s Unhandled [1]", o2.Type().Name())
}
default:
switch f := o.Interface().(type) {
case sql.NullString:
buf = FromNullString(f)
if skipBlank && LenTrim(buf) == 0 {
return "", true, nil
}
case sql.NullBool:
if FromNullBool(f) {
if len(boolTrue) == 0 {
buf = "true"
} else {
buf = Trim(boolTrue)
}
} else {
if skipZero {
return "", true, nil
} else {
if len(boolFalse) == 0 {
buf = "false"
} else {
if Trim(boolTrue) == Trim(boolFalse) {
buf = "false"
} else {
buf = Trim(boolFalse)
}
}
}
}
case sql.NullFloat64:
f64 := FromNullFloat64(f)
if skipZero && f64 == 0.00 {
return "", true, nil
} else {
if zeroBlank && f64 == 0.00 {
buf = ""
} else {
buf = FloatToString(f64)
}
}
case sql.NullInt32:
i32 := FromNullInt(f)
if skipZero && i32 == 0 {
return "", true, nil
} else {
if zeroBlank && i32 == 0 {
buf = ""
} else {
buf = Itoa(i32)
}
}
case sql.NullInt64:
i64 := FromNullInt64(f)
if skipZero && i64 == 0 {
return "", true, nil
} else {
if zeroBlank && i64 == 0 {
buf = ""
} else {
buf = Int64ToString(i64)
}
}
case sql.NullTime:
t := FromNullTime(f)
if skipZero && t.IsZero() {
return "", true, nil
} else {
if LenTrim(timeFormat) == 0 {
buf = FormatDateTime(t)
} else {
if zeroBlank && t.IsZero() {
buf = ""
} else {
buf = t.Format(timeFormat)
}
}
}
case time.Time:
if skipZero && f.IsZero() {
return "", true, nil
} else {
if LenTrim(timeFormat) == 0 {
if zeroBlank && f.IsZero() {
buf = ""
} else {
buf = FormatDateTime(f)
}
} else {
if zeroBlank && f.IsZero() {
buf = ""
} else {
buf = f.Format(timeFormat)
}
}
}
case nil:
if skipZero || skipBlank {
return "", true, nil
} else {
buf = ""
}
default:
return "", false, fmt.Errorf("%s Unhandled [2]", o.Type().Name())
}
}
return buf, false, nil
}
// ReflectStringToField accepts string value and reflects into reflect.Value field based on the field data type
//
// timeFormat:
//
// 2006, 06 = year,
// 01, 1, Jan, January = month,
// 02, 2, _2 = day (_2 = width two, right justified)
// 03, 3, 15 = hour (15 = 24 hour format)
// 04, 4 = minute
// 05, 5 = second
// PM pm = AM PM
func ReflectStringToField(o reflect.Value, v string, timeFormat string) error {
switch o.Kind() {
case reflect.String:
o.SetString(v)
case reflect.Bool:
b, _ := ParseBool(v)
o.SetBool(b)
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
i64, _ := ParseInt64(v)
if !o.OverflowInt(i64) {
o.SetInt(i64)
}
case reflect.Float32:
fallthrough
case reflect.Float64:
f64, _ := ParseFloat64(v)
if !o.OverflowFloat(f64) {
o.SetFloat(f64)
}
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
ui64 := StrToUint64(v)
if !o.OverflowUint(ui64) {
o.SetUint(ui64)
}
case reflect.Ptr:
if o.IsZero() || o.IsNil() {
// create object
baseType, _, _ := DerefPointersZero(o)
o.Set(reflect.New(baseType.Type()))
}
o2 := o.Elem()
if o.IsZero() {
return nil
}
switch o2.Interface().(type) {
case int:
i64, _ := ParseInt64(v)
if !o2.OverflowInt(i64) {
o2.SetInt(i64)
}
case int8:
i64, _ := ParseInt64(v)
if !o2.OverflowInt(i64) {
o2.SetInt(i64)
}
case int16:
i64, _ := ParseInt64(v)
if !o2.OverflowInt(i64) {
o2.SetInt(i64)
}
case int32:
i64, _ := ParseInt64(v)
if !o2.OverflowInt(i64) {
o2.SetInt(i64)
}
case int64:
i64, _ := ParseInt64(v)
if !o2.OverflowInt(i64) {
o2.SetInt(i64)
}
case float32:
f64, _ := ParseFloat64(v)
if !o2.OverflowFloat(f64) {
o2.SetFloat(f64)
}
case float64:
f64, _ := ParseFloat64(v)
if !o2.OverflowFloat(f64) {
o2.SetFloat(f64)
}
case uint:
if !o2.OverflowUint(StrToUint64(v)) {
o2.SetUint(StrToUint64(v))
}
case uint64:
if !o2.OverflowUint(StrToUint64(v)) {
o2.SetUint(StrToUint64(v))
}
case string:
o2.SetString(v)
case bool:
b, _ := ParseBool(v)
o2.SetBool(b)
case time.Time:
if LenTrim(timeFormat) == 0 {
o2.Set(reflect.ValueOf(ParseDate(v)))
} else {
o2.Set(reflect.ValueOf(ParseDateTimeCustom(v, timeFormat)))
}
default:
return fmt.Errorf(o2.Type().Name() + " Unhandled [1]")
}
default:
switch o.Interface().(type) {
case sql.NullString:
o.Set(reflect.ValueOf(sql.NullString{String: v, Valid: true}))
case sql.NullBool:
b, _ := ParseBool(v)
o.Set(reflect.ValueOf(sql.NullBool{Bool: b, Valid: true}))
case sql.NullFloat64:
f64, _ := ParseFloat64(v)
o.Set(reflect.ValueOf(sql.NullFloat64{Float64: f64, Valid: true}))
case sql.NullInt32:
i32, _ := ParseInt32(v)
o.Set(reflect.ValueOf(sql.NullInt32{Int32: int32(i32), Valid: true}))
case sql.NullInt64:
i64, _ := ParseInt64(v)
o.Set(reflect.ValueOf(sql.NullInt64{Int64: i64, Valid: true}))
case sql.NullTime:
var tv time.Time
if LenTrim(timeFormat) == 0 {
tv = ParseDateTime(v)
} else {
tv = ParseDateTimeCustom(v, timeFormat)
}
o.Set(reflect.ValueOf(sql.NullTime{Time: tv, Valid: true}))
case time.Time:
if LenTrim(timeFormat) == 0 {
o.Set(reflect.ValueOf(ParseDateTime(v)))
} else {
o.Set(reflect.ValueOf(ParseDateTimeCustom(v, timeFormat)))
}
case nil:
return nil
default:
return fmt.Errorf(o.Type().Name() + " Unhandled [2]")
}
}
return nil
}
// DerefPointersZero gets pointer base type
func DerefPointersZero(rv reflect.Value) (drv reflect.Value, isPtr bool, isNilPtr bool) {
for rv.Kind() == reflect.Ptr {
isPtr = true
if rv.IsNil() {
isNilPtr = true
rt := rv.Type().Elem()
for rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
drv = reflect.New(rt).Elem()
return
}
rv = rv.Elem()
}
drv = rv
return
}
// DerefError dereferences reflect.Value to error object if underlying type was error
func DerefError(v reflect.Value) error {
if e, ok := v.Interface().(error); ok {
// v is error, check if error exists
if e != nil {
return e
}
}
return nil
}
// ReflectGetType returns the type of obj interface{} passed in.
// if obj interface{} is a pointer, then its base type will be returned instead
func ReflectGetType(obj interface{}) reflect.Type {
if obj == nil {
return nil
} else {
t1 := reflect.TypeOf(obj)
if t1.Kind() == reflect.Ptr {
return t1.Elem()
} else {
return t1
}
}
}
// ReflectObjectNewPtr creates a new object ptr for the object type given at parameter.
// the return interface{} represents the actual object ptr created
func ReflectObjectNewPtr(objType reflect.Type) interface{} {
if objType == nil {
return nil
} else {
return reflect.New(objType).Interface()
}
}