接続を管理する

このドキュメントでは、BigQuery 接続を表示、一覧表示、共有、編集、削除、トラブルシューティングする方法について説明します。

BigQuery 管理者は、サービスと外部データソースへの接続に使用する接続を作成し、管理できます。BigQuery アナリストは、これらの接続を使用して、BigQuery にデータを移動することやコピーすることなく、外部データソースにクエリを送信します。次のタイプの接続を作成できます。

プロジェクトのデフォルト接続を作成するには、デフォルトの接続の概要をご覧ください。

始める前に

必要なロール

接続の管理に必要な権限を取得するには、管理者に次の IAM ロールを付与するよう依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

デフォルトの接続を作成して使用するために必要なロールについては、必要なロールと権限をご覧ください。

これらの事前定義ロールには、このドキュメントのタスクを実行するために必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • 接続の詳細を表示する: bigquery.connections.get
  • すべての接続を一覧表示する: bigquery.connections.list
  • 接続を編集、削除する: bigquery.connections.update
  • 接続を共有する: bigquery.connections.setIamPolicy

すべての接続を一覧表示する

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

    接続は、プロジェクトで [接続] というグループに一覧表示されます。

  2. 左側のペインで、 [エクスプローラ] をクリックします。

    ハイライト表示された [エクスプローラ] ペインのボタン。

    左側のペインが表示されていない場合は、 [左ペインを開く] をクリックしてペインを開きます。

  3. [エクスプローラ] ペインで、プロジェクト名をクリックし、[接続] をクリックして、すべての接続のリストを表示します。

bq

bq ls コマンドを入力し、--connection フラグを指定します。必要に応じて、--project_id フラグと --location フラグを指定して、一覧表示する接続のプロジェクトとロケーションを特定します。

bq ls --connection --project_id=PROJECT_ID --location=REGION

次のように置き換えます。

API

REST API リファレンス セクションの projects.locations.connections.list メソッドを使用します。

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Python の設定手順を完了してください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import google.api_core.exceptions
from google.cloud import bigquery_connection_v1


def list_connections(project_id: str, location: str):
    """Prints all connections in a given project and location.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the connections (for example, "us", "us-central1").
    """
    client = bigquery_connection_v1.ConnectionServiceClient()

    parent = client.common_location_path(project_id, location)

    request = bigquery_connection_v1.ListConnectionsRequest(
        parent=parent,
        page_size=100,
    )

    print(f"Listing connections in project '{project_id}' and location '{location}':")

    try:
        for connection in client.list_connections(request=request):
            print(f"Connection ID: {connection.name.split('/')[-1]}")
            print(f"Friendly Name: {connection.friendly_name}")
            print(f"Has Credential: {connection.has_credential}")
            print("-" * 20)

        print("Finished listing connections.")

    except google.api_core.exceptions.InvalidArgument as e:
        print(
            f"Could not list connections. Please check that the project ID '{project_id}' "
            f"and location '{location}' are correct. Details: {e}"
        )

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Node.js の設定手順を完了してください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

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

const client = new ConnectionServiceClient();

/**
 * Lists BigQuery connections in a given project and location.
 *
 * @param {string} projectId The Google Cloud project ID. for example, 'example-project-id'
 * @param {string} location The location to list connections for. for example, 'us-central1'
 */
