Skip to content

Commit

Permalink
Add default port for mysql connections (#13)
Browse files Browse the repository at this point in the history
The pq driver already supports this natively, but the mysql driver does not. This commit adds a default port 3306 for mysql connections.
  • Loading branch information
amacneil committed May 5, 2017
1 parent e393f38 commit 9029bbb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
7 changes: 7 additions & 0 deletions mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ type MySQLDriver struct {
func normalizeMySQLURL(u *url.URL) string {
normalizedURL := *u
normalizedURL.Scheme = ""

// set default port
if normalizedURL.Port() == "" {
normalizedURL.Host = fmt.Sprintf("%s:3306", normalizedURL.Host)
}

// host format required by go-sql-driver/mysql
normalizedURL.Host = fmt.Sprintf("tcp(%s)", normalizedURL.Host)

query := normalizedURL.Query()
Expand Down
20 changes: 19 additions & 1 deletion mysql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func mySQLTestURL(t *testing.T) *url.URL {
u, err := url.Parse("mysql://root:root@mysql:3306/dbmate")
u, err := url.Parse("mysql://root:root@mysql/dbmate")
require.Nil(t, err)

return u
Expand All @@ -34,6 +34,24 @@ func prepTestMySQLDB(t *testing.T) *sql.DB {
return db
}

func TestNormalizeMySQLURLDefaults(t *testing.T) {
u, err := url.Parse("mysql://host/foo")
require.Nil(t, err)
require.Equal(t, "", u.Port())

s := normalizeMySQLURL(u)
require.Equal(t, "tcp(host:3306)/foo?multiStatements=true", s)
}

func TestNormalizeMySQLURLCustom(t *testing.T) {
u, err := url.Parse("mysql://bob:secret@host:123/foo?flag=on")
require.Nil(t, err)
require.Equal(t, "123", u.Port())

s := normalizeMySQLURL(u)
require.Equal(t, "bob:secret@tcp(host:123)/foo?flag=on&multiStatements=true", s)
}

func TestMySQLCreateDropDatabase(t *testing.T) {
drv := MySQLDriver{}
u := mySQLTestURL(t)
Expand Down

0 comments on commit 9029bbb

Please sign in to comment.