-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.go
104 lines (81 loc) · 1.74 KB
/
queries.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
package corroclient
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
)
var ErrNoRows = errors.New("corroclient: no rows")
func (c *CorroClient) Query(ctx context.Context, stmt Statement) (*Rows, error) {
payload, err := json.Marshal(stmt)
if err != nil {
return nil, err
}
buffer := bytes.NewBuffer(payload)
request, err := http.NewRequestWithContext(ctx, "POST", c.getURL("/v1/queries"), buffer)
if err != nil {
return nil, err
}
resp, err := c.request(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("corroclient: invalid status code: %d, body: %s", resp.StatusCode, string(bodyBytes))
}
reader := bufio.NewReader(resp.Body)
var columns Columns
rows := []*Row{}
for {
data, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}
var e event
if err := json.Unmarshal(data, &e); err != nil {
return nil, err
}
if e.Columns != nil {
columns = e.Columns
continue
}
if e.Row != nil {
row, err := readRow(e.Row)
if err != nil {
return nil, err
}
rows = append(rows, row)
}
if e.EOQ != nil {
break
}
}
if len(rows) == 0 {
return nil, ErrNoRows
}
return &Rows{
columns: columns,
rows: rows,
mutex: sync.RWMutex{},
currentIndex: -1,
}, nil
}
func (c *CorroClient) QueryRow(ctx context.Context, stmt Statement) (*Row, error) {
rows, err := c.Query(ctx, stmt)
if err != nil {
return nil, err
}
if !rows.Next() {
return nil, ErrNoRows // should never append but just in case...
}
row := rows.rows[rows.currentIndex]
row.columns = rows.columns
return row, nil
}