Skip to content

Commit

Permalink
feat!: return cleanup func to close dialer (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
enocom committed Feb 8, 2022
1 parent ab80b88 commit fa9b845
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 25 deletions.
7 changes: 2 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,14 +143,11 @@ import (
)

func Connect() {
// Without any options:
err := pgxv4.RegisterDriver("cloudsql-postgres")
cleanup, err := pgxv4.RegisterDriver("cloudsql-postgres", cloudsqlconn.WithIAMAuthN())
if err != nil {
// ... handle error
}

// Or, with options:
// pgxv4.RegisterDriver("cloudsql-postgres", cloudsqlconn.WithIAMAuthN())
defer cleanup()

db, err := sql.Open(
"cloudsql-postgres",
Expand Down
30 changes: 10 additions & 20 deletions postgres/pgxv4/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,21 @@ import (
// RegisterDriver registers a Postgres driver that uses the cloudsqlconn.Dialer
// configured with the provided options. The choice of name is entirely up to
// the caller and may be used to distinguish between multiple registrations of
// differently configured Dialers.
// Note: The underlying driver uses the latest version of pgx.
func RegisterDriver(name string, opts ...cloudsqlconn.Option) error {
// differently configured Dialers. The driver uses pgx/v4 internally.
// RegisterDriver returns a cleanup function that should be called one the
// database connection is no longer needed.
func RegisterDriver(name string, opts ...cloudsqlconn.Option) (func() error, error) {
d, err := cloudsqlconn.NewDialer(context.Background(), opts...)
if err != nil {
return err
return func() error { return nil }, err
}
sql.Register(name, &pgDriver{
d: d,
})
return nil
}

type dialerConn struct {
driver.Conn
dialer *cloudsqlconn.Dialer
}

func (c *dialerConn) Close() error {
c.dialer.Close()
return c.Conn.Close()
return func() error {
d.Close()
return nil
}, nil
}

type pgDriver struct {
Expand All @@ -72,9 +66,5 @@ func (p *pgDriver) Open(name string) (driver.Conn, error) {
return p.d.Dial(ctx, instConnName)
}
dbURI := stdlib.RegisterConnConfig(config)
conn, err := stdlib.GetDefaultDriver().Open(dbURI)
if err != nil {
return nil, err
}
return &dialerConn{Conn: conn, dialer: p.d}, nil
return stdlib.GetDefaultDriver().Open(dbURI)
}

0 comments on commit fa9b845

Please sign in to comment.