go-gorm / gorm.io

GORM official site
https://gorm.io
252 stars 353 forks source link

[Question] #761

Open enocom opened 4 months ago

enocom commented 4 months ago

Document Link

https://gorm.io/docs/connecting_to_the_database.html#Customize-Driver-1

Your Question

Currently the Gorm docs showcase how to connect to Cloud SQL using the v1 Cloud SQL Proxy. Meanwhile, there is a newer Cloud SQL Go Connector.

Expected answer

This is a request to update the docs to show how to use the Cloud SQL Go Connector with Gorm.

If there's interest, I'm happy to send the PR to do this work. Opening an issue to discuss first.

Here's a full example:

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")
        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)
}

cc @jackwotherspoon