You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "lalitx17 (via GitHub)" <gi...@apache.org> on 2026/06/10 04:13:43 UTC

[PR] Add BigQueryIO support for clone table creation [beam]

lalitx17 opened a new pull request, #38883:
URL: https://github.com/apache/beam/pull/38883

   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](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](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](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5494001452

   Reminder, please take a look at this pr: @ahmedabu98 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4980665811

   Reminder, please take a look at this pr: @kennknowles 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4799509173

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @ahmedabu98 for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5355760037

   Reminder, please take a look at this pr: @chamikaramj 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5634481497

   Reminder, please take a look at this pr: @chamikaramj 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5226062797

   Reminder, please take a look at this pr: @ahmedabu98 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38883:
URL: https://github.com/apache/beam/pull/38883#discussion_r3413854579


##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,197 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference destinationWithDefaultProject = withDefaultProject(options, destination);
+    TableReference source =
+        withDefaultProject(options, cloneSource, destinationWithDefaultProject.getProjectId());
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destinationWithDefaultProject)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destinationWithDefaultProject.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService,
+            destinationWithDefaultProject.getProjectId(),
+            destinationWithDefaultProject.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destinationWithDefaultProject);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    createJobReference(jobId.getJobId(), jobProjectId, bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException e) {
+                  throw new RuntimeException(e);
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    createJobReference(jobId.getJobId(), jobProjectId, bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  throw new RuntimeException(e);
+                }
+              },

