From 60fef69d30eff571a6c316d02a0c0e8e6b057f2a Mon Sep 17 00:00:00 2001 From: Jeff Hodges Date: Tue, 11 Jul 2017 18:48:47 -0700 Subject: [PATCH] sort the generic config.Params in the DSN This sorts the config.Params values as they are placed in the DSN. This makes it easier for other projects to test that they are munging their DSNs correctly and do other similar tasks. --- AUTHORS | 1 + dsn.go | 10 ++++++++-- dsn_test.go | 16 ++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/AUTHORS b/AUTHORS index 10e2ebb94..5526e3e90 100644 --- a/AUTHORS +++ b/AUTHORS @@ -33,6 +33,7 @@ ICHINOSE Shogo INADA Naoki Jacek Szwec James Harr +Jeff Hodges Jian Zhen Joshua Prunier Julien Lefevre diff --git a/dsn.go b/dsn.go index ca1f2bf14..ab2fdfc6a 100644 --- a/dsn.go +++ b/dsn.go @@ -15,6 +15,7 @@ import ( "fmt" "net" "net/url" + "sort" "strconv" "strings" "time" @@ -257,7 +258,12 @@ func (cfg *Config) FormatDSN() string { // other params if cfg.Params != nil { - for param, value := range cfg.Params { + var params []string + for param := range cfg.Params { + params = append(params, param) + } + sort.Strings(params) + for _, param := range params { if hasParam { buf.WriteByte('&') } else { @@ -267,7 +273,7 @@ func (cfg *Config) FormatDSN() string { buf.WriteString(param) buf.WriteByte('=') - buf.WriteString(url.QueryEscape(value)) + buf.WriteString(url.QueryEscape(cfg.Params[param])) } } diff --git a/dsn_test.go b/dsn_test.go index 4fd76b813..d1957f8e8 100644 --- a/dsn_test.go +++ b/dsn_test.go @@ -220,6 +220,22 @@ func TestDSNUnsafeCollation(t *testing.T) { } } +func TestParamsAreSorted(t *testing.T) { + expected := "/dbname?interpolateParams=true&foobar=baz&quux=loo" + dsn := &Config{ + DBName: "dbname", + InterpolateParams: true, + Params: map[string]string{ + "quux": "loo", + "foobar": "baz", + }, + } + actual := dsn.FormatDSN() + if actual != expected { + t.Errorf("generic Config.Params were not sorted: want %#v, got %#v", expected, actual) + } +} + func BenchmarkParseDSN(b *testing.B) { b.ReportAllocs()