forked from mix-go/xsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_sql.go
More file actions
56 lines (50 loc) · 1.34 KB
/
make_sql.go
File metadata and controls
56 lines (50 loc) · 1.34 KB
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
package xsql
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
)
func MakeOraSqlByStruct(data any, queryType string) (string, error) {
table := ""
fields := make([]string, 0)
bindAvgs := ""
value := reflect.ValueOf(data)
switch value.Kind() {
case reflect.Struct:
if tab, ok := data.(Table); ok {
table = tab.TableName()
} else {
table = value.Type().Name()
}
for i := 0; i < value.NumField(); i++ {
if !value.Field(i).CanInterface() {
continue
}
tag := value.Type().Field(i).Tag.Get("xsql")
if tag == "" || tag == "-" || tag == "_" {
continue
}
fields = append(fields, tag) //映射得字段名称
switch value.Field(i).Type().String() {
case "string":
bindAvgs += fmt.Sprintf("'%v',", value.Field(i).Interface())
case "time.Time": // time特殊处理
ti := value.Field(i).Interface().(time.Time)
t := ti.Format("2006-01-02 15:04:05")
bindAvgs += fmt.Sprintf("TO_TIMESTAMP('%s','SYYYY-MM-DD HH24:MI:SS:FF6'),", t)
default:
bindAvgs += fmt.Sprintf("%v,", value.Field(i).Interface())
}
}
break
default:
return "", errors.New("sql: only for struct type")
}
if queryType == "insert" {
SQL := fmt.Sprintf(`%s %s (%s) VALUES (%s)`, "INSERT INTO", table, strings.Join(fields, ", "), strings.Trim(bindAvgs, ","))
return SQL, nil
}
return "", errors.New("sql: noe")
}