Переглянути джерело

Merge pull request #44 from arnehormann/master

test for thrown error when no charset could be set
Julien Schmidt 12 роки тому
батько
коміт
bb6e79bf64
2 змінених файлів з 20 додано та 8 видалено
  1. 9 6
      connection.go
  2. 11 2
      driver_test.go

+ 9 - 6
connection.go

@@ -50,13 +50,16 @@ func (mc *mysqlConn) handleParams() (err error) {
 			for _, charset := range charsets {
 				// ignore errors here - a charset may not exist
 				err = mc.exec("SET NAMES " + charset)
-				if err == nil {
-					var value []byte
-					value, err = mc.getSystemVar("character_set_connection")
-					if string(value) == charset {
-						break
-					}
+				if err != nil {
+					continue
 				}
+				var value []byte
+				value, _ = mc.getSystemVar("character_set_connection")
+				if string(value) == charset {
+					err = nil
+					break
+				}
+				err = errors.New("Could not set charset " + charset)
 			}
 			if err != nil {
 				return

+ 11 - 2
driver_test.go

@@ -84,7 +84,7 @@ func mustQuery(t *testing.T, db *sql.DB, query string, args ...interface{}) (row
 func mustSetCharset(t *testing.T, charsetParam, expected string) {
 	db, err := sql.Open("mysql", strings.Replace(dsn, charset, charsetParam, 1))
 	if err != nil {
-		t.Fatalf("Error connecting: %v", err)
+		t.Fatalf("Error on Open: %v", err)
 	}
 
 	rows := mustQuery(t, db, ("SELECT @@character_set_connection"))
@@ -98,7 +98,6 @@ func mustSetCharset(t *testing.T, charsetParam, expected string) {
 	if got != expected {
 		t.Fatalf("Expected connection charset %s but got %s", expected, got)
 	}
-	db.Close()
 }
 
 func TestCharset(t *testing.T) {
@@ -111,6 +110,16 @@ func TestCharset(t *testing.T) {
 	mustSetCharset(t, "charset=ascii", "ascii")
 }
 
+func TestFailingCharset(t *testing.T) {
+	db, err := sql.Open("mysql", strings.Replace(dsn, charset, "charset=none", 1))
+	// run query to really establish connection...
+	_, err = db.Exec("SELECT 1")
+	if err == nil {
+		db.Close()
+		t.Fatalf("Connection must not succeed without a valid charset")
+	}
+}
+
 func TestFallbackCharset(t *testing.T) {
 	if !getEnv() {
 		t.Logf("MySQL-Server not running on %s. Skipping TestFallbackCharset", netAddr)