async function listConnections(projectId, location) {
  const parent = client.locationPath(projectId, location);

  const request = {
    parent,
    pageSize: 100,
  };

  try {
    const [connections] = await client.listConnections(request, {
      autoPaginate: false,
    });

    if (connections.length === 0) {
      console.log(
        `No connections found in ${location} for project ${projectId}.`,
      );
      return;
    }

    console.log('Connections:');
    for (const connection of connections) {
      console.log(`  Name: ${connection.name}`);
      console.log(`  Friendly Name: ${connection.friendlyName}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.log(
        `Project '${projectId}' or location '${location}' not found.`,
      );
    } else {
      console.error('Error listing connections:', err);
    }
  }
}

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Java の設定手順を完了してください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import com.google.cloud.bigquery.connection.v1.ListConnectionsRequest;
import com.google.cloud.bigquery.connection.v1.LocationName;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import java.io.IOException;

// Sample to get list of connections
public class ListConnections {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String location = "MY_LOCATION";
    listConnections(projectId, location);
  }

  static void listConnections(String projectId, String location) throws IOException {
    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      LocationName parent = LocationName.of(projectId, location);
      int pageSize = 10;
      ListConnectionsRequest request =
          ListConnectionsRequest.newBuilder()
              .setParent(parent.toString())
              .setPageSize(pageSize)
              .build();
      client
          .listConnections(request)
          .iterateAll()
          .forEach(con -> System.out.println("Connection Id :" + con.getName()));
    }
  }
}

接続の詳細を表示する

接続を作成すると、接続の構成に関する情報を取得できます。この構成には、転送を作成したときに指定した値が含まれます。

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

  2. 接続は、プロジェクトで [接続] というグループに一覧表示されます。

  3. 左側のペインで、 [エクスプローラ] をクリックします。

    [エクスプローラ] ペインのボタンがハイライト表示されている。

  4. [エクスプローラ] ペインで、プロジェクト名をクリックし、[接続] をクリックして、すべての接続のリストを表示します。

  5. 接続をクリックして詳細を表示します。

bq

bq show コマンドを入力し、--connection フラグを指定します。必要に応じて、接続 ID をプロジェクト ID と接続のリージョンで修飾します。

bq show --connection PROJECT_ID.REGION.CONNECTION_ID

次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID
  • REGION: 接続リージョン
  • CONNECTION_ID: 接続 ID

API

REST API リファレンス セクションの projects.locations.connections.get メソッドを使用します。

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Python の設定手順を完了してください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import google.api_core.exceptions
from google.cloud import bigquery_connection_v1

client = bigquery_connection_v1.ConnectionServiceClient()


def get_connection(project_id: str, location: str, connection_id: str):
    """Retrieves connection metadata about a specified BigQuery connection.

    A connection stores metadata about an external data source and credentials to access it.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the connection (for example, "us-central1").
        connection_id: The ID of the connection to retrieve.
    """

    name = client.connection_path(project_id, location, connection_id)

    try:
        connection = client.get_connection(name=name)

        print(f"Successfully retrieved connection: {connection.name}")
        print(f"Friendly name: {connection.friendly_name}")
        print(f"Description: {connection.description}")
        if connection.cloud_sql:
            print(f"Cloud SQL instance ID: {connection.cloud_sql.instance_id}")
    except google.api_core.exceptions.NotFound:
        print(f"Connection '{name}' not found.")

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Node.js の設定手順を完了してください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const client = new ConnectionServiceClient();

/**
 * Retrieves connection metadata about a specified BigQuery connection.
 *
 * A connection stores metadata about an external data source and credentials to access it.
 *
 * @param {string} projectId - Google Cloud project ID. for example, 'example-project-id'
 * @param {string} location - The location of the connection. for example, 'us-central1'
 * @param {string} connectionId - The ID of the connection to retrieve. for example, 'example_connection'
 */
async function getConnection(projectId, location, connectionId) {
  const name = client.connectionPath(projectId, location, connectionId);

  const request = {
    name,
  };

  try {
    const [connection] = await client.getConnection(request);

    console.log(`Successfully retrieved connection: ${connection.name}`);
    console.log(`  Friendly name: ${connection.friendlyName}`);
    console.log(`  Description: ${connection.description}`);
    console.log(`  Has credential: ${connection.hasCredential}`);

    if (connection.cloudSql) {
      console.log(`  Cloud SQL instance ID: ${connection.cloudSql.instanceId}`);
      console.log(`  Cloud SQL database: ${connection.cloudSql.database}`);
      console.log(`  Cloud SQL type: ${connection.cloudSql.type}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.log(`Connection ${name} not found.`);
    } else {
      console.error(`Error getting connection ${name}:`, err);
    }
  }
}

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Java の設定手順を完了してください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import com.google.cloud.bigquery.connection.v1.Connection;
import com.google.cloud.bigquery.connection.v1.ConnectionName;
import com.google.cloud.bigquery.connection.v1.GetConnectionRequest;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import java.io.IOException;

// Sample to get connection
public class GetConnection {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String location = "MY_LOCATION";
    String connectionId = "MY_CONNECTION_ID";
    getConnection(projectId, location, connectionId);
  }

  static void getConnection(String projectId, String location, String connectionId)
      throws IOException {
    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      ConnectionName name = ConnectionName.of(projectId, location, connectionId);
      GetConnectionRequest request =
          GetConnectionRequest.newBuilder().setName(name.toString()).build();
      Connection response = client.getConnection(request);
      System.out.println("Connection info retrieved successfully :" + response.getName());
    }
  }
}

接続に対する Identity and Access Management(IAM)ポリシーを取得する

接続の IAM ポリシーを取得する手順は次のとおりです。

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Python の設定手順を完了してください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。


import google.api_core.exceptions
from google.cloud import bigquery_connection_v1

client = bigquery_connection_v1.ConnectionServiceClient()


