-
Notifications
You must be signed in to change notification settings - Fork 1
/
result.go
76 lines (57 loc) · 1.28 KB
/
result.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
package unsafe
import (
"github.com/jmoiron/sqlx"
)
// Item is used as a container for sql rows with unknown values
type Item map[string]interface{}
// Content is used as a container for Unsafe Items
type Content []Item
// Column is used to inform the column order as well as column type
type Column struct {
Name string `json:"name"`
Type string `json:"type"`
}
// Result is the container for all sql result info
type Result struct {
Columns []Column `json:"columns"`
Content []interface{} `json:"content"`
}
func (r *Result) addColumns(rows *sqlx.Rows) error {
if len(r.Content) > 0 {
return nil
}
colTypes, err := rows.ColumnTypes()
cols, err := rows.Columns()
if err != nil {
return err
}
for i, col := range cols {
r.Columns = append(r.Columns, Column{
Name: col,
Type: string(colTypes[i].DatabaseTypeName()),
})
}
return nil
}
func (r *Result) addItem(rows *sqlx.Rows) error {
item := Item{}
values, err := rows.SliceScan()
if err != nil {
return err
}
for i, value := range values {
col := r.Columns[i]
switch v := value.(type) {
case []byte:
newVal, err := coerceValue(col.Type, v)
if err != nil {
return err
}
item[col.Name] = newVal
default:
item[col.Name] = v
}
}
r.Content = append(r.Content, item)
return nil
}