Autorizzare un set di dati BigQuery

Autorizzare un set di dati BigQuery

Esempio di codice

Java

Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida di BigQuery all'utilizzo delle librerie client. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API Java di BigQuery.

import com.google.cloud.bigquery.Acl;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;

public class AuthorizeDataset {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "PROJECT_ID";
    String sourceDatasetName = "BIGQUERY_SOURCE_DATASET_NAME";
    String userDatasetName = "BIGQUERY_USER_DATASET_NAME";
    authorizeDataset(
        DatasetId.of(projectId, sourceDatasetName), DatasetId.of(projectId, userDatasetName));
  }

  // This method will update userDataset's ACL with sourceDataset's ACL
  public static void authorizeDataset(DatasetId sourceDatasetId, DatasetId userDatasetId) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Get both source and user dataset's references
      Dataset sourceDataset = bigquery.getDataset(sourceDatasetId);
      Dataset userDataset = bigquery.getDataset(userDatasetId);

      // Get the source dataset's ACL
      List<Acl> sourceDatasetAcl = new ArrayList<>(sourceDataset.getAcl());

      // Add the user dataset's DatasetAccessEntry object to the existing sourceDatasetAcl
      List<String> targetTypes = ImmutableList.of("VIEWS");
      Acl.DatasetAclEntity userDatasetAclEntity =
          new Acl.DatasetAclEntity(userDatasetId, targetTypes);
      sourceDatasetAcl.add(Acl.of(userDatasetAclEntity));

      // update the user dataset with source dataset's ACL
      Dataset updatedUserDataset =
          userDataset.toBuilder().setAcl(sourceDatasetAcl).build().update();

      System.out.printf(
          "Dataset %s updated with the added authorization\n", updatedUserDataset.getDatasetId());

    } catch (BigQueryException e) {
      System.out.println("Dataset Authorization failed due to error: \n" + e);
    }
  }
}

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.