-
Notifications
You must be signed in to change notification settings - Fork 0
/
getjsonstruct.go
50 lines (38 loc) · 1.22 KB
/
getjsonstruct.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
package mysqlkebab
import (
"context"
"encoding/json"
"fmt"
"time"
)
// MustGetJSONStruct tries to scan query result's single column value into given struct
// If sql.ErrNoRows occurs, it's returned.
// The other routines ( without "Must" preffix ) ignores sql.ErrNoRows
func (l *DBLink) MustGetJSONStruct(target interface{}, sqlQuery string, args ...interface{}) error {
if !l.supposedReady {
return fmt.Errorf("connection not properly initialized")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(l.executionTimeoutSeconds)*time.Second)
defer cancel()
var 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 err
}
if data, err := j.MarshalJSON(); err != nil {
return err
} else {
if err0 := json.Unmarshal(data, &target); err0 != nil {
return err0
}
}
return nil
}
// GetJSONStruct tries to scan query result's single column value into given struct
func (l *DBLink) GetJSONStruct(target interface{}, sqlQuery string, args ...interface{}) error {
err := l.MustGetJSONStruct(target, sqlQuery, args...)
if l.IsEmptyErr(err) {
err = nil
}
return err
}