-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscan.go
More file actions
60 lines (52 loc) · 1.23 KB
/
scan.go
File metadata and controls
60 lines (52 loc) · 1.23 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
57
58
59
60
package procapi
import (
"github.com/jackc/pgx/v4"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
func ScanMap(rows pgx.Rows, dest *map[string]interface{}) error {
columns := FieldNames(rows)
/*
values := make([]interface{}, len(columns))
for i := range values {
x := new(interface{})
values[i] = x
//values[i] = "" //interface{}{}
}
err := rows.Scan(values...)
*/
values, err := rows.Values()
if err != nil {
return errors.Wrap(err, "ScanMap")
}
for i, column := range columns {
(*dest)[string(column)] = values[i]
// (*dest)[string(column)] = *(values[i].(*interface{}))
}
return rows.Err()
}
func ScanStruct(rows pgx.Rows, dest interface{}) error {
m := map[string]interface{}{}
err := ScanMap(rows, &m)
if err != nil {
return errors.Wrap(err, "Map")
}
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: dest,
TagName: "db",
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return errors.Wrap(err, "Decoder")
}
return decoder.Decode(m)
}
func FieldNames(rows pgx.Rows) []string {
columns := rows.FieldDescriptions()
names := make([]string, len(columns))
for i, column := range columns {
names[i] = string(column.Name)
}
return names
}