-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpull_query.go
83 lines (66 loc) · 1.68 KB
/
pull_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
package ksqldbx
import (
"bufio"
"context"
"encoding/json"
"errors"
"io"
)
var ErrNoRows = errors.New("no rows in result set")
// Pull run PULL query, which will return all result at once.
// A PULL query is a query that didn't EMIT CHANGES,
// running a query that use EMIT CHANGES will cause this method to
// block indefinitely
func (ksql *KsqlDB) Pull(ctx context.Context, q QuerySQL) (Header, []Row, error) {
// TODO
// check if sql parse option is enabled, if yes
// then parse sql before exec
var header Header
var rows []Row
res, err := ksql.queryStreamRequest(ctx, q)
if err != nil {
return header, rows, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return header, rows, newErrFromReader(res.Body)
}
reader := bufio.NewReader(res.Body)
headerFound := false
for {
body, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF && err != context.Canceled {
return header, rows, err
}
if len(rows) == 0 {
return header, rows, ErrNoRows
}
return header, rows, nil
}
if !headerFound {
if err := json.Unmarshal(body, &header); err != nil {
return header, rows, err
}
headerFound = true
continue
}
var row Row
if err := json.Unmarshal(body, &row); err != nil {
return header, rows, err
}
rows = append(rows, row)
}
}
// PullRow pull exactly one Row of data.
// It does not care even if you did not specify a LIMIT 1,
// it will only return the first Row of the result set
func (ksql *KsqlDB) PullRow(ctx context.Context, q QuerySQL) (Header, Row, error) {
var header Header
var row Row
header, rows, err := ksql.Pull(ctx, q)
if err != nil {
return header, row, err
}
return header, rows[0], nil
}