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