cloudsqlconn

package module
v1.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 42 Imported by: 114

README

cloud-sql-go-connector image

Cloud SQL Go Connector

Open In Codelab CI Go Reference

The Cloud SQL Go Connector is a Cloud SQL connector designed for use with the Go language. Using a Cloud SQL connector provides a native alternative to the Cloud SQL Auth Proxy while providing the following benefits:

  • IAM Authorization: uses IAM permissions to control who/what can connect to your Cloud SQL instances
  • Improved Security: uses robust, updated TLS 1.3 encryption and identity verification between the client connector and the server-side proxy, independent of the database protocol.
  • Convenience: removes the requirement to use and distribute SSL certificates, as well as manage firewalls or source/destination IP addresses.
  • (optionally) IAM DB Authentication: provides support for Cloud SQL’s automatic IAM DB AuthN feature.

For users migrating from the Cloud SQL Proxy drivers, see the migration guide.

For a quick example, try out the Go Connector in a Codelab.

[!WARNING] Go versions 1.25.2 and 1.24.8 are NOT compatible with Cloud SQL Go Connector.

A recent update to the Go version 1.25.2 and Go 1.24.8 breaks SAN verificaton in Go Connector. This is because Cloud SQL includes a trailing dot in the DNS name within the certificate's Subject Alternative Name (SAN), which the above Go versions reject as a malformed DNS name.

For more details, please see the related Go issue: crypto/x509: quadratic complexity when checking name constraints .

Installation

[!IMPORTANT] The Cloud SQL Go Connector requires Go 1.26 or later. Go 1.25 is no longer supported, because required security fixes in golang.org/x/crypto (v0.56.0+) and other dependencies need Go 1.26. See Supported Go Versions.

You can install this repo with go get:

go get cloud.google.com/go/cloudsqlconn

Usage

This package provides several functions for authorizing and encrypting connections. These functions can be used with your database driver to connect to your Cloud SQL instance.

The instance connection name for your Cloud SQL instance is always in the format project:region:instance.

APIs and Services

This package requires the following to successfully make Cloud SQL Connections:

  • IAM principal (user, service account, etc.) with the Cloud SQL Client role or equivalent. This IAM principal will be used for credentials.
  • The Cloud SQL Admin API to be enabled within your Google Cloud Project. By default, the API will be called in the project associated with the IAM principal.

Credentials

This project uses the Application Default Credentials (ADC) strategy for resolving credentials. Please see these instructions for how to set your ADC (Google Cloud Application vs Local Development, IAM user vs service account credentials), or consult the golang.org/x/oauth2/google documentation.

To explicitly set a specific source for the Credentials, see Using Options below.

Connecting to a database

Postgres

Postgres users have the option of using the database/sql interface or using pgx directly. See pgx's advice on which to choose.

Using the dialer with pgx

To use the dialer with pgx, we recommend using connection pooling with pgxpool by configuring a Config.DialFunc like so:

import (
    "context"
    "net"

    "cloud.google.com/go/cloudsqlconn"
    "github.com/jackc/pgx/v5/pgxpool"
)

func connect() {
    // Configure the driver to connect to the database
    dsn := "user=myuser password=mypass dbname=mydb sslmode=disable"
    config, err := pgxpool.ParseConfig(dsn)
    if err != nil {
        /* handle error */
    }

    // Create a new dialer with any options
    d, err := cloudsqlconn.NewDialer(context.Background())
    if err != nil {
        /* handle error */
    }

    // Tell the driver to use the Cloud SQL Go Connector to create connections
    config.ConnConfig.DialFunc = func(ctx context.Context, _ string, instance string) (net.Conn, error) {
        return d.Dial(ctx, "project:region:instance")
    }

    // Interact with the driver directly as you normally would
    pool, err := pgxpool.NewWithConfig(context.Background(), config)
    if err != nil {
        /* handle error */
    }

    // call cleanup when you're done with the database connection
    cleanup := func() error { return d.Close() }
    // ... etc
}
Using the dialer with database/sql

To use database/sql, call pgxv5.RegisterDriver with any necessary Dialer configuration. Note: the connection string must use the keyword/value format with host set to the instance connection name. The returned cleanup func will stop the dialer's background refresh goroutine and so should only be called when you're done with the Dialer.

[!NOTE]

Keyword/value connection strings follow PostgreSQL libpq escaping rules (pgx v5.11.0+). If your password or other values contain spaces, single quotes ('), or backslashes (\), wrap the value in single quotes and escape ' as \' and \ as \\.

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/postgres/pgxv5"
)

func connect() {
    cleanup, err := pgxv5.RegisterDriver("cloudsql-postgres", cloudsqlconn.WithIAMAuthN())
    if err != nil {
        // ... handle error
    }
    // call cleanup when you're done with the database connection
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-postgres",
        "host=project:region:instance user=myuser password=mypass dbname=mydb sslmode=disable",
    )
    if err != nil {
        // ... handle error
    }
    // close the pool before cleanup() so that connection-close metrics are
    // recorded by the Dialer before it shuts down
    defer db.Close()
    // ... etc
}
MySQL

To use database/sql, use mysql.RegisterDriver with any necessary Dialer configuration. The returned cleanup func will stop the dialer's background refresh goroutine and so should only be called when you're done with the Dialer.

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/mysql/mysql"
)

