KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > testsuite > regression > ConnectionRegressionTest


1 /*
2  Copyright (C) 2002-2004 MySQL AB
3
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of version 2 of the GNU General Public License as
6  published by the Free Software Foundation.
7
8  There are special exceptions to the terms and conditions of the GPL
9  as it is applied to this software. View the full text of the
10  exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
11  software distribution.
12
13  This program is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with this program; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22
23
24  */

25 package testsuite.regression;
26
27 import java.sql.Connection JavaDoc;
28 import java.sql.DriverManager JavaDoc;
29 import java.sql.ResultSet JavaDoc;
30 import java.sql.SQLException JavaDoc;
31 import java.sql.Statement JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.Locale JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Properties JavaDoc;
37 import java.util.StringTokenizer JavaDoc;
38
39 import testsuite.BaseTestCase;
40
41 import com.mysql.jdbc.Driver;
42 import com.mysql.jdbc.NonRegisteringDriver;
43
44 /**
45  * Regression tests for Connections
46  *
47  * @author Mark Matthews
48  * @version $Id: ConnectionRegressionTest.java,v 1.1.2.1 2005/05/13 18:58:38
49  * mmatthews Exp $
50  */

51 public class ConnectionRegressionTest extends BaseTestCase {
52     /**
53      * DOCUMENT ME!
54      *
55      * @param name
56      * the name of the testcase
57      */

58     public ConnectionRegressionTest(String JavaDoc name) {
59         super(name);
60     }
61
62     /**
63      * Runs all test cases in this test suite
64      *
65      * @param args
66      */

67     public static void main(String JavaDoc[] args) {
68         junit.textui.TestRunner.run(ConnectionRegressionTest.class);
69     }
70
71     /**
72      * DOCUMENT ME!
73      *
74      * @throws Exception
75      * ...
76      */

77     public void testBug1914() throws Exception JavaDoc {
78         System.out.println(this.conn
79                 .nativeSQL("{fn convert(foo(a,b,c), BIGINT)}"));
80         System.out.println(this.conn
81                 .nativeSQL("{fn convert(foo(a,b,c), BINARY)}"));
82         System.out
83                 .println(this.conn.nativeSQL("{fn convert(foo(a,b,c), BIT)}"));
84         System.out.println(this.conn
85                 .nativeSQL("{fn convert(foo(a,b,c), CHAR)}"));
86         System.out.println(this.conn
87                 .nativeSQL("{fn convert(foo(a,b,c), DATE)}"));
88         System.out.println(this.conn
89                 .nativeSQL("{fn convert(foo(a,b,c), DECIMAL)}"));
90         System.out.println(this.conn
91                 .nativeSQL("{fn convert(foo(a,b,c), DOUBLE)}"));
92         System.out.println(this.conn
93                 .nativeSQL("{fn convert(foo(a,b,c), FLOAT)}"));
94         System.out.println(this.conn
95                 .nativeSQL("{fn convert(foo(a,b,c), INTEGER)}"));
96         System.out.println(this.conn
97                 .nativeSQL("{fn convert(foo(a,b,c), LONGVARBINARY)}"));
98         System.out.println(this.conn
99                 .nativeSQL("{fn convert(foo(a,b,c), LONGVARCHAR)}"));
100         System.out.println(this.conn
101                 .nativeSQL("{fn convert(foo(a,b,c), TIME)}"));
102         System.out.println(this.conn
103                 .nativeSQL("{fn convert(foo(a,b,c), TIMESTAMP)}"));
104         System.out.println(this.conn
105                 .nativeSQL("{fn convert(foo(a,b,c), TINYINT)}"));
106         System.out.println(this.conn
107                 .nativeSQL("{fn convert(foo(a,b,c), VARBINARY)}"));
108         System.out.println(this.conn
109                 .nativeSQL("{fn convert(foo(a,b,c), VARCHAR)}"));
110     }
111
112     /**
113      * Tests fix for BUG#3554 - Not specifying database in URL causes
114      * MalformedURL exception.
115      *
116      * @throws Exception
117      * if an error ocurrs.
118      */

119     public void testBug3554() throws Exception JavaDoc {
120         try {
121             new NonRegisteringDriver().connect(
122                     "jdbc:mysql://localhost:3306/?user=root&password=root",
123                     new Properties JavaDoc());
124         } catch (SQLException JavaDoc sqlEx) {
125             assertTrue(sqlEx.getMessage().indexOf("Malformed") == -1);
126         }
127     }
128
129     /**
130      * DOCUMENT ME!
131      *
132      * @throws Exception
133      * ...
134      */

135     public void testBug3790() throws Exception JavaDoc {
136         String JavaDoc field2OldValue = "foo";
137         String JavaDoc field2NewValue = "bar";
138         int field1OldValue = 1;
139
140         Connection JavaDoc conn1 = null;
141         Connection JavaDoc conn2 = null;
142         Statement JavaDoc stmt1 = null;
143         Statement JavaDoc stmt2 = null;
144         ResultSet JavaDoc rs2 = null;
145
146         Properties JavaDoc props = new Properties JavaDoc();
147
148         try {
149             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3790");
150             this.stmt
151                     .executeUpdate("CREATE TABLE testBug3790 (field1 INT NOT NULL PRIMARY KEY, field2 VARCHAR(32)) TYPE=InnoDB");
152             this.stmt.executeUpdate("INSERT INTO testBug3790 VALUES ("
153                     + field1OldValue + ", '" + field2OldValue + "')");
154
155             conn1 = getConnectionWithProps(props); // creates a new connection
156
conn2 = getConnectionWithProps(props); // creates another new
157
// connection
158
conn1.setAutoCommit(false);
159             conn2.setAutoCommit(false);
160
161             stmt1 = conn1.createStatement();
162             stmt1.executeUpdate("UPDATE testBug3790 SET field2 = '"
163                     + field2NewValue + "' WHERE field1=" + field1OldValue);
164             conn1.commit();
165
166             stmt2 = conn2.createStatement();
167
168             rs2 = stmt2.executeQuery("SELECT field1, field2 FROM testBug3790");
169
170             assertTrue(rs2.next());
171             assertTrue(rs2.getInt(1) == field1OldValue);
172             assertTrue(rs2.getString(2).equals(field2NewValue));
173         } finally {
174             this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3790");
175
176             if (rs2 != null) {
177                 rs2.close();
178             }
179
180             if (stmt2 != null) {
181                 stmt2.close();
182             }
183
184             if (stmt1 != null) {
185                 stmt1.close();
186             }
187
188             if (conn1 != null) {
189                 conn1.close();
190             }
191
192             if (conn2 != null) {
193                 conn2.close();
194             }
195         }
196     }
197
198     /**
199      * Tests if the driver configures character sets correctly for 4.1.x
200      * servers. Requires that the 'admin connection' is configured, as this test
201      * needs to create/drop databases.
202      *
203      * @throws Exception
204      * if an error occurs
205      */

206     public void testCollation41() throws Exception JavaDoc {
207         if (versionMeetsMinimum(4, 1) && isAdminConnectionConfigured()) {
208             Map JavaDoc charsetsAndCollations = getCharacterSetsAndCollations();
209             charsetsAndCollations.remove("latin7"); // Maps to multiple Java
210
// charsets
211
charsetsAndCollations.remove("ucs2"); // can't be used as a
212
// connection charset
213

214             Iterator JavaDoc charsets = charsetsAndCollations.keySet().iterator();
215
216             while (charsets.hasNext()) {
217                 Connection JavaDoc charsetConn = null;
218                 Statement JavaDoc charsetStmt = null;
219
220                 try {
221                     String JavaDoc charsetName = charsets.next().toString();
222                     String JavaDoc collationName = charsetsAndCollations.get(
223                             charsetName).toString();
224                     Properties JavaDoc props = new Properties JavaDoc();
225                     props.put("characterEncoding", charsetName);
226
227                     System.out.println("Testing character set " + charsetName);
228
229                     charsetConn = getAdminConnectionWithProps(props);
230
231                     charsetStmt = charsetConn.createStatement();
232
233                     charsetStmt
234                             .executeUpdate("DROP DATABASE IF EXISTS testCollation41");
235                     charsetStmt
236                             .executeUpdate("DROP TABLE IF EXISTS testCollation41");
237
238                     charsetStmt
239                             .executeUpdate("CREATE DATABASE testCollation41 DEFAULT CHARACTER SET "
240                                     + charsetName);
241                     charsetConn.setCatalog("testCollation41");
242
243                     // We've switched catalogs, so we need to recreate the
244
// statement to pick this up...
245
charsetStmt = charsetConn.createStatement();
246
247                     StringBuffer JavaDoc createTableCommand = new StringBuffer JavaDoc(
248                             "CREATE TABLE testCollation41"
249                                     + "(field1 VARCHAR(255), field2 INT)");
250
251                     charsetStmt.executeUpdate(createTableCommand.toString());
252
253                     charsetStmt
254                             .executeUpdate("INSERT INTO testCollation41 VALUES ('abc', 0)");
255
256                     int updateCount = charsetStmt
257                             .executeUpdate("UPDATE testCollation41 SET field2=1 WHERE field1='abc'");
258                     assertTrue(updateCount == 1);
259                 } finally {
260                     if (charsetStmt != null) {
261                         charsetStmt
262                                 .executeUpdate("DROP TABLE IF EXISTS testCollation41");
263                         charsetStmt
264                                 .executeUpdate("DROP DATABASE IF EXISTS testCollation41");
265                         charsetStmt.close();
266                     }
267
268                     if (charsetConn != null) {
269                         charsetConn.close();
270                     }
271                 }
272             }
273         }
274     }
275
276     /**
277      * Tests setReadOnly() being reset during failover
278      *
279      * @throws Exception
280      * if an error occurs.
281      */

282     public void testSetReadOnly() throws Exception JavaDoc {
283         Properties JavaDoc props = new Properties JavaDoc();
284         props.put("autoReconnect", "true");
285
286         String JavaDoc sepChar = "?";
287
288         if (BaseTestCase.dbUrl.indexOf("?") != -1) {
289             sepChar = "&";
290         }
291
292         Connection JavaDoc reconnectableConn = DriverManager.getConnection(
293                 BaseTestCase.dbUrl + sepChar + "autoReconnect=true", props);
294
295         this.rs = reconnectableConn.createStatement().executeQuery(
296                 "SELECT CONNECTION_ID()");
297         this.rs.next();
298
299         String JavaDoc connectionId = this.rs.getString(1);
300
301         reconnectableConn.setReadOnly(true);
302
303         boolean isReadOnly = reconnectableConn.isReadOnly();
304
305         Connection JavaDoc killConn = getConnectionWithProps(null);
306
307         killConn.createStatement().executeUpdate("KILL " + connectionId);
308         Thread.sleep(30000);
309
310         try {
311             reconnectableConn.createStatement().executeQuery("SELECT 1");
312         } catch (SQLException JavaDoc sqlEx) {
313             ; // ignore
314
}
315
316         System.out
317                 .println("Executing statement on reconnectable connection...");
318
319         this.rs = reconnectableConn.createStatement().executeQuery(
320                 "SELECT CONNECTION_ID()");
321         this.rs.next();
322         assertTrue("Connection is not a reconnected-connection", !connectionId
323                 .equals(this.rs.getString(1)));
324
325         try {
326             reconnectableConn.createStatement().executeQuery("SELECT 1");
327         } catch (SQLException JavaDoc sqlEx) {
328             ; // ignore
329
}
330
331         reconnectableConn.createStatement().executeQuery("SELECT 1");
332
333         assertTrue(reconnectableConn.isReadOnly() == isReadOnly);
334     }
335
336     private Map JavaDoc getCharacterSetsAndCollations() throws Exception JavaDoc {
337         Map JavaDoc charsetsToLoad = new HashMap JavaDoc();
338
339         try {
340             this.rs = this.stmt.executeQuery("SHOW character set");
341
342             while (this.rs.next()) {
343                 charsetsToLoad.put(this.rs.getString("Charset"), this.rs
344                         .getString("Default collation"));
345             }
346
347             //
348
// These don't have mappings in Java...
349
//
350
charsetsToLoad.remove("swe7");
351             charsetsToLoad.remove("hp8");
352             charsetsToLoad.remove("dec8");
353             charsetsToLoad.remove("koi8u");
354             charsetsToLoad.remove("keybcs2");
355             charsetsToLoad.remove("geostd8");
356             charsetsToLoad.remove("armscii8");
357         } finally {
358             if (this.rs != null) {
359                 this.rs.close();
360             }
361         }
362
363         return charsetsToLoad;
364     }
365
366     /**
367      * Tests fix for BUG#4334, port #'s not being picked up for
368      * failover/autoreconnect.
369      *
370      * @throws Exception
371      * if an error occurs.
372      */

373     public void testBug4334() throws Exception JavaDoc {
374         if (isAdminConnectionConfigured()) {
375             Connection JavaDoc adminConnection = null;
376
377             try {
378                 adminConnection = getAdminConnection();
379
380                 int bogusPortNumber = 65534;
381
382                 NonRegisteringDriver driver = new NonRegisteringDriver();
383
384                 Properties JavaDoc oldProps = driver.parseURL(BaseTestCase.dbUrl, null);
385
386                 String JavaDoc host = driver.host(oldProps);
387                 int port = driver.port(oldProps);
388                 String JavaDoc database = oldProps
389                         .getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
390                 String JavaDoc user = oldProps
391                         .getProperty(NonRegisteringDriver.USER_PROPERTY_KEY);
392                 String JavaDoc password = oldProps
393                         .getProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY);
394
395                 StringBuffer JavaDoc newUrlToTestPortNum = new StringBuffer JavaDoc(
396                         "jdbc:mysql://");
397
398                 if (host != null) {
399                     newUrlToTestPortNum.append(host);
400                 }
401
402                 newUrlToTestPortNum.append(":").append(port);
403                 newUrlToTestPortNum.append(",");
404
405                 if (host != null) {
406                     newUrlToTestPortNum.append(host);
407                 }
408
409                 newUrlToTestPortNum.append(":").append(bogusPortNumber);
410                 newUrlToTestPortNum.append("/");
411
412                 if (database != null) {
413                     newUrlToTestPortNum.append(database);
414                 }
415
416                 if ((user != null) || (password != null)) {
417                     newUrlToTestPortNum.append("?");
418
419                     if (user != null) {
420                         newUrlToTestPortNum.append("user=").append(user);
421
422                         if (password != null) {
423                             newUrlToTestPortNum.append("&");
424                         }
425                     }
426
427                     if (password != null) {
428                         newUrlToTestPortNum.append("password=")
429                                 .append(password);
430                     }
431                 }
432
433                 Properties JavaDoc autoReconnectProps = new Properties JavaDoc();
434                 autoReconnectProps.put("autoReconnect", "true");
435
436                 System.out.println(newUrlToTestPortNum);
437
438                 //
439
// First test that port #'s are being correctly picked up
440
//
441
// We do this by looking at the error message that is returned
442
//
443
Connection JavaDoc portNumConn = DriverManager.getConnection(
444                         newUrlToTestPortNum.toString(), autoReconnectProps);
445                 Statement JavaDoc portNumStmt = portNumConn.createStatement();
446                 this.rs = portNumStmt.executeQuery("SELECT connection_id()");
447                 this.rs.next();
448
449                 killConnection(adminConnection, this.rs.getString(1));
450
451                 try {
452                     portNumStmt.executeQuery("SELECT connection_id()");
453                 } catch (SQLException JavaDoc sqlEx) {
454                     // we expect this one
455
}
456
457                 try {
458                     portNumStmt.executeQuery("SELECT connection_id()");
459                 } catch (SQLException JavaDoc sqlEx) {
460                     assertTrue(sqlEx.getMessage().toLowerCase().indexOf(
461                             "connection refused") != -1);
462                 }
463
464                 //
465
// Now make sure failover works
466
//
467
StringBuffer JavaDoc newUrlToTestFailover = new StringBuffer JavaDoc(
468                         "jdbc:mysql://");
469
470                 if (host != null) {
471                     newUrlToTestFailover.append(host);
472                 }
473
474                 newUrlToTestFailover.append(":").append(port);
475                 newUrlToTestFailover.append(",");
476
477                 if (host != null) {
478                     newUrlToTestFailover.append(host);
479                 }
480
481                 newUrlToTestFailover.append(":").append(bogusPortNumber);
482                 newUrlToTestFailover.append("/");
483
484                 if (database != null) {
485                     newUrlToTestFailover.append(database);
486                 }
487
488                 if ((user != null) || (password != null)) {
489                     newUrlToTestFailover.append("?");
490
491                     if (user != null) {
492                         newUrlToTestFailover.append("user=").append(user);
493
494                         if (password != null) {
495                             newUrlToTestFailover.append("&");
496                         }
497                     }
498
499                     if (password != null) {
500                         newUrlToTestFailover.append("password=").append(
501                                 password);
502                     }
503                 }
504
505                 Connection JavaDoc failoverConn = DriverManager.getConnection(
506                         newUrlToTestFailover.toString(), autoReconnectProps);
507                 Statement JavaDoc failoverStmt = portNumConn.createStatement();
508                 this.rs = failoverStmt.executeQuery("SELECT connection_id()");
509                 this.rs.next();
510
511                 killConnection(adminConnection, this.rs.getString(1));
512
513                 try {
514                     failoverStmt.executeQuery("SELECT connection_id()");
515                 } catch (SQLException JavaDoc sqlEx) {
516                     // we expect this one
517
}
518
519                 failoverStmt.executeQuery("SELECT connection_id()");
520             } finally {
521                 if (adminConnection != null) {
522                     adminConnection.close();
523                 }
524             }
525         }
526     }
527
528     private static void killConnection(Connection JavaDoc adminConn, String JavaDoc threadId)
529             throws SQLException JavaDoc {
530         adminConn.createStatement().execute("KILL " + threadId);
531     }
532
533     /**
534      * Tests fix for BUG#6966, connections starting up failed-over (due to down
535      * master) never retry master.
536      *
537      * @throws Exception
538      * if the test fails...Note, test is timing-dependent, but
539      * should work in most cases.
540      */

