Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build CreateWriteStream lazily in BigQuery #20857

Merged
merged 1 commit into from
Feb 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;

import static com.google.cloud.bigquery.storage.v1.WriteStream.Type.COMMITTED;
import static com.google.common.base.Preconditions.checkArgument;
Expand All @@ -48,7 +49,8 @@ public class BigQueryPageSink
implements ConnectorPageSink
{
private final BigQueryWriteClient client;
private final WriteStream writeStream;
private final CreateWriteStreamRequest createWriteStreamRequest;
private final AtomicReference<WriteStream> writeStream = new AtomicReference<>();
private final List<String> columnNames;
private final List<Type> columnTypes;
private final ConnectorPageSinkId pageSinkId;
Expand Down Expand Up @@ -78,11 +80,10 @@ public BigQueryPageSink(
.orElseGet(remoteTableName::toTableName);
// TODO: Consider using PENDING mode
WriteStream stream = WriteStream.newBuilder().setType(COMMITTED).build();
CreateWriteStreamRequest createWriteStreamRequest = CreateWriteStreamRequest.newBuilder()
createWriteStreamRequest = CreateWriteStreamRequest.newBuilder()
.setParent(tableName.toString())
.setWriteStream(stream)
.build();
this.writeStream = client.createWriteStream(createWriteStreamRequest);
}

@Override
Expand All @@ -104,7 +105,8 @@ public CompletableFuture<?> appendPage(Page page)

private void insertWithCommitted(JSONArray batch)
{
try (JsonStreamWriter writer = JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema(), client).build()) {
WriteStream stream = writeStream.updateAndGet(this::getOrCreateWriteStream);
try (JsonStreamWriter writer = JsonStreamWriter.newBuilder(stream.getName(), stream.getTableSchema(), client).build()) {
ApiFuture<AppendRowsResponse> future = writer.append(batch);
AppendRowsResponse response = future.get(); // Throw error
if (response.hasError()) {
Expand All @@ -116,6 +118,14 @@ private void insertWithCommitted(JSONArray batch)
}
}

private WriteStream getOrCreateWriteStream(WriteStream current)
{
if (current == null) {
return client.createWriteStream(createWriteStreamRequest);
}
return current;
}

@Override
public CompletableFuture<Collection<Slice>> finish()
{
Expand Down
Loading