-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathBigQueryStatement.java
More file actions
1704 lines (1527 loc) · 59.3 KB
/
Copy pathBigQueryStatement.java
File metadata and controls
1704 lines (1527 loc) · 59.3 KB
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery.jdbc;
import com.google.api.core.InternalApi;
import com.google.api.gax.paging.Page;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.StatusCode;
import com.google.cloud.Tuple;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQuery.JobListOption;
import com.google.cloud.bigquery.BigQuery.QueryResultsOption;
import com.google.cloud.bigquery.BigQuery.TableDataListOption;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.EncryptionConfiguration;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobConfiguration;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.JobStatistics;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics.StatementType;
import com.google.cloud.bigquery.JobStatistics.ScriptStatistics;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableResult;
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
import com.google.cloud.bigquery.exception.BigQueryJdbcSqlFeatureNotSupportedException;
import com.google.cloud.bigquery.exception.BigQueryJdbcSqlSyntaxErrorException;
import com.google.cloud.bigquery.storage.v1.ArrowRecordBatch;
import com.google.cloud.bigquery.storage.v1.ArrowSchema;
import com.google.cloud.bigquery.storage.v1.BigQueryReadClient;
import com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest;
import com.google.cloud.bigquery.storage.v1.DataFormat;
import com.google.cloud.bigquery.storage.v1.ReadRowsRequest;
import com.google.cloud.bigquery.storage.v1.ReadRowsResponse;
import com.google.cloud.bigquery.storage.v1.ReadSession;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Uninterruptibles;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import java.lang.ref.ReferenceQueue;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
/**
* An implementation of {@link java.sql.Statement} for executing BigQuery SQL statement and
* returning the results it produces.
*
* @see BigQueryConnection#createStatement
* @see ResultSet
*/
public class BigQueryStatement extends BigQueryNoOpsStatement {
// TODO (obada): Update this after benchmarking
private static final int MAX_PROCESS_QUERY_THREADS_CNT = 50;
protected static ExecutorService queryTaskExecutor =
Executors.newFixedThreadPool(MAX_PROCESS_QUERY_THREADS_CNT);
private final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(this.toString());
private static final String DEFAULT_DATASET_NAME = "_google_jdbc";
private static final String DEFAULT_TABLE_NAME = "temp_table_";
private static final String JDBC_JOB_PREFIX = "google-jdbc-";
private static final int MAX_RETRY_COUNT = 5;
private static final long RETRY_DELAY_MS = 2000L;
protected ResultSet currentResultSet;
protected long currentUpdateCount = -1;
protected List<JobId> jobIds = new ArrayList<>();
protected JobIdWrapper parentJobId = null;
protected int currentJobIdIndex = -1;
protected List<String> batchQueries = new ArrayList<>();
protected BigQueryConnection connection;
protected String connectionId;
protected int maxFieldSize = 0;
protected int maxRows = 0;
protected boolean isClosed = false;
protected boolean closeOnCompletion = false;
protected Object cancelLock = new Object();
protected boolean isCanceled = false;
protected boolean poolable;
protected int queryTimeout = 0;
protected SQLWarning warning;
private int fetchDirection = ResultSet.FETCH_FORWARD;
private int fetchSize;
private String scriptQuery;
private Map<String, String> extraLabels = new HashMap<>();
private BigQueryReadClient bigQueryReadClient = null;
private final BigQuery bigQuery;
final BigQuerySettings querySettings;
private BlockingQueue<BigQueryFieldValueListWrapper> bigQueryFieldValueListWrapperBlockingQueue;
private BlockingQueue<BigQueryArrowBatchWrapper> arrowBatchWrapperBlockingQueue;
// Variables Required for the ReferenceQueue implementation
static ReferenceQueue<BigQueryArrowResultSet> referenceQueueArrowRs = new ReferenceQueue<>();
static ReferenceQueue<BigQueryJsonResultSet> referenceQueueJsonRs = new ReferenceQueue<>();
static List<BigQueryResultSetFinalizers.ArrowResultSetFinalizer> arrowResultSetFinalizers =
new ArrayList<>();
static List<BigQueryResultSetFinalizers.JsonResultSetFinalizer> jsonResultSetFinalizers =
new ArrayList<>();
private static final ThreadFactory JDBC_THREAD_FACTORY =
new BigQueryThreadFactory("BigQuery-Thread-");
static {
BigQueryDaemonPollingTask.startGcDaemonTask(
referenceQueueArrowRs,
referenceQueueJsonRs,
arrowResultSetFinalizers,
jsonResultSetFinalizers);
}
@VisibleForTesting
public BigQueryStatement(BigQueryConnection connection) {
this.connection = connection;
this.connectionId = connection.getConnectionId();
this.bigQuery = connection.getBigQuery();
this.querySettings = generateBigQuerySettings();
}
private void resetStatementFields() {
this.isCanceled = false;
this.scriptQuery = null;
this.parentJobId = null;
this.currentJobIdIndex = -1;
this.currentUpdateCount = -1;
}
private BigQuerySettings generateBigQuerySettings() {
LOG.finer("++enter++");
BigQuerySettings.Builder querySettings = BigQuerySettings.newBuilder();
DatasetId defaultDataset = this.connection.getDefaultDataset();
if (defaultDataset != null) {
querySettings.setDefaultDataset(this.connection.defaultDataset);
}
Long maxBytesBilled = this.connection.getMaxBytesBilled();
if (maxBytesBilled > 0) {
querySettings.setMaxBytesBilled(maxBytesBilled);
}
if (this.connection.getLabels() != null && !this.connection.getLabels().isEmpty()) {
querySettings.setLabels(this.connection.getLabels());
}
querySettings.setMaxResultPerPage(this.connection.getMaxResults());
querySettings.setUseReadAPI(this.connection.isEnableHighThroughputAPI());
querySettings.setHighThroughputMinTableSize(this.connection.getHighThroughputMinTableSize());
querySettings.setHighThroughputActivationRatio(
this.connection.getHighThroughputActivationRatio());
querySettings.setUnsupportedHTAPIFallback(this.connection.isUnsupportedHTAPIFallback());
querySettings.setUseQueryCache(this.connection.isUseQueryCache());
querySettings.setQueryDialect(this.connection.getQueryDialect());
querySettings.setKmsKeyName(this.connection.getKmsKeyName());
querySettings.setQueryProperties(this.connection.getQueryProperties());
querySettings.setAllowLargeResults(this.connection.isAllowLargeResults());
if (this.connection.getJobTimeoutInSeconds() > 0) {
querySettings.setJobTimeoutMs(this.connection.getJobTimeoutInSeconds() * 1000L);
}
if (this.connection.getDestinationTable() != null) {
querySettings.setDestinationTable(this.connection.getDestinationTable());
}
if (this.connection.getDestinationDataset() != null) {
querySettings.setDestinationDataset(this.connection.getDestinationDataset());
querySettings.setDestinationDatasetExpirationTime(
this.connection.getDestinationDatasetExpirationTime());
}
// only create session if enable session and session info is null
if (this.connection.enableSession) {
if (this.connection.sessionInfoConnectionProperty == null) {
querySettings.setEnableSession(this.connection.isSessionEnabled());
} else {
querySettings.setSessionInfoConnectionProperty(
this.connection.getSessionInfoConnectionProperty());
}
}
querySettings.setUseWriteAPI(this.connection.isEnableWriteAPI());
querySettings.setWriteAPIActivationRowCount(this.connection.getWriteAPIActivationRowCount());
querySettings.setWriteAPIAppendRowCount(this.connection.getWriteAPIAppendRowCount());
return querySettings.build();
}
/**
* This method executes a BigQuery SQL query, return a single {@code ResultSet} object.
*
* <p>Example of running a query:
*
* <pre>
* Connection connection = DriverManager.getConnection(CONNECTION_URL);
* Statement bigQueryStatement = bigQueryConnection.createStatement();
* ResultSet result = bigQueryStatement.executeQuery(QUERY);
* </pre>
*
* @param sql BigQuery SQL query
* @return {@code ResultSet} containing the output of the query
* @throws SQLException if a BigQuery access error occurs, this method is called on a closed
* {@code Statement}, the given SQL statement produces multiple or no result sets.
* @see java.sql.Statement#executeQuery(String)
*/
@Override
public ResultSet executeQuery(String sql) throws SQLException {
checkClosed();
return BigQueryJdbcOpenTelemetry.withTracing(
"BigQueryStatement.executeQuery", this.connection, sql, () -> executeQueryImpl(sql));
}
private ResultSet executeQueryImpl(String sql) throws SQLException {
logQueryExecutionStart(sql);
try {
QueryJobConfiguration jobConfiguration =
setDestinationDatasetAndTableInJobConfig(getJobConfig(sql).build());
runQuery(sql, jobConfiguration);
} catch (InterruptedException ex) {
throw new BigQueryJdbcException("Interrupted during executeQuery", ex);
}
if (!isSingularResultSet()) {
throw new BigQueryJdbcException(
"Query returned more than one or didn't return any ResultSet.");
}
return getCurrentResultSet();
}
@Override
public long executeLargeUpdate(String sql) throws SQLException {
checkClosed();
return BigQueryJdbcOpenTelemetry.withTracing(
"BigQueryStatement.executeLargeUpdate",
this.connection,
sql,
() -> executeLargeUpdateImpl(sql));
}
private long executeLargeUpdateImpl(String sql) throws SQLException {
logQueryExecutionStart(sql);
try {
QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql);
runQuery(sql, jobConfiguration.build());
} catch (InterruptedException ex) {
throw new BigQueryJdbcRuntimeException("Interrupted during executeLargeUpdate", ex);
}
if (this.currentUpdateCount == -1) {
throw new BigQueryJdbcException(
"Update query expected to return affected row count. Double check query type.");
}
return this.currentUpdateCount;
}
@Override
public int executeUpdate(String sql) throws SQLException {
return checkUpdateCount(executeLargeUpdate(sql));
}
int checkUpdateCount(long updateCount) {
LOG.finer("++enter++");
if (updateCount > Integer.MAX_VALUE) {
LOG.warning("Warning: Table update exceeded maximum limit!");
// Update count is -2 if update is successful but the update count exceeds Integer.MAX_VALUE
return -2;
}
return (int) updateCount;
}
@Override
public boolean execute(String sql) throws SQLException {
checkClosed();
return BigQueryJdbcOpenTelemetry.withTracing(
"BigQueryStatement.execute", this.connection, sql, () -> executeImpl(sql));
}
private boolean executeImpl(String sql) throws SQLException {
logQueryExecutionStart(sql);
try {
QueryJobConfiguration jobConfiguration = getJobConfig(sql).build();
// If Large Results are enabled, ensure query type is SELECT
if (isLargeResultsEnabled() && getQueryType(jobConfiguration, null) == SqlType.SELECT) {
jobConfiguration = setDestinationDatasetAndTableInJobConfig(jobConfiguration);
}
runQuery(sql, jobConfiguration);
} catch (InterruptedException ex) {
throw new BigQueryJdbcRuntimeException("Interrupted during execute", ex);
}
return getCurrentResultSet() != null;
}
StatementType getStatementType(QueryJobConfiguration queryJobConfiguration) throws SQLException {
LOG.finer("++enter++");
// BQ Read-only tokens are not recommended to use, they have a lot of known flaws.
// We're supporting them in a limited capacity, for pure SELECT statements.
if (this.connection.isReadOnlyTokenUsed()) {
LOG.warning(
"Read-only token detected, skipping dry run and assuming StatementType is SELECT.");
return StatementType.SELECT;
}
QueryJobConfiguration dryRunJobConfiguration =
queryJobConfiguration.toBuilder().setDryRun(true).build();
Job job;
try {
job = bigQuery.create(JobInfo.of(dryRunJobConfiguration));
} catch (BigQueryException ex) {
if (ex.getMessage().contains("Syntax error")) {
throw new BigQueryJdbcSqlSyntaxErrorException(
"BigQueryException during getStatementType", ex);
}
throw new BigQueryJdbcException("BigQueryException during getStatementType", ex);
}
QueryStatistics statistics = job.getStatistics();
return statistics.getStatementType();
}
SqlType getQueryType(QueryJobConfiguration jobConfiguration, StatementType statementType)
throws SQLException {
LOG.finer("++enter++");
if (statementType == null) {
statementType = getStatementType(jobConfiguration);
}
SqlType sqlType = BigQuerySqlTypeConverter.getSqlTypeFromStatementType(statementType);
LOG.fine(
"Query: %s, Statement Type: %s, SQL Type: %s",
jobConfiguration.getQuery(), statementType, sqlType);
return sqlType;
}
QueryStatistics getQueryStatistics(QueryJobConfiguration queryJobConfiguration)
throws BigQueryJdbcSqlSyntaxErrorException, BigQueryJdbcException {
LOG.finer("++enter++");
QueryJobConfiguration dryRunJobConfiguration =
queryJobConfiguration.toBuilder().setDryRun(true).build();
Job job;
try {
job = this.bigQuery.create(JobInfo.of(dryRunJobConfiguration));
return job.getStatistics();
} catch (BigQueryException ex) {
if (ex.getMessage().contains("Syntax error")) {
throw new BigQueryJdbcSqlSyntaxErrorException(
"BigQueryException during getQueryStatistics", ex);
}
throw new BigQueryJdbcException("BigQueryException during getQueryStatistics", ex);
}
}
/**
* Releases this Statement's BigQuery and JDBC resources immediately instead of waiting for this
* to happen when it is automatically closed. These resources include the {@code ResultSet}
* object, batch queries, job IDs, and BigQuery connection <br>
*
* <p>Calling the method close on a Statement object that is already closed has no effect.
*
* @throws SQLException if a BigQuery access error occurs
*/
@Override
public void close() throws SQLException {
if (isClosed()) {
return;
}
LOG.fine("Closing Statement %s.", this);
boolean cancelSucceeded = false;
try {
cancel(); // This attempts to cancel jobs and calls closeStatementResources()
cancelSucceeded = true;
} catch (SQLException e) {
LOG.warning("Failed to cancel statement during close().", e);
} finally {
if (!cancelSucceeded) {
closeStatementResources();
}
this.connection = null;
this.isClosed = true;
}
}
@Override
public int getMaxFieldSize() {
return this.maxFieldSize;
}
@Override
public void setMaxFieldSize(int max) {
this.maxFieldSize = max;
}
@Override
public int getMaxRows() {
return this.maxRows;
}
@Override
public void setMaxRows(int max) {
this.maxRows = max;
}
@Override
public void setEscapeProcessing(boolean enable) {
// TODO: verify how to implement this method
}
@Override
public int getQueryTimeout() {
return this.queryTimeout;
}
@Override
public void setQueryTimeout(int seconds) {
if (seconds < 0) {
IllegalArgumentException ex = new IllegalArgumentException("Query Timeout should be >= 0.");
LOG.severe(ex.getMessage(), ex);
throw ex;
}
this.queryTimeout = seconds;
}
/**
* Cancels this {@code Statement} object, the running threads, and BigQuery jobs.
*
* @throws SQLException if a BigQuery access error occurs or this method is called on a closed
* {@code Statement}
*/
@Override
public void cancel() throws SQLException {
LOG.finer("Statement %s cancelled", this);
synchronized (cancelLock) {
this.isCanceled = true;
for (JobId jobId : this.jobIds) {
try {
this.bigQuery.cancel(jobId);
LOG.info("Job " + jobId + "cancelled.");
} catch (BigQueryException e) {
if (e.getMessage() != null
&& (e.getMessage().contains("Job is already in state DONE")
|| e.getMessage().contains("Error: 3848323"))) {
LOG.warning("Attempted to cancel a job that was already done: " + jobId);
} else {
throw new BigQueryJdbcException(e);
}
}
}
jobIds.clear();
}
// If a ResultSet exists, then it will be closed as well, closing the
// ownedThreads
closeStatementResources();
}
@Override
public SQLWarning getWarnings() {
return this.warning;
}
@Override
public void clearWarnings() {
this.warning = null;
}
@Override
public ResultSet getResultSet() {
return this.currentResultSet;
}
@VisibleForTesting
void setUpdateCount(long count) {
this.currentUpdateCount = count;
}
@Override
public int getUpdateCount() {
return (int) this.currentUpdateCount;
}
@Override
public long getLargeUpdateCount() {
return this.currentUpdateCount;
}
@Override
public boolean getMoreResults() throws SQLException {
return getMoreResults(CLOSE_CURRENT_RESULT);
}
private void closeStatementResources() throws SQLException {
LOG.finer("++enter++");
if (this.currentResultSet != null) {
// If Statement has 'CloseOnCompletion' set, resultset might
// call into the same function; In order to avoid stack overflow
// we will cleanup resultset before calling into 'close'.
ResultSet tmp = this.currentResultSet;
this.currentResultSet = null;
tmp.close();
}
this.batchQueries.clear();
this.currentUpdateCount = -1;
this.currentJobIdIndex = -1;
if (this.connection != null) {
if (this.connection.isTransactionStarted()) {
this.connection.rollback();
}
this.connection.removeStatement(this);
}
}
private boolean isSingularResultSet() {
return this.currentResultSet != null
&& (this.parentJobId == null || this.parentJobId.getJobs().size() == 1);
}
private String generateJobId() {
return JDBC_JOB_PREFIX + UUID.randomUUID().toString();
}
private class ExecuteResult {
public final TableResult tableResult;
public final Job job;
ExecuteResult(TableResult tableResult, Job job) {
this.tableResult = tableResult;
this.job = job;
}
}
@InternalApi
ExecuteResult executeJob(QueryJobConfiguration jobConfiguration)
throws InterruptedException, BigQueryException, BigQueryJdbcException {
LOG.finer("++enter++");
Job job = null;
// Location is not properly passed from the connection,
// so we need to explicitly set it;
// Do not set custom JobId here or it will disable jobless queries.
JobId jobId = JobId.newBuilder().setLocation(connection.getLocation()).build();
Object result = bigQuery.queryWithTimeout(jobConfiguration, jobId, null);
if (result instanceof TableResult) {
TableResult tableResult = (TableResult) result;
if (tableResult.getJobId() != null) {
return new ExecuteResult(tableResult, bigQuery.getJob(tableResult.getJobId()));
}
return new ExecuteResult((TableResult) result, null);
}
if (result instanceof Job) {
job = (Job) result;
} else {
throw new BigQueryJdbcException("Unexpected result type from queryWithTimeout");
}
synchronized (cancelLock) {
if (isCanceled) {
job.cancel();
throw new BigQueryJdbcException("Query was cancelled.");
}
jobId = job.getJobId();
jobIds.add(jobId);
}
LOG.info("Query submitted with Job ID: " + job.getJobId().getJob());
TableResult tableResult =
job.getQueryResults(QueryResultsOption.pageSize(querySettings.getMaxResultPerPage()));
synchronized (cancelLock) {
jobIds.remove(jobId);
}
return new ExecuteResult(tableResult, job);
}
/**
* Execute the SQL script and sets the reference of the underlying job, passing null querySettings
* will result in the FastQueryPath
*/
@InternalApi
void runQuery(String query, QueryJobConfiguration jobConfiguration)
throws SQLException, InterruptedException {
LOG.finer("++enter++");
LOG.fine("Run Query started");
if (queryTimeout > 0) {
jobConfiguration =
jobConfiguration.toBuilder().setJobTimeoutMs(Long.valueOf(queryTimeout) * 1000).build();
}
try {
resetStatementFields();
ExecuteResult executeResult = executeJob(jobConfiguration);
StatementType statementType =
executeResult.job == null
? getStatementType(jobConfiguration)
: ((QueryStatistics) executeResult.job.getStatistics()).getStatementType();
SqlType queryType = getQueryType(jobConfiguration, statementType);
handleQueryResult(query, executeResult.tableResult, queryType);
} catch (InterruptedException ex) {
throw new BigQueryJdbcRuntimeException("Interrupted during runQuery", ex);
} catch (BigQueryException ex) {
if (ex.getMessage().contains("Syntax error")) {
throw new BigQueryJdbcSqlSyntaxErrorException("BigQueryException during runQuery", ex);
}
throw new BigQueryJdbcException("BigQueryException during runQuery", ex);
}
}
private boolean isLargeResultsEnabled() {
String destinationTable = this.querySettings.getDestinationTable();
String destinationDataset = this.querySettings.getDestinationDataset();
return destinationDataset != null || destinationTable != null;
}
private QueryJobConfiguration setDestinationDatasetAndTableInJobConfig(
QueryJobConfiguration jobConfiguration) {
String destinationTable = this.querySettings.getDestinationTable();
String destinationDataset = this.querySettings.getDestinationDataset();
if (destinationDataset != null || destinationTable != null) {
if (destinationDataset != null) {
checkIfDatasetExistElseCreate(destinationDataset);
}
if (jobConfiguration.useLegacySql() && destinationDataset == null) {
checkIfDatasetExistElseCreate(DEFAULT_DATASET_NAME);
destinationDataset = DEFAULT_DATASET_NAME;
}
if (destinationTable == null) {
destinationTable = getDefaultDestinationTable();
}
return jobConfiguration.toBuilder()
.setAllowLargeResults(this.querySettings.getAllowLargeResults())
.setDestinationTable(TableId.of(destinationDataset, destinationTable))
.setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED)
.setWriteDisposition(JobInfo.WriteDisposition.WRITE_TRUNCATE)
.build();
}
return jobConfiguration;
}
Job getNextJob() {
if (this.parentJobId == null) {
return null;
}
while (this.currentJobIdIndex + 1 < this.parentJobId.getJobs().size()) {
this.currentJobIdIndex += 1;
Job currentJob = this.parentJobId.getJobs().get(this.currentJobIdIndex);
QueryStatistics queryStatistics = currentJob.getStatistics();
ScriptStatistics scriptStatistics = queryStatistics.getScriptStatistics();
// EXPRESSION jobs are not relevant for customer query and can be
// created by BQ depending on various conditions. We will just ignore
// them when presenting results.
if (!"expression".equalsIgnoreCase(scriptStatistics.getEvaluationKind())) {
return currentJob;
}
}
return null;
}
void handleQueryResult(String query, TableResult results, SqlType queryType)
throws SQLException, InterruptedException {
LOG.finer("++enter++");
switch (queryType) {
case SELECT:
processQueryResponse(query, results);
break;
case DML:
case DML_EXTRA:
try {
Job completedJob = this.bigQuery.getJob(results.getJobId()).waitFor();
JobStatistics.QueryStatistics statistics = completedJob.getStatistics();
updateAffectedRowCount(statistics.getNumDmlAffectedRows());
} catch (InterruptedException ex) {
throw new BigQueryJdbcRuntimeException(ex);
} catch (NullPointerException ex) {
throw new BigQueryJdbcException(ex);
}
break;
case TCL:
case DDL:
updateAffectedRowCount(results.getTotalRows());
break;
case SCRIPT:
try {
Page<Job> childJobs =
this.bigQuery.listJobs(JobListOption.parentJobId(results.getJobId().getJob()));
ArrayList<Job> childJobList = new ArrayList<>();
Iterator<Job> iterableJobs = childJobs.iterateAll().iterator();
iterableJobs.forEachRemaining(childJobList::add);
Collections.reverse(childJobList);
this.scriptQuery = query;
this.parentJobId = new JobIdWrapper(results.getJobId(), results, childJobList);
this.currentJobIdIndex = -1;
Job currentJob = getNextJob();
if (currentJob == null) {
return;
}
StatementType statementType =
((QueryStatistics) (currentJob.getStatistics())).getStatementType();
SqlType sqlType = getQueryType(currentJob.getConfiguration(), statementType);
handleQueryResult(query, currentJob.getQueryResults(), sqlType);
} catch (NullPointerException ex) {
throw new BigQueryJdbcException(ex);
}
break;
case OTHER:
throw new BigQueryJdbcException(String.format("Unexpected value: " + queryType));
}
}
private void updateAffectedRowCount(Long count) throws SQLException {
// TODO(neenu): check if this need to be closed vs removed)
if (this.currentResultSet != null) {
try {
this.currentResultSet.close();
this.currentResultSet = null;
} catch (SQLException ex) {
throw new BigQueryJdbcException(ex);
}
}
this.currentUpdateCount = count;
}
@InternalApi
BigQueryReadClient getBigQueryReadClient() {
if (this.bigQueryReadClient == null) {
this.bigQueryReadClient = this.connection.getBigQueryReadClient();
}
return this.bigQueryReadClient;
}
@InternalApi
ReadSession getReadSession(CreateReadSessionRequest readSessionRequest) {
LOG.finer("++enter++");
return getBigQueryReadClient().createReadSession(readSessionRequest);
}
@InternalApi
ArrowSchema getArrowSchema(ReadSession readSession) {
return readSession.getArrowSchema();
}
/** Uses Bigquery Storage Read API and returns the stream as ResultSet */
@InternalApi
ResultSet processArrowResultSet(TableResult results) throws SQLException {
LOG.finer("++enter++");
// set the resultset
long totalRows = (getMaxRows() > 0) ? getMaxRows() : results.getTotalRows();
JobId currentJobId = results.getJobId();
TableId destinationTable = getDestinationTable(currentJobId);
Schema schema = results.getSchema();
try {
String parent = String.format("projects/%s", destinationTable.getProject());
String srcTable =
String.format(
"projects/%s/datasets/%s/tables/%s",
destinationTable.getProject(),
destinationTable.getDataset(),
destinationTable.getTable());
// Read all the columns if the source table (temp table) and stream the data back in Arrow
// format
ReadSession.Builder sessionBuilder =
ReadSession.newBuilder().setTable(srcTable).setDataFormat(DataFormat.ARROW);
CreateReadSessionRequest.Builder builder =
CreateReadSessionRequest.newBuilder()
.setParent(parent)
.setReadSession(sessionBuilder)
.setMaxStreamCount(1);
ReadSession readSession = getReadSession(builder.build());
this.arrowBatchWrapperBlockingQueue = new LinkedBlockingDeque<>(getBufferSize());
// deserialize and populate the buffer async, so that the client isn't blocked
Thread populateBufferWorker =
populateArrowBufferedQueue(
readSession, this.arrowBatchWrapperBlockingQueue, this.bigQueryReadClient);
BigQueryArrowResultSet arrowResultSet =
BigQueryArrowResultSet.of(
schema,
getArrowSchema(readSession),
totalRows,
this,
this.arrowBatchWrapperBlockingQueue,
populateBufferWorker,
this.bigQuery);
arrowResultSetFinalizers.add(
new BigQueryResultSetFinalizers.ArrowResultSetFinalizer(
arrowResultSet, referenceQueueArrowRs, populateBufferWorker));
arrowResultSet.setJobId(currentJobId);
return arrowResultSet;
} catch (Exception ex) {
throw new BigQueryJdbcException(ex.getMessage(), ex);
}
}
/** Asynchronously reads results and populates an arrow record queue */
@InternalApi
Thread populateArrowBufferedQueue(
ReadSession readSession,
BlockingQueue<BigQueryArrowBatchWrapper> arrowBatchWrapperBlockingQueue,
BigQueryReadClient bqReadClient) {
LOG.finer("++enter++");
Runnable arrowStreamProcessor =
Context.current()
.wrap(
() ->
processArrowStream(readSession, arrowBatchWrapperBlockingQueue, bqReadClient));
Thread populateBufferWorker = JDBC_THREAD_FACTORY.newThread(arrowStreamProcessor);
populateBufferWorker.start();
return populateBufferWorker;
}
private void processArrowStream(
ReadSession readSession,
BlockingQueue<BigQueryArrowBatchWrapper> arrowBatchWrapperBlockingQueue,
BigQueryReadClient bqReadClient) {
long rowsRead = 0;
int retryCount = 0;
try {
// Use the first stream to perform reading.
String streamName = readSession.getStreams(0).getName();
while (true) {
try {
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder().setReadStream(streamName).setOffset(rowsRead).build();
// Process each block of rows as they arrive and decode using our simple row
// reader.
com.google.api.gax.rpc.ServerStream<ReadRowsResponse> stream =
bqReadClient.readRowsCallable().call(readRowsRequest);
for (ReadRowsResponse response : stream) {
if (Thread.currentThread().isInterrupted() || queryTaskExecutor.isShutdown()) {
break;
}
ArrowRecordBatch currentBatch = response.getArrowRecordBatch();
Uninterruptibles.putUninterruptibly(
arrowBatchWrapperBlockingQueue, BigQueryArrowBatchWrapper.of(currentBatch));
rowsRead += response.getRowCount();
}
break;
} catch (ApiException e) {
if (e.getStatusCode().getCode() == StatusCode.Code.NOT_FOUND) {
LOG.warning("Read session expired or not found: %s", e.getMessage());
enqueueError(arrowBatchWrapperBlockingQueue, e);
break;
}
if (retryCount >= MAX_RETRY_COUNT) {
LOG.log(
Level.SEVERE,
"\n"
+ Thread.currentThread().getName()
+ " Interrupted @ arrowStreamProcessor, max retries exceeded",
e);
enqueueError(arrowBatchWrapperBlockingQueue, e);
break;
}
retryCount++;
LOG.warning(
"Connection interrupted during arrow stream read, retrying. attempt: %d", retryCount);
Thread.sleep(RETRY_DELAY_MS);
}
}
} catch (InterruptedException e) {
LOG.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ arrowStreamProcessor",
e);
enqueueError(arrowBatchWrapperBlockingQueue, e);
Thread.currentThread().interrupt();
} catch (Exception e) {
if (e.getCause() instanceof InterruptedException || Thread.currentThread().isInterrupted()) {
LOG.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ arrowStreamProcessor",
e);
enqueueError(arrowBatchWrapperBlockingQueue, e);
Thread.currentThread().interrupt();
} else {
LOG.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Error @ arrowStreamProcessor",
e);
enqueueError(arrowBatchWrapperBlockingQueue, e);
}
} finally { // logic needed for graceful shutdown
enqueueEndOfStream(arrowBatchWrapperBlockingQueue);
}
}
/** Executes SQL query using either fast query path or read API */
void processQueryResponse(String query, TableResult results) throws SQLException {
JobId jobId = results.getJobId();
String queryId = results.getQueryId();
LOG.info(
"Processing query response. JobId: %s, QueryId: %s, Total rows: %s",
jobId, queryId, results.getTotalRows());
LOG.fine("Processing query response. Query: %s", query);
ResultSet resultSet = null;
if (jobId != null && useReadAPI(results)) {
try {
LOG.info("Using ReadAPI to read the data.");
resultSet = processArrowResultSet(results);
} catch (SQLException e) {
if (!isPermissionDeniedException(e)) {
throw e;
}
LOG.log(Level.WARNING, "Permission denied for Read API, falling back to JSON API", e);
}
}
if (resultSet == null) {
LOG.info("Using Standard API to read the data.");
resultSet = processJsonResultSet(results);
}
this.currentResultSet = resultSet;
this.currentUpdateCount = -1;
}
private boolean isPermissionDeniedException(Throwable t) {
while (t != null) {
if (t instanceof StatusRuntimeException) {
return ((StatusRuntimeException) t).getStatus().getCode() == Status.Code.PERMISSION_DENIED;
}
if (t instanceof ApiException) {
return ((ApiException) t).getStatusCode().getCode() == StatusCode.Code.PERMISSION_DENIED;
}
t = t.getCause();
}
return false;
}
// The read Ratio should be met
// AND the User must not have disabled the Read API
@VisibleForTesting
boolean useReadAPI(TableResult results) throws BigQueryJdbcSqlFeatureNotSupportedException {
LOG.finer("++enter++");
if (!meetsReadRatio(results)) {
return false;
}
LOG.fine("Read API threshold is met.");
return querySettings.getUseReadAPI();
}
private boolean meetsReadRatio(TableResult results) {
LOG.finer("++enter++");
long totalRows = results.getTotalRows();
// SAFEGUARD: If all data has already been retrieved in the first page,
// NEVER switch to the Read API as it would discard in-memory data and cause a double-fetch.
if (totalRows == 0
|| totalRows < querySettings.getHighThroughputMinTableSize()
|| !results.hasNextPage()) {
return false;
}