func connect() {
    cleanup, err := mysql.RegisterDriver("cloudsql-mysql", cloudsqlconn.WithCredentialsFile("key.json"))
    if err != nil {
        // ... handle error
    }
    // call cleanup when you're done with the database connection
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-mysql",
        "myuser:mypass@cloudsql-mysql(project:region:instance)/mydb",
    )
    // ... etc
}
SQL Server

To use database/sql, use mssql.RegisterDriver with any necessary Dialer configuration. The returned cleanup func will stop the dialer's background refresh goroutine and so should only be called when you're done with the Dialer.

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/sqlserver/mssql"
)

func connect() {
    cleanup, err := mssql.RegisterDriver("cloudsql-sqlserver", cloudsqlconn.WithCredentialsFile("key.json"))
    if err != nil {
        // ... handle error
    }
    // call cleanup when you're done with the database connection
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-sqlserver",
        "sqlserver://user:password@localhost?database=mydb&cloudsql=project:region:instance",
    )
    // ... etc
}

Using Advanced Disaster Recovery and DNS domain names to identify instances

The connector can be configured to use DNS to look up an instance. Use a DNS name managed by Cloud SQL Advanced Disaster Recovery, or a domain name that you manage.

Using Advanced Recovery Write Endpoint DNS Name

Advanced Disaster Recovery creates geographically distributed replicas of your Cloud SQL database instance. When you perform switchover or failover on the database instance, the connector will gracefully disconnect from the old primary instance and reconnect to the new primary instance.

Follow the instructions in Connect using Write Endpoint to get the write endpoint DNS name for your primary instance. Then, use this write endpoint DNS name to configure the connector.

Configure your DNS Records

The connector may be configured to use DNS that you define as well.

Add a DNS TXT record for the Cloud SQL instance to a private DNS server or a private Google Cloud DNS Zone used by your application.

Note: You are strongly discouraged from adding DNS records for your Cloud SQL instances to a public DNS server. This would allow anyone on the internet to discover the Cloud SQL instance name.

For example: suppose you wanted to use the domain name prod-db.mycompany.example.com to connect to your database instance my-project:region:my-instance. You would create the following DNS record:

  • Record type: TXT
  • Name: prod-db.mycompany.example.com – This is the domain name used by the application
  • Value: my-project:region:my-instance – This is the instance name
Configure the connector

Configure the connector as described above, replacing the connector ID with the DNS name.

Adapting the MySQL + database/sql example above:

package main

import (
	"database/sql"

	"cloud.google.com/go/cloudsqlconn"
	"cloud.google.com/go/cloudsqlconn/mysql/mysql"
)

func connect() {
	cleanup, err := mysql.RegisterDriver("cloudsql-mysql",
		cloudsqlconn.WithDNSResolver())
	if err != nil {
		// ... handle error
	}
	// call cleanup when you're done with the database connection
	defer cleanup()

	db, err := sql.Open(
		"cloudsql-mysql",
		"myuser:mypass@cloudsql-mysql(prod-db.mycompany.example.com)/mydb",
	)
	// ... etc
}

Automatic fail-over using DNS domain names

When the connector is configured using a domain name, the connector will periodically check if the DNS record for an instance changes. When the connector detects that the domain name refers to a different instance, the connector will close all open connections to the old instance. Subsequent connection attempts will be directed to the new instance.

For example: suppose application is configured to connect using the domain name prod-db.mycompany.example.com. Initially the corporate DNS zone has a TXT record with the value my-project:region:my-instance. The application establishes connections to the my-project:region:my-instance Cloud SQL instance.

Then, to reconfigure the application to use a different database instance, change the value of the prod-db.mycompany.example.com DNS record from my-project:region:my-instance to my-project:other-region:my-instance-2

The connector inside the application detects the change to this DNS record. Now, when the application connects to its database using the domain name prod-db.mycompany.example.com, it will connect to the my-project:other-region:my-instance-2 Cloud SQL instance.

The connector will automatically close all existing connections to my-project:region:my-instance. This will force the connection pools to establish new connections. Also, it may cause database queries in progress to fail.

The connector will poll for changes to the DNS name every 30 seconds by default. You may configure the frequency of the connections using the option WithFailoverPeriod(d time.Duration). When this is set to 0, the connector will disable polling and only check if the DNS record changed when it is creating a new connection.

Using Options

If you need to customize something about the Dialer, you can initialize directly with NewDialer:

d, err := cloudsqlconn.NewDialer(
    ctx,
    cloudsqlconn.WithCredentialsFile("key.json"),
)
if err != nil {
    log.Fatalf("unable to initialize dialer: %s", err)
}

conn, err := d.Dial(ctx, "project:region:instance")

For a full list of customizable behavior, see Option.

Using DialOptions

If you want to customize things about how the connection is created, use Option:

conn, err := d.Dial(
    ctx,
    "project:region:instance",
    cloudsqlconn.WithPrivateIP(),
)

You can also use the WithDefaultDialOptions Option to specify DialOptions to be used by default:

d, err := cloudsqlconn.NewDialer(
    ctx,
    cloudsqlconn.WithDefaultDialOptions(
        cloudsqlconn.WithPrivateIP(),
    ),
)

