Skip to content

Commit

Permalink
fix: memory leak in database/sql integration (#162)
Browse files Browse the repository at this point in the history
  • Loading branch information
stepan-romankov authored Apr 4, 2022
1 parent d19ce8a commit 47cdf2d
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions postgres/pgxv4/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"database/sql"
"database/sql/driver"
"net"
"sync"

"cloud.google.com/go/cloudsqlconn"
"github.com/jackc/pgx/v4"
Expand All @@ -39,13 +40,17 @@ func RegisterDriver(name string, opts ...cloudsqlconn.Option) (func() error, err
return func() error { return nil }, err
}
sql.Register(name, &pgDriver{
d: d,
d: d,
dbURIs: make(map[string]string),
})
return func() error { return d.Close() }, nil
}

type pgDriver struct {
d *cloudsqlconn.Dialer
d *cloudsqlconn.Dialer
mu sync.RWMutex
// dbURIs is a map of DSN to DB URI for registered connection names.
dbURIs map[string]string
}

// Open accepts a keyword/value formatted connection string and returns a
Expand All @@ -54,6 +59,19 @@ type pgDriver struct {
//
// "host=my-project:us-central1:my-db-instance user=myuser password=mypass"
func (p *pgDriver) Open(name string) (driver.Conn, error) {
var (
dbURI string
ok bool
)

p.mu.RLock()
dbURI, ok = p.dbURIs[name]
p.mu.RUnlock()

if ok {
return stdlib.GetDefaultDriver().Open(dbURI)
}

config, err := pgx.ParseConfig(name)
if err != nil {
return nil, err
Expand All @@ -63,6 +81,13 @@ func (p *pgDriver) Open(name string) (driver.Conn, error) {
config.DialFunc = func(ctx context.Context, _, _ string) (net.Conn, error) {
return p.d.Dial(ctx, instConnName)
}
dbURI := stdlib.RegisterConnConfig(config)

p.mu.Lock()
dbURI, ok = p.dbURIs[name] // check again if another goroutine already registered config
if !ok {
dbURI = stdlib.RegisterConnConfig(config)
p.dbURIs[name] = dbURI
}
p.mu.Unlock()
return stdlib.GetDefaultDriver().Open(dbURI)
}

0 comments on commit 47cdf2d

Please sign in to comment.