541     public void testBug6966() throws Exception JavaDoc {
542         Properties JavaDoc props = new Driver().parseURL(BaseTestCase.dbUrl, null);
543         props.setProperty("autoReconnect", "true");
544
545         // Re-build the connection information
546
int firstIndexOfHost = BaseTestCase.dbUrl.indexOf("//") + 2;
547         int lastIndexOfHost = BaseTestCase.dbUrl.indexOf("/", firstIndexOfHost);
548
549         String JavaDoc hostPortPair = BaseTestCase.dbUrl.substring(firstIndexOfHost,
550                 lastIndexOfHost);
551
552         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(hostPortPair, ":");
553
554         String JavaDoc host = null;
555         String JavaDoc port = null;
556
557         if (st.hasMoreTokens()) {
558             String JavaDoc possibleHostOrPort = st.nextToken();
559
560             if (Character.isDigit(possibleHostOrPort.charAt(0))) {
561                 port = possibleHostOrPort;
562                 host = "localhost";
563             } else {
564                 host = possibleHostOrPort;
565             }
566         }
567
568         if (st.hasMoreTokens()) {
569             port = st.nextToken();
570         }
571
572         if (host == null) {
573             host = "";
574         }
575
576         if (port == null) {
577             port = "3306";
578         }
579
580         StringBuffer JavaDoc newHostBuf = new StringBuffer JavaDoc();
581         newHostBuf.append(host);
582         newHostBuf.append(":0"); // make sure the master fails
583
newHostBuf.append(",");
584         newHostBuf.append(host);
585         if (port != null) {
586             newHostBuf.append(":");
587             newHostBuf.append(port);
588         }
589
590         props.remove("PORT");
591
592         props.setProperty("HOST", newHostBuf.toString());
593         props.setProperty("queriesBeforeRetryMaster", "50");
594         props.setProperty("maxReconnects", "1");
595
596         Connection JavaDoc failoverConnection = null;
597
598         try {
599             failoverConnection = getConnectionWithProps("jdbc:mysql://"
600                     + newHostBuf.toString() + "/", props);
601             failoverConnection.setAutoCommit(false);
602
603             for (int i = 0; i < 49; i++) {
604                 failoverConnection.createStatement().executeQuery("SELECT 1");
605             }
606
607             long begin = System.currentTimeMillis();
608
609             failoverConnection.setAutoCommit(true);
610
611             long end = System.currentTimeMillis();
612
613             assertTrue(
614                     "Probably didn't try failing back to the master....check test",
615                     (end - begin) > 500);
616
617             failoverConnection.createStatement().executeQuery("SELECT 1");
618         } finally {
619             if (failoverConnection != null) {
620                 failoverConnection.close();
621             }
622         }
623     }
624
625     /**
626      * Test fix for BUG#7952 -- Infinite recursion when 'falling back' to master
627      * in failover configuration.
628      *
629      * @throws Exception
630      * if the tests fails.
631      */

