-
Notifications
You must be signed in to change notification settings - Fork 10
/
result_strings.go
100 lines (90 loc) · 2.65 KB
/
result_strings.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
package osm
import (
"fmt"
"reflect"
)
var stringType = reflect.TypeOf("")
func checkColumns(columns interface{}) *reflect.Value {
pointValue := reflect.ValueOf(columns)
if pointValue.Kind() != reflect.Ptr {
return nil
}
value := reflect.Indirect(pointValue)
if value.Kind() != reflect.Slice {
return nil
}
eleType := value.Type().Elem()
kind := eleType.Kind()
if kind != reflect.String {
return nil
}
return &value
}
func checkDatas(datas interface{}) *reflect.Value {
pointValue := reflect.ValueOf(datas)
if pointValue.Kind() != reflect.Ptr {
return nil
}
value := reflect.Indirect(pointValue)
if value.Kind() != reflect.Slice {
return nil
}
eleType := value.Type().Elem()
kind := eleType.Kind()
if kind != reflect.Slice {
return nil
}
if eleType.Elem().Kind() != reflect.String {
return nil
}
return &value
}
// resultStrings 数据库结果读入到columns,和datas。columns为[]string,datas为[][]string。
func resultStrings(logPrefix string, o *osmBase, id, sql string, sqlParams []interface{}, columnsContainer, datasContainer interface{}) (int64, error) {
columnsValue := checkColumns(columnsContainer)
if columnsValue == nil {
return 0, fmt.Errorf("sql '%s' error : strings类型Query,查询结果类型第一个为[]string的指针,第二个为[][]string的指针", id)
}
datasValue := checkDatas(datasContainer)
if datasValue == nil {
return 0, fmt.Errorf("sql '%s' error : strings类型Query,查询结果类型第一个为[]string的指针,第二个为[][]string的指针", id)
}
rows, err := o.db.Query(sql, sqlParams...)
if err != nil {
return 0, fmt.Errorf("sql '%s' error : %s", id, err.Error())
}
defer rows.Close()
var rowsCount int64
var columnsCount int
var isPtrs []bool
var elementTypes []reflect.Type
for rows.Next() {
if rowsCount == 0 {
columns, err := rows.Columns()
if err != nil {
return 0, fmt.Errorf("sql '%s' error : %s", id, err.Error())
}
columnsCount = len(columns)
isPtrs = make([]bool, columnsCount)
for _, column := range columns {
elementTypes = append(elementTypes, stringType)
(*columnsValue).Set(reflect.Append(*columnsValue, reflect.ValueOf(column)))
}
}
objs := make([]reflect.Value, columnsCount)
for i := 0; i < columnsCount; i++ {
objs[i] = reflect.New(stringType).Elem()
}
err = o.scanRow(logPrefix, rows, isPtrs, elementTypes, objs)
if err != nil {
return 0, fmt.Errorf("sql '%s' error : %s", id, err.Error())
}
var data []string
for i := 0; i < columnsCount; i++ {
data = append(data, objs[i].String())
}
(*datasValue).Set(reflect.Append(*datasValue, reflect.ValueOf(data)))
rowsCount++
}
return rowsCount, nil
}