/
ITBigQueryStorageTest.java
964 lines (837 loc) · 36.5 KB
/
ITBigQueryStorageTest.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
/*
* Copyright 2020 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.storage.v1beta2.it;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import com.google.api.gax.rpc.ServerStream;
import com.google.cloud.RetryOption;
import com.google.cloud.ServiceOptions;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.Field.Mode;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.JobInfo.WriteDisposition;
import com.google.cloud.bigquery.LegacySQLTypeName;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.StandardTableDefinition;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableInfo;
import com.google.cloud.bigquery.TimePartitioning;
import com.google.cloud.bigquery.storage.v1beta2.BigQueryReadClient;
import com.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest;
import com.google.cloud.bigquery.storage.v1beta2.DataFormat;
import com.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest;
import com.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse;
import com.google.cloud.bigquery.storage.v1beta2.ReadSession;
import com.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers;
import com.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions;
import com.google.cloud.bigquery.storage.v1beta2.ReadStream;
import com.google.cloud.bigquery.storage.v1beta2.it.SimpleRowReader.AvroRowConsumer;
import com.google.cloud.bigquery.testing.RemoteBigQueryHelper;
import com.google.common.base.Preconditions;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.apache.avro.Conversions;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.util.Utf8;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.threeten.bp.Duration;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
/** Integration tests for BigQuery Storage API. */
public class ITBigQueryStorageTest {
private static final Logger LOG = Logger.getLogger(ITBigQueryStorageTest.class.getName());
private static final String DATASET = RemoteBigQueryHelper.generateDatasetName();
private static final String DESCRIPTION = "BigQuery Storage Java client test dataset";
private static BigQueryReadClient client;
private static String parentProjectId;
private static BigQuery bigquery;
@BeforeClass
public static void beforeClass() throws IOException {
client = BigQueryReadClient.create();
parentProjectId = String.format("projects/%s", ServiceOptions.getDefaultProjectId());
LOG.info(
String.format(
"%s tests running with parent project: %s",
ITBigQueryStorageTest.class.getSimpleName(), parentProjectId));
RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create();
bigquery = bigqueryHelper.getOptions().getService();
DatasetInfo datasetInfo =
DatasetInfo.newBuilder(/* datasetId = */ DATASET).setDescription(DESCRIPTION).build();
bigquery.create(datasetInfo);
LOG.info("Created test dataset: " + DATASET);
}
@AfterClass
public static void afterClass() {
if (client != null) {
client.close();
}
if (bigquery != null) {
RemoteBigQueryHelper.forceDelete(bigquery, DATASET);
LOG.info("Deleted test dataset: " + DATASET);
}
}
@Test
public void testSimpleRead() {
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ "bigquery-public-data",
/* datasetId = */ "samples",
/* tableId = */ "shakespeare");
ReadSession session =
client.createReadSession(
/* parent = */ parentProjectId,
/* readSession = */ ReadSession.newBuilder()
.setTable(table)
.setDataFormat(DataFormat.AVRO)
.build(),
/* maxStreamCount = */ 1);
assertEquals(
String.format(
"Did not receive expected number of streams for table '%s' CreateReadSession"
+ " response:%n%s",
table, session.toString()),
1,
session.getStreamsCount());
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder().setReadStream(session.getStreams(0).getName()).build();
long rowCount = 0;
ServerStream<ReadRowsResponse> stream = client.readRowsCallable().call(readRowsRequest);
for (ReadRowsResponse response : stream) {
rowCount += response.getRowCount();
}
assertEquals(164_656, rowCount);
}
@Test
public void testSimpleReadAndResume() {
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ "bigquery-public-data",
/* datasetId = */ "samples",
/* tableId = */ "shakespeare");
ReadSession session =
client.createReadSession(
/* parent = */ parentProjectId,
/* readSession = */ ReadSession.newBuilder()
.setTable(table)
.setDataFormat(DataFormat.AVRO)
.build(),
/* maxStreamCount = */ 1);
assertEquals(
String.format(
"Did not receive expected number of streams for table '%s' CreateReadSession"
+ " response:%n%s",
table, session.toString()),
1,
session.getStreamsCount());
// We have to read some number of rows in order to be able to resume. More details:
long rowCount = ReadStreamToOffset(session.getStreams(0), /* rowOffset = */ 34_846);
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder()
.setReadStream(session.getStreams(0).getName())
.setOffset(rowCount)
.build();
ServerStream<ReadRowsResponse> stream = client.readRowsCallable().call(readRowsRequest);
for (ReadRowsResponse response : stream) {
rowCount += response.getRowCount();
}
// Verifies that the number of rows skipped and read equals to the total number of rows in the
// table.
assertEquals(164_656, rowCount);
}
@Test
public void testFilter() throws IOException {
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ "bigquery-public-data",
/* datasetId = */ "samples",
/* tableId = */ "shakespeare");
TableReadOptions options =
TableReadOptions.newBuilder().setRowRestriction("word_count > 100").build();
CreateReadSessionRequest request =
CreateReadSessionRequest.newBuilder()
.setParent(parentProjectId)
.setMaxStreamCount(1)
.setReadSession(
ReadSession.newBuilder()
.setTable(table)
.setReadOptions(options)
.setDataFormat(DataFormat.AVRO)
.build())
.build();
ReadSession session = client.createReadSession(request);
assertEquals(
String.format(
"Did not receive expected number of streams for table '%s' CreateReadSession"
+ " response:%n%s",
table, session.toString()),
1,
session.getStreamsCount());
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder().setReadStream(session.getStreams(0).getName()).build();
SimpleRowReader reader =
new SimpleRowReader(new Schema.Parser().parse(session.getAvroSchema().getSchema()));
long rowCount = 0;
ServerStream<ReadRowsResponse> stream = client.readRowsCallable().call(readRowsRequest);
for (ReadRowsResponse response : stream) {
rowCount += response.getRowCount();
reader.processRows(
response.getAvroRows(),
new AvroRowConsumer() {
@Override
public void accept(GenericData.Record record) {
Long wordCount = (Long) record.get("word_count");
assertWithMessage("Row not matching expectations: %s", record.toString())
.that(wordCount)
.isGreaterThan(100L);
}
});
}
assertEquals(1_333, rowCount);
}
@Test
public void testColumnSelection() throws IOException {
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ "bigquery-public-data",
/* datasetId = */ "samples",
/* tableId = */ "shakespeare");
TableReadOptions options =
TableReadOptions.newBuilder()
.addSelectedFields("word")
.addSelectedFields("word_count")
.setRowRestriction("word_count > 100")
.build();
CreateReadSessionRequest request =
CreateReadSessionRequest.newBuilder()
.setParent(parentProjectId)
.setMaxStreamCount(1)
.setReadSession(
ReadSession.newBuilder()
.setTable(table)
.setReadOptions(options)
.setDataFormat(DataFormat.AVRO)
.build())
.build();
ReadSession session = client.createReadSession(request);
assertEquals(
String.format(
"Did not receive expected number of streams for table '%s' CreateReadSession"
+ " response:%n%s",
table, session.toString()),
1,
session.getStreamsCount());
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder().setReadStream(session.getStreams(0).getName()).build();
Schema avroSchema = new Schema.Parser().parse(session.getAvroSchema().getSchema());
String actualSchemaMessage =
String.format(
"Unexpected schema. Actual schema:%n%s", avroSchema.toString(/* pretty = */ true));
assertEquals(actualSchemaMessage, Schema.Type.RECORD, avroSchema.getType());
assertEquals(actualSchemaMessage, "__root__", avroSchema.getName());
assertEquals(actualSchemaMessage, 2, avroSchema.getFields().size());
assertEquals(
actualSchemaMessage, Schema.Type.STRING, avroSchema.getField("word").schema().getType());
assertEquals(
actualSchemaMessage,
Schema.Type.LONG,
avroSchema.getField("word_count").schema().getType());
SimpleRowReader reader = new SimpleRowReader(avroSchema);
long rowCount = 0;
ServerStream<ReadRowsResponse> stream = client.readRowsCallable().call(readRowsRequest);
for (ReadRowsResponse response : stream) {
rowCount += response.getRowCount();
reader.processRows(
response.getAvroRows(),
new AvroRowConsumer() {
@Override
public void accept(GenericData.Record record) {
String rowAssertMessage =
String.format("Row not matching expectations: %s", record.toString());
Long wordCount = (Long) record.get("word_count");
assertWithMessage(rowAssertMessage).that(wordCount).isGreaterThan(100L);
Utf8 word = (Utf8) record.get("word");
assertWithMessage(rowAssertMessage).that(word.length()).isGreaterThan(0);
}
});
}
assertEquals(1_333, rowCount);
}
@Test
public void testReadAtSnapshot() throws InterruptedException, IOException {
Field intFieldSchema =
Field.newBuilder("col", LegacySQLTypeName.INTEGER)
.setMode(Mode.REQUIRED)
.setDescription("IntegerDescription")
.build();
com.google.cloud.bigquery.Schema tableSchema =
com.google.cloud.bigquery.Schema.of(intFieldSchema);
TableId testTableId = TableId.of(/* dataset = */ DATASET, /* table = */ "test_read_snapshot");
bigquery.create(TableInfo.of(testTableId, StandardTableDefinition.of(tableSchema)));
testTableId.toString();
Job firstJob =
RunQueryAppendJobAndExpectSuccess(
/* destinationTableId = */ testTableId, /* query = */ "SELECT 1 AS col");
Job secondJob =
RunQueryAppendJobAndExpectSuccess(
/* destinationTableId = */ testTableId, /* query = */ "SELECT 2 AS col");
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ DATASET,
/* tableId = */ testTableId.getTable());
final List<Long> rowsAfterFirstSnapshot = new ArrayList<>();
ProcessRowsAtSnapshot(
/* table = */ table,
/* snapshotInMillis = */ firstJob.getStatistics().getEndTime(),
/* filter = */ null,
/* consumer = */ new AvroRowConsumer() {
@Override
public void accept(GenericData.Record record) {
rowsAfterFirstSnapshot.add((Long) record.get("col"));
}
});
assertEquals(Arrays.asList(1L), rowsAfterFirstSnapshot);
final List<Long> rowsAfterSecondSnapshot = new ArrayList<>();
ProcessRowsAtSnapshot(
/* table = */ table,
/* snapshotInMillis = */ secondJob.getStatistics().getEndTime(),
/* filter = */ null,
/* consumer = */ new AvroRowConsumer() {
@Override
public void accept(GenericData.Record record) {
rowsAfterSecondSnapshot.add((Long) record.get("col"));
}
});
Collections.sort(rowsAfterSecondSnapshot);
assertEquals(Arrays.asList(1L, 2L), rowsAfterSecondSnapshot);
}
@Test
public void testColumnPartitionedTableByDateField() throws InterruptedException, IOException {
String partitionedTableName = "test_column_partition_table_by_date";
String createTableStatement =
String.format(
" CREATE TABLE %s.%s (num_field INT64, date_field DATE) "
+ " PARTITION BY date_field "
+ " OPTIONS( "
+ " description=\"a table partitioned by date_field\" "
+ " ) "
+ "AS "
+ " SELECT 1, CAST(\"2019-01-01\" AS DATE)"
+ " UNION ALL"
+ " SELECT 2, CAST(\"2019-01-02\" AS DATE)"
+ " UNION ALL"
+ " SELECT 3, CAST(\"2019-01-03\" AS DATE)",
DATASET, partitionedTableName);
RunQueryJobAndExpectSuccess(QueryJobConfiguration.newBuilder(createTableStatement).build());
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ DATASET,
/* tableId = */ partitionedTableName);
List<GenericData.Record> unfilteredRows = ReadAllRows(/* table = */ table, /* filter = */ null);
assertEquals("Actual rows read: " + unfilteredRows.toString(), 3, unfilteredRows.size());
List<GenericData.Record> partitionFilteredRows =
ReadAllRows(
/* table = */ table, /* filter = */ "date_field = CAST(\"2019-01-02\" AS DATE)");
assertEquals(
"Actual rows read: " + partitionFilteredRows.toString(), 1, partitionFilteredRows.size());
assertEquals(2L, partitionFilteredRows.get(0).get("num_field"));
}
@Test
public void testIngestionTimePartitionedTable() throws InterruptedException, IOException {
Field intFieldSchema =
Field.newBuilder("num_field", LegacySQLTypeName.INTEGER)
.setMode(Mode.REQUIRED)
.setDescription("IntegerDescription")
.build();
com.google.cloud.bigquery.Schema tableSchema =
com.google.cloud.bigquery.Schema.of(intFieldSchema);
TableId testTableId =
TableId.of(/* dataset = */ DATASET, /* table = */ "test_date_partitioned_table");
bigquery.create(
TableInfo.of(
testTableId,
StandardTableDefinition.newBuilder()
.setTimePartitioning(TimePartitioning.of(TimePartitioning.Type.DAY))
.setSchema(tableSchema)
.build()));
// Simulate ingestion for 2019-01-01.
RunQueryAppendJobAndExpectSuccess(
/* destinationTableId = */ TableId.of(
/* dataset = */ DATASET, /* table = */ testTableId.getTable() + "$20190101"),
/* query = */ "SELECT 1 AS num_field");
// Simulate ingestion for 2019-01-02.
RunQueryAppendJobAndExpectSuccess(
/* destinationTableId = */ TableId.of(
/* dataset = */ DATASET, /* table = */ testTableId.getTable() + "$20190102"),
/* query = */ "SELECT 2 AS num_field");
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ testTableId.getDataset(),
/* tableId = */ testTableId.getTable());
List<GenericData.Record> unfilteredRows = ReadAllRows(/* table = */ table, /* filter = */ null);
assertEquals("Actual rows read: " + unfilteredRows.toString(), 2, unfilteredRows.size());
List<GenericData.Record> partitionFilteredRows =
ReadAllRows(/* table = */ table, /* filter = */ "_PARTITIONDATE > \"2019-01-01\"");
assertEquals(
"Actual rows read: " + partitionFilteredRows.toString(), 1, partitionFilteredRows.size());
assertEquals(2L, partitionFilteredRows.get(0).get("num_field"));
}
@Test
public void testBasicSqlTypes() throws InterruptedException, IOException {
String tableName = "test_basic_sql_types";
String createTableStatement =
String.format(
" CREATE TABLE %s.%s "
+ " (int_field INT64 NOT NULL,"
+ " num_field NUMERIC NOT NULL,"
+ " float_field FLOAT64 NOT NULL,"
+ " bool_field BOOL NOT NULL,"
+ " str_field STRING NOT NULL,"
+ " bytes_field BYTES NOT NULL) "
+ " OPTIONS( "
+ " description=\"a table with basic column types\" "
+ " ) "
+ "AS "
+ " SELECT "
+ " 17,"
+ " CAST(1234.56 AS NUMERIC),"
+ " 6.547678,"
+ " TRUE,"
+ " \"String field value\","
+ " b\"абвгд\"",
DATASET, tableName);
RunQueryJobAndExpectSuccess(QueryJobConfiguration.newBuilder(createTableStatement).build());
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ DATASET,
/* tableId = */ tableName);
List<GenericData.Record> rows = ReadAllRows(/* table = */ table, /* filter = */ null);
assertEquals("Actual rows read: " + rows.toString(), 1, rows.size());
GenericData.Record record = rows.get(0);
Schema avroSchema = record.getSchema();
String actualSchemaMessage =
String.format(
"Unexpected schema. Actual schema:%n%s", avroSchema.toString(/* pretty = */ true));
String rowAssertMessage = String.format("Row not matching expectations: %s", record.toString());
assertEquals(actualSchemaMessage, Schema.Type.RECORD, avroSchema.getType());
assertEquals(actualSchemaMessage, "__root__", avroSchema.getName());
assertEquals(actualSchemaMessage, 6, avroSchema.getFields().size());
assertEquals(
actualSchemaMessage, Schema.Type.LONG, avroSchema.getField("int_field").schema().getType());
assertEquals(rowAssertMessage, 17L, (long) record.get("int_field"));
assertEquals(
actualSchemaMessage,
Schema.Type.BYTES,
avroSchema.getField("num_field").schema().getType());
assertEquals(
actualSchemaMessage,
LogicalTypes.decimal(/* precision = */ 38, /* scale = */ 9),
avroSchema.getField("num_field").schema().getLogicalType());
BigDecimal actual_num_field =
new Conversions.DecimalConversion()
.fromBytes(
(ByteBuffer) record.get("num_field"),
avroSchema,
avroSchema.getField("num_field").schema().getLogicalType());
assertEquals(
rowAssertMessage,
BigDecimal.valueOf(/* unscaledVal = */ 1_234_560_000_000L, /* scale = */ 9),
actual_num_field);
assertEquals(
actualSchemaMessage,
Schema.Type.DOUBLE,
avroSchema.getField("float_field").schema().getType());
assertEquals(
rowAssertMessage,
/* expected = */ 6.547678d,
/* actual = */ (double) record.get("float_field"),
/* delta = */ 0.0001);
assertEquals(
actualSchemaMessage,
Schema.Type.BOOLEAN,
avroSchema.getField("bool_field").schema().getType());
assertEquals(rowAssertMessage, true, record.get("bool_field"));
assertEquals(
actualSchemaMessage,
Schema.Type.STRING,
avroSchema.getField("str_field").schema().getType());
assertEquals(rowAssertMessage, new Utf8("String field value"), record.get("str_field"));
assertEquals(
actualSchemaMessage,
Schema.Type.BYTES,
avroSchema.getField("bytes_field").schema().getType());
assertArrayEquals(
rowAssertMessage,
Utf8.getBytesFor("абвгд"),
((ByteBuffer) (record.get("bytes_field"))).array());
}
@Test
public void testDateAndTimeSqlTypes() throws InterruptedException, IOException {
String tableName = "test_date_and_time_sql_types";
String createTableStatement =
String.format(
" CREATE TABLE %s.%s "
+ " (date_field DATE NOT NULL,"
+ " datetime_field DATETIME NOT NULL,"
+ " time_field TIME NOT NULL,"
+ " timestamp_field TIMESTAMP NOT NULL)"
+ " OPTIONS( "
+ " description=\"a table with date and time column types\" "
+ " ) "
+ "AS "
+ " SELECT "
+ " CAST(\"2019-05-31\" AS DATE),"
+ " CAST(\"2019-04-30 21:47:59.999999\" AS DATETIME),"
+ " CAST(\"21:47:59.999999\" AS TIME),"
+ " CAST(\"2019-04-30 19:24:19.123456 UTC\" AS TIMESTAMP)",
DATASET, tableName);
RunQueryJobAndExpectSuccess(QueryJobConfiguration.newBuilder(createTableStatement).build());
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ DATASET,
/* tableId = */ tableName);
List<GenericData.Record> rows = ReadAllRows(/* table = */ table, /* filter = */ null);
assertEquals("Actual rows read: " + rows.toString(), 1, rows.size());
GenericData.Record record = rows.get(0);
Schema avroSchema = record.getSchema();
String actualSchemaMessage =
String.format(
"Unexpected schema. Actual schema:%n%s", avroSchema.toString(/* pretty = */ true));
String rowAssertMessage = String.format("Row not matching expectations: %s", record.toString());
assertEquals(actualSchemaMessage, Schema.Type.RECORD, avroSchema.getType());
assertEquals(actualSchemaMessage, "__root__", avroSchema.getName());
assertEquals(actualSchemaMessage, 4, avroSchema.getFields().size());
assertEquals(
actualSchemaMessage, Schema.Type.INT, avroSchema.getField("date_field").schema().getType());
assertEquals(
actualSchemaMessage,
LogicalTypes.date(),
avroSchema.getField("date_field").schema().getLogicalType());
assertEquals(
rowAssertMessage,
LocalDate.of(/* year = */ 2019, /* month = */ 5, /* dayOfMonth = */ 31),
LocalDate.ofEpochDay((int) record.get("date_field")));
assertEquals(
actualSchemaMessage,
Schema.Type.STRING,
avroSchema.getField("datetime_field").schema().getType());
assertEquals(
actualSchemaMessage,
"datetime",
avroSchema.getField("datetime_field").schema().getObjectProp("logicalType"));
assertEquals(
rowAssertMessage,
new Utf8("2019-04-30T21:47:59.999999"),
(Utf8) record.get("datetime_field"));
assertEquals(
actualSchemaMessage,
Schema.Type.LONG,
avroSchema.getField("time_field").schema().getType());
assertEquals(
actualSchemaMessage,
LogicalTypes.timeMicros(),
avroSchema.getField("time_field").schema().getLogicalType());
assertEquals(
rowAssertMessage,
LocalTime.of(
/* hour = */ 21,
/* minute = */ 47,
/* second = */ 59,
/* nanoOfSecond = */ 999_999_000),
LocalTime.ofNanoOfDay(1_000L * (long) record.get("time_field")));
assertEquals(
actualSchemaMessage,
Schema.Type.LONG,
avroSchema.getField("timestamp_field").schema().getType());
assertEquals(
actualSchemaMessage,
LogicalTypes.timestampMicros(),
avroSchema.getField("timestamp_field").schema().getLogicalType());
ZonedDateTime expected_timestamp =
ZonedDateTime.parse(
"2019-04-30T19:24:19Z", DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC))
.withNano(123_456_000);
long actual_timestamp_micros = (long) record.get("timestamp_field");
ZonedDateTime actual_timestamp =
ZonedDateTime.ofInstant(
Instant.ofEpochSecond(
/* epochSecond = */ actual_timestamp_micros / 1_000_000,
(actual_timestamp_micros % 1_000_000) * 1_000),
ZoneOffset.UTC);
assertEquals(rowAssertMessage, expected_timestamp, actual_timestamp);
}
@Test
public void testGeographySqlType() throws InterruptedException, IOException {
String tableName = "test_geography_sql_type";
String createTableStatement =
String.format(
" CREATE TABLE %s.%s "
+ " (geo_field GEOGRAPHY NOT NULL)"
+ " OPTIONS( "
+ " description=\"a table with a geography column type\" "
+ " ) "
+ "AS "
+ " SELECT ST_GEOGPOINT(1.1, 2.2)",
DATASET, tableName);
RunQueryJobAndExpectSuccess(QueryJobConfiguration.newBuilder(createTableStatement).build());
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ DATASET,
/* tableId = */ tableName);
List<GenericData.Record> rows = ReadAllRows(/* table = */ table, /* filter = */ null);
assertEquals("Actual rows read: " + rows.toString(), 1, rows.size());
GenericData.Record record = rows.get(0);
Schema avroSchema = record.getSchema();
String actualSchemaMessage =
String.format(
"Unexpected schema. Actual schema:%n%s", avroSchema.toString(/* pretty = */ true));
String rowAssertMessage = String.format("Row not matching expectations: %s", record.toString());
assertEquals(actualSchemaMessage, Schema.Type.RECORD, avroSchema.getType());
assertEquals(actualSchemaMessage, "__root__", avroSchema.getName());
assertEquals(actualSchemaMessage, 1, avroSchema.getFields().size());
assertEquals(
actualSchemaMessage,
Schema.Type.STRING,
avroSchema.getField("geo_field").schema().getType());
assertEquals(
actualSchemaMessage,
"GEOGRAPHY",
avroSchema.getField("geo_field").schema().getObjectProp("sqlType"));
assertEquals(rowAssertMessage, new Utf8("POINT(1.1 2.2)"), (Utf8) record.get("geo_field"));
}
@Test
public void testStructAndArraySqlTypes() throws InterruptedException, IOException {
String tableName = "test_struct_and_array_sql_types";
String createTableStatement =
String.format(
" CREATE TABLE %s.%s (array_field ARRAY<INT64>, struct_field STRUCT<int_field INT64"
+ " NOT NULL, str_field STRING NOT NULL> NOT NULL) OPTIONS( description=\"a"
+ " table with array and time column types\" ) AS SELECT [1, 2, 3], "
+ " (10, 'abc')",
DATASET, tableName);
RunQueryJobAndExpectSuccess(QueryJobConfiguration.newBuilder(createTableStatement).build());
String table =
BigQueryResource.FormatTableResource(
/* projectId = */ ServiceOptions.getDefaultProjectId(),
/* datasetId = */ DATASET,
/* tableId = */ tableName);
List<GenericData.Record> rows = ReadAllRows(/* table = */ table, /* filter = */ null);
assertEquals("Actual rows read: " + rows.toString(), 1, rows.size());
GenericData.Record record = rows.get(0);
Schema avroSchema = record.getSchema();
String actualSchemaMessage =
String.format(
"Unexpected schema. Actual schema:%n%s", avroSchema.toString(/* pretty = */ true));
String rowAssertMessage = String.format("Row not matching expectations: %s", record.toString());
assertEquals(actualSchemaMessage, Schema.Type.RECORD, avroSchema.getType());
assertEquals(actualSchemaMessage, "__root__", avroSchema.getName());
assertEquals(actualSchemaMessage, 2, avroSchema.getFields().size());
assertEquals(
actualSchemaMessage,
Schema.Type.ARRAY,
avroSchema.getField("array_field").schema().getType());
assertEquals(
actualSchemaMessage,
Schema.Type.LONG,
avroSchema.getField("array_field").schema().getElementType().getType());
assertArrayEquals(
rowAssertMessage,
new Long[] {1L, 2L, 3L},
((GenericData.Array<Long>) record.get("array_field")).toArray(new Long[0]));
// Validate the STRUCT field and its members.
Schema structSchema = avroSchema.getField("struct_field").schema();
assertEquals(actualSchemaMessage, Schema.Type.RECORD, structSchema.getType());
GenericData.Record structRecord = (GenericData.Record) record.get("struct_field");
assertEquals(
actualSchemaMessage,
Schema.Type.LONG,
structSchema.getField("int_field").schema().getType());
assertEquals(rowAssertMessage, 10L, (long) structRecord.get("int_field"));
assertEquals(
actualSchemaMessage,
Schema.Type.STRING,
structSchema.getField("str_field").schema().getType());
assertEquals(rowAssertMessage, new Utf8("abc"), structRecord.get("str_field"));
}
/**
* Reads to the specified row offset within the stream. If the stream does not have the desired
* rows to read, it will read all of them.
*
* @param readStream
* @param rowOffset
* @return the number of requested rows to skip or the total rows read if stream had less rows.
*/
private long ReadStreamToOffset(ReadStream readStream, long rowOffset) {
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder().setReadStream(readStream.getName()).build();
long rowCount = 0;
ServerStream<ReadRowsResponse> serverStream = client.readRowsCallable().call(readRowsRequest);
Iterator<ReadRowsResponse> responseIterator = serverStream.iterator();
while (responseIterator.hasNext()) {
ReadRowsResponse response = responseIterator.next();
rowCount += response.getRowCount();
if (rowCount >= rowOffset) {
return rowOffset;
}
}
return rowCount;
}
/**
* Reads all the rows from the specified table.
*
* <p>For every row, the consumer is called for processing.
*
* @param table
* @param snapshotInMillis Optional. If specified, all rows up to timestamp will be returned.
* @param filter Optional. If specified, it will be used to restrict returned data.
* @param consumer that receives all Avro rows.
* @throws IOException
*/
private void ProcessRowsAtSnapshot(
String table, Long snapshotInMillis, String filter, AvroRowConsumer consumer)
throws IOException {
Preconditions.checkNotNull(table);
Preconditions.checkNotNull(consumer);
CreateReadSessionRequest.Builder createSessionRequestBuilder =
CreateReadSessionRequest.newBuilder()
.setParent(parentProjectId)
.setMaxStreamCount(1)
.setReadSession(
ReadSession.newBuilder().setTable(table).setDataFormat(DataFormat.AVRO).build());
if (snapshotInMillis != null) {
Timestamp snapshotTimestamp =
Timestamp.newBuilder()
.setSeconds(snapshotInMillis / 1_000)
.setNanos((int) ((snapshotInMillis % 1000) * 1000000))
.build();
createSessionRequestBuilder
.getReadSessionBuilder()
.setTableModifiers(
TableModifiers.newBuilder().setSnapshotTime(snapshotTimestamp).build());
}
if (filter != null && !filter.isEmpty()) {
createSessionRequestBuilder
.getReadSessionBuilder()
.setReadOptions(TableReadOptions.newBuilder().setRowRestriction(filter).build());
}
ReadSession session = client.createReadSession(createSessionRequestBuilder.build());
assertEquals(
String.format(
"Did not receive expected number of streams for table '%s' CreateReadSession"
+ " response:%n%s",
table, session.toString()),
1,
session.getStreamsCount());
ReadRowsRequest readRowsRequest =
ReadRowsRequest.newBuilder().setReadStream(session.getStreams(0).getName()).build();
SimpleRowReader reader =
new SimpleRowReader(new Schema.Parser().parse(session.getAvroSchema().getSchema()));
ServerStream<ReadRowsResponse> stream = client.readRowsCallable().call(readRowsRequest);
for (ReadRowsResponse response : stream) {
reader.processRows(response.getAvroRows(), consumer);
}
}
/**
* Reads all the rows from the specified table and returns a list as generic Avro records.
*
* @param table
* @param filter Optional. If specified, it will be used to restrict returned data.
* @return
*/
List<GenericData.Record> ReadAllRows(String table, String filter) throws IOException {
final List<GenericData.Record> rows = new ArrayList<>();
ProcessRowsAtSnapshot(
/* table = */ table,
/* snapshotInMillis = */ null,
/* filter = */ filter,
new AvroRowConsumer() {
@Override
public void accept(GenericData.Record record) {
// clone the record since that reference will be reused by the reader.
rows.add(new GenericRecordBuilder(record).build());
}
});
return rows;
}
/**
* Runs a query job with WRITE_APPEND disposition to the destination table and returns the
* successfully completed job.
*
* @param destinationTableId
* @param query
* @return
* @throws InterruptedException
*/
private Job RunQueryAppendJobAndExpectSuccess(TableId destinationTableId, String query)
throws InterruptedException {
return RunQueryJobAndExpectSuccess(
QueryJobConfiguration.newBuilder(query)
.setDestinationTable(destinationTableId)
.setUseQueryCache(false)
.setUseLegacySql(false)
.setWriteDisposition(WriteDisposition.WRITE_APPEND)
.build());
}
/**
* Runs a query job with provided configuration and returns the successfully completed job.
*
* @param configuration
* @return
* @throws InterruptedException
*/
private Job RunQueryJobAndExpectSuccess(QueryJobConfiguration configuration)
throws InterruptedException {
Job job = bigquery.create(JobInfo.of(configuration));
Job completedJob =
job.waitFor(
RetryOption.initialRetryDelay(Duration.ofSeconds(1)),
RetryOption.totalTimeout(Duration.ofMinutes(1)));
assertNotNull(completedJob);
assertNull(
/* message = */ "Received a job status that is not a success: "
+ completedJob.getStatus().toString(),
/* object = */ completedJob.getStatus().getError());
return completedJob;
}
}