-
Notifications
You must be signed in to change notification settings - Fork 11
/
pull.go
141 lines (121 loc) · 3.9 KB
/
pull.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
package ksqldb
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strconv"
"strings"
"golang.org/x/net/http2"
)
// Pull queries are like "traditional" RDBMS queries in which
// the query terminates once the state has been queried.
//
// To use this function pass in the the SQL query statement, and
// a boolean for whether full table scans should be enabled.
//
// The function returns a ksqldb.Header and ksqldb.Payload
// which will hold one or more rows of data. You will need to
// define variables to hold each column's value. You can adopt
// this pattern to do this:
// var COL1 string
// var COL2 float64
// for _, row := range r {
// COL1 = row[0].(string)
// COL2 = row[1].(float64)
// // Do other stuff with the data here
// }
// }
func (cl *Client) Pull(ctx context.Context, q string, s bool) (h Header, r Payload, err error) {
// Create the request
payload := strings.NewReader("{\"properties\":{\"ksql.query.pull.table.scan.enabled\": " + strconv.FormatBool(s) + "},\"sql\":\"" + q + "\"}")
// payload := strings.NewReader("{\"sql\":\"" + q + "\"}")
req, err := http.NewRequestWithContext(ctx, "POST", cl.url+"/query-stream", payload)
fmt.Printf("%+v", payload)
if err != nil {
return h, r, err
}
req.Header.Add("Accept", "application/json; charset=utf-8")
// If we've got creds to pass, let's pass them
if cl.username != "" {
req.SetBasicAuth(cl.username, cl.password)
}
client := &http.Client{}
if req.URL.Scheme == "http" {
// ksqlDB uses HTTP2 and if the server is on HTTP then Golang will not
// use HTTP2 unless we force it to, thus.
// Without this you get the error `http2: unsupported scheme`
client.Transport = &http2.Transport{
AllowHTTP: true,
// Pretend we are dialing a TLS endpoint.
// Note, we ignore the passed tls.Config
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
}
}
res, err := client.Do(req)
if err != nil {
return h, r, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return h, r, err
}
if res.StatusCode != 200 {
return h, r, fmt.Errorf("The HTTP request did not return a success code:\n%v / %v", res.StatusCode, string(body))
}
var x []interface{}
// Parse the output
if err := json.Unmarshal(body, &x); err != nil {
return h, r, fmt.Errorf("Could not parse the response as JSON:\n%v\n%v", err, string(body))
}
switch len(x) {
case 0:
return h, r, fmt.Errorf("%w (not even a header row) returned from lookup. Maybe we got an error:%v", ErrNotFound, err)
case 1:
// len 1 means we just got a header, no rows
// Should we define our own error types here so we can return more clearly
// an indicator that no rows were found?
return h, r, ErrNotFound
default:
for _, z := range x {
switch zz := z.(type) {
case map[string]interface{}:
// It's a header row, so extract the data
// {"queryId":null,"columnNames":["WINDOW_START","WINDOW_END","DOG_SIZE","DOGS_CT"],"columnTypes":["STRING","STRING","STRING","BIGINT"]}
if _, ok := zz["queryId"].(string); ok {
h.queryId = zz["queryId"].(string)
} else {
cl.log("(Query ID not found - this is expected for a pull query)")
}
names, okn := zz["columnNames"].([]interface{})
types, okt := zz["columnTypes"].([]interface{})
if okn && okt {
for col := range names {
if n, ok := names[col].(string); n != "" && ok {
if t, ok := types[col].(string); t != "" && ok {
a := Column{Name: n, Type: t}
h.columns = append(h.columns, a)
} else {
cl.log("Nil type found for column %v", col)
}
} else {
cl.log("Nil name found for column %v", col)
}
}
} else {
cl.log("Column names/types not found in header:\n%v", zz)
}
case []interface{}:
// It's a row of data
r = append(r, zz)
}
}
return h, r, nil
}
}