-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathBigQueryImpl.java
1629 lines (1509 loc) · 62.9 KB
/
BigQueryImpl.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 2015 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 com.google.cloud.bigquery.PolicyHelper.convertFromApiPolicy;
import static com.google.cloud.bigquery.PolicyHelper.convertToApiPolicy;
import static com.google.common.base.Preconditions.checkArgument;
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.paging.Page;
import com.google.api.services.bigquery.model.ErrorProto;
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
import com.google.api.services.bigquery.model.QueryRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllRequest.Rows;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
import com.google.api.services.bigquery.model.TableDataList;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.cloud.BaseService;
import com.google.cloud.PageImpl;
import com.google.cloud.PageImpl.NextPageFetcher;
import com.google.cloud.Policy;
import com.google.cloud.RetryHelper;
import com.google.cloud.RetryHelper.RetryHelperException;
import com.google.cloud.Tuple;
import com.google.cloud.bigquery.InsertAllRequest.RowToInsert;
import com.google.cloud.bigquery.QueryJobConfiguration.JobCreationMode;
import com.google.cloud.bigquery.spi.v2.BigQueryRpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.FluentIterable;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.threeten.bp.Instant;
import org.threeten.bp.temporal.ChronoUnit;
final class BigQueryImpl extends BaseService<BigQueryOptions> implements BigQuery {
private static class DatasetPageFetcher implements NextPageFetcher<Dataset> {
private static final long serialVersionUID = -3057564042439021278L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
private final String projectId;
DatasetPageFetcher(
String projectId,
BigQueryOptions serviceOptions,
String cursor,
Map<BigQueryRpc.Option, ?> optionMap) {
this.projectId = projectId;
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
}
@Override
public Page<Dataset> getNextPage() {
return listDatasets(projectId, serviceOptions, requestOptions);
}
}
private static class TablePageFetcher implements NextPageFetcher<Table> {
private static final long serialVersionUID = 8611248840504201187L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
private final DatasetId datasetId;
TablePageFetcher(
DatasetId datasetId,
BigQueryOptions serviceOptions,
String cursor,
Map<BigQueryRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.datasetId = datasetId;
}
@Override
public Page<Table> getNextPage() {
return listTables(datasetId, serviceOptions, requestOptions);
}
}
private static class ModelPageFetcher implements NextPageFetcher<Model> {
private static final long serialVersionUID = 8611248811504201187L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
private final DatasetId datasetId;
ModelPageFetcher(
DatasetId datasetId,
BigQueryOptions serviceOptions,
String cursor,
Map<BigQueryRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.datasetId = datasetId;
}
@Override
public Page<Model> getNextPage() {
return listModels(datasetId, serviceOptions, requestOptions);
}
}
private static class RoutinePageFetcher implements NextPageFetcher<Routine> {
private static final long serialVersionUID = 8611242311504201187L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
private final DatasetId datasetId;
RoutinePageFetcher(
DatasetId datasetId,
BigQueryOptions serviceOptions,
String cursor,
Map<BigQueryRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.datasetId = datasetId;
}
@Override
public Page<Routine> getNextPage() {
return listRoutines(datasetId, serviceOptions, requestOptions);
}
}
private static class JobPageFetcher implements NextPageFetcher<Job> {
private static final long serialVersionUID = 8536533282558245472L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
JobPageFetcher(
BigQueryOptions serviceOptions, String cursor, Map<BigQueryRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
}
@Override
public Page<Job> getNextPage() {
return listJobs(serviceOptions, requestOptions);
}
}
private static class TableDataPageFetcher implements NextPageFetcher<FieldValueList> {
private static final long serialVersionUID = -8501991114794410114L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
private final TableId table;
private final Schema schema;
TableDataPageFetcher(
TableId table,
Schema schema,
BigQueryOptions serviceOptions,
String cursor,
Map<BigQueryRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.table = table;
this.schema = schema;
}
@Override
public Page<FieldValueList> getNextPage() {
return listTableData(table, schema, serviceOptions, requestOptions).x();
}
}
private class QueryPageFetcher extends Thread implements NextPageFetcher<FieldValueList> {
private static final long serialVersionUID = -8501991114794410114L;
private final Map<BigQueryRpc.Option, ?> requestOptions;
private final BigQueryOptions serviceOptions;
private Job job;
private final TableId table;
private final Schema schema;
QueryPageFetcher(
JobId jobId,
Schema schema,
BigQueryOptions serviceOptions,
String cursor,
Map<BigQueryRpc.Option, ?> optionMap) {
this.requestOptions =
PageImpl.nextRequestOptions(BigQueryRpc.Option.PAGE_TOKEN, cursor, optionMap);
this.serviceOptions = serviceOptions;
this.job = getJob(jobId);
this.table = ((QueryJobConfiguration) job.getConfiguration()).getDestinationTable();
this.schema = schema;
}
@Override
public Page<FieldValueList> getNextPage() {
while (!JobStatus.State.DONE.equals(job.getStatus().getState())) {
try {
sleep(5000);
} catch (InterruptedException ex) {
throw new RuntimeException(ex.getMessage());
}
job = job.reload();
}
return listTableData(table, schema, serviceOptions, requestOptions).x();
}
}
private final BigQueryRpc bigQueryRpc;
private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG =
BigQueryRetryConfig.newBuilder()
.retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG)
.retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG)
.retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX)
.build(); // retry config with Error Messages and RegEx for RateLimitExceeded Error
BigQueryImpl(BigQueryOptions options) {
super(options);
bigQueryRpc = options.getBigQueryRpcV2();
}
@Override
public Dataset create(DatasetInfo datasetInfo, DatasetOption... options) {
final com.google.api.services.bigquery.model.Dataset datasetPb =
datasetInfo
.setProjectId(
Strings.isNullOrEmpty(datasetInfo.getDatasetId().getProject())
? getOptions().getProjectId()
: datasetInfo.getDatasetId().getProject())
.toPb();
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Dataset.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Dataset>() {
@Override
public com.google.api.services.bigquery.model.Dataset call() {
return bigQueryRpc.create(datasetPb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Table create(TableInfo tableInfo, TableOption... options) {
final com.google.api.services.bigquery.model.Table tablePb =
tableInfo
.setProjectId(
Strings.isNullOrEmpty(tableInfo.getTableId().getProject())
? getOptions().getProjectId()
: tableInfo.getTableId().getProject())
.toPb();
handleExternalTableSchema(tablePb);
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Table.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Table>() {
@Override
public com.google.api.services.bigquery.model.Table call() {
return bigQueryRpc.create(tablePb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
private void handleExternalTableSchema(
final com.google.api.services.bigquery.model.Table tablePb) {
// Set schema on the Table for permanent external table
if (tablePb.getExternalDataConfiguration() != null) {
tablePb.setSchema(tablePb.getExternalDataConfiguration().getSchema());
// clear table schema on ExternalDataConfiguration
tablePb.getExternalDataConfiguration().setSchema(null);
}
}
@Override
public Routine create(RoutineInfo routineInfo, RoutineOption... options) {
final com.google.api.services.bigquery.model.Routine routinePb =
routineInfo
.setProjectId(
Strings.isNullOrEmpty(routineInfo.getRoutineId().getProject())
? getOptions().getProjectId()
: routineInfo.getRoutineId().getProject())
.toPb();
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Routine.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Routine>() {
@Override
public com.google.api.services.bigquery.model.Routine call() {
return bigQueryRpc.create(routinePb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Job create(JobInfo jobInfo, JobOption... options) {
Supplier<JobId> idProvider =
new Supplier<JobId>() {
@Override
public JobId get() {
return JobId.of();
}
};
return create(jobInfo, idProvider, options);
}
@Override
@BetaApi
public Connection createConnection(@NonNull ConnectionSettings connectionSettings)
throws BigQueryException {
return new ConnectionImpl(connectionSettings, getOptions(), bigQueryRpc, DEFAULT_RETRY_CONFIG);
}
@Override
@BetaApi
public Connection createConnection() throws BigQueryException {
ConnectionSettings defaultConnectionSettings = ConnectionSettings.newBuilder().build();
return new ConnectionImpl(
defaultConnectionSettings, getOptions(), bigQueryRpc, DEFAULT_RETRY_CONFIG);
}
@InternalApi("visible for testing")
Job create(JobInfo jobInfo, Supplier<JobId> idProvider, JobOption... options) {
final boolean idRandom = (jobInfo.getJobId() == null);
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
BigQueryException createException;
// NOTE(pongad): This double-try structure is admittedly odd.
// translateAndThrow itself throws, and pretends to return an exception only
// so users can pretend to throw.
// This makes it difficult to translate without throwing.
// Fixing this entails some work on BaseServiceException.translate.
// Since that affects a bunch of APIs, we should fix this as a separate change.
final JobId[] finalJobId = new JobId[1];
try {
try {
return Job.fromPb(
this,
BigQueryRetryHelper.runWithRetries(
new Callable<com.google.api.services.bigquery.model.Job>() {
@Override
public com.google.api.services.bigquery.model.Job call() {
if (idRandom) {
// re-generate a new random job with the same jobInfo when jobId is not
// provided by the user
JobInfo recreatedJobInfo =
jobInfo.toBuilder().setJobId(idProvider.get()).build();
com.google.api.services.bigquery.model.Job newJobPb =
recreatedJobInfo.setProjectId(getOptions().getProjectId()).toPb();
finalJobId[0] = recreatedJobInfo.getJobId();
return bigQueryRpc.create(newJobPb, optionsMap);
} else {
com.google.api.services.bigquery.model.Job jobPb =
jobInfo.setProjectId(getOptions().getProjectId()).toPb();
return bigQueryRpc.create(jobPb, optionsMap);
}
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock(),
DEFAULT_RETRY_CONFIG));
} catch (BigQueryRetryHelper.BigQueryRetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
} catch (BigQueryException e) {
createException = e;
}
if (!idRandom) {
if (createException instanceof BigQueryException && createException.getCause() != null) {
/*GoogleJsonResponseException createExceptionCause =
(GoogleJsonResponseException) createException.getCause();*/
Pattern pattern = Pattern.compile(".*Already.*Exists:.*Job.*", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(createException.getCause().getMessage());
if (matcher.find()) {
// If the Job ALREADY EXISTS, retrieve it.
Job job = this.getJob(jobInfo.getJobId(), JobOption.fields(JobField.STATISTICS));
long jobCreationTime = job.getStatistics().getCreationTime();
long jobMinStaleTime = System.currentTimeMillis();
long jobMaxStaleTime =
Instant.ofEpochMilli(jobMinStaleTime).minus(1, ChronoUnit.DAYS).toEpochMilli();
// Only return the job if it has been created in the past 24 hours.
// This is assuming any job older than 24 hours is a valid duplicate JobID
// and not a false positive like b/290419183
if (jobCreationTime >= jobMaxStaleTime && jobCreationTime <= jobMinStaleTime) {
return job;
}
}
}
throw createException;
}
// If create RPC fails, it's still possible that the job has been successfully
// created, and get might work.
// We can only do this if we randomly generated the ID. Otherwise we might
// mistakenly fetch a job created by someone else.
Job job;
try {
job = getJob(finalJobId[0]);
} catch (BigQueryException e) {
throw createException;
}
if (job == null) {
throw createException;
}
return job;
}
@Override
public Dataset getDataset(String datasetId, DatasetOption... options) {
return getDataset(DatasetId.of(datasetId), options);
}
@Override
public Dataset getDataset(final DatasetId datasetId, DatasetOption... options) {
final DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId());
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
com.google.api.services.bigquery.model.Dataset answer =
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Dataset>() {
@Override
public com.google.api.services.bigquery.model.Dataset call() {
return bigQueryRpc.getDataset(
completeDatasetId.getProject(), completeDatasetId.getDataset(), optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
if (getOptions().getThrowNotFound() && answer == null) {
throw new BigQueryException(HTTP_NOT_FOUND, "Dataset not found");
}
return answer == null ? null : Dataset.fromPb(this, answer);
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Page<Dataset> listDatasets(DatasetListOption... options) {
return listDatasets(getOptions().getProjectId(), options);
}
@Override
public Page<Dataset> listDatasets(String projectId, DatasetListOption... options) {
return listDatasets(projectId, getOptions(), optionMap(options));
}
private static Page<Dataset> listDatasets(
final String projectId,
final BigQueryOptions serviceOptions,
final Map<BigQueryRpc.Option, ?> optionsMap) {
try {
Tuple<String, Iterable<com.google.api.services.bigquery.model.Dataset>> result =
runWithRetries(
new Callable<
Tuple<String, Iterable<com.google.api.services.bigquery.model.Dataset>>>() {
@Override
public Tuple<String, Iterable<com.google.api.services.bigquery.model.Dataset>>
call() {
return serviceOptions.getBigQueryRpcV2().listDatasets(projectId, optionsMap);
}
},
serviceOptions.getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
serviceOptions.getClock());
String cursor = result.x();
return new PageImpl<>(
new DatasetPageFetcher(projectId, serviceOptions, cursor, optionsMap),
cursor,
Iterables.transform(
result.y(),
new Function<com.google.api.services.bigquery.model.Dataset, Dataset>() {
@Override
public Dataset apply(com.google.api.services.bigquery.model.Dataset dataset) {
return Dataset.fromPb(serviceOptions.getService(), dataset);
}
}));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public boolean delete(String datasetId, DatasetDeleteOption... options) {
return delete(DatasetId.of(datasetId), options);
}
@Override
public boolean delete(DatasetId datasetId, DatasetDeleteOption... options) {
final DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId());
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return bigQueryRpc.deleteDataset(
completeDatasetId.getProject(), completeDatasetId.getDataset(), optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public boolean delete(String datasetId, String tableId) {
return delete(TableId.of(datasetId, tableId));
}
@Override
public boolean delete(TableId tableId) {
final TableId completeTableId =
tableId.setProjectId(
Strings.isNullOrEmpty(tableId.getProject())
? getOptions().getProjectId()
: tableId.getProject());
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return bigQueryRpc.deleteTable(
completeTableId.getProject(),
completeTableId.getDataset(),
completeTableId.getTable());
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public boolean delete(ModelId modelId) {
final ModelId completeModelId =
modelId.setProjectId(
Strings.isNullOrEmpty(modelId.getProject())
? getOptions().getProjectId()
: modelId.getProject());
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return bigQueryRpc.deleteModel(
completeModelId.getProject(),
completeModelId.getDataset(),
completeModelId.getModel());
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public boolean delete(RoutineId routineId) {
final RoutineId completeRoutineId =
routineId.setProjectId(
Strings.isNullOrEmpty(routineId.getProject())
? getOptions().getProjectId()
: routineId.getProject());
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return bigQueryRpc.deleteRoutine(
completeRoutineId.getProject(),
completeRoutineId.getDataset(),
completeRoutineId.getRoutine());
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public boolean delete(JobId jobId) {
final JobId completeJobId =
jobId.setProjectId(
Strings.isNullOrEmpty(jobId.getProject())
? getOptions().getProjectId()
: jobId.getProject());
try {
return runWithRetries(
new Callable<Boolean>() {
@Override
public Boolean call() {
return bigQueryRpc.deleteJob(
completeJobId.getProject(), completeJobId.getJob(), completeJobId.getLocation());
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Dataset update(DatasetInfo datasetInfo, DatasetOption... options) {
final com.google.api.services.bigquery.model.Dataset datasetPb =
datasetInfo.setProjectId(getOptions().getProjectId()).toPb();
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Dataset.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Dataset>() {
@Override
public com.google.api.services.bigquery.model.Dataset call() {
return bigQueryRpc.patch(datasetPb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Table update(TableInfo tableInfo, TableOption... options) {
final com.google.api.services.bigquery.model.Table tablePb =
tableInfo
.setProjectId(
Strings.isNullOrEmpty(tableInfo.getTableId().getProject())
? getOptions().getProjectId()
: tableInfo.getTableId().getProject())
.toPb();
handleExternalTableSchema(tablePb);
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Table.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Table>() {
@Override
public com.google.api.services.bigquery.model.Table call() {
return bigQueryRpc.patch(tablePb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Model update(ModelInfo modelInfo, ModelOption... options) {
final com.google.api.services.bigquery.model.Model modelPb =
modelInfo
.setProjectId(
Strings.isNullOrEmpty(modelInfo.getModelId().getProject())
? getOptions().getProjectId()
: modelInfo.getModelId().getProject())
.toPb();
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Model.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Model>() {
@Override
public com.google.api.services.bigquery.model.Model call() {
return bigQueryRpc.patch(modelPb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Routine update(RoutineInfo routineInfo, RoutineOption... options) {
final com.google.api.services.bigquery.model.Routine routinePb =
routineInfo
.setProjectId(
Strings.isNullOrEmpty(routineInfo.getRoutineId().getProject())
? getOptions().getProjectId()
: routineInfo.getRoutineId().getProject())
.toPb();
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
return Routine.fromPb(
this,
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Routine>() {
@Override
public com.google.api.services.bigquery.model.Routine call() {
return bigQueryRpc.update(routinePb, optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock()));
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Table getTable(final String datasetId, final String tableId, TableOption... options) {
return getTable(TableId.of(datasetId, tableId), options);
}
@Override
public Table getTable(TableId tableId, TableOption... options) {
// More context about why this:
// https://github.com/googleapis/google-cloud-java/issues/3808
final TableId completeTableId =
tableId.setProjectId(
Strings.isNullOrEmpty(tableId.getProject())
? getOptions().getProjectId()
: tableId.getProject());
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
com.google.api.services.bigquery.model.Table answer =
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Table>() {
@Override
public com.google.api.services.bigquery.model.Table call() {
return bigQueryRpc.getTable(
completeTableId.getProject(),
completeTableId.getDataset(),
completeTableId.getTable(),
optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
if (getOptions().getThrowNotFound() && answer == null) {
throw new BigQueryException(HTTP_NOT_FOUND, "Table not found");
}
return answer == null ? null : Table.fromPb(this, answer);
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Model getModel(String datasetId, String modelId, ModelOption... options) {
return getModel(ModelId.of(datasetId, modelId), options);
}
@Override
public Model getModel(ModelId modelId, ModelOption... options) {
final ModelId completeModelId =
modelId.setProjectId(
Strings.isNullOrEmpty(modelId.getProject())
? getOptions().getProjectId()
: modelId.getProject());
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
com.google.api.services.bigquery.model.Model answer =
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Model>() {
@Override
public com.google.api.services.bigquery.model.Model call() {
return bigQueryRpc.getModel(
completeModelId.getProject(),
completeModelId.getDataset(),
completeModelId.getModel(),
optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
if (getOptions().getThrowNotFound() && answer == null) {
throw new BigQueryException(HTTP_NOT_FOUND, "Model not found");
}
return answer == null ? null : Model.fromPb(this, answer);
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Routine getRoutine(String datasetId, String routineId, RoutineOption... options) {
return getRoutine(RoutineId.of(datasetId, routineId), options);
}
@Override
public Routine getRoutine(RoutineId routineId, RoutineOption... options) {
final RoutineId completeRoutineId =
routineId.setProjectId(
Strings.isNullOrEmpty(routineId.getProject())
? getOptions().getProjectId()
: routineId.getProject());
final Map<BigQueryRpc.Option, ?> optionsMap = optionMap(options);
try {
com.google.api.services.bigquery.model.Routine answer =
runWithRetries(
new Callable<com.google.api.services.bigquery.model.Routine>() {
@Override
public com.google.api.services.bigquery.model.Routine call() {
return bigQueryRpc.getRoutine(
completeRoutineId.getProject(),
completeRoutineId.getDataset(),
completeRoutineId.getRoutine(),
optionsMap);
}
},
getOptions().getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
getOptions().getClock());
if (getOptions().getThrowNotFound() && answer == null) {
throw new BigQueryException(HTTP_NOT_FOUND, "Routine not found");
}
return answer == null ? null : Routine.fromPb(this, answer);
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);
}
}
@Override
public Page<Table> listTables(String datasetId, TableListOption... options) {
return listTables(
DatasetId.of(getOptions().getProjectId(), datasetId), getOptions(), optionMap(options));
}
@Override
public Page<Table> listTables(DatasetId datasetId, TableListOption... options) {
DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId());
return listTables(completeDatasetId, getOptions(), optionMap(options));
}
@Override
public Page<Model> listModels(String datasetId, ModelListOption... options) {
return listModels(
DatasetId.of(getOptions().getProjectId(), datasetId), getOptions(), optionMap(options));
}
@Override
public Page<Model> listModels(DatasetId datasetId, ModelListOption... options) {
DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId());
return listModels(completeDatasetId, getOptions(), optionMap(options));
}
@Override
public Page<Routine> listRoutines(String datasetId, RoutineListOption... options) {
return listRoutines(
DatasetId.of(getOptions().getProjectId(), datasetId), getOptions(), optionMap(options));
}
@Override
public Page<Routine> listRoutines(DatasetId datasetId, RoutineListOption... options) {
DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId());
return listRoutines(completeDatasetId, getOptions(), optionMap(options));
}
@Override
public List<String> listPartitions(TableId tableId) {
List<String> partitions = new ArrayList<String>();
String partitionsTable = tableId.getTable() + "$__PARTITIONS_SUMMARY__";
TableId metaTableId =
tableId.getProject() == null
? TableId.of(tableId.getDataset(), partitionsTable)
: TableId.of(tableId.getProject(), tableId.getDataset(), partitionsTable);
Table metaTable = getTable(metaTableId);
Schema metaSchema = metaTable.getDefinition().getSchema();
String partition_id = null;
for (Field field : metaSchema.getFields()) {
if (field.getName().equals("partition_id")) {
partition_id = field.getName();
break;
}
}
TableResult result = metaTable.list(metaSchema);
for (FieldValueList list : result.iterateAll()) {
partitions.add(list.get(partition_id).getStringValue());
}
return partitions;
}
private static Page<Table> listTables(
final DatasetId datasetId,
final BigQueryOptions serviceOptions,
final Map<BigQueryRpc.Option, ?> optionsMap) {
try {
Tuple<String, Iterable<com.google.api.services.bigquery.model.Table>> result =
runWithRetries(
new Callable<
Tuple<String, Iterable<com.google.api.services.bigquery.model.Table>>>() {
@Override
public Tuple<String, Iterable<com.google.api.services.bigquery.model.Table>>
call() {
return serviceOptions
.getBigQueryRpcV2()
.listTables(datasetId.getProject(), datasetId.getDataset(), optionsMap);
}
},
serviceOptions.getRetrySettings(),
BigQueryBaseService.BIGQUERY_EXCEPTION_HANDLER,
serviceOptions.getClock());
String cursor = result.x();
Iterable<Table> tables =
Iterables.transform(
result.y(),
new Function<com.google.api.services.bigquery.model.Table, Table>() {
@Override
public Table apply(com.google.api.services.bigquery.model.Table table) {
return Table.fromPb(serviceOptions.getService(), table);
}
});
return new PageImpl<>(
new TablePageFetcher(datasetId, serviceOptions, cursor, optionsMap), cursor, tables);
} catch (RetryHelper.RetryHelperException e) {
throw BigQueryException.translateAndThrow(e);