-
Notifications
You must be signed in to change notification settings - Fork 74
/
construct_sql_query_stmt.go
79 lines (68 loc) · 1.44 KB
/
construct_sql_query_stmt.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
package main
import (
"bytes"
"errors"
"fmt"
"reflect"
"time"
)
func ConstructQueryStmt(obj interface{}) (stmt string, err error) {
// 仅支持struct或struct指针类型
typ := reflect.TypeOf(obj)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct {
err = errors.New("only struct is supported")
return
}
buffer := bytes.NewBufferString("")
buffer.WriteString("SELECT ")
if typ.NumField() == 0 {
err = fmt.Errorf("the type[%s] has no fields", typ.Name())
return
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if i != 0 {
buffer.WriteString(", ")
}
column := field.Name
if tag := field.Tag.Get("orm"); tag != "" {
column = tag
}
buffer.WriteString(column)
}
stmt = fmt.Sprintf("%s FROM %s", buffer.String(), typ.Name())
return
}
type Product struct {
ID uint32
Name string
Price uint32
LeftCount uint32 `orm:"left_count"`
Batch string `orm:"batch_number"`
Updated time.Time
}
type Person struct {
ID string
Name string
Age uint32
Gender string
Addr string `orm:"address"`
Updated time.Time
}
func main() {
stmt, err := ConstructQueryStmt(&Product{})
if err != nil {
fmt.Println("construct query stmt for Product error:", err)
return
}
fmt.Println(stmt)
stmt, err = ConstructQueryStmt(Person{})
if err != nil {
fmt.Println("construct query stmt for Person error:", err)
return
}
fmt.Println(stmt)
}