fix parse mysql dsn addr

pull/476/head
wei cheng 5 years ago
parent 6e1180f53a
commit 02250991aa
No known key found for this signature in database
GPG Key ID: 5AF7E34E6A971D7F
  1. 17
      pkg/database/sql/sql.go
  2. 18
      pkg/database/sql/sql_test.go

@ -4,7 +4,6 @@ import (
"context" "context"
"database/sql" "database/sql"
"fmt" "fmt"
"strings"
"sync/atomic" "sync/atomic"
"time" "time"
@ -13,6 +12,7 @@ import (
"github.com/bilibili/kratos/pkg/net/netutil/breaker" "github.com/bilibili/kratos/pkg/net/netutil/breaker"
"github.com/bilibili/kratos/pkg/net/trace" "github.com/bilibili/kratos/pkg/net/trace"
"github.com/go-sql-driver/mysql"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@ -660,17 +660,12 @@ func (tx *Tx) Prepare(query string) (*Stmt, error) {
// parseDSNAddr parse dsn name and return addr. // parseDSNAddr parse dsn name and return addr.
func parseDSNAddr(dsn string) (addr string) { func parseDSNAddr(dsn string) (addr string) {
if dsn == "" { cfg, err := mysql.ParseDSN(dsn)
return if err != nil {
} // just ignore parseDSN error, mysql client will return error for us when connect.
part0 := strings.Split(dsn, "@") return ""
if len(part0) > 1 {
part1 := strings.Split(part0[1], "?")
if len(part1) > 0 {
addr = part1[0]
}
} }
return return cfg.Addr
} }
func slowLog(statement string, now time.Time) { func slowLog(statement string, now time.Time) {

@ -0,0 +1,18 @@
package sql
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseAddrDSN(t *testing.T) {
t.Run("test parse addr dsn", func(t *testing.T) {
addr := parseDSNAddr("test:test@tcp(172.16.0.148:3306)/test?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8")
assert.Equal(t, "172.16.0.148:3306", addr)
})
t.Run("test password has @", func(t *testing.T) {
addr := parseDSNAddr("root:root@dev@tcp(1.2.3.4:3306)/abc?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8mb4,utf8")
assert.Equal(t, "1.2.3.4:3306", addr)
})
}
Loading…
Cancel
Save