Browse Source

sort the generic config.Params in the DSN (#637)

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.
Jeff Hodges 8 years ago
parent
commit
3955978cac
3 changed files with 25 additions and 2 deletions
  1. 1 0
      AUTHORS
  2. 8 2
      dsn.go
  3. 16 0
      dsn_test.go

+ 1 - 0
AUTHORS

@@ -33,6 +33,7 @@ ICHINOSE Shogo <shogo82148 at gmail.com>
 INADA Naoki <songofacandy at gmail.com>
 Jacek Szwec <szwec.jacek at gmail.com>
 James Harr <james.harr at gmail.com>
+Jeff Hodges <jeff at somethingsimilar.com>
 Jian Zhen <zhenjl at gmail.com>
 Joshua Prunier <joshua.prunier at gmail.com>
 Julien Lefevre <julien.lefevr at gmail.com>

+ 8 - 2
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]))
 		}
 	}
 

+ 16 - 0
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()