@@ -12,6 +12,7 @@ import (
12
12
)
13
13
14
14
var (
15
+ charset string
15
16
dsn string
16
17
netAddr string
17
18
run bool
@@ -43,8 +44,9 @@ func getEnv() bool {
43
44
dbname = "gotest"
44
45
}
45
46
47
+ charset = "charset=utf8"
46
48
netAddr = fmt .Sprintf ("%s(%s)" , prot , addr )
47
- dsn = fmt .Sprintf ("%s:%s@%s/%s?timeout=30s&charset=utf8" , user , pass , netAddr , dbname )
49
+ dsn = fmt .Sprintf ("%s:%s@%s/%s?timeout=30s&" + charset , user , pass , netAddr , dbname )
48
50
49
51
c , err := net .Dial (prot , addr )
50
52
if err == nil {
@@ -78,6 +80,54 @@ func mustQuery(t *testing.T, db *sql.DB, query string, args ...interface{}) (row
78
80
return
79
81
}
80
82
83
+ func mustSetCharset (t * testing.T , charsetParam , expected string ) {
84
+ db , err := sql .Open ("mysql" , strings .Replace (dsn , charset , charsetParam , 1 ))
85
+ if err != nil {
86
+ t .Fatalf ("Error connecting: %v" , err )
87
+ }
88
+
89
+ rows := mustQuery (t , db , ("SELECT @@character_set_connection" ))
90
+ if ! rows .Next () {
91
+ t .Fatalf ("Error getting connection charset: %v" , err )
92
+ }
93
+
94
+ var got string
95
+ rows .Scan (& got )
96
+
97
+ if got != expected {
98
+ t .Fatalf ("Expected connection charset %s but got %s" , expected , got )
99
+ }
100
+ db .Close ()
101
+ }
102
+
103
+ func TestCharset (t * testing.T ) {
104
+ if ! getEnv () {
105
+ t .Logf ("MySQL-Server not running on %s. Skipping TestCharset" , netAddr )
106
+ return
107
+ }
108
+
109
+ // non utf8 test
110
+ mustSetCharset (t , "charset=ascii" , "ascii" )
111
+ }
112
+
113
+ func TestFallbackCharset (t * testing.T ) {
114
+ if ! getEnv () {
115
+ t .Logf ("MySQL-Server not running on %s. Skipping TestCharsets" , netAddr )
116
+ return
117
+ }
118
+
119
+ // when the first charset is invalid, use the second
120
+ mustSetCharset (t , "charset=none,utf8" , "utf8" )
121
+
122
+ // when the first charset is valid, use it
123
+ charsets := []string {"ascii" , "utf8" }
124
+ for i := range charsets {
125
+ expected := charsets [i ]
126
+ other := charsets [1 - i ]
127
+ mustSetCharset (t , "charset=" + expected + "," + other , expected )
128
+ }
129
+ }
130
+
81
131
func TestCRUD (t * testing.T ) {
82
132
if ! getEnv () {
83
133
t .Logf ("MySQL-Server not running on %s. Skipping TestCRUD" , netAddr )
0 commit comments