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
|
package db
import (
"fmt"
"reflect"
)
func StructToDBColumns(s any) ([]string, error) {
typ := reflect.TypeOf(s)
if typ.Kind() != reflect.Struct {
return nil, fmt.Errorf("%s is not a struct", typ)
}
var res []string
for i := 0; i < typ.NumField(); i++ {
fld := typ.Field(i)
if column := fld.Tag.Get("params"); column == "nocreate" {
continue
}
if column := fld.Tag.Get("db"); column != "" {
res = append(res, column)
}
}
return res, nil
}
func StructToDBValues(s any) ([]any, error) {
val := reflect.ValueOf(s)
typ := reflect.TypeOf(s)
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("%s is not a struct", val)
}
var res []any
for i := 0; i < val.NumField(); i++ {
if column := typ.Field(i).Tag.Get("params"); column == "nocreate" {
continue
}
// switch val.Field(i).Kind() {
// case reflect.Struct:
// structVal, err := StructToDBValues(val.Field(i).Interface())
// if err != nil {
// return res, err
// }
// res = append(res, structVal...)
// default:
res = append(res, val.Field(i).Interface())
// }
}
return res, nil
}
func StructToUpdateMap(s any) (map[string]interface{}, error) {
val := reflect.ValueOf(s)
typ := reflect.TypeOf(s)
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("%s is not a struct", val)
}
res := make(map[string]interface{})
for i := 0; i < val.NumField(); i++ {
if column := typ.Field(i).Tag.Get("params"); column == "noupdate" {
continue
}
res[typ.Field(i).Tag.Get("db")] = val.Field(i).Interface()
}
return res, nil
}
|