Automatic IAM Database Authentication

Connections using Automatic IAM database authentication are supported when using Postgres or MySQL drivers.

Make sure to configure your Cloud SQL Instance to allow IAM authentication and add an IAM database user.

A Dialer can be configured to connect to a Cloud SQL instance using automatic IAM database authentication with the WithIAMAuthN Option (recommended) or the WithDialIAMAuthN DialOption.

d, err := cloudsqlconn.NewDialer(ctx, cloudsqlconn.WithIAMAuthN())

When configuring the DSN for IAM authentication, the password field can be omitted and the user field should be formatted as follows:

Postgres: For an IAM user account, this is the user's email address. For a service account, it is the service account's email without the .gserviceaccount.com domain suffix.

MySQL: For an IAM user account, this is the user's email address, without the @ or domain name. For example, for test-user@gmail.com, set the user field to test-user. For a service account, this is the service account's email address without the @project-id.iam.gserviceaccount.com suffix.

Example DSNs using the test-sa@test-project.iam.gserviceaccount.com service account to connect can be found below.

Postgres:

dsn := "user=test-sa@test-project.iam dbname=mydb sslmode=disable"

MySQL:

dsn := "user=test-sa dbname=mydb sslmode=disable"

Built-in Client Metrics (BETA)

The connector reports client-side connection metrics to Cloud Monitoring under the cloudsql.googleapis.com/client/connector/ prefix, using the cloudsql.googleapis.com/InstanceClient monitored resource. These metrics help you (and Cloud SQL) spot connectivity regressions, for example a rise in failed dial attempts or in dial latency. They are enabled by default.

Metric Description
open_connection_count Dial attempts, labelled with status and connection_part
connect_latencies Dial latency distribution (ms)
open_connections Currently open connections
closed_connection_count Closed connections
connection_durations Connection lifetime distribution (s)

Metrics are written to the Cloud SQL instance's project using the same identity the connector uses for the Cloud SQL Admin API. That identity needs the roles/monitoring.metricWriter role on that project. If you pass your own token source or credentials (WithTokenSource, WithCredentials, or an impersonated credential), they must also carry the https://www.googleapis.com/auth/monitoring.write (or cloud-platform) scope; credentials the connector detects itself are scoped automatically. Export is strictly fail-open: it never affects connectivity. If the identity lacks the role or the scope, the connector logs one line per process explaining what to fix and retries with exponential backoff (up to once per hour); all further diagnostics go to the debug logger only.

In a non-default Cloud universe (a universe domain other than googleapis.com), built-in metrics are off unless you pass WithBuiltInMetrics(true).

The export is billed to the caller's project (for a service account, the project it belongs to), which must have the Cloud Monitoring API enabled. WithQuotaProject changes the billed project, as it does for the Cloud SQL Admin API.

Hermetic tests that construct a Dialer against a mock Admin API (WithAdminAPIEndpoint, WithHTTPClient) should pass WithBuiltInMetrics(false) so the test does not try to reach Cloud Monitoring.

To turn built-in metrics off:

d, err := cloudsqlconn.NewDialer(ctx, cloudsqlconn.WithBuiltInMetrics(false))

Two optional labels can be set by the application:

d, err := cloudsqlconn.NewDialer(ctx,
    cloudsqlconn.WithApplicationName("my-service"),                      // application_name
    cloudsqlconn.WithComputePlatform(cloudsqlconn.ComputePlatformCloudRun), // overrides auto-detection
)

application_name identifies your application and groups its metrics across all of its instances. It is only ever the value you set here and is left empty otherwise; the connector does not infer it from the environment (instances are already told apart by client_uid, and compute_platform is auto-detected).

WithComputePlatform accepts only the ComputePlatform* constants. To take the platform from a string such as a flag value, use cloudsqlconn.ParseComputePlatform(s); cloudsqlconn.ComputePlatforms() lists the valid values for help text.

Metrics are exported every 60 seconds and flushed when Dialer.Close() is called, so short-lived processes should close the Dialer before exiting.

These metrics are in BETA: label values are documented in the metric descriptors and pinned by tests, but the feature is subject to the Cloud SQL pre-GA terms.

Enabling Metrics and Tracing

This library includes support for metrics and tracing using OpenCensus. To enable metrics or tracing, you need to configure an exporter. OpenCensus supports many backends for exporters.

Supported metrics include:

  • cloudsqlconn/dial_latency: The distribution of dialer latencies (ms)
  • cloudsqlconn/open_connections: The current number of open Cloud SQL connections
  • cloudsqlconn/dial_failure_count: The number of failed dial attempts
  • cloudsqlconn/refresh_success_count: The number of successful certificate refresh operations
  • cloudsqlconn/refresh_failure_count: The number of failed refresh operations
  • cloudsqlconn/bytes_sent: The number of bytes sent to Cloud SQL
  • cloudsqlconn/bytes_received: The number of bytes received from Cloud SQL

Supported traces include:

  • cloud.google.com/go/cloudsqlconn.Dial: The dial operation including refreshing an ephemeral certificate and connecting the instance
  • cloud.google.com/go/cloudsqlconn/internal.InstanceInfo: The call to retrieve instance metadata (e.g., database engine type, IP address, etc)
  • cloud.google.com/go/cloudsqlconn/internal.Connect: The connection attempt using the ephemeral certificate
  • SQL Admin API client operations

