-
Notifications
You must be signed in to change notification settings - Fork 0
/
getjsonmap.go
52 lines (39 loc) · 1.25 KB
/
getjsonmap.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
package mysqlkebab
import (
"context"
"encoding/json"
"fmt"
"time"
)
// MustGetJSONMap returns the query result's single column value as map
// If sql.ErrNoRows occurs, it's returned.
// The other routines ( without "Must" preffix ) ignores sql.ErrNoRows
func (l *DBLink) MustGetJSONMap(sqlQuery string, args ...interface{}) (map[string]interface{}, error) {
if !l.supposedReady {
return nil, fmt.Errorf("connection not properly initialized")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(l.executionTimeoutSeconds)*time.Second)
defer cancel()
j := json.RawMessage{}
if err := l.db.QueryRowContext(ctx, sqlQuery, args...).Scan(&j); err != nil {
l.log("mysqlkebab.GetJSONAsMap.QueryRowContext().Scan(%s) %v", sqlQuery, err)
return nil, err
}
m := make(map[string]interface{})
if data, err := j.MarshalJSON(); err != nil {
return nil, err
} else {
if err0 := json.Unmarshal(data, &m); err0 != nil {
return nil, err0
}
}
return m, nil
}
// GetJSONMap returns the query result's single column value as map
func (l *DBLink) GetJSONMap(sqlQuery string, args ...interface{}) (map[string]interface{}, error) {
m, err := l.MustGetJSONMap(sqlQuery, args...)
if l.IsEmptyErr(err) {
err = nil
}
return m, err
}