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

fix: avoid holding lock over IO #333

Merged
merged 2 commits into from
Jul 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}