-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathsql.go
207 lines (175 loc) · 5.14 KB
/
sql.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package sql
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
)
type DbClient struct {
*sql.DB
logger *logp.Logger
}
type sqlRow interface {
Scan(dest ...interface{}) error
Next() bool
Columns() ([]string, error)
Err() error
}
// NewDBClient gets a client ready to query the database
func NewDBClient(driver, uri string, l *logp.Logger) (*DbClient, error) {
dbx, err := sql.Open(switchDriverName(driver), uri)
if err != nil {
return nil, errors.Wrap(err, "opening connection")
}
err = dbx.Ping()
if err != nil {
if closeErr := dbx.Close(); closeErr != nil {
return nil, errors.Wrapf(err, "failed to close with %s, after connection test failed", closeErr)
}
return nil, errors.Wrap(err, "testing connection")
}
return &DbClient{DB: dbx, logger: l}, nil
}
// fetchTableMode scan the rows and publishes the event for querys that return the response in a table format.
func (d *DbClient) FetchTableMode(ctx context.Context, q string) ([]mapstr.M, error) {
rows, err := d.QueryContext(ctx, q)
if err != nil {
return nil, err
}
return d.fetchTableMode(rows)
}
// fetchTableMode scan the rows and publishes the event for querys that return the response in a table format.
func (d *DbClient) fetchTableMode(rows sqlRow) ([]mapstr.M, error) {
// Extracted from
// https://stackoverflow.com/questions/23507531/is-golangs-sql-package-incapable-of-ad-hoc-exploratory-queries/23507765#23507765
cols, err := rows.Columns()
if err != nil {
return nil, errors.Wrap(err, "error getting columns")
}
for k, v := range cols {
cols[k] = strings.ToLower(v)
}
vals := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
vals[i] = new(interface{})
}
rr := make([]mapstr.M, 0)
for rows.Next() {
err = rows.Scan(vals...)
if err != nil {
d.logger.Debug(errors.Wrap(err, "error trying to scan rows"))
continue
}
r := mapstr.M{}
for i, c := range cols {
value := getValue(vals[i].(*interface{}))
r.Put(c, value)
}
rr = append(rr, r)
}
if err = rows.Err(); err != nil {
d.logger.Debug(errors.Wrap(err, "error trying to read rows"))
}
return rr, nil
}
// fetchTableMode scan the rows and publishes the event for querys that return the response in a table format.
func (d *DbClient) FetchVariableMode(ctx context.Context, q string) (mapstr.M, error) {
rows, err := d.QueryContext(ctx, q)
if err != nil {
return nil, err
}
return d.fetchVariableMode(rows)
}
// fetchVariableMode scan the rows and publishes the event for querys that return the response in a key/value format.
func (d *DbClient) fetchVariableMode(rows sqlRow) (mapstr.M, error) {
data := mapstr.M{}
for rows.Next() {
var key string
var val interface{}
err := rows.Scan(&key, &val)
if err != nil {
d.logger.Debug(errors.Wrap(err, "error trying to scan rows"))
continue
}
key = strings.ToLower(key)
data[key] = val
}
if err := rows.Err(); err != nil {
d.logger.Debug(errors.Wrap(err, "error trying to read rows"))
}
r := mapstr.M{}
for key, value := range data {
value := getValue(&value)
r.Put(key, value)
}
return r, nil
}
// ReplaceUnderscores takes the root keys of a common.Mapstr and rewrites them replacing underscores with dots. Check tests
// to see an example.
func ReplaceUnderscores(ms mapstr.M) mapstr.M {
dotMap := mapstr.M{}
for k, v := range ms {
dotMap.Put(strings.Replace(k, "_", ".", -1), v)
}
return dotMap
}
func getValue(pval *interface{}) interface{} {
switch v := (*pval).(type) {
case nil, bool:
return v
case []byte:
s := string(v)
num, err := strconv.ParseFloat(s, 64)
if err == nil {
return num
}
return s
case time.Time:
return v.Format(time.RFC3339Nano)
case []interface{}:
return v
default:
s := fmt.Sprint(v)
num, err := strconv.ParseFloat(s, 64)
if err == nil {
return num
}
return s
}
}
// switchDriverName switches between driver name and a pretty name for a driver. For example, 'oracle' driver is called
// 'godror' so this detail implementation must be hidden to the user, that should only choose and see 'oracle' as driver
func switchDriverName(d string) string {
switch d {
case "oracle":
return "godror"
case "cockroachdb":
return "postgres"
case "cockroach":
return "postgres"
case "postgresql":
return "postgres"
}
return d
}