def get_connection_iam_policy(
    project_id: str,
    location: str,
    connection_id: str,
):
    """Gets the IAM policy of a connection.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the connection (for example, "us").
        connection_id: The ID of the connection.
    """

    resource = client.connection_path(project_id, location, connection_id)

    try:
        policy = client.get_iam_policy(resource=resource)

        print(f"Successfully retrieved IAM policy for connection: {resource}")
        if not policy.bindings:
            print("This policy is empty and has no bindings.")

        for binding in policy.bindings:
            print(f"Role: {binding.role}")
            print("Members:")
            for member in binding.members:
                print(f"    - {member}")

    except google.api_core.exceptions.NotFound:
        print(f"Connection not found: {resource}")

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Node.js の設定手順を完了してください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const client = new ConnectionServiceClient();

/**
 * Gets the IAM policy for a BigQuery connection.
 * @param {string} projectId Google Cloud project ID (for example, 'example-project-id').
 * @param {string} location The location of the connection (for example, 'us').
 * @param {string} connectionId The connection ID (for example, 'example-connection').
 */
async function getIamPolicy(projectId, location, connectionId) {

  const resource = client.connectionPath(projectId, location, connectionId);

  const request = {
    resource,
  };

  try {

    const [policy] = await client.getIamPolicy(request);

    console.log(
      `Successfully retrieved IAM policy for connection: ${connectionId}`,
    );

    if (policy.bindings && policy.bindings.length > 0) {
      console.log('Bindings:');
      policy.bindings.forEach(binding => {
        console.log(`  Role: ${binding.role}`);
        console.log('  Members:');
        binding.members.forEach(member => {
          console.log(`    - ${member}`);
        });
      });
    } else {
      console.log('No policy bindings found.');
    }
  } catch (err) {

    if (err.code === status.NOT_FOUND) {
      console.log(
        `Connection '${connectionId}' not found in project '${projectId}' at location '${location}'.`,
      );
    } else {
      console.error('An error occurred while getting the IAM policy:', err);
    }
  }
}

接続をユーザーと共有する

次のロールを付与することで、ユーザーがデータをクエリして接続を管理できます。

  • roles/bigquery.connectionUser: ユーザーが接続を使用して外部データソースに接続し、クエリを実行できるようにします。

  • roles/bigquery.connectionAdmin: ユーザーが接続を管理できるようにします。

BigQuery での IAM のロールと権限について詳しくは、事前定義ロールと権限をご覧ください。

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

    接続は、プロジェクトで [接続] というグループに一覧表示されます。

  2. 左側のペインで、 [エクスプローラ] をクリックします。

    ハイライト表示された [エクスプローラ] ペインのボタン。

    左側のペインが表示されていない場合は、 [左ペインを開く] をクリックしてペインを開きます。

  3. プロジェクトをクリックし、[接続] をクリックして、接続を選択します。

  4. [詳細] ペインで、[共有] をクリックして接続を共有します。次に、以下の操作を行います。

    1. [接続の権限] ダイアログで、プリンシパルを追加または編集して、他のプリンシパルと接続を共有します。

    2. [保存] をクリックします。

bq

bq コマンドライン ツールを使用して接続を共有することはできません。接続を共有するには、 Google Cloud コンソールまたは BigQuery Connections API の接続を共有するためのメソッドを使用します。

API

BigQuery Connections REST API の projects.locations.connections.setIAM メソッドを使用して、policy リソースのインスタンスを指定します。

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Java の設定手順を完了してください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import com.google.api.resourcenames.ResourceName;
import com.google.cloud.bigquery.connection.v1.ConnectionName;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

// Sample to share connections
public class ShareConnection {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String location = "MY_LOCATION";
    String connectionId = "MY_CONNECTION_ID";
    shareConnection(projectId, location, connectionId);
  }

  static void shareConnection(String projectId, String location, String connectionId)
      throws IOException {
    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      ResourceName resource = ConnectionName.of(projectId, location, connectionId);
      Binding binding =
          Binding.newBuilder()
              .addMembers("group:example-analyst-group@google.com")
              .setRole("roles/bigquery.connectionUser")
              .build();
      Policy policy = Policy.newBuilder().addBindings(binding).build();
      SetIamPolicyRequest request =
          SetIamPolicyRequest.newBuilder()
              .setResource(resource.toString())
              .setPolicy(policy)
              .build();
      client.setIamPolicy(request);
      System.out.println("Connection shared successfully");
    }
  }
}

接続を編集する

接続では、接続を作成したユーザーの認証情報が使用されます。接続に関連付けられているユーザーを変更する必要がある場合は、ユーザーの認証情報を更新できます。これは、接続を作成したユーザーが組織のメンバーではなくなった場合に便利です。

