-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
82 lines (60 loc) · 1.37 KB
/
query.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
package main
import (
"database/sql"
"fmt"
"reflect"
)
func queryRows(dest interface{}, db *sql.DB, q string, args ...interface{}) error {
pv := reflect.ValueOf(dest)
mustBePtr(pv, reflect.Slice)
v := pv.Elem()
t := v.Type().Elem()
addrsOf := getStructFields
if t.Kind() != reflect.Struct {
addrsOf = func(v reflect.Value) []interface{} {
return []interface{}{v.Interface()}
}
}
rows, err := db.Query(q, args...)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
p := reflect.New(t)
if err = rows.Scan(addrsOf(p)...); err != nil {
return err
}
v.Set(reflect.Append(v, p.Elem()))
}
return rows.Err()
}
func queryStrings(db *sql.DB, q string, args ...interface{}) ([]string, error) {
var values []string
err := queryRows(&values, db, q, args...)
if err != nil {
return nil, err
}
return values, nil
}
func getStructFields(pv reflect.Value) []interface{} {
mustBePtr(pv, reflect.Struct)
var fields []interface{}
v := pv.Elem()
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.CanAddr() && f.CanInterface() {
fields = append(fields, f.Addr().Interface())
}
}
return fields
}
func mustBe(v reflect.Value, k reflect.Kind) {
if v.Kind() != k {
panic(fmt.Sprintf("expected kind %v, got %v", k, v.Kind()))
}
}
func mustBePtr(v reflect.Value, k reflect.Kind) {
mustBe(v, reflect.Ptr)
mustBe(v.Elem(), k)
}