Review Comment:
   ![critical](https://www.gstatic.com/codereviewagent/critical.svg)
   
   The lambda expression for `pollJob` does not catch `IOException`. Since `jobService.pollJob` throws `IOException` (a checked exception) and `SerializableFunction.apply` does not declare any checked exceptions, this will cause a compilation failure. Please catch `IOException` and wrap it in a `RuntimeException`, similar to how it is handled in the `getJob` and `startCopyJob` lambdas.
   
   ```java
                 jobId -> {
                   JobReference jobRef = 
                       createJobReference(jobId.getJobId(), jobProjectId, bqLocation);
                   try {
                     return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
                   } catch (IOException e) {
                     throw new RuntimeException(e);
                   } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
                     throw new RuntimeException(e);
                   }
                 },
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -221,6 +227,40 @@ public String toString() {
     }
   }
 
+  /** Returns the same clone source for every table. */
+  static class ConstantCloneSourceDestinations<T, DestinationT>
+      extends DelegatingDynamicDestinations<T, DestinationT> {
+    private final ValueProvider<String> jsonCloneSource;
+    private transient @Nullable TableReference cloneSource;

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `cloneSource` field is lazily initialized in `getCloneSource` but is not marked as `volatile`. Since `DynamicDestinations` instances can be accessed concurrently by multiple worker threads, a lack of volatile/synchronization can lead to safe publication issues (e.g., another thread reading a partially constructed `TableReference` object). Marking the field as `volatile` ensures safe publication across threads.
   
   ```suggestion
       private transient volatile @Nullable TableReference cloneSource;
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -442,16 +487,12 @@ private MatchTableDynamicDestinations(
               throw new IllegalStateException("pipeline options cannot be null");
             }
             BigQueryOptions bqOptions = options.as(BigQueryOptions.class);
-            if (tableReference.getProjectId() == null) {
-              tableReference.setProjectId(
-                  bqOptions.getBigQueryProject() == null
-                      ? bqOptions.getProject()
-                      : bqOptions.getBigQueryProject());
-            }
+            TableReference tableReferenceToFetch =
+                withDefaultProject(bqOptions, tableReference, defaultProjectId);

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Use the package-private `CreateTableHelpers.withDefaultProject` helper instead of the duplicated local version to improve maintainability.
   
   ```suggestion
               TableReference tableReferenceToFetch =
                   CreateTableHelpers.withDefaultProject(bqOptions, tableReference, defaultProjectId);
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,197 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference destinationWithDefaultProject = withDefaultProject(options, destination);
+    TableReference source =
+        withDefaultProject(options, cloneSource, destinationWithDefaultProject.getProjectId());
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destinationWithDefaultProject)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destinationWithDefaultProject.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService,
+            destinationWithDefaultProject.getProjectId(),
+            destinationWithDefaultProject.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destinationWithDefaultProject);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    createJobReference(jobId.getJobId(), jobProjectId, bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException e) {
+                  throw new RuntimeException(e);
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    createJobReference(jobId.getJobId(), jobProjectId, bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  throw new RuntimeException(e);
+                }
+              },
+              jobId -> {
+                JobReference jobRef =
+                    createJobReference(jobId.getJobId(), jobProjectId, bqLocation);
+                try {
+                  return jobService.getJob(jobRef);
+                } catch (IOException e) {
+                  throw new RuntimeException(e);
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  throw new RuntimeException(e);
+                }
+              },
+              BatchLoads.DEFAULT_MAX_RETRY_JOBS,
+              jobIdPrefix);
+      cloneJob.runJob();
+      new BigQueryHelpers.PendingJobManager()
+          .addPendingJob(
+              cloneJob,
+              job -> {
+                LOG.info("Created BigQuery clone table {} from {}", tableSpec, source);
+                return null;
+              })
+          .waitForDone();
+    }
+  }
+
+  private static JobReference createJobReference(String jobId, String projectId, String location) {
+    return new JobReference().setProjectId(projectId).setJobId(jobId).setLocation(location);
+  }
+
+  private static TableReference withDefaultProject(
+      BigQueryOptions options, TableReference tableReference) {
+    return withDefaultProject(options, tableReference, null);
+  }
+
+  private static TableReference withDefaultProject(
+      BigQueryOptions options, TableReference tableReference, @Nullable String defaultProjectId) {

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `withDefaultProject` helper method is duplicated between `CreateTableHelpers` and `DynamicDestinationsHelpers`. Since both classes reside in the same package (`org.apache.beam.sdk.io.gcp.bigquery`), we can make this method package-private (by removing `private`) and reuse it in `DynamicDestinationsHelpers` to avoid code duplication.
   
   ```suggestion
     static TableReference withDefaultProject(
         BigQueryOptions options, TableReference tableReference, @Nullable String defaultProjectId) {
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -463,6 +504,25 @@ private MatchTableDynamicDestinations(
       return null;
     }
 
+    private static TableReference withDefaultProject(
+        BigQueryOptions options, TableReference tableReference, @Nullable String defaultProjectId) {
+      TableReference updated = tableReference.clone();
+      if (Strings.isNullOrEmpty(updated.getProjectId())) {
+        if (defaultProjectId != null && !defaultProjectId.isEmpty()) {
+          updated.setProjectId(defaultProjectId);
+        } else {
+          @Nullable String projectId = options.getBigQueryProject();
+          if (projectId == null || projectId.isEmpty()) {
+            projectId = options.getProject();
+          }
+          if (projectId != null && !projectId.isEmpty()) {
+            updated.setProjectId(projectId);
+          }
+        }
+      }
+      return updated;
+    }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   This `withDefaultProject` method is identical to the one in `CreateTableHelpers`. Since both classes are in the same package, we can remove this duplicated method entirely and call `CreateTableHelpers.withDefaultProject` instead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4708230316

   Assigning reviewers:
   
   R: @Abacn for label java.
   
   
   Note: If you would like to opt out of this review, comment `assign to next reviewer`.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4675514756

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


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #38883:
URL: https://github.com/apache/beam/pull/38883#discussion_r3392127956


##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }

Review Comment:
   Catching `InterruptedException` and wrapping it in `RuntimeException` clears the thread’s interrupted status, which can cause subtle issues in runners/executors. Prefer catching `InterruptedException` separately, calling `Thread.currentThread().interrupt()`, and then either rethrowing (or wrapping) so upstream cancellation behavior is preserved.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);

Review Comment:
   `cloneTable(...)` normalizes the clone source with `withDefaultProject(...)`, but it does not normalize the `destination`. If the destination `TableReference` ever lacks a project ID, `jobProjectId` and `getDatasetLocation(...)` will be computed from null, leading to invalid job refs / failures. Consider applying `withDefaultProject(...)` to `destination` at the start of `cloneTable(...)` and using the normalized reference throughout (job project id, dataset location, and copy destination).



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -221,6 +226,34 @@ public String toString() {
     }
   }
 
