forked from speee/go-athena
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
344 lines (292 loc) · 8.58 KB
/
conn.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
package athena
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/cenkalti/backoff/v5"
uuid "github.com/satori/go.uuid"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/athena"
"github.com/aws/aws-sdk-go-v2/service/athena/types"
)
// Query type patterns
var (
ddlQueryPattern = regexp.MustCompile(`(?i)^(ALTER|CREATE|DESCRIBE|DROP|MSCK|SHOW)`)
selectQueryPattern = regexp.MustCompile(`(?i)^SELECT`)
ctasQueryPattern = regexp.MustCompile(`(?i)^CREATE.+AS\s+SELECT`)
)
// queryType represents the type of SQL query
type queryType int
const (
queryTypeUnknown queryType = iota
queryTypeDDL
queryTypeSelect
queryTypeCTAS
)
// getQueryType determines the type of the query
func getQueryType(query string) queryType {
switch {
case ddlQueryPattern.MatchString(query):
return queryTypeDDL
case ctasQueryPattern.MatchString(query):
return queryTypeCTAS
case selectQueryPattern.MatchString(query):
return queryTypeSelect
default:
return queryTypeUnknown
}
}
// isDDLQuery determines if the query is a DDL statement
func isDDLQuery(query string) bool {
return getQueryType(query) == queryTypeDDL
}
// isSelectQuery determines if the query is a SELECT statement
func isSelectQuery(query string) bool {
return getQueryType(query) == queryTypeSelect
}
// isCTASQuery determines if the query is a CREATE TABLE AS SELECT statement
func isCTASQuery(query string) bool {
return getQueryType(query) == queryTypeCTAS
}
type conn struct {
athena *athena.Client
db string
OutputLocation string
workgroup string
pollMode PollMode
pollFrequency time.Duration
resultMode ResultMode
config aws.Config
timeout uint
catalog string
}
func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
if len(args) > 0 {
panic("Athena doesn't support prepared statements. Format your own arguments.")
}
rows, err := c.runQuery(ctx, query)
return rows, err
}
func (c *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
if len(args) > 0 {
panic("Athena doesn't support prepared statements. Format your own arguments.")
}
_, err := c.runQuery(ctx, query)
return nil, err
}
func (c *conn) runQuery(ctx context.Context, query string) (driver.Rows, error) {
// result mode
isSelect := isSelectQuery(query)
resultMode := c.resultMode
if rmode, ok := getResultMode(ctx); ok {
if !isValidResultMode(rmode) {
return nil, ErrInvalidResultMode
}
resultMode = rmode
}
if !isSelect {
resultMode = ResultModeAPI
}
// timeout
timeout := c.timeout
if to, ok := getTimeout(ctx); ok {
timeout = to
}
// catalog
catalog := c.catalog
if cat, ok := getCatalog(ctx); ok {
catalog = cat
}
// output location (with empty value)
if checkOutputLocation(resultMode, c.OutputLocation) {
var err error
c.OutputLocation, err = getOutputLocation(c.athena, c.workgroup)
if err != nil {
return nil, err
}
}
// mode ctas
var ctasTable string
var afterDownload func() error
if isCreatingCTASTable(isSelect, resultMode) {
// Create AS Select
ctasTable = fmt.Sprintf("tmp_ctas_%v", strings.Replace(uuid.NewV4().String(), "-", "", -1))
query = fmt.Sprintf("CREATE TABLE %s WITH (format='TEXTFILE') AS %s", ctasTable, query)
afterDownload = c.dropCTASTable(ctx, ctasTable)
}
queryID, err := c.startQuery(ctx, query)
if err != nil {
return nil, err
}
if err := c.waitOnQuery(ctx, queryID); err != nil {
return nil, err
}
return newRows(rowsConfig{
Athena: c.athena,
QueryID: queryID,
SkipHeader: !isDDLQuery(query),
ResultMode: resultMode,
Config: c.config,
OutputLocation: c.OutputLocation,
Timeout: timeout,
AfterDownload: afterDownload,
CTASTable: ctasTable,
DB: c.db,
Catalog: catalog,
})
}
func (c *conn) dropCTASTable(ctx context.Context, table string) func() error {
return func() error {
query := fmt.Sprintf("DROP TABLE %s", table)
queryID, err := c.startQuery(ctx, query)
if err != nil {
return err
}
return c.waitOnQuery(ctx, queryID)
}
}
// startQuery starts an Athena query and returns its ID.
func (c *conn) startQuery(ctx context.Context, query string) (string, error) {
resp, err := c.athena.StartQueryExecution(ctx, &athena.StartQueryExecutionInput{
QueryString: aws.String(query),
QueryExecutionContext: &types.QueryExecutionContext{
Database: aws.String(c.db),
},
ResultConfiguration: &types.ResultConfiguration{
OutputLocation: aws.String(c.OutputLocation),
},
WorkGroup: aws.String(c.workgroup),
})
if err != nil {
return "", err
}
return *resp.QueryExecutionId, nil
}
func newBackoff(pollMode PollMode, pollFrequency time.Duration) backoff.BackOff {
if pollMode == PollModeExponential {
return backoff.NewExponentialBackOff()
}
return backoff.NewConstantBackOff(pollFrequency)
}
// waitOnQuery blocks until a query finishes, returning an error if it failed.
func (c *conn) waitOnQuery(ctx context.Context, queryID string) error {
backoff := newBackoff(c.pollMode, c.pollFrequency)
for {
statusResp, err := c.athena.GetQueryExecution(ctx, &athena.GetQueryExecutionInput{
QueryExecutionId: aws.String(queryID),
})
if err != nil {
return err
}
switch statusResp.QueryExecution.Status.State {
case types.QueryExecutionStateCancelled:
return context.Canceled
case types.QueryExecutionStateFailed:
reason := *statusResp.QueryExecution.Status.StateChangeReason
return errors.New(reason)
case types.QueryExecutionStateSucceeded:
return nil
case types.QueryExecutionStateQueued:
case types.QueryExecutionStateRunning:
}
select {
case <-ctx.Done():
c.athena.StopQueryExecution(ctx, &athena.StopQueryExecutionInput{
QueryExecutionId: aws.String(queryID),
})
return ctx.Err()
case <-time.After(backoff.NextBackOff()):
continue
}
}
}
func (c *conn) Prepare(query string) (driver.Stmt, error) {
return c.prepareContext(context.Background(), query)
}
func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
stmt, err := c.prepareContext(ctx, query)
select {
default:
case <-ctx.Done():
stmt.Close()
return nil, ctx.Err()
}
return stmt, err
}
func (c *conn) prepareContext(ctx context.Context, query string) (driver.Stmt, error) {
// resultMode
isSelect := isSelectQuery(query)
resultMode := c.resultMode
if rmode, ok := getResultMode(ctx); ok {
resultMode = rmode
}
if !isSelect {
resultMode = ResultModeAPI
}
// ctas
var ctasTable string
var afterDownload func() error
if isCreatingCTASTable(isSelect, resultMode) {
// Create AS Select
ctasTable = fmt.Sprintf("tmp_ctas_%v", strings.Replace(uuid.NewV4().String(), "-", "", -1))
query = fmt.Sprintf("CREATE TABLE %s WITH (format='TEXTFILE') AS %s", ctasTable, query)
afterDownload = c.dropCTASTable(ctx, ctasTable)
}
numInput := len(strings.Split(query, "?")) - 1
// prepare
prepareKey := fmt.Sprintf("tmp_prepare_%v", strings.Replace(uuid.NewV4().String(), "-", "", -1))
_, err := c.athena.CreatePreparedStatement(ctx, &athena.CreatePreparedStatementInput{
StatementName: aws.String(prepareKey),
WorkGroup: aws.String(c.workgroup),
QueryStatement: aws.String(query),
})
if err != nil {
return nil, err
}
return &stmtAthena{
prepareKey: prepareKey,
numInput: numInput,
ctasTable: ctasTable,
afterDownload: afterDownload,
conn: c,
resultMode: resultMode,
}, nil
}
func (c *conn) Begin() (driver.Tx, error) {
panic("Athena doesn't support transactions")
}
func (c *conn) Close() error {
return nil
}
var _ driver.QueryerContext = (*conn)(nil)
var _ driver.ExecerContext = (*conn)(nil)
// HACK(tejasmanohar): database/sql calls Prepare() if your driver doesn't implement
// Queryer. Regardless, db.Query/Exec* calls Query/Exec-Context so I've filed a bug--
// https://github.com/golang/go/issues/22980.
func (c *conn) Query(query string, args []driver.Value) (driver.Rows, error) {
panic("Query() is noop")
}
func (c *conn) Exec(query string, args []driver.Value) (driver.Result, error) {
panic("Exec() is noop")
}
var _ driver.Queryer = (*conn)(nil)
var _ driver.Execer = (*conn)(nil)
func isCreatingCTASTable(isSelect bool, resultMode ResultMode) bool {
return isSelect && resultMode == ResultModeGzipDL
}
// isValidResultMode checks if the given result mode is valid
func isValidResultMode(mode ResultMode) bool {
switch mode {
case ResultModeAPI, ResultModeDL, ResultModeGzipDL:
return true
default:
return false
}
}