-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmysql.go
96 lines (75 loc) · 1.84 KB
/
mysql.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
hierr "github.com/reconquest/hierr-go"
)
var (
statName string
statValue string
result []map[string]string
)
func getRow(dsn, query string) (*sql.Rows, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, hierr.Errorf(err, "can't open %s.", dsn)
}
defer db.Close()
rows, err := db.Query(query)
if err != nil {
return nil, err
}
return rows, nil
}
func getGlobalStats(query, dsn string) ([]map[string]string, error) {
stats := make(map[string]string)
rows, err := getRow(dsn, query)
if err != nil {
return nil, hierr.Errorf(err, "can't do query %s.", query)
}
for rows.Next() {
err = rows.Scan(&statName, &statValue)
if err != nil {
return nil, hierr.Errorf(err, "can't get value from row.")
}
stats[statName] = statValue
}
result = append(result, stats)
if len(result) == 0 {
return nil, fmt.Errorf("return null value in query %s", query)
}
return result, nil
}
func getStats(query, dsn string) ([]map[string]string, error) {
rows, err := getRow(dsn, query)
if err != nil {
return nil, hierr.Errorf(err, "can't do query %s.", query)
}
columns, err := rows.Columns()
if err != nil {
return nil, hierr.Errorf(err, "can't get columns.")
}
values := make([]sql.RawBytes, len(columns))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
for rows.Next() {
err = rows.Scan(scanArgs...)
if err != nil {
return nil, hierr.Errorf(err, "can't get value.")
}
stats := make(map[string]string)
for i, value := range values {
statName = columns[i]
statValue = string(value)
stats[statName] = statValue
}
result = append(result, stats)
}
if len(result) == 0 {
return nil, fmt.Errorf("return null value in query %s", query)
}
return result, nil
}