632     public void testBug7952() throws Exception JavaDoc {
633         Properties JavaDoc props = new Driver().parseURL(BaseTestCase.dbUrl, null);
634         props.setProperty("autoReconnect", "true");
635
636         // Re-build the connection information
637
int firstIndexOfHost = BaseTestCase.dbUrl.indexOf("//") + 2;
638         int lastIndexOfHost = BaseTestCase.dbUrl.indexOf("/", firstIndexOfHost);
639
640         String JavaDoc hostPortPair = BaseTestCase.dbUrl.substring(firstIndexOfHost,
641                 lastIndexOfHost);
642
643         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(hostPortPair, ":");
644
645         String JavaDoc host = null;
646         String JavaDoc port = null;
647
648         if (st.hasMoreTokens()) {
649             String JavaDoc possibleHostOrPort = st.nextToken();
650
651             if (Character.isDigit(possibleHostOrPort.charAt(0))) {
652                 port = possibleHostOrPort;
653                 host = "localhost";
654             } else {
655                 host = possibleHostOrPort;
656             }
657         }
658
659         if (st.hasMoreTokens()) {
660             port = st.nextToken();
661         }
662
663         if (host == null) {
664             host = "";
665         }
666
667         if (port == null) {
668             port = "3306";
669         }
670
671         StringBuffer JavaDoc newHostBuf = new StringBuffer JavaDoc();
672         newHostBuf.append(host);
673         newHostBuf.append(":");
674         newHostBuf.append(port);
675         newHostBuf.append(",");
676         newHostBuf.append(host);
677         if (port != null) {
678             newHostBuf.append(":");
679             newHostBuf.append(port);
680         }
681
682         props.remove("PORT");
683
684         props.setProperty("HOST", newHostBuf.toString());
685         props.setProperty("queriesBeforeRetryMaster", "10");
686         props.setProperty("maxReconnects", "1");
687
688         Connection JavaDoc failoverConnection = null;
689         Connection JavaDoc killerConnection = getConnectionWithProps(null);
690
691         try {
692             failoverConnection = getConnectionWithProps("jdbc:mysql://"
693                     + newHostBuf + "/", props);
694             ((com.mysql.jdbc.Connection) failoverConnection)
695                     .setPreferSlaveDuringFailover(true);
696             failoverConnection.setAutoCommit(false);
697
698             String JavaDoc failoverConnectionId = getSingleIndexedValueWithQuery(
699                     failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
700
701             System.out.println("Connection id: " + failoverConnectionId);
702
703             killConnection(killerConnection, failoverConnectionId);
704
705             Thread.sleep(3000); // This can take some time....
706

707             try {
708                 failoverConnection.createStatement().executeQuery("SELECT 1");
709             } catch (SQLException JavaDoc sqlEx) {
710                 assertTrue("08S01".equals(sqlEx.getSQLState()));
711             }
712
713             ((com.mysql.jdbc.Connection) failoverConnection)
714                     .setPreferSlaveDuringFailover(false);
715             ((com.mysql.jdbc.Connection) failoverConnection)
716                     .setFailedOver(true);
717
718             failoverConnection.setAutoCommit(true);
719
720             String JavaDoc failedConnectionId = getSingleIndexedValueWithQuery(
721                     failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
722             System.out.println("Failed over connection id: "
723                     + failedConnectionId);
724
725             ((com.mysql.jdbc.Connection) failoverConnection)
726                     .setPreferSlaveDuringFailover(false);
727             ((com.mysql.jdbc.Connection) failoverConnection)
728                     .setFailedOver(true);
729
730             for (int i = 0; i < 30; i++) {
731                 failoverConnection.setAutoCommit(true);
732                 System.out.println(getSingleIndexedValueWithQuery(
733                         failoverConnection, 1, "SELECT CONNECTION_ID()"));
734                 // failoverConnection.createStatement().executeQuery("SELECT
735
// 1");
736
failoverConnection.setAutoCommit(true);
737             }
738
739             String JavaDoc fallbackConnectionId = getSingleIndexedValueWithQuery(
740                     failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
741             System.out.println("fallback connection id: "
742                     + fallbackConnectionId);
743
744             /*
745              * long begin = System.currentTimeMillis();
746              *
747              * failoverConnection.setAutoCommit(true);
748              *
749              * long end = System.currentTimeMillis();
750              *
751              * assertTrue("Probably didn't try failing back to the
752              * master....check test", (end - begin) > 500);
753              *
754              * failoverConnection.createStatement().executeQuery("SELECT 1");
755              */

756         } finally {
757             if (failoverConnection != null) {
758                 failoverConnection.close();
759             }
760         }
761     }
762
763     /**
764      * Tests fix for BUG#7607 - MS932, SHIFT_JIS and Windows_31J not recog. as
765      * aliases for sjis.
766      *
767      * @throws Exception
768      * if the test fails.
769      */

770     public void testBug7607() throws Exception JavaDoc {
771         if (versionMeetsMinimum(4, 1)) {
772             Connection JavaDoc ms932Conn = null, cp943Conn = null, shiftJisConn = null, windows31JConn = null;
773
774             try {
775                 Properties JavaDoc props = new Properties JavaDoc();
776                 props.setProperty("characterEncoding", "MS932");
777
778                 ms932Conn = getConnectionWithProps(props);
779
780                 this.rs = ms932Conn.createStatement().executeQuery(
781                         "SHOW VARIABLES LIKE 'character_set_client'");
782                 assertTrue(this.rs.next());
783                 String JavaDoc encoding = this.rs.getString(2);
784                 if (!versionMeetsMinimum(5, 0, 3) &&
785                     !versionMeetsMinimum(4, 1, 11)) {
786                     assertEquals("sjis", encoding.toLowerCase(Locale.ENGLISH));
787                 } else {
788                     assertEquals("cp932", encoding.toLowerCase(Locale.ENGLISH));
789                 }
790
791                 this.rs = ms932Conn.createStatement().executeQuery(
792                         "SELECT 'abc'");
793                 assertTrue(this.rs.next());
794
795                 String JavaDoc charsetToCheck = "ms932";
796
797                 if (versionMeetsMinimum(5, 0, 3) ||
798                     versionMeetsMinimum(4, 1, 11)) {
799                     charsetToCheck = "windows-31j";
800                 }
801
802                 assertEquals(charsetToCheck,
803                         ((com.mysql.jdbc.ResultSetMetaData) this.rs
804                                 .getMetaData()).getColumnCharacterSet(1)
805                                 .toLowerCase(Locale.ENGLISH));
806
807                 try {
808                     ms932Conn.createStatement().executeUpdate(
809                             "drop table if exists testBug7607");
810                     ms932Conn
811                             .createStatement()
812                             .executeUpdate(
813                                     "create table testBug7607 (sortCol int, col1 varchar(100) ) character set sjis");
814                     ms932Conn.createStatement().executeUpdate(
815                             "insert into testBug7607 values(1, 0x835C)"); // standard
816
// sjis
817
ms932Conn.createStatement().executeUpdate(
818                             "insert into testBug7607 values(2, 0x878A)"); // NEC
819
// kanji
820

821                     this.rs = ms932Conn
822                             .createStatement()
823                             .executeQuery(
824                                     "SELECT col1 FROM testBug7607 ORDER BY sortCol ASC");
825                     assertTrue(this.rs.next());
826                     String JavaDoc asString = this.rs.getString(1);
827                     assertTrue("\u30bd".equals(asString));
828
829                     // Can't be fixed unless server is fixed,
830
// this is fixed in 4.1.7.
831

832                     assertTrue(this.rs.next());
833                     asString = this.rs.getString(1);
834                     assertEquals("\u3231", asString);
835                 } finally {
836                     ms932Conn.createStatement().executeUpdate(
837                             "drop table if exists testBug7607");
838                 }
839
840                 props = new Properties JavaDoc();
841                 props.setProperty("characterEncoding", "SHIFT_JIS");
842
843                 shiftJisConn = getConnectionWithProps(props);
844
845                 this.rs = shiftJisConn.createStatement().executeQuery(
846                         "SHOW VARIABLES LIKE 'character_set_client'");
847                 assertTrue(this.rs.next());
848                 encoding = this.rs.getString(2);
849                 assertTrue("sjis".equalsIgnoreCase(encoding));
850
851                 this.rs = shiftJisConn.createStatement().executeQuery(
852                         "SELECT 'abc'");
853                 assertTrue(this.rs.next());
854                 assertTrue("SHIFT_JIS"
855                         .equalsIgnoreCase(((com.mysql.jdbc.ResultSetMetaData) this.rs
856                                 .getMetaData()).getColumnCharacterSet(1)));
857
858                 props = new Properties JavaDoc();
859                 props.setProperty("characterEncoding", "WINDOWS-31J");
860
861                 windows31JConn = getConnectionWithProps(props);
862
863                 this.rs = windows31JConn.createStatement().executeQuery(
864                         "SHOW VARIABLES LIKE 'character_set_client'");
865                 assertTrue(this.rs.next());
866                 encoding = this.rs.getString(2);
867
868                 if (!versionMeetsMinimum(5, 0, 3) &&
869                      !versionMeetsMinimum(4, 1, 11)) {
870                     assertEquals("sjis", encoding.toLowerCase(Locale.ENGLISH));
871                 } else {
872                     assertEquals("cp932", encoding.toLowerCase(Locale.ENGLISH));
873                 }
874
875                 this.rs = windows31JConn.createStatement().executeQuery(
876                         "SELECT 'abc'");
877                 assertTrue(this.rs.next());
878
879                 if (!versionMeetsMinimum(4, 1, 11)) {
880                     assertEquals("sjis".toLowerCase(Locale.ENGLISH),
881                             ((com.mysql.jdbc.ResultSetMetaData) this.rs
882                                     .getMetaData()).getColumnCharacterSet(1)
883                                     .toLowerCase(Locale.ENGLISH));
884                 } else {
885                     assertEquals("windows-31j".toLowerCase(Locale.ENGLISH),
886                             ((com.mysql.jdbc.ResultSetMetaData) this.rs
887                                     .getMetaData()).getColumnCharacterSet(1)
888                                     .toLowerCase(Locale.ENGLISH));
889                 }
890
891                 props = new Properties JavaDoc();
892                 props.setProperty("characterEncoding", "CP943");
893
894                 cp943Conn = getConnectionWithProps(props);
895
896                 this.rs = cp943Conn.createStatement().executeQuery(
897                         "SHOW VARIABLES LIKE 'character_set_client'");
898                 assertTrue(this.rs.next());
899                 encoding = this.rs.getString(2);
900                 assertTrue("sjis".equalsIgnoreCase(encoding));
901
902                 this.rs = cp943Conn.createStatement().executeQuery(
903                         "SELECT 'abc'");
904                 assertTrue(this.rs.next());
905                 assertTrue("CP943"
906                         .equalsIgnoreCase(((com.mysql.jdbc.ResultSetMetaData) this.rs
907                                 .getMetaData()).getColumnCharacterSet(1)));
908
909             } finally {
910                 if (ms932Conn != null) {
911                     ms932Conn.close();
912                 }
913
914                 if (shiftJisConn != null) {
915                     shiftJisConn.close();
916                 }
917
918                 if (windows31JConn != null) {
919                     windows31JConn.close();
920                 }
921
922                 if (cp943Conn != null) {
923                     cp943Conn.close();
924                 }
925             }
926         }
927     }
928
929     public void testBug8643() throws Exception JavaDoc {
930         /*
931          * TODO mark, we should fix this so the ports are not hard coded.
932          */

933         String JavaDoc port1 = "3306";
934         String JavaDoc port2 = "3308";
935         String JavaDoc url = "jdbc:mysql://localhost:" + port1 + ",localhost:" + port2
936                 + "/test";
937         Properties JavaDoc props = new Properties JavaDoc();
938         props.put("autoReconnect", "true");
939         props.put("roundRobinLoadBalance", "true");
940         props.put("failOverReadOnly", "false");
941
942         Connection JavaDoc con = null;
943         try {
944             con = DriverManager.getConnection(url, props);
945             Statement JavaDoc stmt1 = con.createStatement();
946
947             ResultSet JavaDoc rs1 = stmt1.executeQuery("show variables like 'port'");
948             rs1.next();
949             assertEquals(port1, rs1.getString(2));
950
951             rs1 = stmt1.executeQuery("select connection_id()");
952             rs1.next();
953             String JavaDoc originalConnectionId = rs1.getString(1);
954             stmt1.executeUpdate("kill " + originalConnectionId);
955             try {
956                 rs1 = stmt1.executeQuery("show variables like 'port'");
957             } catch (SQLException JavaDoc ex) {
958                 // failover and retry
959
rs1 = stmt1.executeQuery("show variables like 'port'");
960             }
961             rs1.next();
962             assertEquals(port2, rs1.getString(2));
963             rs1 = stmt1.executeQuery("select connection_id()");
964             rs1.next();
965             originalConnectionId = rs1.getString(1);
966             stmt1.executeUpdate("kill " + originalConnectionId);
967             try {
968                 rs1 = stmt1.executeQuery("show variables like 'port'");
969             } catch (SQLException JavaDoc ex) {
970                 // failover and retry
971
rs1 = stmt1.executeQuery("show variables like 'port'");
972             }
973             rs1.next();
974             assertEquals(port1, rs1.getString(2));
975         } finally {
976             if (con != null) {
977                 try {
978                     con.close();
979                 } catch (Exception JavaDoc e) {
980                     e.printStackTrace();
981                 }
982             }
983         }
984     }
985
986     /**
987      * Tests fix for BUG#9206, can not use 'UTF-8' for characterSetResults
988      * configuration property.
989      */

990     public void testBug9206() throws Exception JavaDoc {
991         Properties JavaDoc props = new Properties JavaDoc();
992         props.setProperty("characterSetResults", "UTF-8");
993         getConnectionWithProps(props).close();
994     }
995
996     /**
997      * These two charsets have different names depending on version of MySQL
998      * server.
999      *
1000     * @throws Exception
1001     * if the test fails.
1002     */

1003    public void testNewCharsetsConfiguration() throws Exception JavaDoc {
1004        Properties JavaDoc props = new Properties JavaDoc();
1005        props.setProperty("useUnicode", "true");
1006        props.setProperty("characterEncoding", "EUC_KR");
1007        getConnectionWithProps(props).close();
1008
1009        props = new Properties JavaDoc();
1010        props.setProperty("useUnicode", "true");
1011        props.setProperty("characterEncoding", "KOI8_R");
1012        getConnectionWithProps(props).close();
1013    }
1014
1015    /**
1016     * Tests fix for BUG#10144 - Memory leak in ServerPreparedStatement if
1017     * serverPrepare() fails.
1018     */

1019
1020    public void testBug10144() throws Exception JavaDoc {
1021        if (versionMeetsMinimum(4, 1)) {
1022            Properties JavaDoc props = new Properties JavaDoc();
1023            props.setProperty("emulateUnsupportedPstmts", "false");
1024            Connection JavaDoc bareConn = getConnectionWithProps(props);
1025
1026            int currentOpenStatements = ((com.mysql.jdbc.Connection) bareConn)
1027                    .getActiveStatementCount();
1028
1029            try {
1030                bareConn.prepareStatement("Boo!");
1031                fail("Should not've been able to prepare that one!");
1032            } catch (SQLException JavaDoc sqlEx) {
1033                assertEquals(currentOpenStatements,
1034                        ((com.mysql.jdbc.Connection) bareConn)
1035                                .getActiveStatementCount());
1036            }
1037        }
1038    }
1039
1040    /**
1041     * Tests fix for BUG#10496 - SQLException is thrown when using property
1042     * "characterSetResults"
1043     */

1044    public void testBug10496() throws Exception JavaDoc {
1045        if (versionMeetsMinimum(5, 0, 3)) {
1046            Properties JavaDoc props = new Properties JavaDoc();
1047            props.setProperty("useUnicode", "true");
1048            props.setProperty("characterEncoding", "WINDOWS-31J");
1049            props.setProperty("characterSetResults", "WINDOWS-31J");
1050            getConnectionWithProps(props).close();
1051
1052            props = new Properties JavaDoc();
1053            props.setProperty("useUnicode", "true");
1054            props.setProperty("characterEncoding", "EUC_JP");
1055            props.setProperty("characterSetResults", "EUC_JP");
1056            getConnectionWithProps(props).close();
1057        }
1058    }
1059
1060    /**
1061     * Tests fix for BUG#11259, autoReconnect ping causes exception on
1062     * connection startup.
1063     *
1064     * @throws Exception if the test fails.
1065     */

1066    public void testBug11259() throws Exception JavaDoc {
1067        Connection JavaDoc dsConn = null;
1068        try {
1069            Properties JavaDoc props = new Properties JavaDoc();
1070            props.setProperty("autoReconnect", "true");
1071            dsConn = getConnectionWithProps(props);
1072        } finally {
1073            if (dsConn != null) {
1074                dsConn.close();
1075            }
1076        }
1077    }
1078}
1079
Popular Tags