For example, to use Cloud Monitoring and Cloud Trace, you would configure an exporter like so:

import (
    "contrib.go.opencensus.io/exporter/stackdriver"
    "go.opencensus.io/trace"
)

func main() {
    sd, err := stackdriver.NewExporter(stackdriver.Options{
        ProjectID: "mycoolproject",
    })
    if err != nil {
        // handle error
    }
    defer sd.Flush()
    trace.RegisterExporter(sd)

    sd.StartMetricsExporter()
    defer sd.StopMetricsExporter()

    // Use cloudsqlconn as usual.
    // ...
}

As OpenTelemetry has now reached feature parity with OpenCensus, the migration from OpenCensus to OpenTelemetry is strongly encouraged. OpenTelemetry bridge can be leveraged to migrate to OpenTelemetry without the need of replacing the OpenCensus APIs in this library. Example code is shown below for migrating an application using the OpenTelemetry bridge for traces.

import (
	texporter "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
	"go.opencensus.io/trace"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/bridge/opencensus"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"google.golang.org/api/option"
)

func main() {
	// trace.AlwaysSample() is expensive. Replacing it with your own
	// sampler for production environments is recommended.
	trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})

	exporter, err := texporter.New(
		texporter.WithTraceClientOptions([]option.ClientOption{option.WithTelemetryDisabled()}),
		texporter.WithProjectID("mycoolproject"),
	)
	if err != nil {
		// Handle error
	}

	tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exporter))
	otel.SetTracerProvider(tp)
	tracer := tp.Tracer("Cloud SQL Go Connector Trace")
	trace.DefaultTracer = opencensus.NewTracer(tracer)

	// Use cloudsqlconn as usual.
	// ...
}

A known OpenTelemetry issue has been reported here. It shouldn't impact database operations.

Debug Logging

The Go Connector supports optional debug logging to help diagnose problems with the background certificate refresh. To enable it, provide a logger that implements the debug.ContextLogger interface when initializing the Dialer.

For example:

import (
    "context"
    "net"

    "cloud.google.com/go/cloudsqlconn"
)

type myLogger struct{}

func (l *myLogger) Debugf(ctx context.Context, format string, args ...interface{}) {
    // Log as you like here
}

func connect() {
    l := &myLogger{}

    d, err := NewDialer(
        context.Background(),
        cloudsqlconn.WithContextDebugLogger(l),
    )
    // use dialer as usual...
}

Support policy

Major version lifecycle

This project uses semantic versioning, and uses the following lifecycle regarding support for a major version:

Active - Active versions get all new features and security fixes (that wouldn’t otherwise introduce a breaking change). New major versions are guaranteed to be "active" for a minimum of 1 year.

Deprecated - Deprecated versions continue to receive security and critical bug fixes, but do not receive new features. Deprecated versions will be supported for 1 year.

Unsupported - Any major version that has been deprecated for >=1 year is considered unsupported.

Supported Go Versions

We follow the Go Version Support Policy used by Google Cloud Libraries for Go.

The minimum supported Go version is Go 1.26, as declared in go.mod.

Release cadence

This project aims for a release on at least a monthly basis. If no new features or fixes have been added, a new PATCH version with the latest dependencies is released.

Documentation

Overview

Package cloudsqlconn provides functions for authorizing and encrypting connections. These functions can be used with a database driver to connect to a Cloud SQL instance.

The instance connection name for a Cloud SQL instance is always in the format "project:region:instance".

Creating a Dialer

To start working with this package, create a Dialer. There are two ways of creating a Dialer, which one you use depends on your database driver.

Postgres

Postgres users have the option of using the database/sql interface or using pgx directly.

To use a dialer with pgx, we recommend using connection pooling with pgxpool. To create the dialer use the NewDialer func.

import (
    "context"
    "net"

    "cloud.google.com/go/cloudsqlconn"
    "github.com/jackc/pgx/v5/pgxpool"
)

func connect() {
    // Configure the driver to connect to the database
    dsn := "user=myuser password=mypass dbname=mydb sslmode=disable"
    config, err := pgxpool.ParseConfig(dsn)
    if err != nil {
	    // handle error
    }

    // Create a new dialer with any options
    d, err := cloudsqlconn.NewDialer(context.Background())
    if err != nil {
	    // handle error
    }

    // Tell the driver to use the Cloud SQL Go Connector to create connections
    config.ConnConfig.DialFunc = func(ctx context.Context, _ string, instance string) (net.Conn, error) {
	    return d.Dial(ctx, "project:region:instance")
    }

    // Interact with the driver directly as you normally would
    conn, err := pgxpool.NewWithConfig(context.Background(), config)
    if err != nil {
	    // handle error
    }

    // call cleanup when you're done with the database connection
    cleanup := func() error { return d.Close() }
    // ... etc
}

To use database/sql, call pgxv5.RegisterDriver with any necessary Dialer configuration.

Note: the connection string must use the keyword/value format with host set to the instance connection name. The returned cleanup func will stop the dialer's background refresh goroutine and so should only be called when you're done with the Dialer.

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/postgres/pgxv5"
)

