/
AthenaStatement.java
416 lines (356 loc) · 13.3 KB
/
AthenaStatement.java
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package io.burt.athena;
import io.burt.athena.configuration.ConnectionConfiguration;
import software.amazon.awssdk.services.athena.AthenaAsyncClient;
import software.amazon.awssdk.services.athena.model.QueryExecution;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLTimeoutException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
public class AthenaStatement implements Statement {
private final AthenaAsyncClient athenaClient;
private Clock clock;
private ConnectionConfiguration configuration;
private String queryExecutionId;
private ResultSet currentResultSet;
private Function<String, Optional<String>> clientRequestTokenProvider;
private boolean open;
AthenaStatement(ConnectionConfiguration configuration, Clock clock) {
this.configuration = configuration;
this.athenaClient = configuration.athenaClient();
this.clock = clock;
this.queryExecutionId = null;
this.currentResultSet = null;
this.clientRequestTokenProvider = sql -> Optional.empty();
this.open = true;
}
/**
* Sets a client request token provider for this statement.
*
* If query executions have the same client request token Athena can
* immediately return the results instead of executing the request again and
* again. This is a great way to save costs and improve performance.
*
* The client request token provider receives the SQL to be executed and is
* expected to return an <code>Option</code> containing a token that
* conforms to the requirements of the <code>ClientRequestToken</code>
* property of the <code>StartQueryExecutionRequest</code>, or
* <code>Option.empty()</code> when the request should not have a client
* request token.
*
* @param provider the function that produces the client request token given
* the SQL to be executed
*/
public void setClientRequestTokenProvider(Function<String, Optional<String>> provider) {
if (provider == null) {
clientRequestTokenProvider = sql -> Optional.empty();
} else {
clientRequestTokenProvider = provider;
}
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
execute(sql);
return getResultSet();
}
@Override
public boolean execute(String sql) throws SQLException {
if (currentResultSet != null) {
currentResultSet.close();
currentResultSet = null;
}
try {
Instant deadline = clock.instant().plus(configuration.queryTimeout());
queryExecutionId = startQueryExecution(sql, deadline);
currentResultSet = configuration.pollingStrategy().pollUntilCompleted(this::poll, deadline);
return currentResultSet != null;
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return false;
} catch (TimeoutException te) {
SQLTimeoutException ste = new SQLTimeoutException(te);
if (queryExecutionId != null) {
try {
athenaClient.stopQueryExecution(b -> {
b.queryExecutionId(queryExecutionId);
});
} catch (Exception e) {
ste.addSuppressed(e);
}
}
throw ste;
} catch (ExecutionException ee) {
SQLException eee = new SQLException(ee.getCause());
eee.addSuppressed(ee);
throw eee;
}
}
private String startQueryExecution(String sql, Instant deadline) throws InterruptedException, ExecutionException, TimeoutException {
return athenaClient
.startQueryExecution(b -> {
b.queryString(sql);
b.workGroup(configuration.workGroupName());
b.queryExecutionContext(bb -> bb.database(configuration.databaseName()));
b.resultConfiguration(bb -> bb.outputLocation(configuration.outputLocation()));
clientRequestTokenProvider.apply(sql).ifPresent(b::clientRequestToken);
})
.get(networkTimeoutMillis(deadline), TimeUnit.MILLISECONDS)
.queryExecutionId();
}
private Optional<ResultSet> poll(Instant deadline) throws SQLException, InterruptedException, ExecutionException, TimeoutException {
QueryExecution queryExecution = athenaClient
.getQueryExecution(b -> b.queryExecutionId(queryExecutionId))
.get(networkTimeoutMillis(deadline), TimeUnit.MILLISECONDS)
.queryExecution();
switch (queryExecution.status().state()) {
case SUCCEEDED:
return Optional.of(createResultSet(queryExecution));
case FAILED:
case CANCELLED:
throw new SQLException(queryExecution.status().stateChangeReason());
default:
return Optional.empty();
}
}
private long networkTimeoutMillis(Instant deadline) {
return Math.max(0, Math.min(configuration.networkTimeout().toMillis(), Duration.between(clock.instant(), deadline).toMillis()));
}
private ResultSet createResultSet(QueryExecution queryExecution) {
return new AthenaResultSet(
configuration.createResult(queryExecution),
this
);
}
private void checkClosed() throws SQLException {
if (!open) {
throw new SQLException("Statement is closed");
}
}
@Override
public void close() throws SQLException {
if (currentResultSet != null) {
currentResultSet.close();
}
open = false;
}
@Override
public boolean isClosed() {
return !open;
}
@Override
public void cancel() throws SQLException {
checkClosed();
if (queryExecutionId == null) {
throw new SQLException("Cannot cancel a statement before it has started");
} else if (getResultSet() != null) {
throw new SQLException("Cannot cancel an completed statement");
} else {
athenaClient.stopQueryExecution(b -> b.queryExecutionId(queryExecutionId));
}
}
@Override
public ResultSet getResultSet() {
return currentResultSet;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return iface.cast(this);
} else {
throw new SQLException(String.format("%s is not a wrapper for %s", this.getClass().getName(), iface.getName()));
}
}
@Override
public boolean isWrapperFor(Class<?> iface) {
return iface.isAssignableFrom(getClass());
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
if (autoGeneratedKeys == NO_GENERATED_KEYS) {
return execute(sql);
} else {
throw new SQLFeatureNotSupportedException("Athena does not support auto generated keys");
}
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
throw new SQLFeatureNotSupportedException("Athena does not support auto generated keys");
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
throw new SQLFeatureNotSupportedException("Athena does not support auto generated keys");
}
@Override
public int executeUpdate(String sql) throws SQLException {
execute(sql);
return 0;
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
if (autoGeneratedKeys == NO_GENERATED_KEYS) {
return executeUpdate(sql);
} else {
throw new SQLFeatureNotSupportedException("Athena does not support updates");
}
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
throw new SQLFeatureNotSupportedException("Athena does not support updates");
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
throw new SQLFeatureNotSupportedException("Athena does not support updates");
}
@Override
public long executeLargeUpdate(String sql) throws SQLException {
execute(sql);
return 0;
}
@Override
public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
if (autoGeneratedKeys == NO_GENERATED_KEYS) {
return executeLargeUpdate(sql);
} else {
throw new SQLFeatureNotSupportedException("Athena does not support updates");
}
}
@Override
public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
throw new SQLFeatureNotSupportedException("Athena does not support updates");
}
@Override
public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException {
throw new SQLFeatureNotSupportedException("Athena does not support updates");
}
@Override
public int getMaxFieldSize() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void setMaxFieldSize(int max) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int getMaxRows() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void setMaxRows(int max) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void setEscapeProcessing(boolean enable) {
throw new UnsupportedOperationException("Not implemented");
}
public void setQueryTimeout(Duration timeout) {
configuration = configuration.withQueryTimeout(timeout);
}
@Override
public int getQueryTimeout() {
return (int) configuration.queryTimeout().toMillis() / 1000;
}
@Override
public void setQueryTimeout(int seconds) {
setQueryTimeout(Duration.ofSeconds(seconds));
}
@Override
public SQLWarning getWarnings() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void clearWarnings() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void setCursorName(String name) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int getUpdateCount() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public boolean getMoreResults() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void setFetchDirection(int direction) throws SQLException {
if (direction != ResultSet.FETCH_FORWARD) {
throw new SQLFeatureNotSupportedException("Result set movements other than forward are not supported");
}
}
@Override
public int getFetchDirection() {
return ResultSet.FETCH_FORWARD;
}
@Override
public void setFetchSize(int rows) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int getFetchSize() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int getResultSetConcurrency() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int getResultSetType() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void addBatch(String sql) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void clearBatch() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int[] executeBatch() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public Connection getConnection() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public boolean getMoreResults(int current) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public ResultSet getGeneratedKeys() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public int getResultSetHoldability() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void setPoolable(boolean poolable) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public boolean isPoolable() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void closeOnCompletion() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public boolean isCloseOnCompletion() {
throw new UnsupportedOperationException("Not implemented");
}
}