-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathquery.go
514 lines (482 loc) · 14.4 KB
/
query.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Copyright 2020-2021 InfluxData, Inc. All rights reserved.
// Use of this source code is governed by MIT
// license that can be found in the LICENSE file.
package api
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
http2 "github.com/influxdata/influxdb-client-go/v2/api/http"
"github.com/influxdata/influxdb-client-go/v2/api/query"
"github.com/influxdata/influxdb-client-go/v2/domain"
"github.com/influxdata/influxdb-client-go/v2/internal/log"
ilog "github.com/influxdata/influxdb-client-go/v2/log"
)
const (
stringDatatype = "string"
doubleDatatype = "double"
boolDatatype = "boolean"
longDatatype = "long"
uLongDatatype = "unsignedLong"
durationDatatype = "duration"
base64BinaryDataType = "base64Binary"
timeDatatypeRFC = "dateTime:RFC3339"
timeDatatypeRFCNano = "dateTime:RFC3339Nano"
)
// QueryAPI provides methods for performing synchronously flux query against InfluxDB server.
//
// Flux query can contain reference to parameters, which must be passed via queryParams.
// it can be a struct or map. Param values can be only simple types or time.Time.
// The name of a struct field or a map key (must be a string) will be a param name.
// The name of the parameter represented by a struct field can be specified by JSON annotation:
//
// type Condition struct {
// Start time.Time `json:"start"`
// Field string `json:"field"`
// Value float64 `json:"value"`
// }
//
// Parameters are then accessed via the Flux params object:
//
// query:= `from(bucket: "environment")
// |> range(start: time(v: params.start))
// |> filter(fn: (r) => r._measurement == "air")
// |> filter(fn: (r) => r._field == params.field)
// |> filter(fn: (r) => r._value > params.value)`
type QueryAPI interface {
// QueryRaw executes flux query on the InfluxDB server and returns complete query result as a string with table annotations according to dialect
QueryRaw(ctx context.Context, query string, dialect *domain.Dialect) (string, error)
// QueryRawWithParams executes flux parametrized query on the InfluxDB server and returns complete query result as a string with table annotations according to dialect
QueryRawWithParams(ctx context.Context, query string, dialect *domain.Dialect, params interface{}) (string, error)
// Query executes flux query on the InfluxDB server and returns QueryTableResult which parses streamed response into structures representing flux table parts
Query(ctx context.Context, query string) (*QueryTableResult, error)
// QueryWithParams executes flux parametrized query on the InfluxDB server and returns QueryTableResult which parses streamed response into structures representing flux table parts
QueryWithParams(ctx context.Context, query string, params interface{}) (*QueryTableResult, error)
}
// NewQueryAPI returns new query client for querying buckets belonging to org
func NewQueryAPI(org string, service http2.Service) QueryAPI {
return &queryAPI{
org: org,
httpService: service,
}
}
// QueryTableResult parses streamed flux query response into structures representing flux table parts
// Walking though the result is done by repeatedly calling Next() until returns false.
// Actual flux table info (columns with names, data types, etc) is returned by TableMetadata() method.
// Data are acquired by Record() method.
// Preliminary end can be caused by an error, so when Next() return false, check Err() for an error
type QueryTableResult struct {
io.Closer
csvReader *csv.Reader
tablePosition int
tableChanged bool
table *query.FluxTableMetadata
record *query.FluxRecord
err error
}
// NewQueryTableResult returns new QueryTableResult
func NewQueryTableResult(rawResponse io.ReadCloser) *QueryTableResult {
csvReader := csv.NewReader(rawResponse)
csvReader.FieldsPerRecord = -1
return &QueryTableResult{Closer: rawResponse, csvReader: csvReader}
}
// queryAPI implements QueryAPI interface
type queryAPI struct {
org string
httpService http2.Service
url string
lock sync.Mutex
}
// queryBody holds the body for an HTTP query request.
type queryBody struct {
Dialect *domain.Dialect `json:"dialect,omitempty"`
Query string `json:"query"`
Type domain.QueryType `json:"type"`
Params interface{} `json:"params,omitempty"`
}
func (q *queryAPI) QueryRaw(ctx context.Context, query string, dialect *domain.Dialect) (string, error) {
return q.QueryRawWithParams(ctx, query, dialect, nil)
}
func (q *queryAPI) QueryRawWithParams(ctx context.Context, query string, dialect *domain.Dialect, params interface{}) (string, error) {
if err := checkParamsType(params); err != nil {
return "", err
}
queryURL, err := q.queryURL()
if err != nil {
return "", err
}
qr := queryBody{
Query: query,
Type: domain.QueryTypeFlux,
Dialect: dialect,
Params: params,
}
qrJSON, err := json.Marshal(qr)
if err != nil {
return "", err
}
if log.Level() >= ilog.DebugLevel {
log.Debugf("Query: %s", qrJSON)
}
var body string
perror := q.httpService.DoPostRequest(ctx, queryURL, bytes.NewReader(qrJSON), func(req *http.Request) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept-Encoding", "gzip")
},
func(resp *http.Response) error {
if resp.Header.Get("Content-Encoding") == "gzip" {
resp.Body, err = gzip.NewReader(resp.Body)
if err != nil {
return err
}
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
body = string(respBody)
return nil
})
if perror != nil {
return "", perror
}
return body, nil
}
// DefaultDialect return flux query Dialect with full annotations (datatype, group, default), header and comma char as a delimiter
func DefaultDialect() *domain.Dialect {
annotations := []domain.DialectAnnotations{domain.DialectAnnotationsDatatype, domain.DialectAnnotationsGroup, domain.DialectAnnotationsDefault}
delimiter := ","
header := true
return &domain.Dialect{
Annotations: &annotations,
Delimiter: &delimiter,
Header: &header,
}
}
func (q *queryAPI) Query(ctx context.Context, query string) (*QueryTableResult, error) {
return q.QueryWithParams(ctx, query, nil)
}
func (q *queryAPI) QueryWithParams(ctx context.Context, query string, params interface{}) (*QueryTableResult, error) {
var queryResult *QueryTableResult
if err := checkParamsType(params); err != nil {
return nil, err
}
queryURL, err := q.queryURL()
if err != nil {
return nil, err
}
qr := queryBody{
Query: query,
Type: domain.QueryTypeFlux,
Dialect: DefaultDialect(),
Params: params,
}
qrJSON, err := json.Marshal(qr)
if err != nil {
return nil, err
}
if log.Level() >= ilog.DebugLevel {
log.Debugf("Query: %s", qrJSON)
}
perror := q.httpService.DoPostRequest(ctx, queryURL, bytes.NewReader(qrJSON), func(req *http.Request) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept-Encoding", "gzip")
},
func(resp *http.Response) error {
if resp.Header.Get("Content-Encoding") == "gzip" {
resp.Body, err = gzip.NewReader(resp.Body)
if err != nil {
return err
}
}
csvReader := csv.NewReader(resp.Body)
csvReader.FieldsPerRecord = -1
queryResult = &QueryTableResult{Closer: resp.Body, csvReader: csvReader}
return nil
})
if perror != nil {
return queryResult, perror
}
return queryResult, nil
}
func (q *queryAPI) queryURL() (string, error) {
if q.url == "" {
u, err := url.Parse(q.httpService.ServerAPIURL())
if err != nil {
return "", err
}
u.Path = path.Join(u.Path, "query")
params := u.Query()
params.Set("org", q.org)
u.RawQuery = params.Encode()
q.lock.Lock()
q.url = u.String()
q.lock.Unlock()
}
return q.url, nil
}
// checkParamsType validates the value is struct with simple type fields
// or a map with key as string and value as a simple type
func checkParamsType(p interface{}) error {
if p == nil {
return nil
}
t := reflect.TypeOf(p)
v := reflect.ValueOf(p)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
if t.Kind() != reflect.Struct && t.Kind() != reflect.Map {
return fmt.Errorf("cannot use %v as query params", t)
}
switch t.Kind() {
case reflect.Struct:
fields := reflect.VisibleFields(t)
for _, f := range fields {
fv := v.FieldByIndex(f.Index)
t := getFieldType(fv)
if !validParamType(t) {
return fmt.Errorf("cannot use field '%s' of type '%v' as a query param", f.Name, t)
}
}
case reflect.Map:
key := t.Key()
if key.Kind() != reflect.String {
return fmt.Errorf("cannot use map key of type '%v' for query param name", key)
}
for _, k := range v.MapKeys() {
f := v.MapIndex(k)
t := getFieldType(f)
if !validParamType(t) {
return fmt.Errorf("cannot use map value type '%v' as a query param", t)
}
}
}
return nil
}
// validParamType validates that t is primitive type or string or interface
func validParamType(t reflect.Type) bool {
return (t.Kind() > reflect.Invalid && t.Kind() < reflect.Complex64) ||
t.Kind() == reflect.String ||
t == timeType
}
// TablePosition returns actual flux table position in the result, or -1 if no table was found yet
// Each new table is introduced by an annotation in csv
func (q *QueryTableResult) TablePosition() int {
if q.table != nil {
return q.table.Position()
}
return -1
}
// TableMetadata returns actual flux table metadata
func (q *QueryTableResult) TableMetadata() *query.FluxTableMetadata {
return q.table
}
// TableChanged returns true if last call of Next() found also new result table
// Table information is available via TableMetadata method
func (q *QueryTableResult) TableChanged() bool {
return q.tableChanged
}
// Record returns last parsed flux table data row
// Use Record methods to access value and row properties
func (q *QueryTableResult) Record() *query.FluxRecord {
return q.record
}
type parsingState int
const (
parsingStateNormal parsingState = iota
parsingStateAnnotation
parsingStateNameRow
parsingStateError
)
// Next advances to next row in query result.
// During the first time it is called, Next creates also table metadata
// Actual parsed row is available through Record() function
// Returns false in case of end or an error, otherwise true
func (q *QueryTableResult) Next() bool {
var row []string
// set closing query in case of preliminary return
closer := func() {
if err := q.Close(); err != nil {
message := err.Error()
if q.err != nil {
message = fmt.Sprintf("%s,%s", message, q.err.Error())
}
q.err = errors.New(message)
}
}
defer func() {
closer()
}()
parsingState := parsingStateNormal
q.tableChanged = false
dataTypeAnnotationFound := false
readRow:
row, q.err = q.csvReader.Read()
if q.err == io.EOF {
q.err = nil
return false
}
if q.err != nil {
return false
}
if len(row) <= 1 {
goto readRow
}
if len(row[0]) > 0 && row[0][0] == '#' {
if parsingState == parsingStateNormal {
q.table = query.NewFluxTableMetadata(q.tablePosition)
q.tablePosition++
q.tableChanged = true
for i := range row[1:] {
q.table.AddColumn(query.NewFluxColumn(i))
}
parsingState = parsingStateAnnotation
}
}
if q.table == nil {
q.err = errors.New("parsing error, annotations not found")
return false
}
if len(row)-1 != len(q.table.Columns()) {
q.err = fmt.Errorf("parsing error, row has different number of columns than the table: %d vs %d", len(row)-1, len(q.table.Columns()))
return false
}
switch row[0] {
case "":
switch parsingState {
case parsingStateAnnotation:
if !dataTypeAnnotationFound {
q.err = errors.New("parsing error, datatype annotation not found")
return false
}
parsingState = parsingStateNameRow
fallthrough
case parsingStateNameRow:
if row[1] == "error" {
parsingState = parsingStateError
} else {
for i, n := range row[1:] {
if q.table.Column(i) != nil {
q.table.Column(i).SetName(n)
}
}
parsingState = parsingStateNormal
}
goto readRow
case parsingStateError:
var message string
if len(row) > 1 && len(row[1]) > 0 {
message = row[1]
} else {
message = "unknown query error"
}
reference := ""
if len(row) > 2 && len(row[2]) > 0 {
reference = fmt.Sprintf(",%s", row[2])
}
q.err = fmt.Errorf("%s%s", message, reference)
return false
}
values := make(map[string]interface{})
for i, v := range row[1:] {
if q.table.Column(i) != nil {
values[q.table.Column(i).Name()], q.err = toValue(stringTernary(v, q.table.Column(i).DefaultValue()), q.table.Column(i).DataType(), q.table.Column(i).Name())
if q.err != nil {
return false
}
}
}
q.record = query.NewFluxRecord(q.table.Position(), values)
case "#datatype":
dataTypeAnnotationFound = true
for i, d := range row[1:] {
if q.table.Column(i) != nil {
q.table.Column(i).SetDataType(d)
}
}
goto readRow
case "#group":
for i, g := range row[1:] {
if q.table.Column(i) != nil {
q.table.Column(i).SetGroup(g == "true")
}
}
goto readRow
case "#default":
for i, c := range row[1:] {
if q.table.Column(i) != nil {
q.table.Column(i).SetDefaultValue(c)
}
}
goto readRow
}
// don't close query
closer = func() {}
return true
}
// Err returns an error raised during flux query response parsing
func (q *QueryTableResult) Err() error {
return q.err
}
// Close reads remaining data and closes underlying Closer
func (q *QueryTableResult) Close() error {
var err error
for err == nil {
_, err = q.csvReader.Read()
}
return q.Closer.Close()
}
// stringTernary returns a if not empty, otherwise b
func stringTernary(a, b string) string {
if a == "" {
return b
}
return a
}
// toValues converts s into type by t
func toValue(s, t, name string) (interface{}, error) {
if s == "" {
return nil, nil
}
switch t {
case stringDatatype:
return s, nil
case timeDatatypeRFC:
return time.Parse(time.RFC3339, s)
case timeDatatypeRFCNano:
return time.Parse(time.RFC3339Nano, s)
case durationDatatype:
return time.ParseDuration(s)
case doubleDatatype:
return strconv.ParseFloat(s, 64)
case boolDatatype:
if strings.ToLower(s) == "false" {
return false, nil
}
return true, nil
case longDatatype:
return strconv.ParseInt(s, 10, 64)
case uLongDatatype:
return strconv.ParseUint(s, 10, 64)
case base64BinaryDataType:
return base64.StdEncoding.DecodeString(s)
default:
return nil, fmt.Errorf("%s has unknown data type %s", name, t)
}
}