+  /** Returns the same clone source for every table. */
+  static class ConstantCloneSourceDestinations<T, DestinationT>
+      extends DelegatingDynamicDestinations<T, DestinationT> {
+    private final ValueProvider<String> jsonCloneSource;
+
+    ConstantCloneSourceDestinations(
+        DynamicDestinations<T, DestinationT> inner, ValueProvider<String> jsonCloneSource) {
+      super(inner);
+      Preconditions.checkArgumentNotNull(jsonCloneSource, "jsonCloneSource can not be null");

Review Comment:
   The error message uses “can not”, which should be “cannot” in standard English (and Beam messages typically use “cannot”). Updating this improves consistency and professionalism of surfaced validation errors.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);

Review Comment:
   `JobReference` construction is duplicated in each `PendingJob` lambda. Consider extracting a small helper (e.g., `jobRef(jobId, jobProjectId, bqLocation)`) to reduce duplication and make future changes (adding fields, changing location logic) less error-prone.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -221,6 +226,34 @@ public String toString() {
     }
   }
 
+  /** Returns the same clone source for every table. */
+  static class ConstantCloneSourceDestinations<T, DestinationT>
+      extends DelegatingDynamicDestinations<T, DestinationT> {
+    private final ValueProvider<String> jsonCloneSource;
+
+    ConstantCloneSourceDestinations(
+        DynamicDestinations<T, DestinationT> inner, ValueProvider<String> jsonCloneSource) {
+      super(inner);
+      Preconditions.checkArgumentNotNull(jsonCloneSource, "jsonCloneSource can not be null");
+      this.jsonCloneSource = jsonCloneSource;
+    }
+
+    @Override
+    public TableReference getCloneSource(DestinationT destination) {
+      String jsonCloneSource = this.jsonCloneSource.get();
+      checkArgument(jsonCloneSource != null, "jsonCloneSource can not be null");
+      return BigQueryHelpers.fromJsonString(jsonCloneSource, TableReference.class);
+    }

Review Comment:
   `getCloneSource(...)` reparses the same JSON into a `TableReference` on every call. Since this wrapper is explicitly “constant”, consider memoizing the parsed `TableReference` after the first successful `ValueProvider.get()` (e.g., store it in a transient field) to avoid repeated JSON parsing in hot paths.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());

Review Comment:
   `cloneTable(...)` normalizes the clone source with `withDefaultProject(...)`, but it does not normalize the `destination`. If the destination `TableReference` ever lacks a project ID, `jobProjectId` and `getDatasetLocation(...)` will be computed from null, leading to invalid job refs / failures. Consider applying `withDefaultProject(...)` to `destination` at the start of `cloneTable(...)` and using the normalized reference throughout (job project id, dataset location, and copy destination).



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);

Review Comment:
   `JobReference` construction is duplicated in each `PendingJob` lambda. Consider extracting a small helper (e.g., `jobRef(jobId, jobProjectId, bqLocation)`) to reduce duplication and make future changes (adding fields, changing location logic) less error-prone.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.getJob(jobRef);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }

Review Comment:
   Catching `InterruptedException` and wrapping it in `RuntimeException` clears the thread’s interrupted status, which can cause subtle issues in runners/executors. Prefer catching `InterruptedException` separately, calling `Thread.currentThread().interrupt()`, and then either rethrowing (or wrapping) so upstream cancellation behavior is preserved.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  throw new RuntimeException(e);
+                }

Review Comment:
   Catching `InterruptedException` and wrapping it in `RuntimeException` clears the thread’s interrupted status, which can cause subtle issues in runners/executors. Prefer catching `InterruptedException` separately, calling `Thread.currentThread().interrupt()`, and then either rethrowing (or wrapping) so upstream cancellation behavior is preserved.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -221,6 +226,34 @@ public String toString() {
     }
   }
 
