-
Notifications
You must be signed in to change notification settings - Fork 0
/
rows_to_map.go
55 lines (46 loc) · 1.03 KB
/
rows_to_map.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
package dbal
import (
"database/sql"
)
// MappedSQLRow ...
// Improve this to not use interface{}
type MappedSQLRow map[string]interface{}
// MappedSQLRows ...
type MappedSQLRows map[int]MappedSQLRow
// RowsToMap takes the current sql.Rows and maps each column and value to a
// map[string]interface{}.
func RowsToMap(rows *sql.Rows) (MappedSQLRows, error) {
columns, cErr := rows.Columns()
if cErr != nil {
return nil, cErr
}
count := len(columns)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
finalResult := MappedSQLRows{}
resultID := 0
for rows.Next() {
for i := range columns {
valuePtrs[i] = &values[i]
}
scanErr := rows.Scan(valuePtrs...)
if scanErr != nil {
return nil, scanErr
}
tmpStruct := map[string]interface{}{}
for i, col := range columns {
var v interface{}
val := values[i]
b, ok := val.([]uint8)
if ok {
v = []byte(b)
} else {
v = val
}
tmpStruct[col] = v
}
finalResult[resultID] = tmpStruct
resultID++
}
return finalResult, nil
}