Fix connect with multiple hostnames when one can't be resolved

If multiple hostnames are provided and one cannot be resolved the others
should still be tried.

Longterm, it would be nice for the connect process to return a list of
errors rather than just one.

fixes https://github.com/jackc/pgx/issues/1464
pull/1471/head
Jack Christensen 2023-01-14 09:19:00 -06:00
parent c46d792c93
commit a95cfe5cc5
1 changed files with 10 additions and 1 deletions

View File

@ -203,6 +203,8 @@ func ConnectConfig(octx context.Context, config *Config) (pgConn *PgConn, err er
func expandWithIPs(ctx context.Context, lookupFn LookupFunc, fallbacks []*FallbackConfig) ([]*FallbackConfig, error) {
var configs []*FallbackConfig
var lookupErrors []error
for _, fb := range fallbacks {
// skip resolve for unix sockets
if isAbsolutePath(fb.Host) {
@ -217,7 +219,8 @@ func expandWithIPs(ctx context.Context, lookupFn LookupFunc, fallbacks []*Fallba
ips, err := lookupFn(ctx, fb.Host)
if err != nil {
return nil, err
lookupErrors = append(lookupErrors, err)
continue
}
for _, ip := range ips {
@ -242,6 +245,12 @@ func expandWithIPs(ctx context.Context, lookupFn LookupFunc, fallbacks []*Fallba
}
}
// See https://github.com/jackc/pgx/issues/1464. When Go 1.20 can be used in pgx consider using errors.Join so all
// errors are reported.
if len(configs) == 0 && len(lookupErrors) > 0 {
return nil, lookupErrors[0]
}
return configs, nil
}