/
sql_param.go
executable file
·106 lines (99 loc) · 2.49 KB
/
sql_param.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
package types
import (
"fmt"
"github.com/bnulwh/mybatis-go/log"
"reflect"
"strings"
)
type SqlParamType string
const (
BaseSqlParam SqlParamType = "base"
SliceSqlParam SqlParamType = "slice"
MapSqlParam SqlParamType = "map"
StructSqlParam SqlParamType = "struct"
)
type SqlParam struct {
Name string
TypeName string
Type SqlParamType
Need bool
}
func parseSqlParamFromXmlAttrs(attrs map[string]string) SqlParam {
log.Debugf("--begin parse sql param from: %v", ToJson(attrs))
defer log.Debugf("--finish parse sql param from: %v", ToJson(attrs))
attr, ok := attrs["parameterType"]
if !ok {
return SqlParam{Need: false}
}
val := attr
tn := GetShortName(val)
return SqlParam{
Name: val,
TypeName: tn,
Type: parseSqlParamTypeFrom(tn),
Need: true,
}
}
func (in *SqlParam) validParam(args []interface{}) error {
log.Debugf("sql param valid param %v", args)
if !in.Need {
return nil
}
switch in.Type {
case BaseSqlParam:
if len(args) == 0 {
return fmt.Errorf("need param, type: %v", in.TypeName)
}
val := reflect.ValueOf(args[0])
typ := reflect.Indirect(val).Type()
switch typ.String() {
case "string",
"bool",
"int", "int8", "int16", "int32",
"uint", "uint8", "uint16", "uint32",
"int64", "uint64",
"float32", "float64",
"time.Time":
return nil
}
return fmt.Errorf("not support param type: %v ,need type: %v", typ, in.TypeName)
case SliceSqlParam:
return nil
case MapSqlParam, StructSqlParam:
if len(args) == 0 {
return fmt.Errorf("need param, type: %v", in.TypeName)
}
val := reflect.ValueOf(args[0])
typ := reflect.Indirect(val).Type()
switch typ.String() {
case "string",
"bool",
"int", "int8", "int16", "int32",
"uint", "uint8", "uint16", "uint32",
"int64", "uint64",
"float32", "float64",
"time.Time":
return fmt.Errorf("not support param type: %v ,need type: %v", typ, in.TypeName)
}
if typ.Kind() == reflect.Ptr {
return fmt.Errorf("use two references to the struce %v", typ)
}
}
return nil
}
func parseSqlParamTypeFrom(tn string) SqlParamType {
switch strings.ToUpper(GetShortName(tn)) {
case "STRING", "VARCHAR",
"BOOLEAN", "BOOL",
"INT", "INTEGER", "INT8", "INT16", "INT32", "INT64",
"UINT", "UINT8", "UINT16", "UINT32", "UINT64",
"FLOAT", "FLOAT32", "FLOAT64", "DOUBLE",
"TIME", "TIMESTAMP":
return BaseSqlParam
case "LIST", "ARRAY", "ARRAYLIST", "SLICE":
return SliceSqlParam
case "MAP", "HASHMAP", "TREEMAP":
return MapSqlParam
}
return StructSqlParam
}