Skip to content

Commit c0725c8

Browse files
committed
pgconn: default empty user to current OS user
1 parent 91c80f1 commit c0725c8

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

pgconn/config.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"net"
1414
"net/url"
1515
"os"
16+
"os/user"
1617
"path/filepath"
1718
"strconv"
1819
"strings"
@@ -304,6 +305,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
304305
},
305306
}
306307

308+
if _, present := settings["user"]; present && config.User == "" {
309+
currentUser, err := user.Current()
310+
if err == nil {
311+
config.User = currentUser.Username
312+
}
313+
}
314+
307315
if connectTimeoutSetting, present := settings["connect_timeout"]; present {
308316
connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting)
309317
if err != nil {

pgconn/config_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,3 +1145,41 @@ application_name = spaced string
11451145
assertConfigsEqual(t, tt.config, config, fmt.Sprintf("Test %d (%s)", i, tt.name))
11461146
}
11471147
}
1148+
1149+
func TestParseConfigExplicitEmptyUserDefaultsToOSUser(t *testing.T) {
1150+
skipOnWindows(t)
1151+
clearPgEnvvars(t)
1152+
1153+
currentUser, err := user.Current()
1154+
if err != nil {
1155+
t.Skip("cannot determine current OS user")
1156+
}
1157+
1158+
tests := []struct {
1159+
name string
1160+
connString string
1161+
expected string
1162+
}{
1163+
{
1164+
name: "explicit empty user parameter",
1165+
connString: "host=localhost dbname=test user=",
1166+
expected: currentUser.Username,
1167+
},
1168+
}
1169+
1170+
for i, tt := range tests {
1171+
config, err := pgconn.ParseConfig(tt.connString)
1172+
if !assert.NoErrorf(t, err, "Test %d (%s)", i, tt.name) {
1173+
continue
1174+
}
1175+
1176+
assert.Equalf(
1177+
t,
1178+
tt.expected,
1179+
config.User,
1180+
"Test %d (%s): unexpected user",
1181+
i,
1182+
tt.name,
1183+
)
1184+
}
1185+
}

0 commit comments

Comments
 (0)