Support MySQL connection through unix socket (#131)

Closes #131
This commit is contained in:
Carlo Suriano 2020-05-24 12:55:45 -07:00 committed by Adrian Macneil
parent a45d03acdb
commit 6cd39e1fba
3 changed files with 29 additions and 13 deletions

View file

@ -127,6 +127,12 @@ protocol://username:password@host:port/database_name?options
DATABASE_URL="mysql://username:password@127.0.0.1:3306/database_name"
```
A socket parameter can be specified to connect through a unix socket file:
```sh
DATABASE_URL="mysql://username:password@/database_name?socket=/var/run/mysqld/mysqld.sock"
```
**PostgreSQL**
When connecting to Postgres, you may need to add the `sslmode=disable` option to your connection string, as dbmate by default requires a TLS connection (some other frameworks/languages allow unencrypted connections by default).

View file

@ -19,20 +19,20 @@ type MySQLDriver struct {
}
func normalizeMySQLURL(u *url.URL) string {
// set default port
host := u.Host
if u.Port() == "" {
host = fmt.Sprintf("%s:3306", host)
}
// host format required by go-sql-driver/mysql
host = fmt.Sprintf("tcp(%s)", host)
query := u.Query()
query.Set("multiStatements", "true")
queryString := query.Encode()
host := u.Host
protocol := "tcp"
if query.Get("socket") != "" {
protocol = "unix"
host = query.Get("socket")
query.Del("socket")
} else if u.Port() == "" {
// set default port
host = fmt.Sprintf("%s:3306", host)
}
// Get decoded user:pass
userPassEncoded := u.User.String()
@ -45,8 +45,9 @@ func normalizeMySQLURL(u *url.URL) string {
normalizedString = userPass + "@"
}
normalizedString = fmt.Sprintf("%s%s%s?%s", normalizedString,
host, u.Path, queryString)
// connection string format required by go-sql-driver/mysql
normalizedString = fmt.Sprintf("%s%s(%s)%s?%s", normalizedString,
protocol, host, u.Path, query.Encode())
return normalizedString
}

View file

@ -61,6 +61,15 @@ func TestNormalizeMySQLURLCustomSpecialChars(t *testing.T) {
require.Equal(t, "duhfsd7s:123!@123!@@tcp(host:123)/foo?flag=on&multiStatements=true", s)
}
func TestNormalizeMySQLURLSocket(t *testing.T) {
u, err := url.Parse("mysql:///foo?socket=/var/run/mysqld/mysqld.sock&flag=on")
require.NoError(t, err)
require.Equal(t, "", u.Host)
s := normalizeMySQLURL(u)
require.Equal(t, "unix(/var/run/mysqld/mysqld.sock)/foo?flag=on&multiStatements=true", s)
}
func TestMySQLCreateDropDatabase(t *testing.T) {
drv := MySQLDriver{}
u := mySQLTestURL(t)