Skip to content

Commit a1752d9

Browse files
committed
Don't send dbname= as a startup parameter when database= is used
Fixes #1256
1 parent eec526c commit a1752d9

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

connector.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -758,14 +758,12 @@ func (cfg *Config) setFromTag(o map[string]string, tag string) error {
758758

759759
// Set run-time; we delete map keys as they're set in the struct.
760760
if tag == "postgres" {
761-
// Make sure database= sets dbname=; in startup() we send database for
762-
// dbname, and if we have both set it's inconsistent as the loop order
763-
// is a map.
761+
// Make sure database= sets dbname=, as that previously worked (kind of
762+
// by accident).
763+
// TODO(v2): remove
764764
if d, ok := o["database"]; ok {
765+
cfg.Database = d
765766
delete(o, "database")
766-
if o["dbname"] == "" {
767-
o["dbname"] = d
768-
}
769767
}
770768
cfg.Runtime = o
771769
}

connector_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,23 @@ func TestNewConnector(t *testing.T) {
113113
defer db.Close()
114114
useConn(t, db)
115115
})
116+
117+
t.Run("database=", func(t *testing.T) {
118+
// Make sure database= consistently take precedence over dbname=
119+
for i := 0; i < 10; i++ {
120+
err := pqtest.MustDB(t, "database=err").Ping()
121+
if err == nil || err.Error() != `pq: database "err" does not exist (3D000)` {
122+
t.Errorf("wrong error: %s", err)
123+
}
124+
err = pqtest.MustDB(t, "dbname=one database=two").Ping()
125+
if err == nil || err.Error() != `pq: database "two" does not exist (3D000)` {
126+
t.Errorf("wrong error: %s", err)
127+
}
128+
}
129+
})
116130
}
117131

132+
// TODO: this can be merged with TestNewConfig, I think?
118133
func TestParseOpts(t *testing.T) {
119134
tests := []struct {
120135
in string
@@ -130,6 +145,7 @@ func TestParseOpts(t *testing.T) {
130145
{"dbname=データベース password=パスワード", map[string]string{"dbname": "データベース", "password": "パスワード"}, ""},
131146
{"dbname=hello user=''", map[string]string{"dbname": "hello", "user": ""}, ""},
132147
{"user='' dbname=hello", map[string]string{"dbname": "hello", "user": ""}, ""},
148+
133149
// The last option value is an empty string if there's no non-whitespace after its =
134150
{"dbname=hello user= ", map[string]string{"dbname": "hello", "user": ""}, ""},
135151

@@ -229,6 +245,8 @@ func TestRuntimeParameters(t *testing.T) {
229245
})
230246
}
231247
}
248+
249+
// TODO: this can be merged with TestNewConfig, I think?
232250
func TestParseEnviron(t *testing.T) {
233251
tests := []struct {
234252
in []string

0 commit comments

Comments
 (0)