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/v4/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.ConnectConfig(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 pgxv4.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/pgxv4" ) func connect() { // adjust options as needed cleanup, err := pgxv4.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 }
Variables
ErrDialerClosed
var (
// ErrDialerClosed is used when a caller invokes Dial after closing the
// Dialer.
ErrDialerClosed = errors.New("cloudsqlconn: dialer is closed")
)
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
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
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 WithOneOffDialFunc
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
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 WithTCPKeepAlive
func WithTCPKeepAlive(d time.Duration) DialOption
WithTCPKeepAlive returns a DialOption that specifies the tcp keep alive period for the connection returned by Dial.
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
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
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 must be the instance's connection name, which is in the format "project-name:region:instance-name".
func (*Dialer) EngineVersion
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
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".
Option
type Option func(d *dialerConfig)
An Option is an option for configuring a Dialer.
func WithAdminAPIEndpoint
WithAdminAPIEndpoint configures the underlying SQL Admin API client to use the provided URL.
func WithContextDebugLogger
func WithContextDebugLogger(l debug.ContextLogger) Option
WithContextDebugLogger configures a debug logger for reporting on internal operations. By default the debug logger is disabled.
func WithCredentialsFile
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
WithCredentialsJSON returns an Option that specifies a service account or refresh token JSON credentials to be used as the basis for authentication.
func WithDNSResolver
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
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
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 WithFailoverPeriod
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
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 WithIAMAuthNTokenSources
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:
- https://www.googleapis.com/auth/sqlservice.admin, and
- https://www.googleapis.com/auth/cloud-platform
The IAM AuthN token source on the other hand should only have:
Prefer this option over WithTokenSource when using IAM AuthN which does not distinguish between the two token sources. WithIAMAuthNTokenSources should not be used with WithTokenSource.
func WithLazyRefresh
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
WithOptions turns a list of Option's into a single Option.
func WithQuotaProject
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
WithRefreshTimeout returns an Option that sets a timeout on refresh operations. Defaults to 60s.
func WithResolver
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 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 to set the token source for login tokens separately from the API client token source. WithTokenSource should not be used with WithIAMAuthNTokenSources.
func WithUniverseDomain
WithUniverseDomain configures the underlying SQL Admin API client to use the provided universe domain. Enables Trusted Partner Cloud (TPC).
func WithUserAgent
WithUserAgent returns an Option that sets the User-Agent.