接続の一覧表示

プロジェクト内のすべての接続メタデータを一覧表示します。

さらに詳しい情報

このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。

コードサンプル

Go

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

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


// The bigquery_connection_quickstart application demonstrates basic usage of the
// BigQuery connection API.
package main

import (
	"bytes"
	"context"
	"flag"
	"fmt"
	"log"
	"time"

	connection "cloud.google.com/go/bigquery/connection/apiv1"
	"google.golang.org/api/iterator"
	connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1"
)

func main() {

	// Define two command line flags for controlling the behavior of this quickstart.
	projectID := flag.String("project_id", "", "Cloud Project ID, used for session creation.")
	location := flag.String("location", "US", "BigQuery location used for interactions.")

	// Parse flags and do some minimal validation.
	flag.Parse()
	if *projectID == "" {
		log.Fatal("empty --project_id specified, please provide a valid project ID")
	}
	if *location == "" {
		log.Fatal("empty --location specified, please provide a valid location")
	}

	ctx := context.Background()
	connClient, err := connection.NewClient(ctx)
	if err != nil {
		log.Fatalf("NewClient: %v", err)
	}
	defer connClient.Close()

	s, err := reportConnections(ctx, connClient, *projectID, *location)
	if err != nil {
		log.Fatalf("printCapacityCommitments: %v", err)
	}
	fmt.Println(s)
}

// reportConnections gathers basic information about existing connections in a given project and location.
func reportConnections(ctx context.Context, client *connection.Client, projectID, location string) (string, error) {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "Current connections defined in project %s in location %s:\n", projectID, location)

	req := &connectionpb.ListConnectionsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}
	totalConnections := 0
	it := client.ListConnections(ctx, req)
	for {
		conn, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return "", err
		}
		fmt.Fprintf(&buf, "\tConnection %s was created %s\n", conn.GetName(), unixMillisToTime(conn.GetCreationTime()).Format(time.RFC822Z))
		totalConnections++
	}
	fmt.Fprintf(&buf, "\n%d connections processed.\n", totalConnections)
	return buf.String(), nil
}

// unixMillisToTime converts epoch-millisecond representations used by the API into a time.Time representation.
func unixMillisToTime(m int64) time.Time {
	if m == 0 {
		return time.Time{}
	}
	return time.Unix(0, m*1e6)
}

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 demonstrates basic usage of the BigQuery connection API.
public class QuickstartSample {

  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 connectionServiceClient = ConnectionServiceClient.create()) {
      LocationName parent = LocationName.of(projectId, location);
      int pageSize = 10;
      ListConnectionsRequest request =
          ListConnectionsRequest.newBuilder()
              .setParent(parent.toString())
              .setPageSize(pageSize)
              .build();
      ConnectionServiceClient.ListConnectionsPagedResponse response =
          connectionServiceClient.listConnections(request);

      // Print the results.
      System.out.println("List of connections:");
      response
          .iterateAll()
          .forEach(connection -> System.out.println("Connection Name: " + connection.getName()));
    }
  }
}

Node.js

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

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

// Imports the Google Cloud client library
const {
  ConnectionServiceClient,
} = require('@google-cloud/bigquery-connection');

// Creates a client
const client = new ConnectionServiceClient();

// project = 'my-project' // Project to list connections for.

const parent = `projects/${project}/locations/US`;

async function listConnections() {
  const [connections] = await client.listConnections({
    parent: parent,
  });

  console.info(`found ${connections.length} connections:`);
  console.info(connections);
}
const listConnectionsResponse = listConnections();

Python

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

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


from google.cloud import bigquery_connection_v1 as bq_connection

def main(
    project_id: str = "your-project-id", location: str = "US", transport: str = "grpc"
) -> None:
    """Prints details and summary information about connections for a given admin project and location"""
    client = bq_connection.ConnectionServiceClient(transport=transport)
    print(f"List of connections in project {project_id} in location {location}")
    req = bq_connection.ListConnectionsRequest(
        parent=client.common_location_path(project_id, location)
    )
    for connection in client.list_connections(request=req):
        print(f"\tConnection {connection.friendly_name} ({connection.name})")

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。