-
Notifications
You must be signed in to change notification settings - Fork 21
/
query.go
189 lines (163 loc) · 4.49 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
package handlers
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"strconv"
gabi "github.com/app-sre/gabi/pkg"
"github.com/app-sre/gabi/pkg/middleware"
"github.com/app-sre/gabi/pkg/models"
)
const (
base64EncodeResults byte = 1 << iota
base64DecodeQuery
)
func Query(cfg *gabi.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var (
base64Mode byte
request models.QueryRequest
)
if s := r.URL.Query().Get("base64_results"); s != "" {
if ok, err := strconv.ParseBool(s); err == nil && ok {
base64Mode |= base64EncodeResults
}
}
if ctxQuery := ctx.Value(middleware.ContextKeyQuery); ctxQuery != nil {
if s, ok := ctxQuery.(string); ok {
request.Query = s
}
}
if request.Query == "" {
if s := r.URL.Query().Get("base64_query"); s != "" {
if ok, err := strconv.ParseBool(s); err == nil && ok {
base64Mode |= base64DecodeQuery
}
}
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
cfg.Logger.Errorf("Unable to decode request body: %s", err)
if errors.Is(err, io.EOF) {
http.Error(w, "Request body cannot be empty", http.StatusBadRequest)
return
}
_ = queryErrorResponse(w, err)
return
}
if base64Mode&base64DecodeQuery != 0 {
bytes, err := cfg.Encoder.DecodeString(request.Query)
if err != nil {
l := "Unable to decode Base64-encoded query"
cfg.Logger.Errorf("%s: %s", l, err)
http.Error(w, l, http.StatusBadRequest)
return
}
request.Query = string(bytes)
}
}
tx, err := cfg.DB.BeginTx(ctx, &sql.TxOptions{
ReadOnly: !cfg.DBEnv.AllowWrite,
})
if err != nil {
cfg.Logger.Errorf("Unable to start database transaction: %s", err)
_ = queryErrorResponse(w, err)
return
}
defer func() { _ = tx.Rollback() }()
rows, err := tx.QueryContext(ctx, request.Query)
if err != nil {
cfg.Logger.Errorf("Unable to query database: %s", err)
_ = queryErrorResponse(w, err)
return
}
defer func() { _ = rows.Close() }()
// Remember to check err afterwards.
cols, err := rows.Columns()
if err != nil {
cfg.Logger.Errorf("Unable to process database columns: %s", err)
_ = queryErrorResponse(w, err)
return
}
vals := make([]interface{}, len(cols))
var (
result [][]string
keys []string
)
for i := range cols {
vals[i] = new(sql.RawBytes)
keys = append(keys, cols[i])
}
result = append(result, keys)
for rows.Next() {
err = rows.Scan(vals...)
// Now you can check each element of vals for nil-ness,
// and you can use type introspection and type assertions
// to fetch the column into a typed variable.
if err != nil {
cfg.Logger.Errorf("Unable to process database rows: %s", err)
_ = queryErrorResponse(w, err)
return
}
var row []string
for _, value := range vals {
content, ok := reflect.ValueOf(value).Interface().(*sql.RawBytes)
if !ok {
err = fmt.Errorf("unable to convert value type %T to *sql.RawBytes", value)
cfg.Logger.Errorf("Unable to process database query: %s", err)
_ = queryErrorResponse(w, err)
return
}
s := string(*content)
if base64Mode&base64EncodeResults != 0 {
s = cfg.Encoder.EncodeToString(*content)
}
row = append(row, s)
}
result = append(result, row)
}
err = rows.Err()
if err != nil {
cfg.Logger.Errorf("Unable to process database rows: %s", err)
_ = queryErrorResponse(w, err)
return
}
err = tx.Commit()
if err != nil {
cfg.Logger.Errorf("Unable to commit database changes: %s", err)
_ = queryErrorResponse(w, err)
return
}
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(&models.QueryResponse{
Result: result,
})
}
}
func queryErrorResponse(w http.ResponseWriter, err error) error {
var (
parseError *url.Error
syscallError *os.SyscallError
)
// Stop the SQL drivers from leaking credentials on connection errors.
if errors.As(err, &parseError) || errors.As(err, &syscallError) {
http.Error(w, "Unable to connect to the database", http.StatusServiceUnavailable)
return nil
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
err = json.NewEncoder(w).Encode(&models.QueryResponse{
Error: err.Error(),
})
if err != nil {
return fmt.Errorf("unable to marshal error response: %w", err)
}
return nil
}