Skip to content

Add BigQueryIO support for clone table creation#38883

Open
lalitx17 wants to merge 3 commits into
apache:masterfrom
lalitx17:bigquery-clone-table
Open

Add BigQueryIO support for clone table creation#38883
lalitx17 wants to merge 3 commits into
apache:masterfrom
lalitx17:bigquery-clone-table

Conversation

@lalitx17

Copy link
Copy Markdown
Contributor

This introduces BigQueryIO.Write.withCloneFrom(...) for static clone sources and DynamicDestinations.getCloneSource(...) for dynamic destinations. When a destination table does not exist and CREATE_IF_NEEDED is used, BigQueryIO can now create it with a BigQuery copy job using operationType = CLONE.

addresses #38310


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@lalitx17 lalitx17 marked this pull request as ready for review June 10, 2026 23:02
Copilot AI review requested due to automatic review settings June 10, 2026 23:02
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces support for creating BigQuery destination tables by cloning an existing source table. By leveraging BigQuery's CLONE operation type, users can now initialize new tables more efficiently when CREATE_IF_NEEDED is specified. The changes include new API methods for both static and dynamic destinations, along with the necessary backend logic to handle the copy jobs and validation.

Highlights

  • API Enhancements: Added withCloneFrom to BigQueryIO.Write and getCloneSource to DynamicDestinations to allow users to specify a source table for cloning when creating new destination tables.
  • Table Creation Logic: Implemented CLONE operation support in CreateTableHelpers using BigQuery copy jobs, enabling efficient table initialization when CREATE_IF_NEEDED is enabled.
  • Validation and Safety: Added strict validation to ensure that cloneSource is mutually exclusive with schema-based table creation, preventing configuration conflicts.
  • Serialization Support: Updated BigQueryIOTranslation to support serialization of the new clone source configuration, ensuring compatibility with pipeline translation.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds support for creating missing BigQuery destination tables by cloning an existing “base” table, including plumbing through dynamic destinations and transform translation.

Changes:

  • Introduces withCloneFrom(...)/getCloneSource(...) API surface and wires clone source through table-creation helpers.
  • Implements clone-table creation via BigQuery copy jobs with operation type CLONE.
  • Adds/updates translation + unit tests validating clone creation and config round-tripping.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOWriteTest.java Adds tests covering clone-table creation (static + dynamic destinations) and builder plumbing.
sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslationTest.java Extends translation round-trip tests to include clone source field.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/WriteTables.java Creates clone tables for file-load writes when a clone source is present.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/UpdateSchemaDestination.java Ensures clone-table creation occurs during schema update path for dynamic destinations.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/StorageApiWritesShardedRecords.java Passes clone source supplier into table creation for Storage API sharded writes.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/StorageApiWriteUnshardedRecords.java Passes clone source supplier into table creation for Storage API unsharded writes.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java Adds clone-source delegation/wrappers and falls back to clone-source table metadata/schema.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinations.java Adds getCloneSource(...) extension point to dynamic destinations.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTables.java Threads clone source into possiblyCreateTable(...) calls.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java Adds clone-table creation via copy job and expands table-creation metadata handling.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryResourceNaming.java Introduces JobType.CLONE for clone job naming.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslation.java Adds clone source field to transform payload schema and (de)serialization.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java Adds withCloneFrom(...) API and validation + wiring into dynamic destinations and schema checks.
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BatchLoads.java Uses the pipeline’s createDisposition for load jobs (enabling creation when cloning).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +286 to +288
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
Comment on lines +299 to +301
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Comment on lines +311 to +313
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
@Nullable String kmsKey,
String tableSpec)
throws Exception {
TableReference source = withDefaultProject(options, cloneSource);
Comment on lines +270 to +273
String jobProjectId = destination.getProjectId();
String bqLocation =
BigQueryHelpers.getDatasetLocation(
datasetService, destination.getProjectId(), destination.getDatasetId());
ConstantCloneSourceDestinations(
DynamicDestinations<T, DestinationT> inner, ValueProvider<String> jsonCloneSource) {
super(inner);
Preconditions.checkArgumentNotNull(jsonCloneSource, "jsonCloneSource can not be null");
@Override
public TableReference getCloneSource(DestinationT destination) {
String jsonCloneSource = this.jsonCloneSource.get();
checkArgument(jsonCloneSource != null, "jsonCloneSource can not be null");
Comment on lines +279 to +283
JobReference jobRef =
new JobReference()
.setProjectId(jobProjectId)
.setJobId(jobId.getJobId())
.setLocation(bqLocation);
Comment on lines +292 to +296
JobReference jobRef =
new JobReference()
.setProjectId(jobProjectId)
.setJobId(jobId.getJobId())
.setLocation(bqLocation);
Comment on lines +304 to +308
JobReference jobRef =
new JobReference()
.setProjectId(jobProjectId)
.setJobId(jobId.getJobId())
.setLocation(bqLocation);

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the ability to create missing BigQuery destination tables as clones of a specified base table using the new withCloneFrom option. The changes span BigQueryIO, DynamicDestinations, CreateTableHelpers, and related translation and test classes. The review feedback highlights several critical improvements: ensuring that the clone source table reference is fully qualified with a project ID (defaulting to the destination's project ID if missing) to prevent potential NullPointerException or API errors, restoring the interrupted thread status when catching InterruptedException in CreateTableHelpers, and simplifying the validation check for mutually exclusive table creation arguments in BigQueryIO using Java 8 Streams.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +515 to +520
if (tableToMatch == null) {
@Nullable TableReference cloneSource = super.getCloneSource(destination);
if (cloneSource != null) {
tableToMatch = getBigQueryTable(cloneSource);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If the clone source table reference does not specify a project ID (e.g., if it was parsed from a table spec like dataset.table), calling getBigQueryTable(cloneSource) directly can fail with a NullPointerException or API error because the project ID is missing. We should default the project ID to the destination table's project ID to ensure it is fully qualified before querying.

      if (tableToMatch == null) {
        @Nullable TableReference cloneSource = super.getCloneSource(destination);
        if (cloneSource != null) {
          TableReference cloneSourceWithProject = cloneSource.clone();
          if (cloneSourceWithProject.getProjectId() == null || cloneSourceWithProject.getProjectId().isEmpty()) {
            cloneSourceWithProject.setProjectId(wrappedDestination.getTableReference().getProjectId());
          }
          tableToMatch = getBigQueryTable(cloneSourceWithProject);
        }
      }

Comment on lines +544 to +552
@Nullable TableReference cloneSource = super.getCloneSource(destination);
if (cloneSource != null) {
@Nullable Table cloneSourceTable = getBigQueryTable(cloneSource);
if (cloneSourceTable != null
&& cloneSourceTable.getSchema() != null
&& !cloneSourceTable.getSchema().isEmpty()) {
return cloneSourceTable.getSchema();
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Similar to the above, if the clone source table reference does not specify a project ID, calling getBigQueryTable(cloneSource) can fail. We should default the project ID to the destination table's project ID to ensure it is fully qualified.

        @Nullable TableReference cloneSource = super.getCloneSource(destination);
        if (cloneSource != null) {
          TableReference cloneSourceWithProject = cloneSource.clone();
          if (cloneSourceWithProject.getProjectId() == null || cloneSourceWithProject.getProjectId().isEmpty()) {
            cloneSourceWithProject.setProjectId(super.getTable(destination).getTableReference().getProjectId());
          }
          @Nullable Table cloneSourceTable = getBigQueryTable(cloneSourceWithProject);
          if (cloneSourceTable != null
              && cloneSourceTable.getSchema() != null
              && !cloneSourceTable.getSchema().isEmpty()) {
            return cloneSourceTable.getSchema();
          }
        }

Comment on lines +284 to +288
try {
jobService.startCopyJob(jobRef, copyConfig);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When catching InterruptedException, it is a standard Java best practice to restore the interrupted status of the thread by calling Thread.currentThread().interrupt(). This ensures that higher-level call stacks or the runner are aware of the cancellation/interruption.

Suggested change
try {
jobService.startCopyJob(jobRef, copyConfig);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
try {
jobService.startCopyJob(jobRef, copyConfig);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}

Comment on lines +297 to +301
try {
return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Restore the interrupted status of the thread when catching InterruptedException to ensure the thread's interrupted state is preserved.

                try {
                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
                } catch (InterruptedException e) {
                  Thread.currentThread().interrupt();
                  throw new RuntimeException(e);
                }

Comment on lines +309 to +313
try {
return jobService.getJob(jobRef);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Restore the interrupted status of the thread when catching InterruptedException to ensure the thread's interrupted state is preserved.

                try {
                  return jobService.getJob(jobRef);
                } catch (IOException e) {
                  throw new RuntimeException(e);
                } catch (InterruptedException e) {
                  Thread.currentThread().interrupt();
                  throw new RuntimeException(e);
                }

Comment on lines +3812 to +3820
List<?> allTableCreationMetadataArgs =
Lists.newArrayList(getJsonSchema(), getSchemaFromView(), getJsonCloneSourceTableRef());
checkArgument(
2
> Iterables.size(
allTableCreationMetadataArgs.stream()
.filter(Predicates.notNull()::apply)
.collect(Collectors.toList())),
"No more than one of jsonSchema, schemaFromView, or cloneSource may be set");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This check can be simplified and made more readable by using Java 8 Streams directly, avoiding the creation of unnecessary Guava lists and iterators.

      long activeCreationMetadataCount = java.util.stream.Stream.of(getJsonSchema(), getSchemaFromView(), getJsonCloneSourceTableRef())
          .filter(x -> x != null)
          .count();
      checkArgument(
          activeCreationMetadataCount <= 1,
          "No more than one of jsonSchema, schemaFromView, or cloneSource may be set");

@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants