Search in sources :

Example 1 with CreateReadSessionRequest

use of com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest in project beam by apache.

the class BigQueryStorageSourceBase method split.

@Override
public List<BigQueryStorageStreamSource<T>> split(long desiredBundleSizeBytes, PipelineOptions options) throws Exception {
    BigQueryOptions bqOptions = options.as(BigQueryOptions.class);
    Table targetTable = getTargetTable(bqOptions);
    ReadSession.Builder readSessionBuilder = ReadSession.newBuilder();
    if (targetTable != null) {
        readSessionBuilder.setTable(BigQueryHelpers.toTableResourceName(targetTable.getTableReference()));
    } else {
        // If the table does not exist targetTable will be null.
        // Construct the table id if we can generate it. For error recording/logging.
        @Nullable String tableReferenceId = getTargetTableId(bqOptions);
        if (tableReferenceId != null) {
            readSessionBuilder.setTable(tableReferenceId);
        }
    }
    if (selectedFieldsProvider != null || rowRestrictionProvider != null) {
        ReadSession.TableReadOptions.Builder tableReadOptionsBuilder = ReadSession.TableReadOptions.newBuilder();
        if (selectedFieldsProvider != null) {
            tableReadOptionsBuilder.addAllSelectedFields(selectedFieldsProvider.get());
        }
        if (rowRestrictionProvider != null) {
            tableReadOptionsBuilder.setRowRestriction(rowRestrictionProvider.get());
        }
        readSessionBuilder.setReadOptions(tableReadOptionsBuilder);
    }
    if (format != null) {
        readSessionBuilder.setDataFormat(format);
    }
    int streamCount = 0;
    if (desiredBundleSizeBytes > 0) {
        long tableSizeBytes = (targetTable != null) ? targetTable.getNumBytes() : 0;
        streamCount = (int) Math.min(tableSizeBytes / desiredBundleSizeBytes, MAX_SPLIT_COUNT);
    }
    streamCount = Math.max(streamCount, MIN_SPLIT_COUNT);
    CreateReadSessionRequest createReadSessionRequest = CreateReadSessionRequest.newBuilder().setParent(BigQueryHelpers.toProjectResourceName(bqOptions.getBigQueryProject() == null ? bqOptions.getProject() : bqOptions.getBigQueryProject())).setReadSession(readSessionBuilder).setMaxStreamCount(streamCount).build();
    ReadSession readSession;
    try (StorageClient client = bqServices.getStorageClient(bqOptions)) {
        readSession = client.createReadSession(createReadSessionRequest);
        LOG.info("Sent BigQuery Storage API CreateReadSession request '{}'; received response '{}'.", createReadSessionRequest, readSession);
    }
    if (readSession.getStreamsList().isEmpty()) {
        // The underlying table is empty or all rows have been pruned.
        return ImmutableList.of();
    }
    Schema sessionSchema;
    if (readSession.getDataFormat() == DataFormat.ARROW) {
        org.apache.arrow.vector.types.pojo.Schema schema = ArrowConversion.arrowSchemaFromInput(readSession.getArrowSchema().getSerializedSchema().newInput());
        org.apache.beam.sdk.schemas.Schema beamSchema = ArrowConversion.ArrowSchemaTranslator.toBeamSchema(schema);
        sessionSchema = AvroUtils.toAvroSchema(beamSchema);
    } else if (readSession.getDataFormat() == DataFormat.AVRO) {
        sessionSchema = new Schema.Parser().parse(readSession.getAvroSchema().getSchema());
    } else {
        throw new IllegalArgumentException("data is not in a supported dataFormat: " + readSession.getDataFormat());
    }
    TableSchema trimmedSchema = BigQueryAvroUtils.trimBigQueryTableSchema(targetTable.getSchema(), sessionSchema);
    List<BigQueryStorageStreamSource<T>> sources = Lists.newArrayList();
    for (ReadStream readStream : readSession.getStreamsList()) {
        sources.add(BigQueryStorageStreamSource.create(readSession, readStream, trimmedSchema, parseFn, outputCoder, bqServices));
    }
    return ImmutableList.copyOf(sources);
}
Also used : TableSchema(com.google.api.services.bigquery.model.TableSchema) Schema(org.apache.avro.Schema) TableSchema(com.google.api.services.bigquery.model.TableSchema) ReadStream(com.google.cloud.bigquery.storage.v1.ReadStream) Table(com.google.api.services.bigquery.model.Table) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) Nullable(org.checkerframework.checker.nullness.qual.Nullable) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest)