func connect() {
    // adjust options as needed
    cleanup, err := pgxv5.RegisterDriver("cloudsql-postgres", cloudsqlconn.WithIAMAuthN())
    if err != nil {
    	// ... handle error
    }
    // call cleanup when you're done with the database connection
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-postgres",
        "host=project:region:instance user=myuser password=mypass dbname=mydb sslmode=disable",
    )
    // ... etc
}

MySQL

MySQL users should use database/sql. Use mysql.RegisterDriver with any necessary Dialer configuration.

Note: The returned cleanup func will stop the dialer's background refresh goroutine and should only be called when you're done with the Dialer.

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/mysql/mysql"
)

func connect() {
    // adjust options as needed
    cleanup, err := mysql.RegisterDriver("cloudsql-mysql", cloudsqlconn.WithIAMAuthN())
    if err != nil {
        // ... handle error
    }
    // call cleanup when you're done with the database connection
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-mysql",
        "myuser:mypass@cloudsql-mysql(project:region:instance)/mydb",
    )
    // ... etc
}

SQL Server

SQL Server users should use database/sql. Use mssql.RegisterDriver with any necessary Dialer configuration.

Note: The returned cleanup func will stop the dialer's background refresh goroutine and should only be called when you're done with the Dialer.

import (
    "database/sql"

    "cloud.google.com/go/cloudsqlconn"
    "cloud.google.com/go/cloudsqlconn/sqlserver/mssql"
)

func connect() {
    cleanup, err := mssql.RegisterDriver("cloudsql-sqlserver")
    if err != nil {
        // ... handle error
    }
    // call cleanup when you're done with the database connection
    defer cleanup()

    db, err := sql.Open(
        "cloudsql-sqlserver",
        "sqlserver://user:password@localhost?database=mydb&cloudsql=project:region:instance",
    )
    // ... etc
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDialerClosed is used when a caller invokes Dial after closing the
	// Dialer.
	ErrDialerClosed = errors.New("cloudsqlconn: dialer is closed")
)

Functions

This section is empty.

Types

type ComputePlatform added in v1.26.0

type ComputePlatform string

ComputePlatform identifies the platform an application runs on. It is reported as the compute_platform label of built-in metrics.

The set of valid values is closed: only the ComputePlatform* constants defined in this package are accepted by WithComputePlatform. This keeps the cardinality of the metric's monitored resource bounded.

const (
	// ComputePlatformGCE identifies Compute Engine.
	ComputePlatformGCE ComputePlatform = tel.PlatformGCE
	// ComputePlatformGKE identifies Google Kubernetes Engine.
	ComputePlatformGKE ComputePlatform = tel.PlatformGKE
	// ComputePlatformCloudRun identifies Cloud Run.
	ComputePlatformCloudRun ComputePlatform = tel.PlatformCloudRun
	// ComputePlatformAppEngine identifies App Engine.
	ComputePlatformAppEngine ComputePlatform = tel.PlatformAppEngine
	// ComputePlatformCloudFunctions identifies Cloud Functions.
	ComputePlatformCloudFunctions ComputePlatform = tel.PlatformCloudFunctions
	// ComputePlatformAIStudio identifies applications deployed by Google AI
	// Studio. This platform cannot be auto-detected and must be set
	// explicitly with WithComputePlatform.
	ComputePlatformAIStudio ComputePlatform = tel.PlatformAIStudio
)

func ComputePlatforms added in v1.26.0

func ComputePlatforms() []ComputePlatform

ComputePlatforms returns every valid ComputePlatform value, in a stable order. It is intended for help text and validation in clients that accept the platform as a string, such as a command-line flag.

func ParseComputePlatform added in v1.26.0

func ParseComputePlatform(s string) (ComputePlatform, error)

ParseComputePlatform converts a string, for example a command-line flag value, to a ComputePlatform. Leading and trailing whitespace is ignored and matching is case-insensitive, so "ai_studio", "AI_STUDIO", and " ai_studio " all return ComputePlatformAIStudio. Any other value returns an error that lists the valid values.

Use this rather than a type conversion such as ComputePlatform(s): a conversion accepts any string and is only rejected later, when NewDialer validates the option.

type DialOption

type DialOption func(d *dialConfig)

A DialOption is an option for configuring how a Dialer's Dial call is executed.

func DialOptions

func DialOptions(opts ...DialOption) DialOption

DialOptions turns a list of DialOption instances into an DialOption.

func WithAutoIP added in v1.0.0

func WithAutoIP() DialOption

WithAutoIP returns a DialOption that selects the public IP if available and otherwise falls back to private IP. This option is present for backwards compatibility only and is not recommended for use in production.

func WithDialIAMAuthN added in v0.4.0

func WithDialIAMAuthN(b bool) DialOption

WithDialIAMAuthN allows you to enable or disable IAM Authentication for this instance as described in the documentation for WithIAMAuthN. This value will override the Dialer-level configuration set with WithIAMAuthN.

WARNING: This DialOption can cause a new Refresh operation to be triggered. Toggling this option on or off between Dials may cause increased API usage and/or delayed connection attempts.

func WithMdxClientProtocolType added in v1.19.0

