Skip to content

Commit

Permalink
fix: avoid holding lock over IO (#333)
Browse files Browse the repository at this point in the history
  • Loading branch information
enocom committed Jul 24, 2023
1 parent e53fd10 commit 888e735
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions driver/pgxv4/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,32 +59,29 @@ type pgDriver struct {
//
// "host=projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<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)
dbURI, err := p.dbURI(name)
if err != nil {
return nil, err
}
return stdlib.GetDefaultDriver().Open(dbURI)

}

// dbURI registers a driver using the provided DSN. If the name has already
// been registered, dbURI returns the existing registration.
func (p *pgDriver) dbURI(name string) (string, error) {
p.mu.Lock()
defer p.mu.Unlock()
// Recheck to ensure dbURI wasn't created between locks
dbURI, ok = p.dbURIs[name]
dbURI, ok := p.dbURIs[name]
if ok {
return stdlib.GetDefaultDriver().Open(dbURI)
return dbURI, nil
}

config, err := pgx.ParseConfig(name)
if err != nil {
return nil, err
return "", err
}
instConnName := config.Config.Host // Extract instance URI
instConnName := config.Config.Host // Extract instance connection name
config.Config.Host = "localhost" // Replace it with a default value
config.DialFunc = func(ctx context.Context, _, _ string) (net.Conn, error) {
return p.d.Dial(ctx, instConnName)
Expand All @@ -93,5 +90,5 @@ func (p *pgDriver) Open(name string) (driver.Conn, error) {
dbURI = stdlib.RegisterConnConfig(config)
p.dbURIs[name] = dbURI

return stdlib.GetDefaultDriver().Open(dbURI)
return dbURI, nil
}

0 comments on commit 888e735

Please sign in to comment.