+  /** Returns the same clone source for every table. */
+  static class ConstantCloneSourceDestinations<T, DestinationT>
+      extends DelegatingDynamicDestinations<T, DestinationT> {
+    private final ValueProvider<String> jsonCloneSource;
+
+    ConstantCloneSourceDestinations(
+        DynamicDestinations<T, DestinationT> inner, ValueProvider<String> jsonCloneSource) {
+      super(inner);
+      Preconditions.checkArgumentNotNull(jsonCloneSource, "jsonCloneSource can not be null");
+      this.jsonCloneSource = jsonCloneSource;
+    }
+
+    @Override
+    public TableReference getCloneSource(DestinationT destination) {
+      String jsonCloneSource = this.jsonCloneSource.get();
+      checkArgument(jsonCloneSource != null, "jsonCloneSource can not be null");

Review Comment:
   The error message uses “can not”, which should be “cannot” in standard English (and Beam messages typically use “cannot”). Updating this improves consistency and professionalism of surfaced validation errors.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);

Review Comment:
   `JobReference` construction is duplicated in each `PendingJob` lambda. Consider extracting a small helper (e.g., `jobRef(jobId, jobProjectId, bqLocation)`) to reduce duplication and make future changes (adding fields, changing location logic) less error-prone.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5266779381

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @chamikaramj for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "kennknowles (via GitHub)" <gi...@apache.org>.
kennknowles commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5637882446

   R: @ahmedabu98 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "lalitx17 (via GitHub)" <gi...@apache.org>.
lalitx17 commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4708444800

   /gemini review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4769178534

   Reminder, please take a look at this pr: @Abacn 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5525816762

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @chamikaramj for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5832800040

   resolve conflicts please and rthen I will push for reviews. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "lalitx17 (via GitHub)" <gi...@apache.org>.
lalitx17 commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4708218426

   assign set of reviewers


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5104338749

   Reminder, please take a look at this pr: @Abacn 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5637899032

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4666442956

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


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "lalitx17 (via GitHub)" <gi...@apache.org>.
lalitx17 commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4770331259

   assign to next reviewer


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5034133226

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @Abacn for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38883:
URL: https://github.com/apache/beam/pull/38883#discussion_r3392128824


##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -501,6 +541,15 @@ public TableDestination getTable(DestinationT destination) {
       if (existingTable == null
           || existingTable.getSchema() == null
           || existingTable.getSchema().isEmpty()) {
+        @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();
+          }
+        }

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   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.
   
   ```java
           @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();
             }
           }
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/DynamicDestinationsHelpers.java:
##########
@@ -478,15 +511,22 @@ private static boolean nextBackOff(Sleeper sleeper, BackOff backoff)
     public TableDestination getTable(DestinationT destination) {
       TableDestination wrappedDestination = super.getTable(destination);
       Table existingTable = getBigQueryTable(wrappedDestination.getTableReference());
+      Table tableToMatch = existingTable;
+      if (tableToMatch == null) {
+        @Nullable TableReference cloneSource = super.getCloneSource(destination);
+        if (cloneSource != null) {
+          tableToMatch = getBigQueryTable(cloneSource);
+        }
+      }

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   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.
   
   ```java
         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);
           }
         }
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java:
##########
@@ -3771,6 +3809,16 @@ public WriteResult expand(PCollection<T> input) {
                       .collect(Collectors.toList())),
           "No more than one of jsonSchema, schemaFromView, or dynamicDestinations may be set");
 