Example 2 with CreateReadSessionRequest

use of com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest in project beam by apache.

the class BigQueryIOStorageReadTest method testReadFromBigQueryIO.

@Test
public void testReadFromBigQueryIO() throws Exception {
    fakeDatasetService.createDataset("foo.com:project", "dataset", "", "", null);
    TableReference tableRef = BigQueryHelpers.parseTableSpec("foo.com:project:dataset.table");
    Table table = new Table().setTableReference(tableRef).setNumBytes(10L).setSchema(TABLE_SCHEMA);
    fakeDatasetService.createTable(table);
    CreateReadSessionRequest expectedCreateReadSessionRequest = CreateReadSessionRequest.newBuilder().setParent("projects/project-id").setReadSession(ReadSession.newBuilder().setTable("projects/foo.com:project/datasets/dataset/tables/table").setDataFormat(DataFormat.AVRO)).setMaxStreamCount(10).build();
    ReadSession readSession = ReadSession.newBuilder().setName("readSessionName").setAvroSchema(AvroSchema.newBuilder().setSchema(AVRO_SCHEMA_STRING)).addStreams(ReadStream.newBuilder().setName("streamName")).setDataFormat(DataFormat.AVRO).build();
    ReadRowsRequest expectedReadRowsRequest = ReadRowsRequest.newBuilder().setReadStream("streamName").build();
    List<GenericRecord> records = Lists.newArrayList(createRecord("A", 1, AVRO_SCHEMA), createRecord("B", 2, AVRO_SCHEMA), createRecord("C", 3, AVRO_SCHEMA), createRecord("D", 4, AVRO_SCHEMA));
    List<ReadRowsResponse> readRowsResponses = Lists.newArrayList(createResponse(AVRO_SCHEMA, records.subList(0, 2), 0.0, 0.50), createResponse(AVRO_SCHEMA, records.subList(2, 4), 0.5, 0.75));
    StorageClient fakeStorageClient = mock(StorageClient.class, withSettings().serializable());
    when(fakeStorageClient.createReadSession(expectedCreateReadSessionRequest)).thenReturn(readSession);
    when(fakeStorageClient.readRows(expectedReadRowsRequest, "")).thenReturn(new FakeBigQueryServerStream<>(readRowsResponses));
    PCollection<KV<String, Long>> output = p.apply(BigQueryIO.read(new ParseKeyValue()).from("foo.com:project:dataset.table").withMethod(Method.DIRECT_READ).withFormat(DataFormat.AVRO).withTestServices(new FakeBigQueryServices().withDatasetService(fakeDatasetService).withStorageClient(fakeStorageClient)));
    PAssert.that(output).containsInAnyOrder(ImmutableList.of(KV.of("A", 1L), KV.of("B", 2L), KV.of("C", 3L), KV.of("D", 4L)));
    p.run();
}
Also used : Table(com.google.api.services.bigquery.model.Table) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) ReadRowsRequest(com.google.cloud.bigquery.storage.v1.ReadRowsRequest) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) KV(org.apache.beam.sdk.values.KV) TableReference(com.google.api.services.bigquery.model.TableReference) ReadRowsResponse(com.google.cloud.bigquery.storage.v1.ReadRowsResponse) FakeBigQueryServices(org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices) GenericRecord(org.apache.avro.generic.GenericRecord) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest) Test(org.junit.Test)

Example 3 with CreateReadSessionRequest

use of com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest in project beam by apache.

the class BigQueryIOStorageReadTest method testTableSourceInitialSplit_WithDefaultProject.

@Test
public void testTableSourceInitialSplit_WithDefaultProject() throws Exception {
    fakeDatasetService.createDataset("project-id", "dataset", "", "", null);
    TableReference tableRef = BigQueryHelpers.parseTableSpec("project-id:dataset.table");
    Table table = new Table().setTableReference(tableRef).setNumBytes(1024L * 1024L).setSchema(TABLE_SCHEMA);
    fakeDatasetService.createTable(table);
    CreateReadSessionRequest expectedRequest = CreateReadSessionRequest.newBuilder().setParent("projects/project-id").setReadSession(ReadSession.newBuilder().setTable("projects/project-id/datasets/dataset/tables/table")).setMaxStreamCount(1024).build();
    ReadSession.Builder builder = ReadSession.newBuilder().setAvroSchema(AvroSchema.newBuilder().setSchema(AVRO_SCHEMA_STRING)).setDataFormat(DataFormat.AVRO);
    for (int i = 0; i < 50; i++) {
        builder.addStreams(ReadStream.newBuilder().setName("stream-" + i));
    }
    StorageClient fakeStorageClient = mock(StorageClient.class);
    when(fakeStorageClient.createReadSession(expectedRequest)).thenReturn(builder.build());
    BigQueryStorageTableSource<TableRow> tableSource = BigQueryStorageTableSource.create(ValueProvider.StaticValueProvider.of(BigQueryHelpers.parseTableSpec("dataset.table")), null, null, new TableRowParser(), TableRowJsonCoder.of(), new FakeBigQueryServices().withDatasetService(fakeDatasetService).withStorageClient(fakeStorageClient));
    List<? extends BoundedSource<TableRow>> sources = tableSource.split(1024L, options);
    assertEquals(50L, sources.size());
}
Also used : TableReference(com.google.api.services.bigquery.model.TableReference) Table(com.google.api.services.bigquery.model.Table) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) TableRow(com.google.api.services.bigquery.model.TableRow) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) FakeBigQueryServices(org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest) TableRowParser(org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser) Test(org.junit.Test)

Example 4 with CreateReadSessionRequest

use of com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest in project beam by apache.

the class BigQueryIOStorageReadTest method testTableSourceInitialSplit_EmptyTable.

@Test
public void testTableSourceInitialSplit_EmptyTable() throws Exception {
    fakeDatasetService.createDataset("foo.com:project", "dataset", "", "", null);
    TableReference tableRef = BigQueryHelpers.parseTableSpec("foo.com:project:dataset.table");
    Table table = new Table().setTableReference(tableRef).setNumBytes(1024L * 1024L).setSchema(new TableSchema());
    fakeDatasetService.createTable(table);
    CreateReadSessionRequest expectedRequest = CreateReadSessionRequest.newBuilder().setParent("projects/project-id").setReadSession(ReadSession.newBuilder().setTable("projects/foo.com:project/datasets/dataset/tables/table")).setMaxStreamCount(1024).build();
    ReadSession emptyReadSession = ReadSession.newBuilder().build();
    StorageClient fakeStorageClient = mock(StorageClient.class);
    when(fakeStorageClient.createReadSession(expectedRequest)).thenReturn(emptyReadSession);
    BigQueryStorageTableSource<TableRow> tableSource = BigQueryStorageTableSource.create(ValueProvider.StaticValueProvider.of(tableRef), null, null, new TableRowParser(), TableRowJsonCoder.of(), new FakeBigQueryServices().withDatasetService(fakeDatasetService).withStorageClient(fakeStorageClient));
    List<? extends BoundedSource<TableRow>> sources = tableSource.split(1024L, options);
    assertTrue(sources.isEmpty());
}
Also used : TableReference(com.google.api.services.bigquery.model.TableReference) Table(com.google.api.services.bigquery.model.Table) TableSchema(com.google.api.services.bigquery.model.TableSchema) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) TableRow(com.google.api.services.bigquery.model.TableRow) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) FakeBigQueryServices(org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest) TableRowParser(org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser) Test(org.junit.Test)

Example 5 with CreateReadSessionRequest

use of com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest in project beam by apache.

the class BigQueryIOStorageQueryTest method testQuerySourceInitialSplitWithBigQueryProject_EmptyResult.

