Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] #761

Open
enocom opened this issue May 13, 2024 · 0 comments
Open

[Question] #761

enocom opened this issue May 13, 2024 · 0 comments
Assignees

Comments

@enocom
Copy link

enocom commented May 13, 2024

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

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

No branches or pull requests

2 participants