-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathConnectionImpl.java
1504 lines (1405 loc) · 63.6 KB
/
ConnectionImpl.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
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 2021 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;
import static com.google.cloud.RetryHelper.runWithRetries;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
import com.google.api.services.bigquery.model.JobConfigurationQuery;
import com.google.api.services.bigquery.model.QueryParameter;
import com.google.api.services.bigquery.model.QueryRequest;
import com.google.api.services.bigquery.model.TableDataList;
import com.google.api.services.bigquery.model.TableRow;
import com.google.cloud.RetryHelper;
import com.google.cloud.Tuple;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
import com.google.cloud.bigquery.JobStatistics.SessionInfo;
import com.google.cloud.bigquery.spi.v2.BigQueryRpc;
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.BigQueryReadSettings;
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.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.IOException;
import java.math.BigInteger;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
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.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.VectorLoader;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.ReadChannel;
import org.apache.arrow.vector.ipc.message.MessageSerializer;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel;
/** Implementation for {@link Connection}, the generic BigQuery connection API (not JDBC). */
class ConnectionImpl implements Connection {
private final ConnectionSettings connectionSettings;
private final BigQueryOptions bigQueryOptions;
private final BigQueryRpc bigQueryRpc;
private final BigQueryRetryConfig retryConfig;
private final int bufferSize; // buffer size in Producer Thread
private final int MAX_PROCESS_QUERY_THREADS_CNT = 5;
private final ExecutorService queryTaskExecutor =
Executors.newFixedThreadPool(MAX_PROCESS_QUERY_THREADS_CNT);
private final Logger logger = Logger.getLogger(this.getClass().getName());
private BigQueryReadClient bqReadClient;
private static final long EXECUTOR_TIMEOUT_SEC = 10;
private BlockingQueue<AbstractList<FieldValue>>
bufferFvl; // initialized lazily iff we end up using the tabledata.list end point
private BlockingQueue<BigQueryResultImpl.Row>
bufferRow; // initialized lazily iff we end up using Read API
ConnectionImpl(
ConnectionSettings connectionSettings,
BigQueryOptions bigQueryOptions,
BigQueryRpc bigQueryRpc,
BigQueryRetryConfig retryConfig) {
this.connectionSettings = connectionSettings;
this.bigQueryOptions = bigQueryOptions;
this.bigQueryRpc = bigQueryRpc;
this.retryConfig = retryConfig;
// Sets a reasonable buffer size (a blocking queue) if user input is suboptimal
this.bufferSize =
(connectionSettings == null
|| connectionSettings.getNumBufferedRows() == null
|| connectionSettings.getNumBufferedRows() < 10000
? 20000
: Math.min(connectionSettings.getNumBufferedRows() * 2, 100000));
}
/**
* This method returns the number of records to be stored in the buffer and it ensures that it is
* between a reasonable range
*
* @return The max number of records to be stored in the buffer
*/
private int getBufferSize() {
return (connectionSettings == null
|| connectionSettings.getNumBufferedRows() == null
|| connectionSettings.getNumBufferedRows() < 10000
? 20000
: Math.min(connectionSettings.getNumBufferedRows() * 2, 100000));
}
/**
* Cancel method shutdowns the pageFetcher and producerWorker threads gracefully using interrupt.
* The pageFetcher threat will not request for any subsequent threads after interrupting and
* shutdown as soon as any ongoing RPC call returns. The producerWorker will not populate the
* buffer with any further records and clear the buffer, put a EoF marker and shutdown.
*
* @return Boolean value true if the threads were interrupted
* @throws BigQuerySQLException
*/
@BetaApi
@Override
public synchronized boolean close() throws BigQuerySQLException {
flagEndOfStream(); // an End of Stream flag in the buffer so that the `ResultSet.next()` stops
// advancing the cursor
queryTaskExecutor.shutdownNow();
try {
if (queryTaskExecutor.awaitTermination(EXECUTOR_TIMEOUT_SEC, TimeUnit.SECONDS)) {
return true;
} // else queryTaskExecutor.isShutdown() will be returned outside this try block
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Exception while awaitTermination",
e); // Logging InterruptedException instead of throwing the exception back, close method
// will return queryTaskExecutor.isShutdown()
}
return queryTaskExecutor.isShutdown(); // check if the executor has been shutdown
}
/**
* This method runs a dry run query
*
* @param sql SQL SELECT statement
* @return BigQueryDryRunResult containing List<Parameter> and Schema
* @throws BigQuerySQLException
*/
@BetaApi
@Override
public BigQueryDryRunResult dryRun(String sql) throws BigQuerySQLException {
com.google.api.services.bigquery.model.Job dryRunJob = createDryRunJob(sql);
Schema schema = Schema.fromPb(dryRunJob.getStatistics().getQuery().getSchema());
List<QueryParameter> queryParametersPb =
dryRunJob.getStatistics().getQuery().getUndeclaredQueryParameters();
List<Parameter> queryParameters =
queryParametersPb == null
? Collections.emptyList()
: Lists.transform(queryParametersPb, QUERY_PARAMETER_FROM_PB_FUNCTION);
QueryStatistics queryStatistics = JobStatistics.fromPb(dryRunJob);
SessionInfo sessionInfo =
queryStatistics.getSessionInfo() == null ? null : queryStatistics.getSessionInfo();
BigQueryResultStats bigQueryResultStats =
new BigQueryResultStatsImpl(queryStatistics, sessionInfo);
return new BigQueryDryRunResultImpl(schema, queryParameters, bigQueryResultStats);
}
/**
* This method executes a SQL SELECT query
*
* @param sql SQL SELECT statement
* @return BigQueryResult containing the output of the query
* @throws BigQuerySQLException
*/
@BetaApi
@Override
public BigQueryResult executeSelect(String sql) throws BigQuerySQLException {
return getExecuteSelectResponse(sql, null, null);
}
/**
* This method executes a SQL SELECT query
*
* @param sql SQL SELECT query
* @param parameters named or positional parameters. The set of query parameters must either be
* all positional or all named parameters.
* @param labels the labels associated with this query. You can use these to organize and group
* your query jobs. Label keys and values can be no longer than 63 characters, can only
* contain lowercase letters, numeric characters, underscores and dashes. International
* characters are allowed. Label values are optional and Label is a Varargs. You should pass
* all the Labels in a single Map .Label keys must start with a letter and each label in the
* list must have a different key.
* @return BigQueryResult containing the output of the query
* @throws BigQuerySQLException
*/
@BetaApi
@Override
public BigQueryResult executeSelect(
String sql, List<Parameter> parameters, Map<String, String>... labels)
throws BigQuerySQLException {
return getExecuteSelectResponse(sql, parameters, labels);
}
private BigQueryResult getExecuteSelectResponse(
String sql, List<Parameter> parameters, Map<String, String>... labels)
throws BigQuerySQLException {
Map<String, String> labelMap = null;
if (labels != null
&& labels.length == 1) { // We expect label as a key value pair in a single Map
labelMap = labels[0];
}
try {
// use jobs.query if possible
if (isFastQuerySupported()) {
logger.log(Level.INFO, "\n Using Fast Query Path");
final String projectId = bigQueryOptions.getProjectId();
final QueryRequest queryRequest =
createQueryRequest(connectionSettings, sql, parameters, labelMap);
return queryRpc(projectId, queryRequest, sql, parameters != null);
}
// use jobs.insert otherwise
logger.log(Level.INFO, "\n Not Using Fast Query Path, using jobs.insert");
com.google.api.services.bigquery.model.Job queryJob =
createQueryJob(sql, connectionSettings, parameters, labelMap);
JobId jobId = JobId.fromPb(queryJob.getJobReference());
GetQueryResultsResponse firstPage = getQueryResultsFirstPage(jobId);
return getResultSet(firstPage, jobId, sql, parameters != null);
} catch (BigQueryException e) {
throw new BigQuerySQLException(e.getMessage(), e, e.getErrors());
}
}
/**
* Execute a SQL statement that returns a single ResultSet and returns a ListenableFuture to
* process the response asynchronously.
*
* <p>Example of running a query.
*
* <pre>
* {
* @code
* ConnectionSettings connectionSettings =
* ConnectionSettings.newBuilder()
* .setUseReadAPI(true)
* .build();
* Connection connection = bigquery.createConnection(connectionSettings);
* String selectQuery = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;";
* ListenableFuture<ExecuteSelectResponse> executeSelectFuture = connection.executeSelectAsync(selectQuery);
* ExecuteSelectResponse executeSelectRes = executeSelectFuture.get();
*
* if(!executeSelectRes.getIsSuccessful()){
* throw executeSelectRes.getBigQuerySQLException();
* }
*
* BigQueryResult bigQueryResult = executeSelectRes.getBigQueryResult();
* ResultSet rs = bigQueryResult.getResultSet();
* while (rs.next()) {
* System.out.println(rs.getString(1));
* }
*
* </pre>
*
* @param sql a static SQL SELECT statement
* @return a ListenableFuture that is used to get the data produced by the query
* @throws BigQuerySQLException upon failure
*/
@BetaApi
@Override
public ListenableFuture<ExecuteSelectResponse> executeSelectAsync(String sql)
throws BigQuerySQLException {
return getExecuteSelectFuture(sql, null);
}
/** This method calls the overloaded executeSelect(...) methods and returns a Future */
private ListenableFuture<ExecuteSelectResponse> getExecuteSelectFuture(
String sql, List<Parameter> parameters, Map<String, String>... labels)
throws BigQuerySQLException {
ExecutorService execService =
Executors.newFixedThreadPool(
2); // two fixed threads. One for the async operation and the other for processing the
// callback
ListeningExecutorService lExecService = MoreExecutors.listeningDecorator(execService);
ListenableFuture<ExecuteSelectResponse> executeSelectFuture =
lExecService.submit(
() -> {
try {
return ExecuteSelectResponse.newBuilder()
.setResultSet(
this.executeSelect(
sql,
parameters,
labels)) // calling the overloaded executeSelect method, it takes care
// of null parameters and labels
.setIsSuccessful(true)
.build();
} catch (BigQuerySQLException ex) {
return ExecuteSelectResponse
.newBuilder() // passing back the null result with isSuccessful set to false
.setIsSuccessful(false)
.setBigQuerySQLException(ex)
.build();
}
});
Futures.addCallback(
executeSelectFuture,
new FutureCallback<ExecuteSelectResponse>() {
public void onSuccess(ExecuteSelectResponse result) {
execService.shutdownNow(); // shutdown the executor service as we do not need it
}
public void onFailure(Throwable t) {
logger.log(
Level.WARNING,
"\n"
+ String.format(
"Async task failed or cancelled with error %s", t.getMessage()));
try {
close(); // attempt to stop the execution as the developer might have called
// Future.cancel()
} catch (BigQuerySQLException e) {
logger.log(
Level.WARNING,
"\n"
+ String.format("Exception while closing the connection %s", e.getMessage()));
}
execService.shutdownNow(); // shutdown the executor service as we do not need it
}
},
execService);
return executeSelectFuture;
}
/**
* Execute a SQL statement that returns a single ResultSet and returns a ListenableFuture to
* process the response asynchronously.
*
* <p>Example of running a query.
*
* <pre>
* {
* @code
* ConnectionSettings connectionSettings =
* ConnectionSettings.newBuilder()
* ..setUseReadAPI(true)
* .build();
* Connection connection = bigquery.createConnection(connectionSettings);
* String selectQuery =
* "SELECT TimestampField, StringField, BooleanField FROM "
* + MY_TABLE
* + " WHERE StringField = @stringParam"
* + " AND IntegerField IN UNNEST(@integerList)";
* QueryParameterValue stringParameter = QueryParameterValue.string("stringValue");
* QueryParameterValue intArrayParameter =
* QueryParameterValue.array(new Integer[] {3, 4}, Integer.class);
* Parameter stringParam =
* Parameter.newBuilder().setName("stringParam").setValue(stringParameter).build();
* Parameter intArrayParam =
* Parameter.newBuilder().setName("integerList").setValue(intArrayParameter).build();
* List<Parameter> parameters = ImmutableList.of(stringParam, intArrayParam);
*
* ListenableFuture<ExecuteSelectResponse> executeSelectFut =
* connection.executeSelectAsync(selectQuery, parameters);
* ExecuteSelectResponse executeSelectRes = executeSelectFuture.get();
*
* if(!executeSelectRes.getIsSuccessful()){
* throw executeSelectRes.getBigQuerySQLException();
* }
*
* BigQueryResult bigQueryResult = executeSelectRes.getBigQueryResult();
* ResultSet rs = bigQueryResult.getResultSet();
* while (rs.next()) {
* System.out.println(rs.getString(1));
* }
*
* </pre>
*
* @param sql SQL SELECT query
* @param parameters named or positional parameters. The set of query parameters must either be
* all positional or all named parameters.
* @param labels (optional) the labels associated with this query. You can use these to organize
* and group your query jobs. Label keys and values can be no longer than 63 characters, can
* only contain lowercase letters, numeric characters, underscores and dashes. International
* characters are allowed. Label values are optional and Label is a Varargs. You should pass
* all the Labels in a single Map .Label keys must start with a letter and each label in the
* list must have a different key.
* @return a ListenableFuture that is used to get the data produced by the query
* @throws BigQuerySQLException upon failure
*/
@BetaApi
@Override
public ListenableFuture<ExecuteSelectResponse> executeSelectAsync(
String sql, List<Parameter> parameters, Map<String, String>... labels)
throws BigQuerySQLException {
return getExecuteSelectFuture(sql, parameters, labels);
}
@VisibleForTesting
BigQueryResult getResultSet(
GetQueryResultsResponse firstPage, JobId jobId, String sql, Boolean hasQueryParameters) {
if (firstPage.getTotalRows().compareTo(BigInteger.ZERO) > 0) {
return getSubsequentQueryResultsWithJob(
firstPage.getTotalRows().longValue(),
(long) firstPage.getRows().size(),
jobId,
firstPage,
hasQueryParameters);
}
return new BigQueryResultImpl(Schema.fromPb(firstPage.getSchema()), 0, null, null);
}
static class EndOfFieldValueList
extends AbstractList<
FieldValue> { // A reference of this class is used as a token to inform the thread
// consuming `buffer` BigQueryResultImpl that we have run out of records
@Override
public FieldValue get(int index) {
return null;
}
@Override
public int size() {
return 0;
}
}
private BigQueryResult queryRpc(
final String projectId,
final QueryRequest queryRequest,
String sql,
Boolean hasQueryParameters) {
com.google.api.services.bigquery.model.QueryResponse results;
try {
results =
BigQueryRetryHelper.runWithRetries(
() -> bigQueryRpc.queryRpc(projectId, queryRequest),
bigQueryOptions.getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
bigQueryOptions.getClock(),
retryConfig);
} catch (BigQueryRetryHelper.BigQueryRetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
if (results.getErrors() != null) {
List<BigQueryError> bigQueryErrors =
results.getErrors().stream()
.map(BigQueryError.FROM_PB_FUNCTION)
.collect(Collectors.toList());
// Throwing BigQueryException since there may be no JobId, and we want to stay consistent
// with the case where there is an HTTP error
throw new BigQueryException(bigQueryErrors);
}
// Query finished running and we can paginate all the results
if (results.getJobComplete() && results.getSchema() != null) {
return processQueryResponseResults(results);
} else {
// Query is long-running (> 10s) and hasn't completed yet, or query completed but didn't
// return the schema, fallback to jobs.insert path. Some operations don't return the schema
// and can be optimized here, but this is left as future work.
Long totalRows = results.getTotalRows() == null ? null : results.getTotalRows().longValue();
Long pageRows = results.getRows() == null ? null : (long) (results.getRows().size());
logger.log(
Level.WARNING,
"\n"
+ String.format(
"results.getJobComplete(): %s, isSchemaNull: %s , totalRows: %s, pageRows: %s",
results.getJobComplete(), results.getSchema() == null, totalRows, pageRows));
JobId jobId = JobId.fromPb(results.getJobReference());
GetQueryResultsResponse firstPage = getQueryResultsFirstPage(jobId);
return getSubsequentQueryResultsWithJob(
totalRows, pageRows, jobId, firstPage, hasQueryParameters);
}
}
@VisibleForTesting
BigQueryResultStats getBigQueryResultSetStats(JobId jobId) {
// Create GetQueryResultsResponse query statistics
Job queryJob = getQueryJobRpc(jobId);
QueryStatistics queryStatistics = queryJob.getStatistics();
SessionInfo sessionInfo =
queryStatistics.getSessionInfo() == null ? null : queryStatistics.getSessionInfo();
return new BigQueryResultStatsImpl(queryStatistics, sessionInfo);
}
/* This method processed the first page of GetQueryResultsResponse and then it uses tabledata.list */
@VisibleForTesting
BigQueryResult tableDataList(GetQueryResultsResponse firstPage, JobId jobId) {
Schema schema;
long numRows;
schema = Schema.fromPb(firstPage.getSchema());
numRows = firstPage.getTotalRows().longValue();
BigQueryResultStats bigQueryResultStats = getBigQueryResultSetStats(jobId);
// Keeps the deserialized records at the row level, which is consumed by BigQueryResult
bufferFvl = new LinkedBlockingDeque<>(getBufferSize());
// Keeps the parsed FieldValueLists
BlockingQueue<Tuple<Iterable<FieldValueList>, Boolean>> pageCache =
new LinkedBlockingDeque<>(
getPageCacheSize(connectionSettings.getNumBufferedRows(), schema));
// Keeps the raw RPC responses
BlockingQueue<Tuple<TableDataList, Boolean>> rpcResponseQueue =
new LinkedBlockingDeque<>(
getPageCacheSize(connectionSettings.getNumBufferedRows(), schema));
runNextPageTaskAsync(firstPage.getPageToken(), getDestinationTable(jobId), rpcResponseQueue);
parseRpcDataAsync(
firstPage.getRows(),
schema,
pageCache,
rpcResponseQueue); // parses data on a separate thread, thus maximising processing
// throughput
populateBufferAsync(
rpcResponseQueue, pageCache, bufferFvl); // spawns a thread to populate the buffer
// This will work for pagination as well, as buffer is getting updated asynchronously
return new BigQueryResultImpl<AbstractList<FieldValue>>(
schema, numRows, bufferFvl, bigQueryResultStats);
}
@VisibleForTesting
BigQueryResult processQueryResponseResults(
com.google.api.services.bigquery.model.QueryResponse results) {
Schema schema;
long numRows;
schema = Schema.fromPb(results.getSchema());
numRows =
results.getTotalRows() == null
? 0
: results.getTotalRows().longValue(); // in case of DML or DDL
// QueryResponse only provides cache hits, dmlStats, and sessionInfo as query processing
// statistics
DmlStats dmlStats =
results.getDmlStats() == null ? null : DmlStats.fromPb(results.getDmlStats());
Boolean cacheHit = results.getCacheHit();
QueryStatistics queryStatistics =
QueryStatistics.newBuilder().setDmlStats(dmlStats).setCacheHit(cacheHit).build();
// We cannot directly set sessionInfo in QueryStatistics
SessionInfo sessionInfo =
results.getSessionInfo() == null
? null
: JobStatistics.SessionInfo.fromPb(results.getSessionInfo());
BigQueryResultStats bigQueryResultStats =
new BigQueryResultStatsImpl(queryStatistics, sessionInfo);
bufferFvl = new LinkedBlockingDeque<>(getBufferSize());
BlockingQueue<Tuple<Iterable<FieldValueList>, Boolean>> pageCache =
new LinkedBlockingDeque<>(
getPageCacheSize(connectionSettings.getNumBufferedRows(), schema));
BlockingQueue<Tuple<TableDataList, Boolean>> rpcResponseQueue =
new LinkedBlockingDeque<>(
getPageCacheSize(connectionSettings.getNumBufferedRows(), schema));
JobId jobId = JobId.fromPb(results.getJobReference());
// Thread to make rpc calls to fetch data from the server
runNextPageTaskAsync(results.getPageToken(), getDestinationTable(jobId), rpcResponseQueue);
// Thread to parse data received from the server to client library objects
parseRpcDataAsync(results.getRows(), schema, pageCache, rpcResponseQueue);
// Thread to populate the buffer (a blocking queue) shared with the consumer
populateBufferAsync(rpcResponseQueue, pageCache, bufferFvl);
return new BigQueryResultImpl<AbstractList<FieldValue>>(
schema, numRows, bufferFvl, bigQueryResultStats);
}
@VisibleForTesting
void runNextPageTaskAsync(
String firstPageToken,
TableId destinationTable,
BlockingQueue<Tuple<TableDataList, Boolean>> rpcResponseQueue) {
// This thread makes the RPC calls and paginates
Runnable nextPageTask =
() -> {
String pageToken = firstPageToken; // results.getPageToken();
try {
while (pageToken != null) { // paginate for non null token
if (Thread.currentThread().isInterrupted()
|| queryTaskExecutor.isShutdown()) { // do not process further pages and shutdown
logger.log(
Level.WARNING,
"\n"
+ Thread.currentThread().getName()
+ " Interrupted @ runNextPageTaskAsync");
break;
}
TableDataList tabledataList = tableDataListRpc(destinationTable, pageToken);
pageToken = tabledataList.getPageToken();
rpcResponseQueue.put(
Tuple.of(
tabledataList,
true)); // this will be parsed asynchronously without blocking the current
// thread
}
rpcResponseQueue.put(
Tuple.of(
null, false)); // this will stop the parseDataTask as well when the pagination
// completes
} catch (Exception e) {
throw new BigQueryException(0, e.getMessage(), e);
} // We cannot do queryTaskExecutor.shutdownNow() here as populate buffer method may not
// have finished processing the records and even that will be interrupted
};
queryTaskExecutor.execute(nextPageTask);
}
/*
This method takes TableDataList from rpcResponseQueue and populates pageCache with FieldValueList
*/
@VisibleForTesting
void parseRpcDataAsync(
// com.google.api.services.bigquery.model.QueryResponse results,
List<TableRow> tableRows,
Schema schema,
BlockingQueue<Tuple<Iterable<FieldValueList>, Boolean>> pageCache,
BlockingQueue<Tuple<TableDataList, Boolean>> rpcResponseQueue) {
// parse and put the first page in the pageCache before the other pages are parsed from the RPC
// calls
Iterable<FieldValueList> firstFieldValueLists = getIterableFieldValueList(tableRows, schema);
try {
pageCache.put(
Tuple.of(firstFieldValueLists, true)); // this is the first page which we have received.
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ parseRpcDataAsync");
}
// rpcResponseQueue will get null tuple if Cancel method is called, so no need to explicitly use
// thread interrupt here
Runnable parseDataTask =
() -> {
try {
boolean hasMorePages = true;
while (hasMorePages) {
if (Thread.currentThread().isInterrupted()
|| queryTaskExecutor.isShutdown()) { // do not process further data and shutdown
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ parseRpcDataAsync");
break;
}
// no interrupt received till this point, continue processing
Tuple<TableDataList, Boolean> rpcResponse = rpcResponseQueue.take();
TableDataList tabledataList = rpcResponse.x();
hasMorePages = rpcResponse.y();
if (tabledataList != null) {
Iterable<FieldValueList> fieldValueLists =
getIterableFieldValueList(tabledataList.getRows(), schema); // Parse
pageCache.put(Tuple.of(fieldValueLists, true));
}
}
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ parseRpcDataAsync",
e); // Thread might get interrupted while calling the Cancel method, which is
// expected, so logging this instead of throwing the exception back
}
try {
pageCache.put(Tuple.of(null, false)); // no further pages, graceful exit scenario
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ parseRpcDataAsync",
e); // Thread might get interrupted while calling the Cancel method, which is
// expected, so logging this instead of throwing the exception back
} // We cannot do queryTaskExecutor.shutdownNow() here as populate buffer method may not
// have finished processing the records and even that will be interrupted
};
queryTaskExecutor.execute(parseDataTask);
}
@VisibleForTesting
void populateBufferAsync(
BlockingQueue<Tuple<TableDataList, Boolean>> rpcResponseQueue,
BlockingQueue<Tuple<Iterable<FieldValueList>, Boolean>> pageCache,
BlockingQueue<AbstractList<FieldValue>> buffer) {
Runnable populateBufferRunnable =
() -> { // producer thread populating the buffer
Iterable<FieldValueList> fieldValueLists = null;
boolean hasRows = true; // as we have to process the first page
while (hasRows) {
try {
Tuple<Iterable<FieldValueList>, Boolean> nextPageTuple = pageCache.take();
hasRows = nextPageTuple.y();
fieldValueLists = nextPageTuple.x();
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted",
e); // Thread might get interrupted while calling the Cancel method, which is
// expected, so logging this instead of throwing the exception back
break;
}
if (Thread.currentThread().isInterrupted()
|| queryTaskExecutor.isShutdown()
|| fieldValueLists
== null) { // do not process further pages and shutdown (outerloop)
break;
}
for (FieldValueList fieldValueList : fieldValueLists) {
try {
if (Thread.currentThread().isInterrupted()
|| queryTaskExecutor
.isShutdown()) { // do not process further pages and shutdown (inner loop)
break;
}
buffer.put(fieldValueList);
} catch (InterruptedException e) {
throw new BigQueryException(0, e.getMessage(), e);
}
}
}
try {
buffer.put(
new EndOfFieldValueList()); // All the pages has been processed, put this marker
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ populateBufferAsync",
e);
} finally {
queryTaskExecutor
.shutdownNow(); // Shutdown the thread pool. All the records are now processed
}
};
queryTaskExecutor.execute(populateBufferRunnable);
}
/**
* In an interrupt scenario, like when the background threads are still working and the user calls
* `connection.close() then we need to add an End of Stream flag in the buffer so that the
* `ResultSet.next()` stops advancing the cursor. We cannot rely on the `populateBufferAsync`
* method to do this as the `BlockingQueue.put()` call will error out after the interrupt is
* triggerred
*/
@InternalApi
void flagEndOfStream() { // package-private
try {
if (bufferFvl != null) { // that is tabledata.list endpoint is used
bufferFvl.put(
new EndOfFieldValueList()); // All the pages has been processed, put this marker
} else if (bufferRow != null) {
bufferRow.put(
new BigQueryResultImpl.Row(
null, true)); // All the pages has been processed, put this marker
} else {
logger.log(
Level.WARNING,
"\n"
+ Thread.currentThread().getName()
+ " Could not flag End of Stream, both the buffer types are null. This might happen when the connection is close without executing a query");
}
} catch (InterruptedException e) {
logger.log(
Level.WARNING,
"\n" + Thread.currentThread().getName() + " Interrupted @ flagEndOfStream",
e);
}
}
/* Helper method that parse and populate a page with TableRows */
private static Iterable<FieldValueList> getIterableFieldValueList(
Iterable<TableRow> tableDataPb, final Schema schema) {
return ImmutableList.copyOf(
Iterables.transform(
tableDataPb != null ? tableDataPb : ImmutableList.of(),
new Function<TableRow, FieldValueList>() {
final FieldList fields = schema != null ? schema.getFields() : null;
@Override
public FieldValueList apply(TableRow rowPb) {
return FieldValueList.fromPb(rowPb.getF(), fields);
}
}));
}
/* Helper method that determines the optimal number of caches pages to improve read performance */
@VisibleForTesting
int getPageCacheSize(Integer numBufferedRows, Schema schema) {
final int MIN_CACHE_SIZE = 3; // Min number of pages to cache
final int MAX_CACHE_SIZE = 20; // //Min number of pages to cache
int numColumns = schema.getFields().size();
int numCachedPages;
long numCachedRows = numBufferedRows == null ? 0 : numBufferedRows.longValue();
// TODO: Further enhance this logic depending on customer feedback on memory consumption
if (numCachedRows > 10000) {
numCachedPages =
2; // the size of numBufferedRows is quite large and as per our tests we should be able to
// do enough even with low
} else if (numColumns > 15
&& numCachedRows
> 5000) { // too many fields are being read, setting the page size on the lower end
numCachedPages = 3;
} else if (numCachedRows < 2000
&& numColumns < 15) { // low pagesize with fewer number of columns, we can cache more pages
numCachedPages = 20;
} else { // default - under 10K numCachedRows with any number of columns
numCachedPages = 5;
}
return numCachedPages < MIN_CACHE_SIZE
? MIN_CACHE_SIZE
: (Math.min(
numCachedPages,
MAX_CACHE_SIZE)); // numCachedPages should be between the defined min and max
}
/* Returns query results using either tabledata.list or the high throughput Read API */
@VisibleForTesting
BigQueryResult getSubsequentQueryResultsWithJob(
Long totalRows,
Long pageRows,
JobId jobId,
GetQueryResultsResponse firstPage,
Boolean hasQueryParameters) {
TableId destinationTable = getDestinationTable(jobId);
return useReadAPI(totalRows, pageRows, Schema.fromPb(firstPage.getSchema()), hasQueryParameters)
? highThroughPutRead(
destinationTable,
firstPage.getTotalRows().longValue(),
Schema.fromPb(firstPage.getSchema()),
getBigQueryResultSetStats(
jobId)) // discord first page and stream the entire BigQueryResult using
// the Read API
: tableDataList(firstPage, jobId);
}
/* Returns query results using either tabledata.list or the high throughput Read API */
@VisibleForTesting
BigQueryResult getSubsequentQueryResultsWithJob(
Long totalRows,
Long pageRows,
JobId jobId,
GetQueryResultsResponse firstPage,
Schema schema,
Boolean hasQueryParameters) {
TableId destinationTable = getDestinationTable(jobId);
return useReadAPI(totalRows, pageRows, schema, hasQueryParameters)
? highThroughPutRead(
destinationTable,
totalRows == null
? -1L
: totalRows, // totalRows is null when the job is still running. TODO: Check if
// any workaround is possible
schema,
getBigQueryResultSetStats(
jobId)) // discord first page and stream the entire BigQueryResult using
// the Read API
: tableDataList(firstPage, jobId);
}
/* Returns Job from jobId by calling the jobs.get API */
private Job getQueryJobRpc(JobId jobId) {
final JobId completeJobId =
jobId
.setProjectId(bigQueryOptions.getProjectId())
.setLocation(
jobId.getLocation() == null && bigQueryOptions.getLocation() != null
? bigQueryOptions.getLocation()
: jobId.getLocation());
com.google.api.services.bigquery.model.Job jobPb;
try {
jobPb =
runWithRetries(
() ->
bigQueryRpc.getQueryJob(
completeJobId.getProject(),
completeJobId.getJob(),
completeJobId.getLocation()),
bigQueryOptions.getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
bigQueryOptions.getClock());
if (bigQueryOptions.getThrowNotFound() && jobPb == null) {
throw new BigQueryException(HTTP_NOT_FOUND, "Query job not found");
}
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
return Job.fromPb(bigQueryOptions.getService(), jobPb);
}
/* Returns the destinationTable from jobId by calling jobs.get API */
@VisibleForTesting
TableId getDestinationTable(JobId jobId) {
Job job = getQueryJobRpc(jobId);
return ((QueryJobConfiguration) job.getConfiguration()).getDestinationTable();
}
@VisibleForTesting
TableDataList tableDataListRpc(TableId destinationTable, String pageToken) {
try {
final TableId completeTableId =
destinationTable.setProjectId(
Strings.isNullOrEmpty(destinationTable.getProject())
? bigQueryOptions.getProjectId()
: destinationTable.getProject());
TableDataList results =
runWithRetries(
() ->
bigQueryOptions
.getBigQueryRpcV2()
.listTableDataWithRowLimit(
completeTableId.getProject(),
completeTableId.getDataset(),
completeTableId.getTable(),
connectionSettings.getMaxResultPerPage(),
pageToken),
bigQueryOptions.getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
bigQueryOptions.getClock());
return results;
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@VisibleForTesting
BigQueryResult highThroughPutRead(
TableId destinationTable, long totalRows, Schema schema, BigQueryResultStats stats) {
try {
if (bqReadClient == null) { // if the read client isn't already initialized. Not thread safe.
BigQueryReadSettings settings =
BigQueryReadSettings.newBuilder()
.setCredentialsProvider(
FixedCredentialsProvider.create(bigQueryOptions.getCredentials()))
.build();
bqReadClient = BigQueryReadClient.create(settings);
}
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) // Currently just one stream is allowed
// DO a regex check using order by and use multiple streams
;
ReadSession readSession = bqReadClient.createReadSession(builder.build());
bufferRow = new LinkedBlockingDeque<>(getBufferSize());
Map<String, Integer> arrowNameToIndex = new HashMap<>();
// deserialize and populate the buffer async, so that the client isn't blocked
processArrowStreamAsync(
readSession,
bufferRow,
new ArrowRowReader(readSession.getArrowSchema(), arrowNameToIndex),
schema);
logger.log(Level.INFO, "\n Using BigQuery Read API");
return new BigQueryResultImpl<BigQueryResultImpl.Row>(schema, totalRows, bufferRow, stats);