func WithMdxClientProtocolType(s string) DialOption

WithMdxClientProtocolType controls client protocol type is sent to the server in the metadata exchange request. This may be one of cloudsql.ClientProtocolTLS cloudsql.ClientProtocolTCP or cloudsql.ClientProtocolUDS. If this is empty, it will be omitted from the MDX request. This is important for MySQL clients that use caching_sha2_password. Valid values: "tls" "tcp" "uds"

func WithOneOffDialFunc added in v1.3.0

func WithOneOffDialFunc(dial func(ctx context.Context, network, addr string) (net.Conn, error)) DialOption

WithOneOffDialFunc configures the dial function on a one-off basis for an individual call to Dial. To configure a dial function across all invocations of Dial, use WithDialFunc.

func WithPSC added in v1.4.0

func WithPSC() DialOption

WithPSC returns a DialOption that specifies a PSC endpoint will be used to connect.

func WithPrivateIP

func WithPrivateIP() DialOption

WithPrivateIP returns a DialOption that specifies a private IP (VPC) will be used to connect.

func WithPublicIP

func WithPublicIP() DialOption

WithPublicIP returns a DialOption that specifies a public IP will be used to connect.

func WithSQLData added in v1.22.0

func WithSQLData() DialOption

WithSQLData returns a DialOption that routes traffic through the SQL Data API endpoint. This dial option allows the dialer to reach the target instance when there is not a network path.

func WithTCPKeepAlive

func WithTCPKeepAlive(d time.Duration) DialOption

WithTCPKeepAlive returns a DialOption that specifies the tcp keep alive period for the connection returned by Dial.

type Dialer

type Dialer struct {
	// contains filtered or unexported fields
}

A Dialer is used to create connections to Cloud SQL instances.

Use NewDialer to initialize a Dialer.

func NewDialer

func NewDialer(ctx context.Context, opts ...Option) (*Dialer, error)

NewDialer creates a new Dialer.

Initial calls to NewDialer make take longer than normal because generation of an RSA keypair is performed. Calls with a WithRSAKeyPair DialOption or after a default RSA keypair is generated will be faster.

func (*Dialer) Close

func (d *Dialer) Close() error

Close closes the Dialer; it prevents the Dialer from refreshing the information needed to connect.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context, icn string, opts ...DialOption) (conn net.Conn, err error)

Dial returns a net.Conn connected to the specified Cloud SQL instance. The icn argument may be the instance's connection name in the format "project-name:region:instance-name" or a DNS name that resolves to an instance connection name.

func (*Dialer) EngineVersion

func (d *Dialer) EngineVersion(ctx context.Context, icn string) (string, error)

EngineVersion returns the engine type and version for the instance connection name. The value will correspond to one of the following types for the instance: https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/SqlDatabaseVersion

func (*Dialer) Warmup added in v0.4.0

func (d *Dialer) Warmup(ctx context.Context, icn string, opts ...DialOption) error

Warmup starts the background refresh necessary to connect to the instance. Use Warmup to start the refresh process early if you don't know when you'll need to call "Dial".

type Option

type Option func(d *dialerConfig)

An Option is an option for configuring a Dialer.

func WithAdminAPIEndpoint added in v0.3.0

func WithAdminAPIEndpoint(url string) Option

WithAdminAPIEndpoint configures the underlying SQL Admin API client to use the provided URL.

func WithApplicationName added in v1.26.0

func WithApplicationName(name string) Option

WithApplicationName returns an Option that sets the application_name label of the built-in metrics, which identifies the application and groups its metrics across all of its instances (for example "checkout-api").

The label is only ever what the application declares here; when it is not set it is left empty. The connector does not infer a value from the environment: compute_platform already says where the connector runs and client_uid already tells instances apart, and a per-instance name (VM or pod) would split a service's metrics into one series per instance.

func WithBuiltInMetrics added in v1.26.0

func WithBuiltInMetrics(enabled bool) Option

WithBuiltInMetrics enables or disables the built-in metric export. When enabled, the Dialer reports on its internal operations (connection attempts, dial latency, open connections, connection durations) to Cloud Monitoring under the cloudsql.googleapis.com/client/connector metric prefix, using the cloudsql.googleapis.com/InstanceClient monitored resource. These metrics help Cloud SQL improve performance and identify client connectivity problems.

Built-in metrics are enabled by default and are in BETA. Pass false to turn them off. In a non-default Cloud universe (a universe domain other than googleapis.com) they are off by default and must be enabled explicitly.

Metrics never affect connectivity. If the exporter cannot be created, or an export fails (for example, a missing IAM permission), connections continue to work: the first permanent failure is reported once per process on the standard logger with remediation steps, further failures are reported through the debug logger only, and exports are retried with backoff.

The identity used by the Dialer must have the roles/monitoring.metricWriter role on the Cloud SQL instance's project for the export to succeed.

The metric export uses the same identity as the Dialer's API calls. When the Dialer detects credentials itself (Application Default Credentials, WithCredentialsFile, or WithCredentialsJSON), it requests the https://www.googleapis.com/auth/monitoring.write scope for the export. When a token source or credentials are supplied directly (WithTokenSource, WithCredentials, WithIAMAuthNTokenSources, WithIAMAuthNCredentials), the supplied API token source is used as-is and must carry either the monitoring.write or the cloud-platform scope.

