@@ -11,11 +11,54 @@ package mysql
1111import (
1212 "context"
1313 "database/sql/driver"
14+ "fmt"
1415 "net"
16+ "os"
17+ "strconv"
18+ "strings"
1519)
1620
1721type connector struct {
18- cfg * Config // immutable private copy.
22+ cfg * Config // immutable private copy.
23+ encodedAttributes string // Encoded connection attributes.
24+ }
25+
26+ func encodeConnectionAttributes (textAttributes string ) string {
27+ connAttrsBuf := make ([]byte , 0 , 251 )
28+
29+ // default connection attributes
30+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrClientName )
31+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrClientNameValue )
32+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrOS )
33+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrOSValue )
34+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrPlatform )
35+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrPlatformValue )
36+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , connAttrPid )
37+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , strconv .Itoa (os .Getpid ()))
38+
39+ // user-defined connection attributes
40+ for _ , connAttr := range strings .Split (textAttributes , "," ) {
41+ attr := strings .SplitN (connAttr , ":" , 2 )
42+ if len (attr ) != 2 {
43+ continue
44+ }
45+ for _ , v := range attr {
46+ connAttrsBuf = appendLengthEncodedString (connAttrsBuf , v )
47+ }
48+ }
49+
50+ return string (connAttrsBuf )
51+ }
52+
53+ func newConnector (cfg * Config ) (* connector , error ) {
54+ encodedAttributes := encodeConnectionAttributes (cfg .ConnectionAttributes )
55+ if len (encodedAttributes ) > 250 {
56+ return nil , fmt .Errorf ("connection attributes are longer than 250 bytes: %dbytes (%q)" , len (encodedAttributes ), cfg .ConnectionAttributes )
57+ }
58+ return & connector {
59+ cfg : cfg ,
60+ encodedAttributes : encodedAttributes ,
61+ }, nil
1962}
2063
2164// Connect implements driver.Connector interface.
@@ -29,6 +72,7 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
2972 maxWriteSize : maxPacketSize - 1 ,
3073 closech : make (chan struct {}),
3174 cfg : c .cfg ,
75+ connector : c ,
3276 }
3377 mc .parseTime = mc .cfg .ParseTime
3478
0 commit comments