接続の次の要素は編集できません。

  • 接続タイプ
  • 接続 ID
  • ロケーション

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

    接続は、プロジェクトの [接続] というグループに一覧表示されます。

  2. 左側のペインで、 [エクスプローラ] をクリックします。

    [エクスプローラ] ペインのボタンがハイライト表示されている。

  3. [エクスプローラ] ペインで、プロジェクト名をクリックし、[接続] をクリックして、すべての接続のリストを表示します。

  4. 詳細を表示するには、接続をクリックします。

  5. [接続情報] セクションで、 [詳細を編集] をクリックします。次に、以下の操作を行います。

    1. [接続の編集] ダイアログで、ユーザー認証情報などの接続の詳細を編集します。

    2. [接続の更新] をクリックします。

bq

bq update コマンドを入力して、接続フラグ --connection を指定します。完全修飾された connection_id が必要です。

  bq update --connection --connection_type='CLOUD_SQL'
      --properties='{"instanceId" : "INSTANCE",
      "database" : "DATABASE", "type" : "MYSQL" }'
      --connection_credential='{"username":"USERNAME", "password":"PASSWORD"}'
      PROJECT.REGION.CONNECTION_ID
 

次のように置き換えます。

  • INSTANCE: Cloud SQL インスタンス
  • DATABASE: データベース名
  • USERNAME: Cloud SQL データベースのユーザー名
  • PASSWORD: Cloud SQL データベースのパスワード
  • PROJECT: Google Cloud プロジェクト ID
  • REGION: 接続リージョン
  • CONNECTION_ID: 接続 ID

たとえば、次のコマンドを使用すると、ID が federation-test で接続 ID が test-mysql のプロジェクト内の接続が更新されます。

bq update --connection --connection_type='CLOUD_SQL'
    --properties='{"instanceId" : "federation-test:us-central1:new-mysql",
    "database" : "imdb2", "type" : "MYSQL" }'
    --connection_credential='{"username":"my_username",
    "password":"my_password"}' federation-test.us.test-mysql

API

REST API リファレンス セクションの projects.locations.connections.patch メソッドを参照し、connection のインスタンスを指定します。

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Python の設定手順を完了してください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

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

client = bigquery_connection_v1.ConnectionServiceClient()


def update_connection(project_id: str, location: str, connection_id: str):
    """Updates a BigQuery connection's friendly name and description.

    For security reasons, updating connection properties also resets the
    credential. The `update_mask` specifies which fields of the connection
    to update. This sample only updates metadata fields to avoid resetting
    credentials.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the connection (for example, "us-central1").
        connection_id: The ID of the connection to update.
    """

    connection_name = client.connection_path(project_id, location, connection_id)

    connection = bigquery_connection_v1.Connection(
        friendly_name="Example Updated BigQuery Connection",
        description="This is an updated description for the connection.",
    )

    update_mask = field_mask_pb2.FieldMask(paths=["friendly_name", "description"])

    try:
        response = client.update_connection(
            name=connection_name,
            connection=connection,
            update_mask=update_mask,
        )

        print(f"Connection '{response.name}' updated successfully.")
        print(f"Friendly Name: {response.friendly_name}")
        print(f"Description: {response.description}")

    except google.api_core.exceptions.NotFound:
        print(f"Connection '{connection_name}' not found. Please create it first.")

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Node.js の設定手順を完了してください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const connectionClient = new ConnectionServiceClient();

/**
 * Updates a BigQuery connection, demonstrating how to update the friendly name and description.
 *
 * @param {string} projectId The Google Cloud project ID. for example, 'example-project-id'
 * @param {string} location The location of the connection. for example, 'us-central1'
 * @param {string} connectionId The ID of the connection to update. for example, 'example-connection-id'
 */
