Atualizar troca de dados (v1)

Atualize a descrição de uma troca de dados.

Exemplo de código

Go

Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Go.

Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.


import (
	"context"
	"fmt"
	"io"

	analyticshub "cloud.google.com/go/bigquery/analyticshub/apiv1"
	analyticshubpb "cloud.google.com/go/bigquery/analyticshub/apiv1/analyticshubpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateDataExchange updates the description of a data exchange.
func updateDataExchange(ctx context.Context, w io.Writer, projectID string, locationID string, dataExchangeID string) error {
	client, err := analyticshub.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("analyticshub.NewClient: %w", err)
	}
	defer client.Close()

	updateMask := &fieldmaskpb.FieldMask{
		Paths: []string{"description"},
	}
	dataExchange := &analyticshubpb.DataExchange{
		Name:        fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, locationID, dataExchangeID),
		Description: "Updated description for this data exchange",
	}

	req := &analyticshubpb.UpdateDataExchangeRequest{
		UpdateMask:   updateMask,
		DataExchange: dataExchange,
	}

	response, err := client.UpdateDataExchange(ctx, req)
	if err != nil {
		return fmt.Errorf("client.UpdateDataExchange: %w", err)
	}

	fmt.Fprintf(w, "Updated data exchange: %s\n", response.GetName())
	return nil
}

Java

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Java.

Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

import com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubServiceClient;
import com.google.cloud.bigquery.analyticshub.v1.DataExchange;
import com.google.protobuf.FieldMask;

public class UpdateDataExchange {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project_id";
    String locationId = "example-location_id";
    String dataExchangeId = "example-data_exchange_id";
    updateDataExchange(projectId, locationId, dataExchangeId);
  }

  public static void updateDataExchange(
      String projectId, String locationId, String dataExchangeId) throws Exception {
    // Initialize client that will be automatically closed when finished.
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      // Specify the fields to update to perform a partial update.
      FieldMask updateMask = FieldMask.newBuilder().addPaths("description").build();

      String dataExchangeName =
          String.format(
              "projects/%s/locations/%s/dataExchanges/%s",
              projectId, locationId, dataExchangeId);
      DataExchange dataExchange =
          DataExchange.newBuilder()
              .setName(dataExchangeName)
              .setDescription("Updated description for example-data-exchange")
              .build();

      DataExchange response = client.updateDataExchange(dataExchange, updateMask);
      System.out.println("Updated data exchange: " + response.getName());
    }
  }
}

Node.js

Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Node.js.

Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

'use strict';

const {AnalyticsHubServiceClient} = require('@google-cloud/bigquery-analyticshub');
const {status} = require('@grpc/grpc-js');

const client = new AnalyticsHubServiceClient();

/**
 * Use the updateDataExchange method
 *
 * @param {string} projectId - The Google Cloud project ID hosting the data exchange.
 * @param {string} locationId - The Google Cloud region or location for the data exchange (e.g., 'us').
 * @param {string} dataExchangeId - The ID of the data exchange to update. Must contain only Unicode letters, numbers (0-9), and underscores (_), max length 100 bytes.
 */
async function updateDataExchange(projectId, locationId, dataExchangeId) {
  try {
    // Populate the resource name to bind the target path and provide the fields to update.
    const dataExchange = {
      name: client.dataExchangePath(projectId, locationId, dataExchangeId),
      description: 'Updated Data Exchange description',
    };

    // Specify the field mask paths matching the fields to modify.
    const updateMask = {
      paths: ['description'],
    };

    const request = {
      dataExchange,
      updateMask,
    };

    const [response] = await client.updateDataExchange(request);

    console.log(`Updated data exchange: ${response.name}`);
    console.log(`Description: ${response.description}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Data exchange not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else {
      console.error(`Failed to update data exchange: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { updateDataExchange };

Python

Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Python.

Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

import google.api_core.exceptions
from google.cloud import bigquery_analyticshub_v1
from google.protobuf import field_mask_pb2


def update_data_exchange(
    project_id: str, location_id: str, data_exchange_id: str
) -> None:
    """Updates an existing data exchange.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The geographic location of the data exchange.
        data_exchange_id: The identifier of the data exchange to update.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    update_mask = field_mask_pb2.FieldMask(paths=["description"])
    data_exchange = bigquery_analyticshub_v1.DataExchange(
        name=f"projects/{project_id}/locations/{location_id}/dataExchanges/{data_exchange_id}",
        description="Updated data exchange description.",
    )

    try:
        response = client.update_data_exchange(
            request=bigquery_analyticshub_v1.UpdateDataExchangeRequest(
                data_exchange=data_exchange,
                update_mask=update_mask,
            )
        )
        print(f"Updated data exchange: {response.name}")
        print(f"Description: {response.description}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Request failed: {e}")

A seguir

Para pesquisar e filtrar exemplos de código de outros Google Cloud produtos, consulte a Google Cloud pesquisa de exemplos de código.