Skip to content

Commit

Permalink
fix<mysql>: generate a correct connection string
Browse files Browse the repository at this point in the history
The generated connection string must follow the format
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]
  • Loading branch information
kmpm authored and timabell committed Jan 28, 2024
1 parent e5b366d commit fb3a25a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
3 changes: 2 additions & 1 deletion mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,11 @@ func buildConnectionString(databaseName string) string {
cs = fmt.Sprintf("%s@", cs)
}
if opts.Host != "" {
cs = fmt.Sprintf("%s%s", cs, opts.Host)
cs = fmt.Sprintf("%stcp(%s", cs, opts.Host)
if opts.Port != "" {
cs = fmt.Sprintf("%s:%s", cs, opts.Port)
}
cs += ")"
}
cs = fmt.Sprintf("%s/", cs)
if databaseName != "" {
Expand Down
43 changes: 43 additions & 0 deletions mysql/mysql_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// +build !skip_mysql

package mysql

import (
"testing"

_ "github.com/go-sql-driver/mysql"
)

func Test_buildConnectionString(t *testing.T) {
type args struct {
databaseName string
}

tests := []struct {
name string
args args
opts mysqlOpts
setOpts bool
want string
}{
{args: args{databaseName: "ssetest"}, setOpts: true, want: "tcp(192.0.2.0)/ssetest",
opts: mysqlOpts{Host: "192.0.2.0", Database: "ssetest"},
},
{args: args{databaseName: "ssetest"}, setOpts: true, want: "/ssetest",
opts: mysqlOpts{Port: "3307", Database: "ssetest"},
},
{args: args{databaseName: "ssetest"}, setOpts: true, want: "sseuser:passwd@tcp(192.0.2.0)/ssetest",
opts: mysqlOpts{Host: "192.0.2.0", Database: "ssetest", User: "sseuser", Password: "passwd"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.setOpts {
opts = &tt.opts
}
if got := buildConnectionString(tt.args.databaseName); got != tt.want {
t.Errorf("buildConnectionString() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit fb3a25a

Please sign in to comment.