async function updateConnection(projectId, location, connectionId) {
  const name = connectionClient.connectionPath(
    projectId,
    location,
    connectionId,
  );

  const connection = {
    friendlyName: 'Example Updated Connection',
    description: 'A new description for the connection',
  };

  const updateMask = {
    paths: ['friendly_name', 'description'],
  };

  const request = {
    name,
    connection,
    updateMask,
  };

  try {
    const [response] = await connectionClient.updateConnection(request);

    console.log(`Connection updated: ${response.name}`);
    console.log(`  Friendly name: ${response.friendlyName}`);
    console.log(`  Description: ${response.description}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.log(`Connection not found: ${name}`);
    } else {
      console.error(`Error updating connection ${name}:`, err);
    }
  }
}

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Java の設定手順を完了してください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import com.google.cloud.bigquery.connection.v1.Connection;
import com.google.cloud.bigquery.connection.v1.ConnectionName;
import com.google.cloud.bigquery.connection.v1.UpdateConnectionRequest;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

// Sample to update connection
public class UpdateConnection {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String location = "MY_LOCATION";
    String connectionId = "MY_CONNECTION_ID";
    String description = "MY_DESCRIPTION";
    Connection connection = Connection.newBuilder().setDescription(description).build();
    updateConnection(projectId, location, connectionId, connection);
  }

  static void updateConnection(
      String projectId, String location, String connectionId, Connection connection)
      throws IOException {
    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      ConnectionName name = ConnectionName.of(projectId, location, connectionId);
      FieldMask updateMask = FieldMaskUtil.fromString("description");
      UpdateConnectionRequest request =
          UpdateConnectionRequest.newBuilder()
              .setName(name.toString())
              .setConnection(connection)
              .setUpdateMask(updateMask)
              .build();
      Connection response = client.updateConnection(request);
      System.out.println("Connection updated successfully :" + response.getDescription());
    }
  }
}

接続を削除する

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

    接続は、プロジェクトの [接続] というグループに一覧表示されます。

  2. 左側のペインで、 [エクスプローラ] をクリックします。

    [エクスプローラ] ペインのボタンがハイライト表示されている。

  3. [エクスプローラ] ペインで、プロジェクト名をクリックし、[接続] をクリックして、すべての接続のリストを表示します。

  4. 接続をクリックして詳細を表示します。

  5. [詳細] ペインで、 [削除] をクリックして接続を削除します。

  6. [接続を削除しますか?] ダイアログ ボックスに「delete」と入力して削除を確定します。

  7. [削除] をクリックします。

bq

bq rm コマンドを入力して、接続フラグ --connection を指定します。完全修飾された connection_id が必要です。

bq rm --connection PROJECT_ID.REGION.CONNECTION_ID

次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID
  • REGION: 接続リージョン
  • CONNECTION_ID: 接続 ID

API

REST API リファレンス セクションの projects.locations.connections.delete メソッドをご覧ください。

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Python の設定手順を完了してください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import google.api_core.exceptions
from google.cloud import bigquery_connection_v1

client = bigquery_connection_v1.ConnectionServiceClient()


def delete_connection(project_id: str, location: str, connection_id: str):
    """Deletes a BigQuery connection.

    Args:
        project_id: The Google Cloud project ID.
        location: Location of the connection (for example, "us-central1").
        connection_id: ID of the connection to delete.
    """
    name = client.connection_path(project_id, location, connection_id)

    try:
        client.delete_connection(name=name)
        print(f"Connection '{connection_id}' was deleted.")
    except google.api_core.exceptions.NotFound:
        print(f"Connection '{connection_id}' not found.")

Node.js

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Node.js の設定手順を完了してください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const client = new ConnectionServiceClient();

/**
 * Deletes a connection and its associated credentials.
 *
 * @param {string} projectId Google Cloud project ID (for example, 'example-project-id').
 * @param {string} location The location where the connection resides (for example, 'us-central1').
 * @param {string} connectionId The ID of the connection to delete (for example, 'example-connection').
 */
async function deleteConnection(projectId, location, connectionId) {
  const request = {
    name: client.connectionPath(projectId, location, connectionId),
  };

  try {
    await client.deleteConnection(request);
    console.log(`Connection ${connectionId} deleted successfully.`);
  } catch (error) {
    if (error.code === status.NOT_FOUND) {
      console.log(
        `Connection ${connectionId} does not exist in location ${location} of project ${projectId}.`,
      );
    } else {
      console.error(`Error deleting connection ${connectionId}:`, error);
    }
  }
}

Java

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Java の設定手順を完了してください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

import com.google.cloud.bigquery.connection.v1.ConnectionName;
import com.google.cloud.bigquery.connection.v1.DeleteConnectionRequest;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import java.io.IOException;

// Sample to delete a connection
public class DeleteConnection {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String location = "MY_LOCATION";
    String connectionName = "MY_CONNECTION_NAME";
    deleteConnection(projectId, location, connectionName);
  }

  static void deleteConnection(String projectId, String location, String connectionName)
      throws IOException {
    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      ConnectionName name = ConnectionName.of(projectId, location, connectionName);
      DeleteConnectionRequest request =
          DeleteConnectionRequest.newBuilder().setName(name.toString()).build();
      client.deleteConnection(request);
      System.out.println("Connection deleted successfully");
    }
  }
}

次のステップ