Package cloud.google.com/go/cloudsqlconn (v1.19.0)

Note: To get more information about this package, such as access to older versions, viewthis package on pkg.go.dev.

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

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

Creating a Dialer

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

Postgres

Postgres users have the option of using thedatabase/sql interface or usingpgx directly.

To use a dialer withpgx, we recommend using connection pooling withpgxpool. To create the dialer use the NewDialer func.

import("context""net""cloud.google.com/go/cloudsqlconn""github.com/jackc/pgx/v4/pgxpool")funcconnect(){// Configure the driver to connect to the databasedsn:="user=myuser password=mypass dbname=mydb sslmode=disable"config,err:=pgxpool.ParseConfig(dsn)iferr!=nil{// handle error}// Create a new dialer with any optionsd,err:=cloudsqlconn.NewDialer(context.Background())iferr!=nil{// handle error}// Tell the driver to use the Cloud SQL Go Connector to create connectionsconfig.ConnConfig.DialFunc=func(ctxcontext.Context,_string,instancestring)(net.Conn,error){returnd.Dial(ctx,"project:region:instance")}// Interact with the driver directly as you normally wouldconn,err:=pgxpool.ConnectConfig(context.Background(),config)iferr!=nil{// handle error}// call cleanup when you're done with the database connectioncleanup:=func()error{returnd.Close()}// ... etc}

To usedatabase/sql, call pgxv4.RegisterDriver with any necessary Dialerconfiguration.

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

import("database/sql""cloud.google.com/go/cloudsqlconn""cloud.google.com/go/cloudsqlconn/postgres/pgxv4")funcconnect(){// adjust options as neededcleanup,err:=pgxv4.RegisterDriver("cloudsql-postgres",cloudsqlconn.WithIAMAuthN())iferr!=nil{// ... handle error}// call cleanup when you're done with the database connectiondefercleanup()db,err:=sql.Open("cloudsql-postgres","host=project:region:instance user=myuser password=mypass dbname=mydb sslmode=disable",)// ... etc}

MySQL

MySQL users should usedatabase/sql. Use mysql.RegisterDriver with anynecessary Dialer configuration.

Note: The returned cleanup func will stop the dialer's background refreshgoroutine 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")funcconnect(){// adjust options as neededcleanup,err:=mysql.RegisterDriver("cloudsql-mysql",cloudsqlconn.WithIAMAuthN())iferr!=nil{// ... handle error}// call cleanup when you're done with the database connectiondefercleanup()db,err:=sql.Open("cloudsql-mysql","myuser:mypass@cloudsql-mysql(project:region:instance)/mydb",)// ... etc}

SQL Server

SQL Server users should usedatabase/sql. Use mssql.RegisterDriver with anynecessary Dialer configuration.

Note: The returned cleanup func will stop the dialer's background refreshgoroutine 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")funcconnect(){cleanup,err:=mssql.RegisterDriver("cloudsql-sqlserver")iferr!=nil{// ... handle error}// call cleanup when you're done with the database connectiondefercleanup()db,err:=sql.Open("cloudsql-sqlserver","sqlserver://user:password@localhost?database=mydb&cloudsql=project:region:instance",)// ... etc}

Variables

ErrDialerClosed

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

DialOption

typeDialOptionfunc(d*dialConfig)

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

func DialOptions

funcDialOptions(opts...DialOption)DialOption

DialOptions turns a list of DialOption instances into an DialOption.

func WithAutoIP

funcWithAutoIP()DialOption

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

func WithDialIAMAuthN

funcWithDialIAMAuthN(bbool)DialOption

WithDialIAMAuthN allows you to enable or disable IAM Authentication for thisinstance as described in the documentation for WithIAMAuthN. This value willoverride 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 usageand/or delayed connection attempts.

func WithMdxClientProtocolType

funcWithMdxClientProtocolType(sstring)DialOption

WithMdxClientProtocolType controls client protocol type is sent to the serverin the metadata exchange request. This may be one of cloudsql.ClientProtocolTLS cloudsql.ClientProtocolTCPor 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

funcWithOneOffDialFunc(dialfunc(ctxcontext.Context,network,addrstring)(net.Conn,error))DialOption

WithOneOffDialFunc configures the dial function on a one-off basis for anindividual call to Dial. To configure a dial function across all invocationsof Dial, use WithDialFunc.

func WithPSC

funcWithPSC()DialOption

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

func WithPrivateIP

funcWithPrivateIP()DialOption

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

func WithPublicIP

funcWithPublicIP()DialOption

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

func WithTCPKeepAlive

funcWithTCPKeepAlive(dtime.Duration)DialOption

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

Dialer

typeDialerstruct{// contains filtered or unexported fields}

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

Use NewDialer to initialize a Dialer.

func NewDialer

funcNewDialer(ctxcontext.Context,opts...Option)(*Dialer,error)

NewDialer creates a new Dialer.

Initial calls to NewDialer make take longer than normal because generation of anRSA keypair is performed. Calls with a WithRSAKeyPair DialOption or after a defaultRSA 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 informationneeded to connect.

func (*Dialer) Dial

func(d*Dialer)Dial(ctxcontext.Context,icnstring,opts...DialOption)(connnet.Conn,errerror)

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

func (*Dialer) EngineVersion

func(d*Dialer)EngineVersion(ctxcontext.Context,icnstring)(string,error)

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

func (*Dialer) Warmup

func(d*Dialer)Warmup(ctxcontext.Context,icnstring,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'llneed to call "Dial".

Option

typeOptionfunc(d*dialerConfig)

An Option is an option for configuring a Dialer.

func WithAdminAPIEndpoint

funcWithAdminAPIEndpoint(urlstring)Option

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

func WithContextDebugLogger

funcWithContextDebugLogger(ldebug.ContextLogger)Option

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

func WithCredentials

funcWithCredentials(c*auth.Credentials)Option

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

When Auth IAM AuthN is enabled, use WithIAMAuthNTokenSources to set the tokensource 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

funcWithCredentialsFile(filenamestring)Option

WithCredentialsFile returns an Option that specifies a service accountor refresh token JSON credentials file to be used as the basis forauthentication.

func WithCredentialsJSON

funcWithCredentialsJSON(b[]byte)Option

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

func WithDNSResolver

funcWithDNSResolver()Option

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

First, add a record for your Cloud SQL instance to aprivate DNS serveror a private Google Cloud DNS Zone used by your application.

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

For example: suppose you wanted to use the domain nameprod-db.mycompany.example.com to connect to your database instancemy-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 bythe application
  • Value:my-project:region:my-instance – This is the instance name

func WithDebugLogger

funcWithDebugLogger(ldebug.Logger)Option

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

Prefer WithContextDebugLogger instead

func WithDefaultDialOptions

funcWithDefaultDialOptions(opts...DialOption)Option

WithDefaultDialOptions returns an Option that specifies the defaultDialOptions used.

func WithDialFunc

funcWithDialFunc(dialfunc(ctxcontext.Context,network,addrstring)(net.Conn,error))Option

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

func WithDisableMetadataExchange

funcWithDisableMetadataExchange()Option

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

func WithFailoverPeriod

funcWithFailoverPeriod(ftime.Duration)Option

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

func WithHTTPClient

funcWithHTTPClient(client*http.Client)Option

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

func WithIAMAuthN

funcWithIAMAuthN()Option

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

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

func WithIAMAuthNCredentials

funcWithIAMAuthNCredentials(apiCreds,iamCreds*auth.Credentials)Option

WithIAMAuthNCredentials sets the oauth2.TokenSource for the API client and asecond token source for IAM AuthN login tokens. The API client token sourceshould 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 notdistinguish between the two token sources.

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

func WithIAMAuthNTokenSources

funcWithIAMAuthNTokenSources(apiTS,iamLoginTSoauth2.TokenSource)Option

WithIAMAuthNTokenSources sets the oauth2.TokenSource for the API client and asecond token source for IAM AuthN login tokens. The API client token sourceshould 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 notdistinguish between the two token sources.

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

func WithLazyRefresh

funcWithLazyRefresh()Option

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

func WithOptions

funcWithOptions(opts...Option)Option

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

func WithQuotaProject

funcWithQuotaProject(pstring)Option

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

func WithRSAKey

funcWithRSAKey(k*rsa.PrivateKey)Option

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

func WithRefreshTimeout

funcWithRefreshTimeout(ttime.Duration)Option

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

func WithResolver

WithResolver replaces the default resolver with an alternateimplementation to resolve the name in the database DSN to a Cloud SQLinstance.

func WithTokenSource

funcWithTokenSource(soauth2.TokenSource)Option

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

When Auth IAM AuthN is enabled, use WithIAMAuthNTokenSources or WithIAMAuthNCredentials to set the tokensource 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

funcWithUniverseDomain(udstring)Option

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

func WithUserAgent

funcWithUserAgent(uastring)Option

WithUserAgent returns an Option that sets the User-Agent.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.