/
ConnectionRegressionTest.java
8745 lines (7295 loc) · 387 KB
/
ConnectionRegressionTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.management.MBeanServer;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.sql.XAConnection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import ErrorReportingExceptionInterceptor;
import AuthenticationPlugin;
import Buffer;
import CharsetMapping;
import ConnectionImpl;
import ConnectionProperties;
import Driver;
import ExceptionInterceptor;
import LoadBalanceExceptionChecker;
import LoadBalancedConnectionProxy;
import Messages;
import MySQLConnection;
import MysqlDataTruncation;
import MysqlErrorNumbers;
import NonRegisteringDriver;
import RandomBalanceStrategy;
import ReplicationConnection;
import ReplicationConnectionGroup;
import ReplicationConnectionGroupManager;
import ReplicationConnectionProxy;
import ResultSetInternalMethods;
import SQLError;
import SocketMetadata;
import StandardSocketFactory;
import StringUtils;
import TimeUtil;
import Util;
import MysqlNativePasswordPlugin;
import Sha256PasswordPlugin;
import MySQLNonTransientConnectionException;
import MySQLTransientException;
import MysqlValidConnectionChecker;
import MysqlConnectionPoolDataSource;
import MysqlXADataSource;
import MysqlXid;
import SuspendableXAConnection;
import ReplicationGroupManagerMBean;
import StandardLogger;
import testsuite.BaseStatementInterceptor;
import testsuite.BaseTestCase;
import testsuite.UnreliableSocketFactory;
/**
* Regression tests for Connections
*/
public class ConnectionRegressionTest extends BaseTestCase {
/**
* @param name
* the name of the testcase
*/
public ConnectionRegressionTest(String name) {
super(name);
}
/**
* Runs all test cases in this test suite
*
* @param args
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(ConnectionRegressionTest.class);
}
public void testBug1914() throws Exception {
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), BIGINT)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), BINARY)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), BIT)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), CHAR)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), DATE)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), DECIMAL)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), DOUBLE)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), FLOAT)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), INTEGER)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), LONGVARBINARY)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), LONGVARCHAR)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), TIME)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), TIMESTAMP)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), TINYINT)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), VARBINARY)}"));
System.out.println(this.conn.nativeSQL("{fn convert(foo(a,b,c), VARCHAR)}"));
}
/**
* Tests fix for BUG#3554 - Not specifying database in URL causes
* MalformedURL exception.
*
* @throws Exception
* if an error ocurrs.
*/
public void testBug3554() throws Exception {
try {
new NonRegisteringDriver().connect("jdbc:mysql://localhost:3306/?user=root&password=root", new Properties());
} catch (SQLException sqlEx) {
assertTrue(sqlEx.getMessage().indexOf("Malformed") == -1);
}
}
public void testBug3790() throws Exception {
String field2OldValue = "foo";
String field2NewValue = "bar";
int field1OldValue = 1;
Connection conn1 = null;
Connection conn2 = null;
Statement stmt1 = null;
Statement stmt2 = null;
ResultSet rs2 = null;
Properties props = new Properties();
try {
createTable("testBug3790", "(field1 INT NOT NULL PRIMARY KEY, field2 VARCHAR(32)) ", "InnoDB");
this.stmt.executeUpdate("INSERT INTO testBug3790 VALUES (" + field1OldValue + ", '" + field2OldValue + "')");
conn1 = getConnectionWithProps(props); // creates a new connection
conn2 = getConnectionWithProps(props); // creates another new
// connection
conn1.setAutoCommit(false);
conn2.setAutoCommit(false);
stmt1 = conn1.createStatement();
stmt1.executeUpdate("UPDATE testBug3790 SET field2 = '" + field2NewValue + "' WHERE field1=" + field1OldValue);
conn1.commit();
stmt2 = conn2.createStatement();
rs2 = stmt2.executeQuery("SELECT field1, field2 FROM testBug3790");
assertTrue(rs2.next());
assertTrue(rs2.getInt(1) == field1OldValue);
assertTrue(rs2.getString(2).equals(field2NewValue));
} finally {
if (rs2 != null) {
rs2.close();
}
if (stmt2 != null) {
stmt2.close();
}
if (stmt1 != null) {
stmt1.close();
}
if (conn1 != null) {
conn1.close();
}
if (conn2 != null) {
conn2.close();
}
}
}
/**
* Tests if the driver configures character sets correctly for 4.1.x
* servers. Requires that the 'admin connection' is configured, as this test
* needs to create/drop databases.
*
* @throws Exception
* if an error occurs
*/
public void testCollation41() throws Exception {
if (versionMeetsMinimum(4, 1) && isAdminConnectionConfigured()) {
Map<String, String> charsetsAndCollations = getCharacterSetsAndCollations();
charsetsAndCollations.remove("latin7"); // Maps to multiple Java
// charsets
charsetsAndCollations.remove("ucs2"); // can't be used as a
// connection charset
for (String charsetName : charsetsAndCollations.keySet()) {
Connection charsetConn = null;
Statement charsetStmt = null;
try {
//String collationName = charsetsAndCollations.get(charsetName);
Properties props = new Properties();
props.put("characterEncoding", charsetName);
System.out.println("Testing character set " + charsetName);
charsetConn = getAdminConnectionWithProps(props);
charsetStmt = charsetConn.createStatement();
charsetStmt.executeUpdate("DROP DATABASE IF EXISTS testCollation41");
charsetStmt.executeUpdate("DROP TABLE IF EXISTS testCollation41");
charsetStmt.executeUpdate("CREATE DATABASE testCollation41 DEFAULT CHARACTER SET " + charsetName);
charsetConn.setCatalog("testCollation41");
// We've switched catalogs, so we need to recreate the
// statement to pick this up...
charsetStmt = charsetConn.createStatement();
StringBuilder createTableCommand = new StringBuilder("CREATE TABLE testCollation41(field1 VARCHAR(255), field2 INT)");
charsetStmt.executeUpdate(createTableCommand.toString());
charsetStmt.executeUpdate("INSERT INTO testCollation41 VALUES ('abc', 0)");
int updateCount = charsetStmt.executeUpdate("UPDATE testCollation41 SET field2=1 WHERE field1='abc'");
assertTrue(updateCount == 1);
} finally {
if (charsetStmt != null) {
charsetStmt.executeUpdate("DROP TABLE IF EXISTS testCollation41");
charsetStmt.executeUpdate("DROP DATABASE IF EXISTS testCollation41");
charsetStmt.close();
}
if (charsetConn != null) {
charsetConn.close();
}
}
}
}
}
/**
* Tests setReadOnly() being reset during failover
*
* @throws Exception
* if an error occurs.
*/
public void testSetReadOnly() throws Exception {
Properties props = new Properties();
props.put("autoReconnect", "true");
String sepChar = "?";
if (BaseTestCase.dbUrl.indexOf("?") != -1) {
sepChar = "&";
}
Connection reconnectableConn = DriverManager.getConnection(BaseTestCase.dbUrl + sepChar + "autoReconnect=true", props);
this.rs = reconnectableConn.createStatement().executeQuery("SELECT CONNECTION_ID()");
this.rs.next();
String connectionId = this.rs.getString(1);
reconnectableConn.setReadOnly(true);
boolean isReadOnly = reconnectableConn.isReadOnly();
Connection killConn = getConnectionWithProps((Properties) null);
killConn.createStatement().executeUpdate("KILL " + connectionId);
Thread.sleep(2000);
SQLException caughtException = null;
int numLoops = 8;
while (caughtException == null && numLoops > 0) {
numLoops--;
try {
reconnectableConn.createStatement().executeQuery("SELECT 1");
} catch (SQLException sqlEx) {
caughtException = sqlEx;
}
}
System.out.println("Executing statement on reconnectable connection...");
this.rs = reconnectableConn.createStatement().executeQuery("SELECT CONNECTION_ID()");
this.rs.next();
assertTrue("Connection is not a reconnected-connection", !connectionId.equals(this.rs.getString(1)));
try {
reconnectableConn.createStatement().executeQuery("SELECT 1");
} catch (SQLException sqlEx) {
// ignore
}
reconnectableConn.createStatement().executeQuery("SELECT 1");
assertTrue(reconnectableConn.isReadOnly() == isReadOnly);
}
private Map<String, String> getCharacterSetsAndCollations() throws Exception {
Map<String, String> charsetsToLoad = new HashMap<String, String>();
try {
this.rs = this.stmt.executeQuery("SHOW character set");
while (this.rs.next()) {
charsetsToLoad.put(this.rs.getString("Charset"), this.rs.getString("Default collation"));
}
//
// These don't have mappings in Java...
//
charsetsToLoad.remove("swe7");
charsetsToLoad.remove("hp8");
charsetsToLoad.remove("dec8");
charsetsToLoad.remove("koi8u");
charsetsToLoad.remove("keybcs2");
charsetsToLoad.remove("geostd8");
charsetsToLoad.remove("armscii8");
} finally {
if (this.rs != null) {
this.rs.close();
}
}
return charsetsToLoad;
}
/**
* Tests fix for BUG#4334, port #'s not being picked up for
* failover/autoreconnect.
*
* @throws Exception
* if an error occurs.
*/
public void testBug4334() throws Exception {
if (isAdminConnectionConfigured()) {
Connection adminConnection = null;
try {
adminConnection = getAdminConnection();
int bogusPortNumber = 65534;
NonRegisteringDriver driver = new NonRegisteringDriver();
Properties oldProps = driver.parseURL(BaseTestCase.dbUrl, null);
String host = driver.host(oldProps);
int port = driver.port(oldProps);
String database = oldProps.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
String user = oldProps.getProperty(NonRegisteringDriver.USER_PROPERTY_KEY);
String password = oldProps.getProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY);
StringBuilder newUrlToTestPortNum = new StringBuilder("jdbc:mysql://");
if (host != null) {
newUrlToTestPortNum.append(host);
}
newUrlToTestPortNum.append(":").append(port);
newUrlToTestPortNum.append(",");
if (host != null) {
newUrlToTestPortNum.append(host);
}
newUrlToTestPortNum.append(":").append(bogusPortNumber);
newUrlToTestPortNum.append("/");
if (database != null) {
newUrlToTestPortNum.append(database);
}
if ((user != null) || (password != null)) {
newUrlToTestPortNum.append("?");
if (user != null) {
newUrlToTestPortNum.append("user=").append(user);
if (password != null) {
newUrlToTestPortNum.append("&");
}
}
if (password != null) {
newUrlToTestPortNum.append("password=").append(password);
}
}
Properties autoReconnectProps = new Properties();
autoReconnectProps.put("autoReconnect", "true");
System.out.println(newUrlToTestPortNum);
//
// First test that port #'s are being correctly picked up
//
// We do this by looking at the error message that is returned
//
Connection portNumConn = DriverManager.getConnection(newUrlToTestPortNum.toString(), autoReconnectProps);
Statement portNumStmt = portNumConn.createStatement();
this.rs = portNumStmt.executeQuery("SELECT connection_id()");
this.rs.next();
killConnection(adminConnection, this.rs.getString(1));
try {
portNumStmt.executeQuery("SELECT connection_id()");
} catch (SQLException sqlEx) {
// we expect this one
}
try {
portNumStmt.executeQuery("SELECT connection_id()");
} catch (SQLException sqlEx) {
assertTrue(sqlEx.getMessage().toLowerCase().indexOf("connection refused") != -1);
}
//
// Now make sure failover works
//
StringBuilder newUrlToTestFailover = new StringBuilder("jdbc:mysql://");
if (host != null) {
newUrlToTestFailover.append(host);
}
newUrlToTestFailover.append(":").append(port);
newUrlToTestFailover.append(",");
if (host != null) {
newUrlToTestFailover.append(host);
}
newUrlToTestFailover.append(":").append(bogusPortNumber);
newUrlToTestFailover.append("/");
if (database != null) {
newUrlToTestFailover.append(database);
}
if ((user != null) || (password != null)) {
newUrlToTestFailover.append("?");
if (user != null) {
newUrlToTestFailover.append("user=").append(user);
if (password != null) {
newUrlToTestFailover.append("&");
}
}
if (password != null) {
newUrlToTestFailover.append("password=").append(password);
}
}
Connection failoverConn = DriverManager.getConnection(newUrlToTestFailover.toString(), autoReconnectProps);
Statement failoverStmt = failoverConn.createStatement();
this.rs = failoverStmt.executeQuery("SELECT connection_id()");
this.rs.next();
killConnection(adminConnection, this.rs.getString(1));
try {
failoverStmt.executeQuery("SELECT connection_id()");
} catch (SQLException sqlEx) {
// we expect this one
}
failoverStmt.executeQuery("SELECT connection_id()");
} finally {
if (adminConnection != null) {
adminConnection.close();
}
}
}
}
private static void killConnection(Connection adminConn, String threadId) throws SQLException {
adminConn.createStatement().execute("KILL " + threadId);
}
/**
* Tests fix for BUG#6966, connections starting up failed-over (due to down
* master) never retry master.
*
* @throws Exception
* if the test fails...Note, test is timing-dependent, but
* should work in most cases.
*/
public void testBug6966() throws Exception {
Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
props.setProperty("autoReconnect", "true");
props.setProperty("socketFactory", "testsuite.UnreliableSocketFactory");
Properties urlProps = new NonRegisteringDriver().parseURL(dbUrl, null);
String host = urlProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
String port = urlProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);
props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
props.remove(NonRegisteringDriver.NUM_HOSTS_PROPERTY_KEY);
props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY + ".1");
props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY + ".1");
props.setProperty("queriesBeforeRetryMaster", "50");
props.setProperty("maxReconnects", "1");
UnreliableSocketFactory.mapHost("master", host);
UnreliableSocketFactory.mapHost("slave", host);
UnreliableSocketFactory.downHost("master");
Connection failoverConnection = null;
try {
failoverConnection = getConnectionWithProps("jdbc:mysql://master:" + port + ",slave:" + port + "/", props);
failoverConnection.setAutoCommit(false);
String originalConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
for (int i = 0; i < 50; i++) {
failoverConnection.createStatement().executeQuery("SELECT 1");
}
UnreliableSocketFactory.dontDownHost("master");
failoverConnection.setAutoCommit(true);
String newConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
assertEquals("/master", UnreliableSocketFactory.getHostFromLastConnection());
assertFalse(newConnectionId.equals(originalConnectionId));
failoverConnection.createStatement().executeQuery("SELECT 1");
} finally {
UnreliableSocketFactory.flushAllStaticData();
if (failoverConnection != null) {
failoverConnection.close();
}
}
}
/**
* Test fix for BUG#7952 -- Infinite recursion when 'falling back' to master
* in failover configuration.
*
* @throws Exception
* if the tests fails.
*/
public void testBug7952() throws Exception {
Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
props.setProperty("autoReconnect", "true");
String host = props.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
if (!NonRegisteringDriver.isHostPropertiesList(host)) {
String port = props.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306");
host = host + ":" + port;
}
host = host + "," + host;
props.remove("PORT");
props.remove("HOST");
props.setProperty("queriesBeforeRetryMaster", "10");
props.setProperty("maxReconnects", "1");
Connection failoverConnection = null;
Connection killerConnection = getConnectionWithProps((String) null);
try {
failoverConnection = getConnectionWithProps("jdbc:mysql://" + host + "/", props);
failoverConnection.setAutoCommit(false);
String failoverConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
System.out.println("Connection id: " + failoverConnectionId);
killConnection(killerConnection, failoverConnectionId);
Thread.sleep(3000); // This can take some time....
try {
failoverConnection.createStatement().executeQuery("SELECT 1");
} catch (SQLException sqlEx) {
assertTrue("08S01".equals(sqlEx.getSQLState()));
}
((com.mysql.jdbc.Connection) failoverConnection).setFailedOver(true);
failoverConnection.setAutoCommit(true);
String failedConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
System.out.println("Failed over connection id: " + failedConnectionId);
((com.mysql.jdbc.Connection) failoverConnection).setFailedOver(true);
for (int i = 0; i < 30; i++) {
failoverConnection.setAutoCommit(true);
System.out.println(getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()"));
// failoverConnection.createStatement().executeQuery("SELECT
// 1");
failoverConnection.setAutoCommit(true);
}
String fallbackConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
System.out.println("fallback connection id: " + fallbackConnectionId);
/*
* long begin = System.currentTimeMillis();
*
* failoverConnection.setAutoCommit(true);
*
* long end = System.currentTimeMillis();
*
* assertTrue("Probably didn't try failing back to the
* master....check test", (end - begin) > 500);
*
* failoverConnection.createStatement().executeQuery("SELECT 1");
*/
} finally {
if (failoverConnection != null) {
failoverConnection.close();
}
}
}
/**
* Tests fix for BUG#7607 - MS932, SHIFT_JIS and Windows_31J not recog. as
* aliases for sjis.
*
* @throws Exception
* if the test fails.
*/
public void testBug7607() throws Exception {
if (versionMeetsMinimum(4, 1)) {
Connection ms932Conn = null, cp943Conn = null, shiftJisConn = null, windows31JConn = null;
try {
Properties props = new Properties();
props.setProperty("characterEncoding", "MS932");
ms932Conn = getConnectionWithProps(props);
this.rs = ms932Conn.createStatement().executeQuery("SHOW VARIABLES LIKE 'character_set_client'");
assertTrue(this.rs.next());
String encoding = this.rs.getString(2);
if (!versionMeetsMinimum(5, 0, 3) && !versionMeetsMinimum(4, 1, 11)) {
assertEquals("sjis", encoding.toLowerCase(Locale.ENGLISH));
} else {
assertEquals("cp932", encoding.toLowerCase(Locale.ENGLISH));
}
this.rs = ms932Conn.createStatement().executeQuery("SELECT 'abc'");
assertTrue(this.rs.next());
String charsetToCheck = "ms932";
assertEquals(charsetToCheck, ((com.mysql.jdbc.ResultSetMetaData) this.rs.getMetaData()).getColumnCharacterSet(1).toLowerCase(Locale.ENGLISH));
try {
ms932Conn.createStatement().executeUpdate("drop table if exists testBug7607");
ms932Conn.createStatement().executeUpdate("create table testBug7607 (sortCol int, col1 varchar(100) ) character set sjis");
ms932Conn.createStatement().executeUpdate("insert into testBug7607 values(1, 0x835C)"); // standard
// sjis
ms932Conn.createStatement().executeUpdate("insert into testBug7607 values(2, 0x878A)"); // NEC
// kanji
this.rs = ms932Conn.createStatement().executeQuery("SELECT col1 FROM testBug7607 ORDER BY sortCol ASC");
assertTrue(this.rs.next());
String asString = this.rs.getString(1);
assertTrue("\u30bd".equals(asString));
// Can't be fixed unless server is fixed,
// this is fixed in 4.1.7.
assertTrue(this.rs.next());
asString = this.rs.getString(1);
assertEquals("\u3231", asString);
} finally {
ms932Conn.createStatement().executeUpdate("drop table if exists testBug7607");
}
props = new Properties();
props.setProperty("characterEncoding", "SHIFT_JIS");
shiftJisConn = getConnectionWithProps(props);
this.rs = shiftJisConn.createStatement().executeQuery("SHOW VARIABLES LIKE 'character_set_client'");
assertTrue(this.rs.next());
encoding = this.rs.getString(2);
assertTrue("sjis".equalsIgnoreCase(encoding));
this.rs = shiftJisConn.createStatement().executeQuery("SELECT 'abc'");
assertTrue(this.rs.next());
String charSetUC = ((com.mysql.jdbc.ResultSetMetaData) this.rs.getMetaData()).getColumnCharacterSet(1).toUpperCase(Locale.US);
// assertEquals("SHIFT_JIS", charSetUC);
props = new Properties();
props.setProperty("characterEncoding", "WINDOWS-31J");
windows31JConn = getConnectionWithProps(props);
this.rs = windows31JConn.createStatement().executeQuery("SHOW VARIABLES LIKE 'character_set_client'");
assertTrue(this.rs.next());
encoding = this.rs.getString(2);
if (!versionMeetsMinimum(5, 0, 3) && !versionMeetsMinimum(4, 1, 11)) {
assertEquals("sjis", encoding.toLowerCase(Locale.ENGLISH));
} else {
assertEquals("cp932", encoding.toLowerCase(Locale.ENGLISH));
}
this.rs = windows31JConn.createStatement().executeQuery("SELECT 'abc'");
assertTrue(this.rs.next());
if (!versionMeetsMinimum(4, 1, 11)) {
assertEquals("sjis".toLowerCase(Locale.ENGLISH),
((com.mysql.jdbc.ResultSetMetaData) this.rs.getMetaData()).getColumnCharacterSet(1).toLowerCase(Locale.ENGLISH));
} else {
assertEquals("windows-31j".toLowerCase(Locale.ENGLISH),
((com.mysql.jdbc.ResultSetMetaData) this.rs.getMetaData()).getColumnCharacterSet(1).toLowerCase(Locale.ENGLISH));
}
props = new Properties();
props.setProperty("characterEncoding", "CP943");
cp943Conn = getConnectionWithProps(props);
this.rs = cp943Conn.createStatement().executeQuery("SHOW VARIABLES LIKE 'character_set_client'");
assertTrue(this.rs.next());
encoding = this.rs.getString(2);
assertTrue("sjis".equalsIgnoreCase(encoding));
this.rs = cp943Conn.createStatement().executeQuery("SELECT 'abc'");
assertTrue(this.rs.next());
charSetUC = ((com.mysql.jdbc.ResultSetMetaData) this.rs.getMetaData()).getColumnCharacterSet(1).toUpperCase(Locale.US);
assertEquals("CP943", charSetUC);
} finally {
if (ms932Conn != null) {
ms932Conn.close();
}
if (shiftJisConn != null) {
shiftJisConn.close();
}
if (windows31JConn != null) {
windows31JConn.close();
}
if (cp943Conn != null) {
cp943Conn.close();
}
}
}
}
/**
* In some case Connector/J's round-robin function doesn't work.
*
* I had 2 mysqld, node1 "localhost:3306" and node2 "localhost:3307".
*
* 1. node1 is up, node2 is up
*
* 2. java-program connect to node1 by using properties
* "autoRecconect=true",
* "roundRobinLoadBalance=true","failOverReadOnly=false".
*
* 3. node1 is down, node2 is up
*
* 4. java-program execute a query and fail, but Connector/J's round-robin
* fashion failover work and if java-program retry a query it can succeed
* (connection is change to node2 by Connector/j)
*
* 5. node1 is up, node2 is up
*
* 6. node1 is up, node2 is down
*
* 7. java-program execute a query, but this time Connector/J doesn't work
* althought node1 is up and usable.
*
*
* @throws Exception
*/
/*
* FIXME: This test is no longer valid with random selection of hosts public
* void testBug8643() throws Exception { if (runMultiHostTests()) {
* Properties defaultProps = getMasterSlaveProps();
*
* defaultProps.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
* defaultProps.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);
*
* defaultProps.put("autoReconnect", "true");
* defaultProps.put("roundRobinLoadBalance", "true");
* defaultProps.put("failOverReadOnly", "false");
*
* Connection con = null; try { con =
* DriverManager.getConnection(getMasterSlaveUrl(), defaultProps); Statement
* stmt1 = con.createStatement();
*
* ResultSet rs1 = stmt1 .executeQuery("show variables like 'port'");
* rs1.next();
*
* rs1 = stmt1.executeQuery("select connection_id()"); rs1.next(); String
* originalConnectionId = rs1.getString(1); this.stmt.executeUpdate("kill "
* + originalConnectionId);
*
* int numLoops = 8;
*
* SQLException caughtException = null;
*
* while (caughtException == null && numLoops > 0) { numLoops--;
*
* try { rs1 = stmt1.executeQuery("show variables like 'port'"); } catch
* (SQLException sqlEx) { caughtException = sqlEx; } }
*
* assertNotNull(caughtException);
*
* // failover and retry rs1 =
* stmt1.executeQuery("show variables like 'port'");
*
* rs1.next(); assertTrue(!((com.mysql.jdbc.Connection) con)
* .isMasterConnection());
*
* rs1 = stmt1.executeQuery("select connection_id()"); rs1.next(); String
* nextConnectionId = rs1.getString(1);
* assertTrue(!nextConnectionId.equals(originalConnectionId));
*
* this.stmt.executeUpdate("kill " + nextConnectionId);
*
* numLoops = 8;
*
* caughtException = null;
*
* while (caughtException == null && numLoops > 0) { numLoops--;
*
* try { rs1 = stmt1.executeQuery("show variables like 'port'"); } catch
* (SQLException sqlEx) { caughtException = sqlEx; } }
*
* assertNotNull(caughtException);
*
* // failover and retry rs1 =
* stmt1.executeQuery("show variables like 'port'");
*
* rs1.next(); assertTrue(((com.mysql.jdbc.Connection) con)
* .isMasterConnection());
*
* } finally { if (con != null) { try { con.close(); } catch (Exception e) {
* e.printStackTrace(); } } } } }
*/
/**
* Tests fix for BUG#9206, can not use 'UTF-8' for characterSetResults
* configuration property.
*/
public void testBug9206() throws Exception {
Properties props = new Properties();
props.setProperty("characterSetResults", "UTF-8");
getConnectionWithProps(props).close();
}
/**
* These two charsets have different names depending on version of MySQL
* server.
*
* @throws Exception
* if the test fails.
*/
public void testNewCharsetsConfiguration() throws Exception {
Properties props = new Properties();
props.setProperty("useUnicode", "true");
props.setProperty("characterEncoding", "EUC_KR");
getConnectionWithProps(props).close();
props = new Properties();
props.setProperty("useUnicode", "true");
props.setProperty("characterEncoding", "KOI8_R");
getConnectionWithProps(props).close();
}
/**
* Tests fix for BUG#10144 - Memory leak in ServerPreparedStatement if
* serverPrepare() fails.
*/
public void testBug10144() throws Exception {
if (versionMeetsMinimum(4, 1)) {
Properties props = new Properties();
props.setProperty("emulateUnsupportedPstmts", "false");
props.setProperty("useServerPrepStmts", "true");
Connection bareConn = getConnectionWithProps(props);
int currentOpenStatements = ((com.mysql.jdbc.Connection) bareConn).getActiveStatementCount();
try {
bareConn.prepareStatement("Boo!");
fail("Should not've been able to prepare that one!");
} catch (SQLException sqlEx) {
assertEquals(currentOpenStatements, ((com.mysql.jdbc.Connection) bareConn).getActiveStatementCount());
} finally {
if (bareConn != null) {
bareConn.close();
}
}
}
}
/**
* Tests fix for BUG#10496 - SQLException is thrown when using property
* "characterSetResults"
*/
public void testBug10496() throws Exception {