+      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");

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   This check can be simplified and made more readable by using Java 8 Streams directly, avoiding the creation of unnecessary Guava lists and iterators.
   
   ```java
         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");
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   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.
   
   ```suggestion
                   try {
                     jobService.startCopyJob(jobRef, copyConfig);
                   } catch (IOException e) {
                     throw new RuntimeException(e);
                   } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
                     throw new RuntimeException(e);
                   }
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.getJob(jobRef);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Restore the interrupted status of the thread when catching `InterruptedException` to ensure the thread's interrupted state is preserved.
   
   ```java
                   try {
                     return jobService.getJob(jobRef);
                   } catch (IOException e) {
                     throw new RuntimeException(e);
                   } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
                     throw new RuntimeException(e);
                   }
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/CreateTableHelpers.java:
##########
@@ -162,67 +176,179 @@ private static void tryCreateTable(
       if (datasetService.getTable(
               tableReference, Collections.emptyList(), DatasetService.TableMetadataView.BASIC)
           == null) {
-        TableSchema tableSchema = schemaSupplier.get();
-        @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
-        Preconditions.checkArgumentNotNull(
-            tableSchema,
-            "Unless create disposition is %s, a schema must be specified, i.e. "
-                + "DynamicDestinations.getSchema() may not return null. "
-                + "However, create disposition is %s, and "
-                + " %s returned null for destination %s",
-            CreateDisposition.CREATE_NEVER,
-            createDisposition,
-            tableDestination);
-        Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
-
-        if (tableConstraints != null) {
-          table = table.setTableConstraints(tableConstraints);
-        }
+        @Nullable TableReference cloneSource = cloneSourceSupplier.get();
+        if (cloneSource != null) {
+          cloneTable(
+              options, datasetService, bqServices, cloneSource, tableReference, kmsKey, tableSpec);
+        } else {
+          TableSchema tableSchema = schemaSupplier.get();
+          @Nullable TableConstraints tableConstraints = tableConstraintsSupplier.get();
+          Preconditions.checkArgumentNotNull(
+              tableSchema,
+              "Unless create disposition is %s, a schema or clone source must be specified, i.e. "
+                  + "DynamicDestinations.getSchema() and DynamicDestinations.getCloneSource() may "
+                  + "not both return null. However, create disposition is %s, and "
+                  + "no schema or clone source was returned for destination %s",
+              CreateDisposition.CREATE_NEVER,
+              createDisposition,
+              tableDestination);
+          Table table = new Table().setTableReference(tableReference).setSchema(tableSchema);
 
-        String tableDescription = tableDestination.getTableDescription();
-        if (tableDescription != null) {
-          table = table.setDescription(tableDescription);
-        }
+          if (tableConstraints != null) {
+            table = table.setTableConstraints(tableConstraints);
+          }
 
-        TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
-        if (timePartitioning != null) {
-          table.setTimePartitioning(timePartitioning);
-        }
+          String tableDescription = tableDestination.getTableDescription();
+          if (tableDescription != null) {
+            table = table.setDescription(tableDescription);
+          }
 
-        Clustering clustering = tableDestination.getClustering();
-        if (clustering != null) {
-          table.setClustering(clustering);
-        }
+          TimePartitioning timePartitioning = tableDestination.getTimePartitioning();
+          if (timePartitioning != null) {
+            table.setTimePartitioning(timePartitioning);
+          }
 
-        if (kmsKey != null) {
-          table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
-        }
-        if (bigLakeConfiguration != null) {
-          TableReference ref = table.getTableReference();
-          table.setBiglakeConfiguration(
-              new BigLakeConfiguration()
-                  .setTableFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("tableFormat"), "iceberg"))
-                  .setFileFormat(
-                      MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
-                  .setConnectionId(
-                      Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
-                  .setStorageUri(
-                      String.format(
-                          "%s/%s/%s/%s",
-                          Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(STORAGE_URI)),
-                          ref.getProjectId(),
-                          ref.getDatasetId(),
-                          ref.getTableId())));
+          Clustering clustering = tableDestination.getClustering();
+          if (clustering != null) {
+            table.setClustering(clustering);
+          }
+
+          if (kmsKey != null) {
+            table.setEncryptionConfiguration(new EncryptionConfiguration().setKmsKeyName(kmsKey));
+          }
+          if (bigLakeConfiguration != null) {
+            TableReference ref = table.getTableReference();
+            table.setBiglakeConfiguration(
+                new BigLakeConfiguration()
+                    .setTableFormat(
+                        MoreObjects.firstNonNull(
+                            bigLakeConfiguration.get("tableFormat"), "iceberg"))
+                    .setFileFormat(
+                        MoreObjects.firstNonNull(bigLakeConfiguration.get("fileFormat"), "parquet"))
+                    .setConnectionId(
+                        Preconditions.checkArgumentNotNull(bigLakeConfiguration.get(CONNECTION_ID)))
+                    .setStorageUri(
+                        String.format(
+                            "%s/%s/%s/%s",
+                            Preconditions.checkArgumentNotNull(
+                                bigLakeConfiguration.get(STORAGE_URI)),
+                            ref.getProjectId(),
+                            ref.getDatasetId(),
+                            ref.getTableId())));
+          }
+          datasetService.createTable(table);
         }
-        datasetService.createTable(table);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     createdTables.add(tableSpec);
   }
 
+  private static void cloneTable(
+      BigQueryOptions options,
+      DatasetService datasetService,
+      BigQueryServices bqServices,
+      TableReference cloneSource,
+      TableReference destination,
+      @Nullable String kmsKey,
+      String tableSpec)
+      throws Exception {
+    TableReference source = withDefaultProject(options, cloneSource);
+    JobConfigurationTableCopy copyConfig =
+        new JobConfigurationTableCopy()
+            .setSourceTables(Collections.singletonList(source))
+            .setDestinationTable(destination)
+            .setOperationType("CLONE")
+            .setWriteDisposition(WriteDisposition.WRITE_EMPTY.name())
+            .setCreateDisposition(CreateDisposition.CREATE_IF_NEEDED.name());
+    if (kmsKey != null) {
+      copyConfig.setDestinationEncryptionConfiguration(
+          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+    }
+
+    String jobProjectId = destination.getProjectId();
+    String bqLocation =
+        BigQueryHelpers.getDatasetLocation(
+            datasetService, destination.getProjectId(), destination.getDatasetId());
+    String jobIdPrefix = createCloneJobIdPrefix(options, source, destination);
+    try (JobService jobService = bqServices.getJobService(options)) {
+      BigQueryHelpers.PendingJob cloneJob =
+          new BigQueryHelpers.PendingJob(
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  jobService.startCopyJob(jobRef, copyConfig);
+                } catch (IOException | InterruptedException e) {
+                  throw new RuntimeException(e);
+                }
+                return null;
+              },
+              jobId -> {
+                JobReference jobRef =
+                    new JobReference()
+                        .setProjectId(jobProjectId)
+                        .setJobId(jobId.getJobId())
+                        .setLocation(bqLocation);
+                try {
+                  return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
+                } catch (InterruptedException e) {
+                  throw new RuntimeException(e);
+                }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Restore the interrupted status of the thread when catching `InterruptedException` to ensure the thread's interrupted state is preserved.
   
   ```java
                   try {
                     return jobService.pollJob(jobRef, BatchLoads.LOAD_JOB_POLL_MAX_RETRIES);
                   } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
                     throw new RuntimeException(e);
                   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5410245847

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @ahmedabu98 for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4876485505

   Reminder, please take a look at this pr: @ahmedabu98 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4904074736

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @kennknowles for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-4675497852

   ## Summary of Changes
   
   Hello, I'm Gemini Code Assist[^1]! 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.
   
   <details>
   <summary><b>New Features</b></summary>
   
   🧠 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](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   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.
   
   <b>Customization</b>
   
   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](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with :thumbsup: and :thumbsdown: 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](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-5143028273

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @ahmedabu98 for label java.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-6322556008

   Hi @lalitium, friendly ping to resolve conflicts. Thanks


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQueryIO support for clone table creation [beam]

Posted by "lalitium (via GitHub)" <gi...@apache.org>.
lalitium commented on PR #38883:
URL: https://github.com/apache/beam/pull/38883#issuecomment-6322942250

   > Hi @lalitium, friendly ping to resolve conflicts. Thanks
   
   I'll resolve the conflict this weekend. Apologies for the delay.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org