Mettre à jour l'échange de données (v1)

Mettez à jour la description d'un échange de données existant.

Exemple de code

Go

Avant d'essayer cet exemple, suivez les instructions de configuration pour Go du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Go.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.


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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Java.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.

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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Node.js du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Node.js.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.

'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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python du guide de démarrage rapide de BigQuery : Utiliser les bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API BigQuery pour Python.

Pour vous authentifier auprès de BigQuery, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez la page Configurer l'authentification pour les bibliothèques clientes.

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}")

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud , consultez l'explorateur d'exemplesGoogle Cloud .