func WithComputePlatform added in v1.26.0

func WithComputePlatform(p ComputePlatform) Option

WithComputePlatform returns an Option that overrides the auto-detected compute platform reported in built-in metrics. Use it when the Dialer is embedded in a client that knows its deployment environment better than runtime heuristics can determine (for example, the Cloud SQL Auth Proxy running as a sidecar for an AI Studio application).

Only the ComputePlatform* constants are accepted; any other value causes NewDialer to return a configuration error. To accept the platform as a string (for example from a command-line flag), convert it with ParseComputePlatform first. When this option is not provided, the platform is detected from the runtime environment.

func WithContextDebugLogger added in v1.10.0

func WithContextDebugLogger(l debug.ContextLogger) Option

WithContextDebugLogger configures a debug logger for reporting on internal operations. By default the debug logger is disabled.

func WithCredentials added in v1.18.0

func WithCredentials(c *auth.Credentials) Option

WithCredentials returns an Option that specifies an OAuth2 token source to be used as the basis for authentication.

When Auth IAM AuthN is enabled, use WithIAMAuthNTokenSources to set the token source for login tokens separately from the API client token source.

You may only use one of the following options: WithIAMAuthNCredentials, WithIAMAuthNTokenSources, WithCredentials, WithTokenSource

func WithCredentialsFile

func WithCredentialsFile(filename string) Option

WithCredentialsFile returns an Option that specifies a service account or refresh token JSON credentials file to be used as the basis for authentication.

func WithCredentialsJSON

func WithCredentialsJSON(b []byte) Option

WithCredentialsJSON returns an Option that specifies a service account or refresh token JSON credentials to be used as the basis for authentication.

func WithDNSResolver added in v1.12.0

func WithDNSResolver() Option

WithDNSResolver replaces the default resolver (which only resolves instance names) with the DNSResolver, which will attempt to first parse the instance name, and then will attempt to resolve the DNS TXT record to determine the instance name.

First, add a record for your Cloud SQL instance to a **private** DNS server or a private Google Cloud DNS Zone used by your application.

**Note:** You are strongly discouraged from adding DNS records for your Cloud SQL instances to a public DNS server. This would allow anyone on the internet to discover the Cloud SQL instance name.

For example: suppose you wanted to use the domain name `prod-db.mycompany.example.com` to connect to your database instance `my-project:region:my-instance`. You would create the following DNS record:

  • Record type: `TXT`
  • Name: `prod-db.mycompany.example.com` – This is the domain name used by the application
  • Value: `my-project:region:my-instance` – This is the instance name

func WithDebugLogger added in v1.7.0

func WithDebugLogger(l debug.Logger) Option

WithDebugLogger configures a debug lgoger for reporting on internal operations. By default the debug logger is disabled.

Prefer WithContextDebugLogger instead

func WithDefaultDialOptions

func WithDefaultDialOptions(opts ...DialOption) Option

WithDefaultDialOptions returns an Option that specifies the default DialOptions used.

func WithDialFunc

func WithDialFunc(dial func(ctx context.Context, network, addr string) (net.Conn, error)) Option

WithDialFunc configures the function used to connect to the address on the named network. This option is generally unnecessary except for advanced use-cases. The function is used for all invocations of Dial. To configure a dial function per individual calls to dial, use WithOneOffDialFunc.

func WithDisableMetadataExchange added in v1.19.0

func WithDisableMetadataExchange() Option

WithDisableMetadataExchange enables or disables the dialer from sending the metadata exchange message to the instance on each connection. This is necessary for MySQL instances with caching_sha2_passwords. Metadata Exchange is enabled by default for instances that accept MDX.

func WithFailoverPeriod added in v1.13.0

func WithFailoverPeriod(f time.Duration) Option

WithFailoverPeriod will cause the connector to periodically check the SRV DNS records of instance configured using DNS names. By default, this is 30 seconds. If this is set to 0, the connector will only check for domain name changes when establishing a new connection.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient configures the underlying SQL Admin API client with the provided HTTP client. This option is generally unnecessary except for advanced use-cases.

func WithIAMAuthN

func WithIAMAuthN() Option

WithIAMAuthN enables automatic IAM Authentication. If no token source has been configured (such as with WithTokenSource, WithCredentialsFile, etc), the dialer will use the default token source as defined by https://pkg.go.dev/golang.org/x/oauth2/google#FindDefaultCredentialsWithParams.

For documentation on automatic IAM Authentication, see https://cloud.google.com/sql/docs/postgres/authentication.

func WithIAMAuthNCredentials added in v1.18.0

func WithIAMAuthNCredentials(apiCreds, iamCreds *auth.Credentials) Option

WithIAMAuthNCredentials sets the oauth2.TokenSource for the API client and a second token source for IAM AuthN login tokens. The API client token source should have the following scopes:

  1. https://www.googleapis.com/auth/sqlservice.admin, and
  2. https://www.googleapis.com/auth/cloud-platform

The IAM AuthN token source on the other hand should only have:

  1. https://www.googleapis.com/auth/sqlservice.login.