@Test
@ProjectOverride
public void testQuerySourceInitialSplitWithBigQueryProject_EmptyResult() throws Exception {
    TableReference sourceTableRef = BigQueryHelpers.parseTableSpec("bigquery-project-id:dataset.table");
    fakeDatasetService.createDataset(sourceTableRef.getProjectId(), sourceTableRef.getDatasetId(), "asia-northeast1", "Fake plastic tree^H^H^H^Htables", null);
    fakeDatasetService.createTable(new Table().setTableReference(sourceTableRef).setLocation("asia-northeast1"));
    Table queryResultTable = new Table().setSchema(TABLE_SCHEMA).setNumBytes(0L);
    String encodedQuery = FakeBigQueryServices.encodeQueryResult(queryResultTable);
    fakeJobService.expectDryRunQuery(options.getBigQueryProject(), encodedQuery, new JobStatistics().setQuery(new JobStatistics2().setTotalBytesProcessed(1024L * 1024L).setReferencedTables(ImmutableList.of(sourceTableRef))));
    String stepUuid = "testStepUuid";
    TableReference tempTableReference = createTempTableReference(options.getBigQueryProject(), BigQueryResourceNaming.createJobIdPrefix(options.getJobName(), stepUuid, JobType.QUERY), Optional.empty());
    CreateReadSessionRequest expectedRequest = CreateReadSessionRequest.newBuilder().setParent("projects/" + options.getBigQueryProject()).setReadSession(ReadSession.newBuilder().setTable(BigQueryHelpers.toTableResourceName(tempTableReference)).setDataFormat(DataFormat.AVRO)).setMaxStreamCount(10).build();
    ReadSession emptyReadSession = ReadSession.newBuilder().build();
    StorageClient fakeStorageClient = mock(StorageClient.class);
    when(fakeStorageClient.createReadSession(expectedRequest)).thenReturn(emptyReadSession);
    BigQueryStorageQuerySource<TableRow> querySource = BigQueryStorageQuerySource.create(stepUuid, ValueProvider.StaticValueProvider.of(encodedQuery), /* flattenResults = */
    true, /* useLegacySql = */
    true, /* priority = */
    QueryPriority.BATCH, /* location = */
    null, /* queryTempDataset = */
    null, /* kmsKey = */
    null, DataFormat.AVRO, new TableRowParser(), TableRowJsonCoder.of(), new FakeBigQueryServices().withDatasetService(fakeDatasetService).withJobService(fakeJobService).withStorageClient(fakeStorageClient));
    List<? extends BoundedSource<TableRow>> sources = querySource.split(1024L, options);
    assertTrue(sources.isEmpty());
}
Also used : JobStatistics(com.google.api.services.bigquery.model.JobStatistics) JobStatistics2(com.google.api.services.bigquery.model.JobStatistics2) Table(com.google.api.services.bigquery.model.Table) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) StorageClient(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient) ByteString(com.google.protobuf.ByteString) TableRowParser(org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser) TableReference(com.google.api.services.bigquery.model.TableReference) BigQueryResourceNaming.createTempTableReference(org.apache.beam.sdk.io.gcp.bigquery.BigQueryResourceNaming.createTempTableReference) TableRow(com.google.api.services.bigquery.model.TableRow) FakeBigQueryServices(org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest) Test(org.junit.Test)

Aggregations

CreateReadSessionRequest (com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest)14 Table (com.google.api.services.bigquery.model.Table)12 ReadSession (com.google.cloud.bigquery.storage.v1.ReadSession)12 StorageClient (org.apache.beam.sdk.io.gcp.bigquery.BigQueryServices.StorageClient)12 TableReference (com.google.api.services.bigquery.model.TableReference)11 FakeBigQueryServices (org.apache.beam.sdk.io.gcp.testing.FakeBigQueryServices)11 Test (org.junit.Test)11 TableRow (com.google.api.services.bigquery.model.TableRow)9 TableRowParser (org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser)8 ByteString (com.google.protobuf.ByteString)5 JobStatistics (com.google.api.services.bigquery.model.JobStatistics)4 JobStatistics2 (com.google.api.services.bigquery.model.JobStatistics2)4 TableSchema (com.google.api.services.bigquery.model.TableSchema)4 BigQueryResourceNaming.createTempTableReference (org.apache.beam.sdk.io.gcp.bigquery.BigQueryResourceNaming.createTempTableReference)4 ReadRowsRequest (com.google.cloud.bigquery.storage.v1.ReadRowsRequest)3 ReadRowsResponse (com.google.cloud.bigquery.storage.v1.ReadRowsResponse)3 Schema (org.apache.avro.Schema)3 TableFieldSchema (com.google.api.services.bigquery.model.TableFieldSchema)2 AvroSchema (com.google.cloud.bigquery.storage.v1.AvroSchema)2 GenericRecord (org.apache.avro.generic.GenericRecord)2