/
HttpBigQueryRpc.java
660 lines (623 loc) · 22.6 KB
/
HttpBigQueryRpc.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
/*
* 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.spi.v2;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_OK;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.core.InternalApi;
import com.google.api.core.InternalExtensionOnly;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.model.Dataset;
import com.google.api.services.bigquery.model.DatasetList;
import com.google.api.services.bigquery.model.DatasetReference;
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobList;
import com.google.api.services.bigquery.model.JobStatus;
import com.google.api.services.bigquery.model.ListModelsResponse;
import com.google.api.services.bigquery.model.ListRoutinesResponse;
import com.google.api.services.bigquery.model.Model;
import com.google.api.services.bigquery.model.ModelReference;
import com.google.api.services.bigquery.model.Routine;
import com.google.api.services.bigquery.model.RoutineReference;
import com.google.api.services.bigquery.model.Table;
import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
import com.google.api.services.bigquery.model.TableDataList;
import com.google.api.services.bigquery.model.TableList;
import com.google.api.services.bigquery.model.TableReference;
import com.google.cloud.Tuple;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.http.HttpTransportOptions;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
@InternalExtensionOnly
public class HttpBigQueryRpc implements BigQueryRpc {
public static final String DEFAULT_PROJECTION = "full";
private static final String BASE_RESUMABLE_URI =
"https://www.googleapis.com/upload/bigquery/v2/projects/";
// see: https://cloud.google.com/bigquery/loading-data-post-request#resume-upload
private static final int HTTP_RESUME_INCOMPLETE = 308;
private final BigQueryOptions options;
private final Bigquery bigquery;
@InternalApi("Visible for testing")
static final Function<DatasetList.Datasets, Dataset> LIST_TO_DATASET =
new Function<DatasetList.Datasets, Dataset>() {
@Override
public Dataset apply(DatasetList.Datasets datasetPb) {
return new Dataset()
.setDatasetReference(datasetPb.getDatasetReference())
.setFriendlyName(datasetPb.getFriendlyName())
.setId(datasetPb.getId())
.setKind(datasetPb.getKind())
.setLabels(datasetPb.getLabels());
}
};
public HttpBigQueryRpc(BigQueryOptions options) {
HttpTransportOptions transportOptions = (HttpTransportOptions) options.getTransportOptions();
HttpTransport transport = transportOptions.getHttpTransportFactory().create();
HttpRequestInitializer initializer = transportOptions.getHttpRequestInitializer(options);
this.options = options;
bigquery =
new Bigquery.Builder(transport, new JacksonFactory(), initializer)
.setRootUrl(options.getHost())
.setApplicationName(options.getApplicationName())
.build();
}
private static BigQueryException translate(IOException exception) {
return new BigQueryException(exception);
}
@Override
public Dataset getDataset(String projectId, String datasetId, Map<Option, ?> options) {
try {
return bigquery
.datasets()
.get(projectId, datasetId)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return null;
}
throw serviceException;
}
}
@Override
public Tuple<String, Iterable<Dataset>> listDatasets(String projectId, Map<Option, ?> options) {
try {
DatasetList datasetsList =
bigquery
.datasets()
.list(projectId)
.setAll(Option.ALL_DATASETS.getBoolean(options))
.setFilter(Option.LABEL_FILTER.getString(options))
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.execute();
Iterable<DatasetList.Datasets> datasets = datasetsList.getDatasets();
return Tuple.of(
datasetsList.getNextPageToken(),
Iterables.transform(
datasets != null ? datasets : ImmutableList.<DatasetList.Datasets>of(),
LIST_TO_DATASET));
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Dataset create(Dataset dataset, Map<Option, ?> options) {
try {
return bigquery
.datasets()
.insert(dataset.getDatasetReference().getProjectId(), dataset)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Table create(Table table, Map<Option, ?> options) {
try {
// unset the type, as it is output only
table.setType(null);
TableReference reference = table.getTableReference();
return bigquery
.tables()
.insert(reference.getProjectId(), reference.getDatasetId(), table)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Routine create(Routine routine, Map<Option, ?> options) {
try {
RoutineReference reference = routine.getRoutineReference();
return bigquery
.routines()
.insert(reference.getProjectId(), reference.getDatasetId(), routine)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Job create(Job job, Map<Option, ?> options) {
try {
String projectId =
job.getJobReference() != null
? job.getJobReference().getProjectId()
: this.options.getProjectId();
return bigquery
.jobs()
.insert(projectId, job)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public boolean deleteDataset(String projectId, String datasetId, Map<Option, ?> options) {
try {
bigquery
.datasets()
.delete(projectId, datasetId)
.setDeleteContents(Option.DELETE_CONTENTS.getBoolean(options))
.execute();
return true;
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return false;
}
throw serviceException;
}
}
@Override
public Dataset patch(Dataset dataset, Map<Option, ?> options) {
try {
DatasetReference reference = dataset.getDatasetReference();
return bigquery
.datasets()
.patch(reference.getProjectId(), reference.getDatasetId(), dataset)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Table patch(Table table, Map<Option, ?> options) {
try {
// unset the type, as it is output only
table.setType(null);
TableReference reference = table.getTableReference();
return bigquery
.tables()
.patch(reference.getProjectId(), reference.getDatasetId(), reference.getTableId(), table)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Table getTable(
String projectId, String datasetId, String tableId, Map<Option, ?> options) {
try {
return bigquery
.tables()
.get(projectId, datasetId, tableId)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return null;
}
throw serviceException;
}
}
@Override
public Tuple<String, Iterable<Table>> listTables(
String projectId, String datasetId, Map<Option, ?> options) {
try {
TableList tableList =
bigquery
.tables()
.list(projectId, datasetId)
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.execute();
Iterable<TableList.Tables> tables = tableList.getTables();
return Tuple.of(
tableList.getNextPageToken(),
Iterables.transform(
tables != null ? tables : ImmutableList.<TableList.Tables>of(),
new Function<TableList.Tables, Table>() {
@Override
public Table apply(TableList.Tables tablePb) {
return new Table()
.setFriendlyName(tablePb.getFriendlyName())
.setId(tablePb.getId())
.setKind(tablePb.getKind())
.setTableReference(tablePb.getTableReference())
.setType(tablePb.getType())
.setCreationTime(tablePb.getCreationTime())
.setTimePartitioning(tablePb.getTimePartitioning())
.setRangePartitioning(tablePb.getRangePartitioning());
}
}));
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public boolean deleteTable(String projectId, String datasetId, String tableId) {
try {
bigquery.tables().delete(projectId, datasetId, tableId).execute();
return true;
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return false;
}
throw serviceException;
}
}
@Override
public Model patch(Model model, Map<Option, ?> options) {
try {
// unset the type, as it is output only
ModelReference reference = model.getModelReference();
return bigquery
.models()
.patch(reference.getProjectId(), reference.getDatasetId(), reference.getModelId(), model)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Model getModel(
String projectId, String datasetId, String modelId, Map<Option, ?> options) {
try {
return bigquery
.models()
.get(projectId, datasetId, modelId)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return null;
}
throw serviceException;
}
}
@Override
public Tuple<String, Iterable<Model>> listModels(
String projectId, String datasetId, Map<Option, ?> options) {
try {
ListModelsResponse modelList =
bigquery
.models()
.list(projectId, datasetId)
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.execute();
Iterable<Model> models = modelList.getModels();
return Tuple.of(modelList.getNextPageToken(), models);
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public boolean deleteModel(String projectId, String datasetId, String modelId) {
try {
bigquery.models().delete(projectId, datasetId, modelId).execute();
return true;
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return false;
}
throw serviceException;
}
}
@Override
public Routine update(Routine routine, Map<Option, ?> options) {
try {
RoutineReference reference = routine.getRoutineReference();
return bigquery
.routines()
.update(
reference.getProjectId(), reference.getDatasetId(), reference.getRoutineId(), routine)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Routine getRoutine(
String projectId, String datasetId, String routineId, Map<Option, ?> options) {
try {
return bigquery
.routines()
.get(projectId, datasetId, routineId)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return null;
}
throw serviceException;
}
}
@Override
public Tuple<String, Iterable<Routine>> listRoutines(
String projectId, String datasetId, Map<Option, ?> options) {
try {
ListRoutinesResponse routineList =
bigquery
.routines()
.list(projectId, datasetId)
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.execute();
Iterable<Routine> routines = routineList.getRoutines();
return Tuple.of(routineList.getNextPageToken(), routines);
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public boolean deleteRoutine(String projectId, String datasetId, String routineId) {
try {
bigquery.routines().delete(projectId, datasetId, routineId).execute();
return true;
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return false;
}
throw serviceException;
}
}
@Override
public TableDataInsertAllResponse insertAll(
String projectId, String datasetId, String tableId, TableDataInsertAllRequest request) {
try {
return bigquery.tabledata().insertAll(projectId, datasetId, tableId, request).execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public TableDataList listTableData(
String projectId, String datasetId, String tableId, Map<Option, ?> options) {
try {
return bigquery
.tabledata()
.list(projectId, datasetId, tableId)
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.setStartIndex(
Option.START_INDEX.getLong(options) != null
? BigInteger.valueOf(Option.START_INDEX.getLong(options))
: null)
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Job getJob(String projectId, String jobId, String location, Map<Option, ?> options) {
try {
return bigquery
.jobs()
.get(projectId, jobId)
.setLocation(location)
.setFields(Option.FIELDS.getString(options))
.execute();
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return null;
}
throw serviceException;
}
}
@Override
public Tuple<String, Iterable<Job>> listJobs(String projectId, Map<Option, ?> options) {
try {
Bigquery.Jobs.List request =
bigquery
.jobs()
.list(projectId)
.setAllUsers(Option.ALL_USERS.getBoolean(options))
.setFields(Option.FIELDS.getString(options))
.setStateFilter(Option.STATE_FILTER.<List<String>>get(options))
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.setProjection(DEFAULT_PROJECTION)
.setParentJobId(Option.PARENT_JOB_ID.getString(options));
if (Option.MIN_CREATION_TIME.getLong(options) != null) {
request.setMinCreationTime(BigInteger.valueOf(Option.MIN_CREATION_TIME.getLong(options)));
}
if (Option.MAX_CREATION_TIME.getLong(options) != null) {
request.setMaxCreationTime(BigInteger.valueOf(Option.MAX_CREATION_TIME.getLong(options)));
}
JobList jobsList = request.execute();
Iterable<JobList.Jobs> jobs = jobsList.getJobs();
return Tuple.of(
jobsList.getNextPageToken(),
Iterables.transform(
jobs != null ? jobs : ImmutableList.<JobList.Jobs>of(),
new Function<JobList.Jobs, Job>() {
@Override
public Job apply(JobList.Jobs jobPb) {
JobStatus statusPb =
jobPb.getStatus() != null ? jobPb.getStatus() : new JobStatus();
if (statusPb.getState() == null) {
statusPb.setState(jobPb.getState());
}
if (statusPb.getErrorResult() == null) {
statusPb.setErrorResult(jobPb.getErrorResult());
}
return new Job()
.setConfiguration(jobPb.getConfiguration())
.setId(jobPb.getId())
.setJobReference(jobPb.getJobReference())
.setKind(jobPb.getKind())
.setStatistics(jobPb.getStatistics())
.setStatus(statusPb)
.setUserEmail(jobPb.getUserEmail());
}
}));
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public boolean cancel(String projectId, String jobId, String location) {
try {
bigquery.jobs().cancel(projectId, jobId).setLocation(location).execute();
return true;
} catch (IOException ex) {
BigQueryException serviceException = translate(ex);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return false;
}
throw serviceException;
}
}
@Override
public GetQueryResultsResponse getQueryResults(
String projectId, String jobId, String location, Map<Option, ?> options) {
try {
return bigquery
.jobs()
.getQueryResults(projectId, jobId)
.setLocation(location)
.setMaxResults(Option.MAX_RESULTS.getLong(options))
.setPageToken(Option.PAGE_TOKEN.getString(options))
.setStartIndex(
Option.START_INDEX.getLong(options) != null
? BigInteger.valueOf(Option.START_INDEX.getLong(options))
: null)
.setTimeoutMs(Option.TIMEOUT.getLong(options))
.execute();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public String open(Job loadJob) {
try {
String builder = BASE_RESUMABLE_URI + options.getProjectId() + "/jobs";
GenericUrl url = new GenericUrl(builder);
url.set("uploadType", "resumable");
JsonFactory jsonFactory = bigquery.getJsonFactory();
HttpRequestFactory requestFactory = bigquery.getRequestFactory();
HttpRequest httpRequest =
requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, loadJob));
httpRequest.getHeaders().set("X-Upload-Content-Value", "application/octet-stream");
HttpResponse response = httpRequest.execute();
return response.getHeaders().getLocation();
} catch (IOException ex) {
throw translate(ex);
}
}
@Override
public Job write(
String uploadId,
byte[] toWrite,
int toWriteOffset,
long destOffset,
int length,
boolean last) {
try {
if (length == 0) {
return null;
}
GenericUrl url = new GenericUrl(uploadId);
HttpRequest httpRequest =
bigquery
.getRequestFactory()
.buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length));
httpRequest.setParser(bigquery.getObjectParser());
long limit = destOffset + length;
StringBuilder range = new StringBuilder("bytes ");
range.append(destOffset).append('-').append(limit - 1).append('/');
if (last) {
range.append(limit);
} else {
range.append('*');
}
httpRequest.getHeaders().setContentRange(range.toString());
int code;
String message;
IOException exception = null;
HttpResponse response = null;
try {
response = httpRequest.execute();
code = response.getStatusCode();
message = response.getStatusMessage();
} catch (HttpResponseException ex) {
exception = ex;
code = ex.getStatusCode();
message = ex.getStatusMessage();
}
if (!last && code != HTTP_RESUME_INCOMPLETE
|| last && !(code == HTTP_OK || code == HTTP_CREATED)) {
if (exception != null) {
throw exception;
}
throw new BigQueryException(code, message);
}
return last && response != null ? response.parseAs(Job.class) : null;
} catch (IOException ex) {
throw translate(ex);
}
}
}