Skip to content

Instantly share code, notes, and snippets.

@erans
Last active April 23, 2024 20:22
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erans/795f7616049f310b2a71a50e5df4529a to your computer and use it in GitHub Desktop.
Save erans/795f7616049f310b2a71a50e5df4529a to your computer and use it in GitHub Desktop.
Go Example: Google CloudSQL with CloudSQL Proxy and GORM
package main
import (
"github.com/jinzhu/gorm"
_ "database/sql"
_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql"
)
// You can read more in this post: http://forecastcloudy.net/2016/06/28/using-google-cloud-sql-from-go-with-gorm-in-google-container-engine-and-google-compute-engine/
func main() {
// Using cloudsql-proxy will help you avoid white listing IPs and handling SSL.
// In this case, it will also run inside your Go program and will not require
// an additional process or container.
// Connection String details:
// * user - the user created inside the DB. You can see more details on how to create it without password here:
// https://cloud.google.com/sql/docs/sql-proxy#flags
// * project-id - your project id
// * zone - your general zone (us-central1/us-west1/etc)
// * db-name - the name of the database instance as it appears in the console
var dbConnectionString = "user@cloudsql(project-id:zone:instance-name)/db-name?charset=utf8&parseTime=True&loc=UTC"
var db *gorm.DB
var err error
if db, err = gorm.Open("mysql", dbConnectionString); err != nil {
panic(err)
}
}
@austincollinpena
Copy link

It's now in the docs, towards the bottom: https://gorm.io/docs/connecting_to_the_database.html

@erans
Copy link
Author

erans commented Oct 7, 2020

Thanks. It's nice to know. Thanks for sending the link!

@nnashwin
Copy link

This is awesome. Thanks!

@enocom
Copy link

enocom commented Apr 23, 2024

For folks who find this through a Google search, there's a newer and more reliable way to do this with the Cloud SQL Go Connector.

See https://stackoverflow.com/a/78374807/927514 for details.

TL;DR:

package main

import (
        "fmt"
        "time"

        "cloud.google.com/go/cloudsqlconn"
        "cloud.google.com/go/cloudsqlconn/postgres/pgxv5"
        "gorm.io/driver/postgres"
        "gorm.io/gorm"
)

func main() {
        cleanup, err := pgxv5.RegisterDriver(
                "cloudsql-postgres",
                cloudsqlconn.WithLazyRefresh(),
                cloudsqlconn.WithIAMAuthN(),
        )
        if err != nil {
                panic(err)
        }
        // cleanup will stop the driver from retrieving ephemeral certificates
        // Don't call cleanup until you're done with your database connections
        defer cleanup()

        dsn := "host=my-project:us-central1:my-instance user=postgres password=postgres dbname=postgres sslmode=disable"

        db, err := gorm.Open(postgres.New(postgres.Config{
                DriverName: "cloudsql-postgres",
                DSN:        dsn,
        }))
        if err != nil {
                panic(err)
        }

        // get the underlying *sql.DB type to verify the connection
        sdb, err := db.DB()
        if err != nil {
                panic(err)
        }

        var t time.Time
        if err := sdb.QueryRow("select now()").Scan(&t); err != nil {
                panic(err)
        }

        fmt.Println(t)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment