@@ -44,7 +44,6 @@ type Config struct {
4444 DBName string // Database name
4545 Params map [string ]string // Connection parameters
4646 ConnectionAttributes string // Connection Attributes, comma-delimited string of user-defined "key:value" pairs
47- charsets []string // Connection charset. When set, this will be set in SET NAMES <charset> query
4847 Collation string // Connection collation. When set, this will be set in SET NAMES <charset> COLLATE <collation> query
4948 Loc * time.Location // Location for time.Time values
5049 MaxAllowedPacket int // Max packet size allowed
@@ -81,6 +80,7 @@ type Config struct {
8180 beforeConnect func (context.Context , * Config ) error // Invoked before a connection is established
8281 pubKey * rsa.PublicKey // Server public key
8382 timeTruncate time.Duration // Truncate time.Time values to the specified duration
83+ charsets []string // Connection charset. When set, this will be set in SET NAMES <charset> query
8484}
8585
8686// Functional Options Pattern
@@ -135,6 +135,21 @@ func EnableCompression(yes bool) Option {
135135 }
136136}
137137
138+ // Charset sets the connection charset and collation.
139+ //
140+ // charset is the connection charset.
141+ // collation is the connection collation. It can be null or empty string.
142+ //
143+ // When collation is not specified, `SET NAMES <charset>` command is sent when the connection is established.
144+ // When collation is specified, `SET NAMES <charset> COLLATE <collation>` command is sent when the connection is established.
145+ func Charset (charset , collation string ) Option {
146+ return func (cfg * Config ) error {
147+ cfg .charsets = []string {charset }
148+ cfg .Collation = collation
149+ return nil
150+ }
151+ }
152+
138153func (cfg * Config ) Clone () * Config {
139154 cp := * cfg
140155 if cp .TLS != nil {
@@ -307,6 +322,10 @@ func (cfg *Config) FormatDSN() string {
307322 writeDSNParam (& buf , & hasParam , "columnsWithAlias" , "true" )
308323 }
309324
325+ if cfg .ConnectionAttributes != "" {
326+ writeDSNParam (& buf , & hasParam , "connectionAttributes" , url .QueryEscape (cfg .ConnectionAttributes ))
327+ }
328+
310329 if cfg .compress {
311330 writeDSNParam (& buf , & hasParam , "compress" , "true" )
312331 }
0 commit comments