Prefer this option over WithTokenSource or WithCredentials when using IAM AuthN which does not distinguish between the two token sources.

You may only use one of the following options: WithIAMAuthNCredentials, WithIAMAuthNTokenSources, WithCredentials, WithTokenSource

func WithIAMAuthNTokenSources added in v1.0.0

func WithIAMAuthNTokenSources(apiTS, iamLoginTS oauth2.TokenSource) Option

WithIAMAuthNTokenSources sets the oauth2.TokenSource for the API client and a second token source for IAM AuthN login tokens. The API client token source should have the following scopes:

  1. https://www.googleapis.com/auth/sqlservice.admin, and
  2. https://www.googleapis.com/auth/cloud-platform

The IAM AuthN token source on the other hand should only have:

  1. https://www.googleapis.com/auth/sqlservice.login.

Prefer this option over WithTokenSource or WithCredentials when using IAM AuthN which does not distinguish between the two token sources.

You may only use one of the following options: WithIAMAuthNCredentials, WithIAMAuthNTokenSources, WithCredentials, WithTokenSource

func WithLazyRefresh added in v1.9.0

func WithLazyRefresh() Option

WithLazyRefresh configures the dialer to refresh certificates on an as-needed basis. If a certificate is expired when a connection request occurs, the Go Connector will block the attempt and refresh the certificate immediately. This option is useful when running the Go Connector in environments where the CPU may be throttled, thus preventing a background goroutine from running consistently (e.g., in Cloud Run the CPU is throttled outside of a request context causing the background refresh to fail).

func WithOptions

func WithOptions(opts ...Option) Option

WithOptions turns a list of Option's into a single Option.

func WithQuotaProject added in v0.5.0

func WithQuotaProject(p string) Option

WithQuotaProject returns an Option that specifies the project used for quota and billing purposes.

func WithRSAKey

func WithRSAKey(k *rsa.PrivateKey) Option

WithRSAKey returns an Option that specifies a rsa.PrivateKey used to represent the client.

func WithRefreshTimeout

func WithRefreshTimeout(t time.Duration) Option

WithRefreshTimeout returns an Option that sets a timeout on refresh operations. Defaults to 60s.

func WithResolver added in v1.12.0

func WithResolver(r instance.ConnectionNameResolver) Option

WithResolver replaces the default resolver with an alternate implementation to resolve the name in the database DSN to a Cloud SQL instance.

func WithResourceExhaustedCooldownPeriod added in v1.24.0

func WithResourceExhaustedCooldownPeriod(period time.Duration) Option

WithResourceExhaustedCooldownPeriod sets the cooldown period after a ResourceExhausted error.

func WithSQLDataDialer added in v1.22.0

func WithSQLDataDialer(dialer sqldataclient.Dialer) Option

WithSQLDataDialer allows callers to override the default dialer for the SQLDataService with an alternate dialer.

func WithSQLDataEndpoint added in v1.22.0

func WithSQLDataEndpoint(endpoint string) Option

WithSQLDataEndpoint allows callers to override the default endpoint for the SQL Data API. Typically, this is for development only and should be ignored otherwise.

func WithSQLDataStreamTimeout added in v1.22.0

func WithSQLDataStreamTimeout(timeout time.Duration) Option

WithSQLDataStreamTimeout sets the maximum time allowed for a stream to SQLDataService

func WithTokenSource

func WithTokenSource(s oauth2.TokenSource) Option

WithTokenSource returns an Option that specifies an OAuth2 token source to be used as the basis for authentication.

When Auth IAM AuthN is enabled, use WithIAMAuthNTokenSources or WithIAMAuthNCredentials to set the token source for login tokens separately from the API client token source.

You may only use one of the following options: WithIAMAuthNCredentials, WithIAMAuthNTokenSources, WithCredentials, WithTokenSource

func WithUniverseDomain added in v1.8.0

func WithUniverseDomain(ud string) Option

WithUniverseDomain configures the underlying SQL Admin API client to use the provided universe domain. Enables Trusted Partner Cloud (TPC).

func WithUserAgent added in v0.3.0

func WithUserAgent(ua string) Option

WithUserAgent returns an Option that sets the User-Agent.

Directories

Path Synopsis
Package errtype provides a number of concrete types which are used by the cloudsqlconn package.
Package errtype provides a number of concrete types which are used by the cloudsqlconn package.
internal
mdx
tel
Package mysql provides a Cloud SQL MySQL driver that uses go-sql-driver/mysql and works with database/sql
Package mysql provides a Cloud SQL MySQL driver that uses go-sql-driver/mysql and works with database/sql
postgres
pgxv4
Package pgxv4 provides a Cloud SQL Postgres driver that uses pgx v4 and works with the database/sql package.
Package pgxv4 provides a Cloud SQL Postgres driver that uses pgx v4 and works with the database/sql package.
pgxv5
Package pgxv5 provides a Cloud SQL Postgres driver that uses pgx v5 and works with the database/sql package.
Package pgxv5 provides a Cloud SQL Postgres driver that uses pgx v5 and works with the database/sql package.
sqlserver
mssql
Package mssql provides a Cloud SQL SQL Server driver that works with the database/sql package.
Package mssql provides a Cloud SQL SQL Server driver that works with the database/sql package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL