Skip to content
Merged
Show file tree
Hide file tree
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
18 changes: 12 additions & 6 deletions dsn.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,19 @@ func (cfg *Config) FormatDSN() string {
}

// [protocol[(address)]]
if len(cfg.Net) > 0 {
buf.WriteString(cfg.Net)
if len(cfg.Addr) > 0 {
buf.WriteByte('(')
buf.WriteString(cfg.Addr)
buf.WriteByte(')')
if len(cfg.Addr) > 0 {
net := cfg.Net
if net == "" {
net = "tcp"
}
buf.WriteString(net)
buf.WriteByte('(')
buf.WriteString(cfg.Addr)
buf.WriteByte(')')
Comment thread
coderabbitai[bot] marked this conversation as resolved.
} else if cfg.Net != "" && cfg.Net != "tcp" {
// Preserve an explicit non-default protocol when there's no
// address, so e.g. Net="unix" still round-trips.
buf.WriteString(cfg.Net)
}

// /dbname
Expand Down
37 changes: 37 additions & 0 deletions dsn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,43 @@ func TestDSNUnsafeCollation(t *testing.T) {
}
}

func TestFormatDSN_NetWithoutAddr(t *testing.T) {
// An explicit non-default Net should still appear in the formatted
// DSN when Addr is empty, so the Config round-trips.
cases := []struct {
name string
net string
want string
}{
{"unix without addr", "unix", "unix/"},
// tcp is the default; dropping it is a no-op on parse.
{"tcp without addr", "tcp", "/"},
{"empty net empty addr", "", "/"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cfg := NewConfig()
cfg.Net = tc.net
cfg.Addr = ""
if got := cfg.FormatDSN(); got != tc.want {
t.Errorf("FormatDSN() = %q, want %q", got, tc.want)
}
})
}
}

func TestFormatDSN_AddrWithoutNet(t *testing.T) {
// Direct check of the bug from #1616: an Addr-only Config should
// format with the default tcp protocol so it round-trips.
cfg := NewConfig()
cfg.Addr = "myhost:3306"
got := cfg.FormatDSN()
want := "tcp(myhost:3306)/"
if got != want {
t.Errorf("FormatDSN() = %q, want %q", got, want)
}
}

func TestParamsAreSorted(t *testing.T) {
expected := "/dbname?interpolateParams=true&foobar=baz&quux=loo"
cfg := NewConfig()
Expand Down
Loading