PageRenderTime 34ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/EQEmuJSM/mysql-connector-java-5.1.13/src/testsuite/regression/ConnectionRegressionTest.java

http://cubbers-eqemu-utils.googlecode.com/
Java | 2321 lines | 1448 code | 418 blank | 455 comment | 232 complexity | 2e00013c44736fcde2ab7e08c5fd7140 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
  3. The MySQL Connector/J is licensed under the terms of the GPL,
  4. like most MySQL Connectors. There are special exceptions to the
  5. terms and conditions of the GPL as it is applied to this software,
  6. see the FLOSS License Exception available on mysql.com.
  7. This program is free software; you can redistribute it and/or
  8. modify it under the terms of the GNU General Public License as
  9. published by the Free Software Foundation; version 2 of the
  10. License.
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License
  16. along with this program; if not, write to the Free Software
  17. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  18. 02110-1301 USA
  19. */
  20. package testsuite.regression;
  21. import java.io.ByteArrayOutputStream;
  22. import java.io.IOException;
  23. import java.io.PrintStream;
  24. import java.lang.reflect.InvocationTargetException;
  25. import java.lang.reflect.Method;
  26. import java.net.Socket;
  27. import java.net.SocketException;
  28. import java.sql.Connection;
  29. import java.sql.DriverManager;
  30. import java.sql.DriverPropertyInfo;
  31. import java.sql.PreparedStatement;
  32. import java.sql.ResultSet;
  33. import java.sql.SQLException;
  34. import java.sql.Statement;
  35. import java.util.Enumeration;
  36. import java.util.HashMap;
  37. import java.util.HashSet;
  38. import java.util.Iterator;
  39. import java.util.LinkedList;
  40. import java.util.List;
  41. import java.util.Locale;
  42. import java.util.Map;
  43. import java.util.Properties;
  44. import java.util.Set;
  45. import java.util.StringTokenizer;
  46. import java.util.regex.Matcher;
  47. import java.util.regex.Pattern;
  48. import javax.sql.XAConnection;
  49. import javax.transaction.xa.XAResource;
  50. import javax.transaction.xa.Xid;
  51. import testsuite.BaseTestCase;
  52. import testsuite.UnreliableSocketFactory;
  53. import com.mysql.jdbc.ConnectionImpl;
  54. import com.mysql.jdbc.Driver;
  55. import com.mysql.jdbc.LoadBalancingConnectionProxy;
  56. import com.mysql.jdbc.Messages;
  57. import com.mysql.jdbc.MySQLConnection;
  58. import com.mysql.jdbc.MysqlDataTruncation;
  59. import com.mysql.jdbc.NonRegisteringDriver;
  60. import com.mysql.jdbc.RandomBalanceStrategy;
  61. import com.mysql.jdbc.ReplicationConnection;
  62. import com.mysql.jdbc.SQLError;
  63. import com.mysql.jdbc.StandardSocketFactory;
  64. import com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker;
  65. import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
  66. import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;
  67. import com.mysql.jdbc.jdbc2.optional.MysqlXid;
  68. import com.mysql.jdbc.jdbc2.optional.SuspendableXAConnection;
  69. import com.mysql.jdbc.log.StandardLogger;
  70. /**
  71. * Regression tests for Connections
  72. *
  73. * @author Mark Matthews
  74. * @version $Id: ConnectionRegressionTest.java,v 1.1.2.1 2005/05/13 18:58:38
  75. * mmatthews Exp $
  76. */
  77. public class ConnectionRegressionTest extends BaseTestCase {
  78. /**
  79. * DOCUMENT ME!
  80. *
  81. * @param name
  82. * the name of the testcase
  83. */
  84. public ConnectionRegressionTest(String name) {
  85. super(name);
  86. }
  87. /**
  88. * Runs all test cases in this test suite
  89. *
  90. * @param args
  91. */
  92. public static void main(String[] args) {
  93. junit.textui.TestRunner.run(ConnectionRegressionTest.class);
  94. }
  95. /**
  96. * DOCUMENT ME!
  97. *
  98. * @throws Exception
  99. * ...
  100. */
  101. public void testBug1914() throws Exception {
  102. System.out.println(this.conn
  103. .nativeSQL("{fn convert(foo(a,b,c), BIGINT)}"));
  104. System.out.println(this.conn
  105. .nativeSQL("{fn convert(foo(a,b,c), BINARY)}"));
  106. System.out
  107. .println(this.conn.nativeSQL("{fn convert(foo(a,b,c), BIT)}"));
  108. System.out.println(this.conn
  109. .nativeSQL("{fn convert(foo(a,b,c), CHAR)}"));
  110. System.out.println(this.conn
  111. .nativeSQL("{fn convert(foo(a,b,c), DATE)}"));
  112. System.out.println(this.conn
  113. .nativeSQL("{fn convert(foo(a,b,c), DECIMAL)}"));
  114. System.out.println(this.conn
  115. .nativeSQL("{fn convert(foo(a,b,c), DOUBLE)}"));
  116. System.out.println(this.conn
  117. .nativeSQL("{fn convert(foo(a,b,c), FLOAT)}"));
  118. System.out.println(this.conn
  119. .nativeSQL("{fn convert(foo(a,b,c), INTEGER)}"));
  120. System.out.println(this.conn
  121. .nativeSQL("{fn convert(foo(a,b,c), LONGVARBINARY)}"));
  122. System.out.println(this.conn
  123. .nativeSQL("{fn convert(foo(a,b,c), LONGVARCHAR)}"));
  124. System.out.println(this.conn
  125. .nativeSQL("{fn convert(foo(a,b,c), TIME)}"));
  126. System.out.println(this.conn
  127. .nativeSQL("{fn convert(foo(a,b,c), TIMESTAMP)}"));
  128. System.out.println(this.conn
  129. .nativeSQL("{fn convert(foo(a,b,c), TINYINT)}"));
  130. System.out.println(this.conn
  131. .nativeSQL("{fn convert(foo(a,b,c), VARBINARY)}"));
  132. System.out.println(this.conn
  133. .nativeSQL("{fn convert(foo(a,b,c), VARCHAR)}"));
  134. }
  135. /**
  136. * Tests fix for BUG#3554 - Not specifying database in URL causes
  137. * MalformedURL exception.
  138. *
  139. * @throws Exception
  140. * if an error ocurrs.
  141. */
  142. public void testBug3554() throws Exception {
  143. try {
  144. new NonRegisteringDriver().connect(
  145. "jdbc:mysql://localhost:3306/?user=root&password=root",
  146. new Properties());
  147. } catch (SQLException sqlEx) {
  148. assertTrue(sqlEx.getMessage().indexOf("Malformed") == -1);
  149. }
  150. }
  151. /**
  152. * DOCUMENT ME!
  153. *
  154. * @throws Exception
  155. * ...
  156. */
  157. public void testBug3790() throws Exception {
  158. String field2OldValue = "foo";
  159. String field2NewValue = "bar";
  160. int field1OldValue = 1;
  161. Connection conn1 = null;
  162. Connection conn2 = null;
  163. Statement stmt1 = null;
  164. Statement stmt2 = null;
  165. ResultSet rs2 = null;
  166. Properties props = new Properties();
  167. try {
  168. createTable("testBug3790", "(field1 INT NOT NULL PRIMARY KEY, field2 VARCHAR(32)) ", "InnoDB");
  169. this.stmt.executeUpdate("INSERT INTO testBug3790 VALUES ("
  170. + field1OldValue + ", '" + field2OldValue + "')");
  171. conn1 = getConnectionWithProps(props); // creates a new connection
  172. conn2 = getConnectionWithProps(props); // creates another new
  173. // connection
  174. conn1.setAutoCommit(false);
  175. conn2.setAutoCommit(false);
  176. stmt1 = conn1.createStatement();
  177. stmt1.executeUpdate("UPDATE testBug3790 SET field2 = '"
  178. + field2NewValue + "' WHERE field1=" + field1OldValue);
  179. conn1.commit();
  180. stmt2 = conn2.createStatement();
  181. rs2 = stmt2.executeQuery("SELECT field1, field2 FROM testBug3790");
  182. assertTrue(rs2.next());
  183. assertTrue(rs2.getInt(1) == field1OldValue);
  184. assertTrue(rs2.getString(2).equals(field2NewValue));
  185. } finally {
  186. if (rs2 != null) {
  187. rs2.close();
  188. }
  189. if (stmt2 != null) {
  190. stmt2.close();
  191. }
  192. if (stmt1 != null) {
  193. stmt1.close();
  194. }
  195. if (conn1 != null) {
  196. conn1.close();
  197. }
  198. if (conn2 != null) {
  199. conn2.close();
  200. }
  201. }
  202. }
  203. /**
  204. * Tests if the driver configures character sets correctly for 4.1.x
  205. * servers. Requires that the 'admin connection' is configured, as this test
  206. * needs to create/drop databases.
  207. *
  208. * @throws Exception
  209. * if an error occurs
  210. */
  211. public void testCollation41() throws Exception {
  212. if (versionMeetsMinimum(4, 1) && isAdminConnectionConfigured()) {
  213. Map charsetsAndCollations = getCharacterSetsAndCollations();
  214. charsetsAndCollations.remove("latin7"); // Maps to multiple Java
  215. // charsets
  216. charsetsAndCollations.remove("ucs2"); // can't be used as a
  217. // connection charset
  218. Iterator charsets = charsetsAndCollations.keySet().iterator();
  219. while (charsets.hasNext()) {
  220. Connection charsetConn = null;
  221. Statement charsetStmt = null;
  222. try {
  223. String charsetName = charsets.next().toString();
  224. String collationName = charsetsAndCollations.get(
  225. charsetName).toString();
  226. Properties props = new Properties();
  227. props.put("characterEncoding", charsetName);
  228. System.out.println("Testing character set " + charsetName);
  229. charsetConn = getAdminConnectionWithProps(props);
  230. charsetStmt = charsetConn.createStatement();
  231. charsetStmt
  232. .executeUpdate("DROP DATABASE IF EXISTS testCollation41");
  233. charsetStmt
  234. .executeUpdate("DROP TABLE IF EXISTS testCollation41");
  235. charsetStmt
  236. .executeUpdate("CREATE DATABASE testCollation41 DEFAULT CHARACTER SET "
  237. + charsetName);
  238. charsetConn.setCatalog("testCollation41");
  239. // We've switched catalogs, so we need to recreate the
  240. // statement to pick this up...
  241. charsetStmt = charsetConn.createStatement();
  242. StringBuffer createTableCommand = new StringBuffer(
  243. "CREATE TABLE testCollation41"
  244. + "(field1 VARCHAR(255), field2 INT)");
  245. charsetStmt.executeUpdate(createTableCommand.toString());
  246. charsetStmt
  247. .executeUpdate("INSERT INTO testCollation41 VALUES ('abc', 0)");
  248. int updateCount = charsetStmt
  249. .executeUpdate("UPDATE testCollation41 SET field2=1 WHERE field1='abc'");
  250. assertTrue(updateCount == 1);
  251. } finally {
  252. if (charsetStmt != null) {
  253. charsetStmt
  254. .executeUpdate("DROP TABLE IF EXISTS testCollation41");
  255. charsetStmt
  256. .executeUpdate("DROP DATABASE IF EXISTS testCollation41");
  257. charsetStmt.close();
  258. }
  259. if (charsetConn != null) {
  260. charsetConn.close();
  261. }
  262. }
  263. }
  264. }
  265. }
  266. /**
  267. * Tests setReadOnly() being reset during failover
  268. *
  269. * @throws Exception
  270. * if an error occurs.
  271. */
  272. public void testSetReadOnly() throws Exception {
  273. Properties props = new Properties();
  274. props.put("autoReconnect", "true");
  275. String sepChar = "?";
  276. if (BaseTestCase.dbUrl.indexOf("?") != -1) {
  277. sepChar = "&";
  278. }
  279. Connection reconnectableConn = DriverManager.getConnection(
  280. BaseTestCase.dbUrl + sepChar + "autoReconnect=true", props);
  281. this.rs = reconnectableConn.createStatement().executeQuery(
  282. "SELECT CONNECTION_ID()");
  283. this.rs.next();
  284. String connectionId = this.rs.getString(1);
  285. reconnectableConn.setReadOnly(true);
  286. boolean isReadOnly = reconnectableConn.isReadOnly();
  287. Connection killConn = getConnectionWithProps((Properties)null);
  288. killConn.createStatement().executeUpdate("KILL " + connectionId);
  289. Thread.sleep(2000);
  290. SQLException caughtException = null;
  291. int numLoops = 8;
  292. while (caughtException == null && numLoops > 0) {
  293. numLoops--;
  294. try {
  295. reconnectableConn.createStatement().executeQuery("SELECT 1");
  296. } catch (SQLException sqlEx) {
  297. caughtException = sqlEx;
  298. }
  299. }
  300. System.out
  301. .println("Executing statement on reconnectable connection...");
  302. this.rs = reconnectableConn.createStatement().executeQuery(
  303. "SELECT CONNECTION_ID()");
  304. this.rs.next();
  305. assertTrue("Connection is not a reconnected-connection", !connectionId
  306. .equals(this.rs.getString(1)));
  307. try {
  308. reconnectableConn.createStatement().executeQuery("SELECT 1");
  309. } catch (SQLException sqlEx) {
  310. ; // ignore
  311. }
  312. reconnectableConn.createStatement().executeQuery("SELECT 1");
  313. assertTrue(reconnectableConn.isReadOnly() == isReadOnly);
  314. }
  315. private Map getCharacterSetsAndCollations() throws Exception {
  316. Map charsetsToLoad = new HashMap();
  317. try {
  318. this.rs = this.stmt.executeQuery("SHOW character set");
  319. while (this.rs.next()) {
  320. charsetsToLoad.put(this.rs.getString("Charset"), this.rs
  321. .getString("Default collation"));
  322. }
  323. //
  324. // These don't have mappings in Java...
  325. //
  326. charsetsToLoad.remove("swe7");
  327. charsetsToLoad.remove("hp8");
  328. charsetsToLoad.remove("dec8");
  329. charsetsToLoad.remove("koi8u");
  330. charsetsToLoad.remove("keybcs2");
  331. charsetsToLoad.remove("geostd8");
  332. charsetsToLoad.remove("armscii8");
  333. } finally {
  334. if (this.rs != null) {
  335. this.rs.close();
  336. }
  337. }
  338. return charsetsToLoad;
  339. }
  340. /**
  341. * Tests fix for BUG#4334, port #'s not being picked up for
  342. * failover/autoreconnect.
  343. *
  344. * @throws Exception
  345. * if an error occurs.
  346. */
  347. public void testBug4334() throws Exception {
  348. if (isAdminConnectionConfigured()) {
  349. Connection adminConnection = null;
  350. try {
  351. adminConnection = getAdminConnection();
  352. int bogusPortNumber = 65534;
  353. NonRegisteringDriver driver = new NonRegisteringDriver();
  354. Properties oldProps = driver.parseURL(BaseTestCase.dbUrl, null);
  355. String host = driver.host(oldProps);
  356. int port = driver.port(oldProps);
  357. String database = oldProps
  358. .getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
  359. String user = oldProps
  360. .getProperty(NonRegisteringDriver.USER_PROPERTY_KEY);
  361. String password = oldProps
  362. .getProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY);
  363. StringBuffer newUrlToTestPortNum = new StringBuffer(
  364. "jdbc:mysql://");
  365. if (host != null) {
  366. newUrlToTestPortNum.append(host);
  367. }
  368. newUrlToTestPortNum.append(":").append(port);
  369. newUrlToTestPortNum.append(",");
  370. if (host != null) {
  371. newUrlToTestPortNum.append(host);
  372. }
  373. newUrlToTestPortNum.append(":").append(bogusPortNumber);
  374. newUrlToTestPortNum.append("/");
  375. if (database != null) {
  376. newUrlToTestPortNum.append(database);
  377. }
  378. if ((user != null) || (password != null)) {
  379. newUrlToTestPortNum.append("?");
  380. if (user != null) {
  381. newUrlToTestPortNum.append("user=").append(user);
  382. if (password != null) {
  383. newUrlToTestPortNum.append("&");
  384. }
  385. }
  386. if (password != null) {
  387. newUrlToTestPortNum.append("password=")
  388. .append(password);
  389. }
  390. }
  391. Properties autoReconnectProps = new Properties();
  392. autoReconnectProps.put("autoReconnect", "true");
  393. System.out.println(newUrlToTestPortNum);
  394. //
  395. // First test that port #'s are being correctly picked up
  396. //
  397. // We do this by looking at the error message that is returned
  398. //
  399. Connection portNumConn = DriverManager.getConnection(
  400. newUrlToTestPortNum.toString(), autoReconnectProps);
  401. Statement portNumStmt = portNumConn.createStatement();
  402. this.rs = portNumStmt.executeQuery("SELECT connection_id()");
  403. this.rs.next();
  404. killConnection(adminConnection, this.rs.getString(1));
  405. try {
  406. portNumStmt.executeQuery("SELECT connection_id()");
  407. } catch (SQLException sqlEx) {
  408. // we expect this one
  409. }
  410. try {
  411. portNumStmt.executeQuery("SELECT connection_id()");
  412. } catch (SQLException sqlEx) {
  413. assertTrue(sqlEx.getMessage().toLowerCase().indexOf(
  414. "connection refused") != -1);
  415. }
  416. //
  417. // Now make sure failover works
  418. //
  419. StringBuffer newUrlToTestFailover = new StringBuffer(
  420. "jdbc:mysql://");
  421. if (host != null) {
  422. newUrlToTestFailover.append(host);
  423. }
  424. newUrlToTestFailover.append(":").append(port);
  425. newUrlToTestFailover.append(",");
  426. if (host != null) {
  427. newUrlToTestFailover.append(host);
  428. }
  429. newUrlToTestFailover.append(":").append(bogusPortNumber);
  430. newUrlToTestFailover.append("/");
  431. if (database != null) {
  432. newUrlToTestFailover.append(database);
  433. }
  434. if ((user != null) || (password != null)) {
  435. newUrlToTestFailover.append("?");
  436. if (user != null) {
  437. newUrlToTestFailover.append("user=").append(user);
  438. if (password != null) {
  439. newUrlToTestFailover.append("&");
  440. }
  441. }
  442. if (password != null) {
  443. newUrlToTestFailover.append("password=").append(
  444. password);
  445. }
  446. }
  447. Connection failoverConn = DriverManager.getConnection(
  448. newUrlToTestFailover.toString(), autoReconnectProps);
  449. Statement failoverStmt = portNumConn.createStatement();
  450. this.rs = failoverStmt.executeQuery("SELECT connection_id()");
  451. this.rs.next();
  452. killConnection(adminConnection, this.rs.getString(1));
  453. try {
  454. failoverStmt.executeQuery("SELECT connection_id()");
  455. } catch (SQLException sqlEx) {
  456. // we expect this one
  457. }
  458. failoverStmt.executeQuery("SELECT connection_id()");
  459. } finally {
  460. if (adminConnection != null) {
  461. adminConnection.close();
  462. }
  463. }
  464. }
  465. }
  466. private static void killConnection(Connection adminConn, String threadId)
  467. throws SQLException {
  468. adminConn.createStatement().execute("KILL " + threadId);
  469. }
  470. /**
  471. * Tests fix for BUG#6966, connections starting up failed-over (due to down
  472. * master) never retry master.
  473. *
  474. * @throws Exception
  475. * if the test fails...Note, test is timing-dependent, but
  476. * should work in most cases.
  477. */
  478. public void testBug6966() throws Exception {
  479. Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
  480. props.setProperty("autoReconnect", "true");
  481. props.setProperty("socketFactory", "testsuite.UnreliableSocketFactory");
  482. Properties urlProps = new NonRegisteringDriver().parseURL(this.dbUrl, null);
  483. String host = urlProps.getProperty(Driver.HOST_PROPERTY_KEY);
  484. String port = urlProps.getProperty(Driver.PORT_PROPERTY_KEY);
  485. props.remove(Driver.HOST_PROPERTY_KEY);
  486. props.remove(Driver.NUM_HOSTS_PROPERTY_KEY);
  487. props.remove(Driver.HOST_PROPERTY_KEY + ".1");
  488. props.remove(Driver.PORT_PROPERTY_KEY + ".1");
  489. props.setProperty("queriesBeforeRetryMaster", "50");
  490. props.setProperty("maxReconnects", "1");
  491. UnreliableSocketFactory.mapHost("master", host);
  492. UnreliableSocketFactory.mapHost("slave", host);
  493. UnreliableSocketFactory.downHost("master");
  494. Connection failoverConnection = null;
  495. try {
  496. failoverConnection = getConnectionWithProps("jdbc:mysql://master:" + port + ",slave:" + port + "/", props);
  497. failoverConnection.setAutoCommit(false);
  498. String originalConnectionId = getSingleIndexedValueWithQuery(
  499. failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
  500. for (int i = 0; i < 50; i++) {
  501. failoverConnection.createStatement().executeQuery("SELECT 1");
  502. }
  503. ((com.mysql.jdbc.Connection)failoverConnection).clearHasTriedMaster();
  504. UnreliableSocketFactory.dontDownHost("master");
  505. failoverConnection.setAutoCommit(true);
  506. String newConnectionId = getSingleIndexedValueWithQuery(
  507. failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
  508. assertTrue(((com.mysql.jdbc.Connection)failoverConnection).hasTriedMaster());
  509. assertTrue(!newConnectionId.equals(originalConnectionId));
  510. failoverConnection.createStatement().executeQuery("SELECT 1");
  511. } finally {
  512. UnreliableSocketFactory.flushAllHostLists();
  513. if (failoverConnection != null) {
  514. failoverConnection.close();
  515. }
  516. }
  517. }
  518. /**
  519. * Test fix for BUG#7952 -- Infinite recursion when 'falling back' to master
  520. * in failover configuration.
  521. *
  522. * @throws Exception
  523. * if the tests fails.
  524. */
  525. public void testBug7952() throws Exception {
  526. Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
  527. props.setProperty("autoReconnect", "true");
  528. // Re-build the connection information
  529. int firstIndexOfHost = BaseTestCase.dbUrl.indexOf("//") + 2;
  530. int lastIndexOfHost = BaseTestCase.dbUrl.indexOf("/", firstIndexOfHost);
  531. String hostPortPair = BaseTestCase.dbUrl.substring(firstIndexOfHost,
  532. lastIndexOfHost);
  533. StringTokenizer st = new StringTokenizer(hostPortPair, ":");
  534. String host = null;
  535. String port = null;
  536. if (st.hasMoreTokens()) {
  537. String possibleHostOrPort = st.nextToken();
  538. if (possibleHostOrPort.indexOf(".") == -1
  539. && Character.isDigit(possibleHostOrPort.charAt(0))) {
  540. port = possibleHostOrPort;
  541. host = "localhost";
  542. } else {
  543. host = possibleHostOrPort;
  544. }
  545. }
  546. if (st.hasMoreTokens()) {
  547. port = st.nextToken();
  548. }
  549. if (host == null) {
  550. host = "";
  551. }
  552. if (port == null) {
  553. port = "3306";
  554. }
  555. StringBuffer newHostBuf = new StringBuffer();
  556. newHostBuf.append(host);
  557. newHostBuf.append(":");
  558. newHostBuf.append(port);
  559. newHostBuf.append(",");
  560. newHostBuf.append(host);
  561. if (port != null) {
  562. newHostBuf.append(":");
  563. newHostBuf.append(port);
  564. }
  565. props.remove("PORT");
  566. props.setProperty("HOST", newHostBuf.toString());
  567. props.setProperty("queriesBeforeRetryMaster", "10");
  568. props.setProperty("maxReconnects", "1");
  569. Connection failoverConnection = null;
  570. Connection killerConnection = getConnectionWithProps((String)null);
  571. try {
  572. failoverConnection = getConnectionWithProps("jdbc:mysql://"
  573. + newHostBuf + "/", props);
  574. ((com.mysql.jdbc.Connection) failoverConnection)
  575. .setPreferSlaveDuringFailover(true);
  576. failoverConnection.setAutoCommit(false);
  577. String failoverConnectionId = getSingleIndexedValueWithQuery(
  578. failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
  579. System.out.println("Connection id: " + failoverConnectionId);
  580. killConnection(killerConnection, failoverConnectionId);
  581. Thread.sleep(3000); // This can take some time....
  582. try {
  583. failoverConnection.createStatement().executeQuery("SELECT 1");
  584. } catch (SQLException sqlEx) {
  585. assertTrue("08S01".equals(sqlEx.getSQLState()));
  586. }
  587. ((com.mysql.jdbc.Connection) failoverConnection)
  588. .setPreferSlaveDuringFailover(false);
  589. ((com.mysql.jdbc.Connection) failoverConnection)
  590. .setFailedOver(true);
  591. failoverConnection.setAutoCommit(true);
  592. String failedConnectionId = getSingleIndexedValueWithQuery(
  593. failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
  594. System.out.println("Failed over connection id: "
  595. + failedConnectionId);
  596. ((com.mysql.jdbc.Connection) failoverConnection)
  597. .setPreferSlaveDuringFailover(false);
  598. ((com.mysql.jdbc.Connection) failoverConnection)
  599. .setFailedOver(true);
  600. for (int i = 0; i < 30; i++) {
  601. failoverConnection.setAutoCommit(true);
  602. System.out.println(getSingleIndexedValueWithQuery(
  603. failoverConnection, 1, "SELECT CONNECTION_ID()"));
  604. // failoverConnection.createStatement().executeQuery("SELECT
  605. // 1");
  606. failoverConnection.setAutoCommit(true);
  607. }
  608. String fallbackConnectionId = getSingleIndexedValueWithQuery(
  609. failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
  610. System.out.println("fallback connection id: "
  611. + fallbackConnectionId);
  612. /*
  613. * long begin = System.currentTimeMillis();
  614. *
  615. * failoverConnection.setAutoCommit(true);
  616. *
  617. * long end = System.currentTimeMillis();
  618. *
  619. * assertTrue("Probably didn't try failing back to the
  620. * master....check test", (end - begin) > 500);
  621. *
  622. * failoverConnection.createStatement().executeQuery("SELECT 1");
  623. */
  624. } finally {
  625. if (failoverConnection != null) {
  626. failoverConnection.close();
  627. }
  628. }
  629. }
  630. /**
  631. * Tests fix for BUG#7607 - MS932, SHIFT_JIS and Windows_31J not recog. as
  632. * aliases for sjis.
  633. *
  634. * @throws Exception
  635. * if the test fails.
  636. */
  637. public void testBug7607() throws Exception {
  638. if (versionMeetsMinimum(4, 1)) {
  639. Connection ms932Conn = null, cp943Conn = null, shiftJisConn = null, windows31JConn = null;
  640. try {
  641. Properties props = new Properties();
  642. props.setProperty("characterEncoding", "MS932");
  643. ms932Conn = getConnectionWithProps(props);
  644. this.rs = ms932Conn.createStatement().executeQuery(
  645. "SHOW VARIABLES LIKE 'character_set_client'");
  646. assertTrue(this.rs.next());
  647. String encoding = this.rs.getString(2);
  648. if (!versionMeetsMinimum(5, 0, 3)
  649. && !versionMeetsMinimum(4, 1, 11)) {
  650. assertEquals("sjis", encoding.toLowerCase(Locale.ENGLISH));
  651. } else {
  652. assertEquals("cp932", encoding.toLowerCase(Locale.ENGLISH));
  653. }
  654. this.rs = ms932Conn.createStatement().executeQuery(
  655. "SELECT 'abc'");
  656. assertTrue(this.rs.next());
  657. String charsetToCheck = "ms932";
  658. if (versionMeetsMinimum(5, 0, 3)
  659. || versionMeetsMinimum(4, 1, 11)) {
  660. charsetToCheck = "windows-31j";
  661. }
  662. assertEquals(charsetToCheck,
  663. ((com.mysql.jdbc.ResultSetMetaData) this.rs
  664. .getMetaData()).getColumnCharacterSet(1)
  665. .toLowerCase(Locale.ENGLISH));
  666. try {
  667. ms932Conn.createStatement().executeUpdate(
  668. "drop table if exists testBug7607");
  669. ms932Conn
  670. .createStatement()
  671. .executeUpdate(
  672. "create table testBug7607 (sortCol int, col1 varchar(100) ) character set sjis");
  673. ms932Conn.createStatement().executeUpdate(
  674. "insert into testBug7607 values(1, 0x835C)"); // standard
  675. // sjis
  676. ms932Conn.createStatement().executeUpdate(
  677. "insert into testBug7607 values(2, 0x878A)"); // NEC
  678. // kanji
  679. this.rs = ms932Conn
  680. .createStatement()
  681. .executeQuery(
  682. "SELECT col1 FROM testBug7607 ORDER BY sortCol ASC");
  683. assertTrue(this.rs.next());
  684. String asString = this.rs.getString(1);
  685. assertTrue("\u30bd".equals(asString));
  686. // Can't be fixed unless server is fixed,
  687. // this is fixed in 4.1.7.
  688. assertTrue(this.rs.next());
  689. asString = this.rs.getString(1);
  690. assertEquals("\u3231", asString);
  691. } finally {
  692. ms932Conn.createStatement().executeUpdate(
  693. "drop table if exists testBug7607");
  694. }
  695. props = new Properties();
  696. props.setProperty("characterEncoding", "SHIFT_JIS");
  697. shiftJisConn = getConnectionWithProps(props);
  698. this.rs = shiftJisConn.createStatement().executeQuery(
  699. "SHOW VARIABLES LIKE 'character_set_client'");
  700. assertTrue(this.rs.next());
  701. encoding = this.rs.getString(2);
  702. assertTrue("sjis".equalsIgnoreCase(encoding));
  703. this.rs = shiftJisConn.createStatement().executeQuery(
  704. "SELECT 'abc'");
  705. assertTrue(this.rs.next());
  706. String charSetUC = ((com.mysql.jdbc.ResultSetMetaData) this.rs
  707. .getMetaData()).getColumnCharacterSet(1).toUpperCase(
  708. Locale.US);
  709. if (isRunningOnJdk131()) {
  710. assertEquals("WINDOWS-31J", charSetUC);
  711. } else {
  712. // assertEquals("SHIFT_JIS", charSetUC);
  713. }
  714. props = new Properties();
  715. props.setProperty("characterEncoding", "WINDOWS-31J");
  716. windows31JConn = getConnectionWithProps(props);
  717. this.rs = windows31JConn.createStatement().executeQuery(
  718. "SHOW VARIABLES LIKE 'character_set_client'");
  719. assertTrue(this.rs.next());
  720. encoding = this.rs.getString(2);
  721. if (!versionMeetsMinimum(5, 0, 3)
  722. && !versionMeetsMinimum(4, 1, 11)) {
  723. assertEquals("sjis", encoding.toLowerCase(Locale.ENGLISH));
  724. } else {
  725. assertEquals("cp932", encoding.toLowerCase(Locale.ENGLISH));
  726. }
  727. this.rs = windows31JConn.createStatement().executeQuery(
  728. "SELECT 'abc'");
  729. assertTrue(this.rs.next());
  730. if (!versionMeetsMinimum(4, 1, 11)) {
  731. assertEquals("sjis".toLowerCase(Locale.ENGLISH),
  732. ((com.mysql.jdbc.ResultSetMetaData) this.rs
  733. .getMetaData()).getColumnCharacterSet(1)
  734. .toLowerCase(Locale.ENGLISH));
  735. } else {
  736. assertEquals("windows-31j".toLowerCase(Locale.ENGLISH),
  737. ((com.mysql.jdbc.ResultSetMetaData) this.rs
  738. .getMetaData()).getColumnCharacterSet(1)
  739. .toLowerCase(Locale.ENGLISH));
  740. }
  741. props = new Properties();
  742. props.setProperty("characterEncoding", "CP943");
  743. cp943Conn = getConnectionWithProps(props);
  744. this.rs = cp943Conn.createStatement().executeQuery(
  745. "SHOW VARIABLES LIKE 'character_set_client'");
  746. assertTrue(this.rs.next());
  747. encoding = this.rs.getString(2);
  748. assertTrue("sjis".equalsIgnoreCase(encoding));
  749. this.rs = cp943Conn.createStatement().executeQuery(
  750. "SELECT 'abc'");
  751. assertTrue(this.rs.next());
  752. charSetUC = ((com.mysql.jdbc.ResultSetMetaData) this.rs
  753. .getMetaData()).getColumnCharacterSet(1).toUpperCase(
  754. Locale.US);
  755. if (isRunningOnJdk131()) {
  756. assertEquals("WINDOWS-31J", charSetUC);
  757. } else {
  758. assertEquals("CP943", charSetUC);
  759. }
  760. } finally {
  761. if (ms932Conn != null) {
  762. ms932Conn.close();
  763. }
  764. if (shiftJisConn != null) {
  765. shiftJisConn.close();
  766. }
  767. if (windows31JConn != null) {
  768. windows31JConn.close();
  769. }
  770. if (cp943Conn != null) {
  771. cp943Conn.close();
  772. }
  773. }
  774. }
  775. }
  776. /**
  777. * In some case Connector/J's round-robin function doesn't work.
  778. *
  779. * I had 2 mysqld, node1 "localhost:3306" and node2 "localhost:3307".
  780. *
  781. * 1. node1 is up, node2 is up
  782. *
  783. * 2. java-program connect to node1 by using properties
  784. * "autoRecconect=true","roundRobinLoadBalance=true","failOverReadOnly=false".
  785. *
  786. * 3. node1 is down, node2 is up
  787. *
  788. * 4. java-program execute a query and fail, but Connector/J's round-robin
  789. * fashion failover work and if java-program retry a query it can succeed
  790. * (connection is change to node2 by Connector/j)
  791. *
  792. * 5. node1 is up, node2 is up
  793. *
  794. * 6. node1 is up, node2 is down
  795. *
  796. * 7. java-program execute a query, but this time Connector/J doesn't work
  797. * althought node1 is up and usable.
  798. *
  799. *
  800. * @throws Exception
  801. */
  802. /* FIXME: This test is no longer valid with random selection of hosts
  803. public void testBug8643() throws Exception {
  804. if (runMultiHostTests()) {
  805. Properties defaultProps = getMasterSlaveProps();
  806. defaultProps.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
  807. defaultProps.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);
  808. defaultProps.put("autoReconnect", "true");
  809. defaultProps.put("roundRobinLoadBalance", "true");
  810. defaultProps.put("failOverReadOnly", "false");
  811. Connection con = null;
  812. try {
  813. con = DriverManager.getConnection(getMasterSlaveUrl(),
  814. defaultProps);
  815. Statement stmt1 = con.createStatement();
  816. ResultSet rs1 = stmt1
  817. .executeQuery("show variables like 'port'");
  818. rs1.next();
  819. rs1 = stmt1.executeQuery("select connection_id()");
  820. rs1.next();
  821. String originalConnectionId = rs1.getString(1);
  822. this.stmt.executeUpdate("kill " + originalConnectionId);
  823. int numLoops = 8;
  824. SQLException caughtException = null;
  825. while (caughtException == null && numLoops > 0) {
  826. numLoops--;
  827. try {
  828. rs1 = stmt1.executeQuery("show variables like 'port'");
  829. } catch (SQLException sqlEx) {
  830. caughtException = sqlEx;
  831. }
  832. }
  833. assertNotNull(caughtException);
  834. // failover and retry
  835. rs1 = stmt1.executeQuery("show variables like 'port'");
  836. rs1.next();
  837. assertTrue(!((com.mysql.jdbc.Connection) con)
  838. .isMasterConnection());
  839. rs1 = stmt1.executeQuery("select connection_id()");
  840. rs1.next();
  841. String nextConnectionId = rs1.getString(1);
  842. assertTrue(!nextConnectionId.equals(originalConnectionId));
  843. this.stmt.executeUpdate("kill " + nextConnectionId);
  844. numLoops = 8;
  845. caughtException = null;
  846. while (caughtException == null && numLoops > 0) {
  847. numLoops--;
  848. try {
  849. rs1 = stmt1.executeQuery("show variables like 'port'");
  850. } catch (SQLException sqlEx) {
  851. caughtException = sqlEx;
  852. }
  853. }
  854. assertNotNull(caughtException);
  855. // failover and retry
  856. rs1 = stmt1.executeQuery("show variables like 'port'");
  857. rs1.next();
  858. assertTrue(((com.mysql.jdbc.Connection) con)
  859. .isMasterConnection());
  860. } finally {
  861. if (con != null) {
  862. try {
  863. con.close();
  864. } catch (Exception e) {
  865. e.printStackTrace();
  866. }
  867. }
  868. }
  869. }
  870. }
  871. */
  872. /**
  873. * Tests fix for BUG#9206, can not use 'UTF-8' for characterSetResults
  874. * configuration property.
  875. */
  876. public void testBug9206() throws Exception {
  877. Properties props = new Properties();
  878. props.setProperty("characterSetResults", "UTF-8");
  879. getConnectionWithProps(props).close();
  880. }
  881. /**
  882. * These two charsets have different names depending on version of MySQL
  883. * server.
  884. *
  885. * @throws Exception
  886. * if the test fails.
  887. */
  888. public void testNewCharsetsConfiguration() throws Exception {
  889. Properties props = new Properties();
  890. props.setProperty("useUnicode", "true");
  891. props.setProperty("characterEncoding", "EUC_KR");
  892. getConnectionWithProps(props).close();
  893. props = new Properties();
  894. props.setProperty("useUnicode", "true");
  895. props.setProperty("characterEncoding", "KOI8_R");
  896. getConnectionWithProps(props).close();
  897. }
  898. /**
  899. * Tests fix for BUG#10144 - Memory leak in ServerPreparedStatement if
  900. * serverPrepare() fails.
  901. */
  902. public void testBug10144() throws Exception {
  903. if (versionMeetsMinimum(4, 1)) {
  904. Properties props = new Properties();
  905. props.setProperty("emulateUnsupportedPstmts", "false");
  906. props.setProperty("useServerPrepStmts", "true");
  907. Connection bareConn = getConnectionWithProps(props);
  908. int currentOpenStatements = ((com.mysql.jdbc.Connection) bareConn)
  909. .getActiveStatementCount();
  910. try {
  911. bareConn.prepareStatement("Boo!");
  912. fail("Should not've been able to prepare that one!");
  913. } catch (SQLException sqlEx) {
  914. assertEquals(currentOpenStatements,
  915. ((com.mysql.jdbc.Connection) bareConn)
  916. .getActiveStatementCount());
  917. } finally {
  918. if (bareConn != null) {
  919. bareConn.close();
  920. }
  921. }
  922. }
  923. }
  924. /**
  925. * Tests fix for BUG#10496 - SQLException is thrown when using property
  926. * "characterSetResults"
  927. */
  928. public void testBug10496() throws Exception {
  929. if (versionMeetsMinimum(5, 0, 3)) {
  930. Properties props = new Properties();
  931. props.setProperty("useUnicode", "true");
  932. props.setProperty("characterEncoding", "WINDOWS-31J");
  933. props.setProperty("characterSetResults", "WINDOWS-31J");
  934. getConnectionWithProps(props).close();
  935. props = new Properties();
  936. props.setProperty("useUnicode", "true");
  937. props.setProperty("characterEncoding", "EUC_JP");
  938. props.setProperty("characterSetResults", "EUC_JP");
  939. getConnectionWithProps(props).close();
  940. }
  941. }
  942. /**
  943. * Tests fix for BUG#11259, autoReconnect ping causes exception on
  944. * connection startup.
  945. *
  946. * @throws Exception
  947. * if the test fails.
  948. */
  949. public void testBug11259() throws Exception {
  950. Connection dsConn = null;
  951. try {
  952. Properties props = new Properties();
  953. props.setProperty("autoReconnect", "true");
  954. dsConn = getConnectionWithProps(props);
  955. } finally {
  956. if (dsConn != null) {
  957. dsConn.close();
  958. }
  959. }
  960. }
  961. /**
  962. * Tests fix for BUG#11879 -- ReplicationConnection won't switch to slave,
  963. * throws "Catalog can't be null" exception.
  964. *
  965. * @throws Exception
  966. * if the test fails
  967. */
  968. public void testBug11879() throws Exception {
  969. if (runMultiHostTests()) {
  970. Connection replConn = null;
  971. try {
  972. replConn = getMasterSlaveReplicationConnection();
  973. replConn.setReadOnly(true);
  974. replConn.setReadOnly(false);
  975. } finally {
  976. if (replConn != null) {
  977. replConn.close();
  978. }
  979. }
  980. }
  981. }
  982. /**
  983. * Tests fix for BUG#11976 - maxPerformance.properties mis-spells
  984. * "elideSetAutoCommits".
  985. *
  986. * @throws Exception
  987. * if the test fails.
  988. */
  989. public void testBug11976() throws Exception {
  990. if (isRunningOnJdk131()) {
  991. return; // test not valid on JDK-1.3.1
  992. }
  993. if (!versionMeetsMinimum(6, 0)) {
  994. return; // server status is broken until MySQL-6.0
  995. }
  996. Properties props = new Properties();
  997. props.setProperty("useConfigs", "maxPerformance");
  998. Connection maxPerfConn = getConnectionWithProps(props);
  999. assertEquals(true, ((com.mysql.jdbc.Connection) maxPerfConn)
  1000. .getElideSetAutoCommits());
  1001. }
  1002. /**
  1003. * Tests fix for BUG#12218, properties shared between master and slave with
  1004. * replication connection.
  1005. *
  1006. * @throws Exception
  1007. * if the test fails.
  1008. */
  1009. public void testBug12218() throws Exception {
  1010. if (runMultiHostTests()) {
  1011. Connection replConn = null;
  1012. try {
  1013. replConn = getMasterSlaveReplicationConnection();
  1014. assertTrue(!((MySQLConnection) ((ReplicationConnection) replConn)
  1015. .getMasterConnection()).hasSameProperties(
  1016. ((ReplicationConnection) replConn)
  1017. .getSlavesConnection()));
  1018. } finally {
  1019. if (replConn != null) {
  1020. replConn.close();
  1021. }
  1022. }
  1023. }
  1024. }
  1025. /**
  1026. * Tests fix for BUG#12229 - explainSlowQueries hangs with server-side
  1027. * prepared statements.
  1028. *
  1029. * @throws Exception
  1030. * if the test fails.
  1031. */
  1032. public void testBug12229() throws Exception {
  1033. createTable("testBug12229", "(`int_field` integer )");
  1034. this.stmt.executeUpdate("insert into testBug12229 values (123456),(1)");
  1035. Properties props = new Properties();
  1036. props.put("profileSQL", "true");
  1037. props.put("slowQueryThresholdMillis", "0");
  1038. props.put("logSlowQueries", "true");
  1039. props.put("explainSlowQueries", "true");
  1040. props.put("useServerPrepStmts", "true");
  1041. Connection explainConn = getConnectionWithProps(props);
  1042. this.pstmt = explainConn
  1043. .prepareStatement("SELECT `int_field` FROM `testBug12229` WHERE `int_field` = ?");
  1044. this.pstmt.setInt(1, 1);
  1045. this.rs = this.pstmt.executeQuery();
  1046. assertTrue(this.rs.next());
  1047. this.rs = this.pstmt.executeQuery();
  1048. assertTrue(this.rs.next());
  1049. this.rs = this.pstmt.executeQuery();
  1050. assertTrue(this.rs.next());
  1051. }
  1052. /**
  1053. * Tests fix for BUG#12752 - Cp1251 incorrectly mapped to win1251 for
  1054. * servers newer than 4.0.x.
  1055. *
  1056. * @throws Exception
  1057. * if the test fails.
  1058. */
  1059. public void testBug12752() throws Exception {
  1060. Properties props = new Properties();
  1061. props.setProperty("characterEncoding", "Cp1251");
  1062. getConnectionWithProps(props).close();
  1063. }
  1064. /**
  1065. * Tests fix for BUG#12753, sessionVariables=....=...., doesn't work as it's
  1066. * tokenized incorrectly.
  1067. *
  1068. * @throws Exception
  1069. * if the test fails.
  1070. */
  1071. public void testBug12753() throws Exception {
  1072. if (versionMeetsMinimum(4, 1)) {
  1073. Properties props = new Properties();
  1074. props.setProperty("sessionVariables", "sql_mode=ansi");
  1075. Connection sessionConn = null;
  1076. try {
  1077. sessionConn = getConnectionWithProps(props);
  1078. String sqlMode = getMysqlVariable(sessionConn, "sql_mode");
  1079. assertTrue(sqlMode.indexOf("ANSI") != -1);
  1080. } finally {
  1081. if (sessionConn != null) {
  1082. sessionConn.close();
  1083. sessionConn = null;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. /**
  1089. * Tests fix for BUG#13048 - maxQuerySizeToLog is not respected.
  1090. *
  1091. * @throws Exception
  1092. * if the test fails
  1093. */
  1094. public void testBug13048() throws Exception {
  1095. Connection profileConn = null;
  1096. PrintStream oldErr = System.err;
  1097. try {
  1098. ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  1099. System.setErr(new PrintStream(bOut));
  1100. Properties props = new Properties();
  1101. props.setProperty("profileSQL", "true");
  1102. props.setProperty("maxQuerySizeToLog", "2");
  1103. props.setProperty("logger", "com.mysql.jdbc.log.StandardLogger");
  1104. profileConn = getConnectionWithProps(props);
  1105. StringBuffer queryBuf = new StringBuffer("SELECT '");
  1106. for (int i = 0; i < 500; i++) {
  1107. queryBuf.append("a");
  1108. }
  1109. queryBuf.append("'");
  1110. this.rs = profileConn.createStatement().executeQuery(
  1111. queryBuf.toString());
  1112. this.rs.close();
  1113. String logString = new String(bOut.toString("ISO8859-1"));
  1114. assertTrue(logString.indexOf("... (truncated)") != -1);
  1115. bOut = new ByteArrayOutputStream();
  1116. System.setErr(new PrintStream(bOut));
  1117. this.rs = profileConn.prepareStatement(queryBuf.toString())
  1118. .executeQuery();
  1119. logString = new String(bOut.toString("ISO8859-1"));
  1120. assertTrue(logString.indexOf("... (truncated)") != -1);
  1121. } finally {
  1122. System.setErr(oldErr);
  1123. if (profileConn != null) {
  1124. profileConn.close();
  1125. }
  1126. if (this.rs != null) {
  1127. ResultSet toClose = this.rs;
  1128. this.rs = null;
  1129. toClose.close();
  1130. }
  1131. }
  1132. }
  1133. /**
  1134. * Tests fix for BUG#13453 - can't use & or = in URL configuration values
  1135. * (we now allow you to use www-form-encoding).
  1136. *
  1137. * @throws Exception
  1138. * if the test fails
  1139. */
  1140. public void testBug13453() throws Exception {
  1141. StringBuffer urlBuf = new StringBuffer(dbUrl);
  1142. if (dbUrl.indexOf('?') == -1) {
  1143. urlBuf.append('?');
  1144. } else {
  1145. urlBuf.append('&');
  1146. }
  1147. urlBuf.append("sessionVariables=@testBug13453='%25%26+%3D'");
  1148. Connection encodedConn = null;
  1149. try {
  1150. encodedConn = DriverManager.getConnection(urlBuf.toString(), null);
  1151. this.rs = encodedConn.createStatement().executeQuery(
  1152. "SELECT @testBug13453");
  1153. assertTrue(this.rs.next());
  1154. assertEquals("%& =", this.rs.getString(1));
  1155. } finally {
  1156. if (this.rs != null) {
  1157. this.rs.close();
  1158. this.rs = null;
  1159. }
  1160. if (encodedConn != null) {
  1161. encodedConn.close();
  1162. }
  1163. }
  1164. }
  1165. /**
  1166. * Tests fix for BUG#15065 - Usage advisor complains about unreferenced
  1167. * columns, even though they've been referenced.
  1168. *
  1169. * @throws Exception
  1170. * if the test fails.
  1171. */
  1172. public void testBug15065() throws Exception {
  1173. if (isRunningOnJdk131()) {
  1174. return; // test not valid on JDK-1.3.1
  1175. }
  1176. createTable("testBug15065", "(field1 int)");
  1177. this.stmt.executeUpdate("INSERT INTO testBug15065 VALUES (1)");
  1178. Connection advisorConn = null;
  1179. Statement advisorStmt = null;
  1180. try {
  1181. Properties props = new Properties();
  1182. props.setProperty("useUsageAdvisor", "true");
  1183. props.setProperty("logger", "com.mysql.jdbc.log.StandardLogger");
  1184. advisorConn = getConnectionWithProps(props);
  1185. advisorStmt = advisorConn.createStatement();
  1186. Method[] getMethods = ResultSet.class.getMethods();
  1187. PrintStream oldErr = System.err;
  1188. try {
  1189. ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  1190. System.setErr(new PrintStream(bOut));
  1191. HashMap methodsToSkipMap = new HashMap();
  1192. // Needs an actual URL
  1193. methodsToSkipMap.put("getURL", null);
  1194. // Java6 JDBC4.0 methods we don't implement
  1195. methodsToSkipMap.put("getNCharacterStream", null);
  1196. methodsToSkipMap.put("getNClob", null);
  1197. methodsToSkipMap.put("getNString", null);
  1198. methodsToSkipMap.put("getRowId", null);
  1199. methodsToSkipMap.put("getSQLXML", null);
  1200. for (int j = 0; j < 2; j++) {
  1201. for (int i = 0; i < getMethods.length; i++) {
  1202. String methodName = getMethods[i].getName();
  1203. if (methodName.startsWith("get")
  1204. && !methodsToSkipMap.containsKey(methodName)) {
  1205. Class[] parameterTypes = getMethods[i]
  1206. .getParameterTypes();
  1207. if (parameterTypes.length == 1
  1208. && parameterTypes[0] == Integer.TYPE) {
  1209. if (j == 0) {
  1210. this.rs = advisorStmt
  1211. .executeQuery("SELECT COUNT(*) FROM testBug15065");
  1212. } else {
  1213. this.rs = advisorConn
  1214. .prepareStatement(
  1215. "SELECT COUNT(*) FROM testBug15065")
  1216. .executeQuery();
  1217. }
  1218. this.rs.next();
  1219. try {
  1220. getMethods[i].invoke(this.rs,
  1221. new Object[] { new Integer(1) });
  1222. } catch (InvocationTargetException invokeEx) {
  1223. // we don't care about bad values, just that
  1224. // the
  1225. // column gets "touched"
  1226. if (!invokeEx
  1227. .getCause()
  1228. .getClass()
  1229. .isAssignableFrom(
  1230. java.sql.SQLException.class)
  1231. && !invokeEx
  1232. .getCause()
  1233. .getClass()
  1234. .getName()
  1235. .equals(
  1236. "com.mysql.jdbc.NotImplemented")
  1237. && !invokeEx
  1238. .getCause()
  1239. .getClass()
  1240. .getName()
  1241. .equals(
  1242. "java.sql.SQLFeatureNotSupportedException")) {
  1243. throw invokeEx;
  1244. }
  1245. }
  1246. this.rs.close();
  1247. this.rs = null;
  1248. }
  1249. }
  1250. }
  1251. }
  1252. String logOut = bOut.toString("ISO8859-1");
  1253. if (logOut.indexOf(".Level") != -1) {
  1254. return; // we ignore for warnings
  1255. }
  1256. assertTrue("Usage advisor complained about columns:\n\n"
  1257. + logOut, logOut.indexOf("columns") == -1);
  1258. } finally {
  1259. System.setErr(oldErr);
  1260. }
  1261. } finally {
  1262. if (advisorConn != null) {
  1263. advisorConn.close();
  1264. }
  1265. }
  1266. }
  1267. /**
  1268. * Tests fix for BUG#15544, no "dos" character set in MySQL > 4.1.0
  1269. *
  1270. * @throws Exception
  1271. * if the test fails
  1272. */
  1273. public void testBug15544() throws Exception {
  1274. Properties props = new Properties();
  1275. props.setProperty("characterEncoding", "Cp437");
  1276. Connection dosConn = null;
  1277. try {
  1278. dosConn = getConnectionWithProps(props);
  1279. } finally {
  1280. if (dosConn != null) {
  1281. dosConn.close();
  1282. }
  1283. }
  1284. }
  1285. public void testCSC5765() throws Exception {
  1286. if (isRunningOnJdk131()) {
  1287. return; // test not valid on JDK-1.3.1
  1288. }
  1289. Properties props = new Properties();
  1290. props.setProperty("useUnicode", "true");
  1291. props.setProperty("characterEncoding", "utf8");
  1292. props.setProperty("characterSetResults", "utf8");
  1293. props.setProperty("connectionCollation", "utf8_bin");
  1294. Connection utf8Conn = null;
  1295. try {
  1296. utf8Conn = getConnectionWithProps(props);
  1297. this.rs = utf8Conn.createStatement().executeQuery(
  1298. "SHOW VARIABLES LIKE 'character_%'");
  1299. while (this.rs.next()) {
  1300. System.out.println(this.rs.getString(1) + " = "
  1301. + this.rs.getString(2));
  1302. }
  1303. this.rs = utf8Conn.createStatement().executeQuery(
  1304. "SHOW VARIABLES LIKE 'collation_%'");
  1305. while (this.rs.next()) {
  1306. System.out.println(this.rs.getString(1) + " = "
  1307. + this.rs.getString(2));
  1308. }
  1309. } finally {
  1310. if (utf8Conn != null) {
  1311. utf8Conn.close();
  1312. }
  1313. }
  1314. }
  1315. /**
  1316. * Tests fix for BUG#15570 - ReplicationConnection incorrectly copies state,
  1317. * doesn't transfer connection context correctly when transitioning between
  1318. * the same read-only states.
  1319. *
  1320. * (note, this test will fail if the test user doesn't have permission to
  1321. * "USE 'mysql'".
  1322. *
  1323. * @throws Exception
  1324. * if the test fails.
  1325. */
  1326. public void testBug15570() throws Exception {
  1327. Connection replConn = null;
  1328. try {
  1329. replConn = getMasterSlaveReplicationConnection();
  1330. int masterConnectionId = Integer
  1331. .parseInt(getSingleIndexedValueWithQuery(replConn, 1,
  1332. "SELECT CONNECTION_ID()").toString());
  1333. replConn.setReadOnly(false);
  1334. assertEquals(masterConnectionId, Integer
  1335. .parseInt(getSingleIndexedValueWithQuery(replConn, 1,
  1336. "SELECT CONNECTION_ID()").toString()));
  1337. String currentCatalog = replConn.getCatalog();
  1338. replConn.setCatalog(currentCatalog);
  1339. assertEquals(currentCatalog, replConn.getCatalog());
  1340. replConn.setReadOnly(true);
  1341. int slaveConnectionId = Integer
  1342. .parseInt(getSingleIndexedValueWithQuery(replConn, 1,
  1343. "SELECT CONNECTION_ID()").toString());
  1344. // The following test is okay for now, as the chance
  1345. // of MySQL wrapping the connection id counter during our
  1346. // testsuite is very small.
  1347. assertTrue("Slave id " + slaveConnectionId
  1348. + " is not newer than master id " + masterConnectionId,
  1349. slaveConnectionId > masterConnectionId);
  1350. assertEquals(currentCatalog, replConn.getCatalog());
  1351. String newCatalog = "mysql";
  1352. replConn.setCatalog(newCatalog);
  1353. assertEquals(newCatalog, replConn.getCatalog());
  1354. replConn.setReadOnly(true);
  1355. assertEquals(newCatalog, replConn.getCatalog());
  1356. replConn.setReadOnly(false);
  1357. assertEquals(masterConnectionId, Integer
  1358. .parseInt(getSingleIndexedValueWithQuery(replConn, 1,
  1359. "SELECT CONNECTION_ID()").toString()));
  1360. } finally {
  1361. if (replConn != null) {
  1362. replConn.close();
  1363. }
  1364. }
  1365. }
  1366. /**
  1367. * Tests bug where downed slave caused round robin load balance not to
  1368. * cycle back to first host in the list.
  1369. *
  1370. * @throws Exception
  1371. * if the test fails...Note, test is timing-dependent, but
  1372. * should work in most cases.
  1373. */
  1374. public void testBug23281() throws Exception {
  1375. Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
  1376. props.setProperty("autoReconnect", "false");
  1377. props.setProperty("roundRobinLoadBalance", "true");
  1378. props.setProperty("failoverReadOnly", "false");
  1379. if (!isRunningOnJdk131()) {
  1380. props.setProperty("connectTimeout", "5000");
  1381. }
  1382. // Re-build the connection information
  1383. int firstIndexOfHost = BaseTestCase.dbUrl.indexOf("//") + 2;
  1384. int lastIndexOfHost = BaseTestCase.dbUrl.indexOf("/", firstIndexOfHost);
  1385. String hostPortPair = BaseTestCase.dbUrl.substring(firstIndexOfHost,
  1386. lastIndexOfHost);
  1387. StringTokenizer st = new StringTokenizer(hostPortPair, ":");
  1388. String host = null;
  1389. String port = null;
  1390. if (st.hasMoreTokens()) {
  1391. String possibleHostOrPort = st.nextToken();
  1392. if (Character.isDigit(possibleHostOrPort.charAt(0)) &&
  1393. (possibleHostOrPort.indexOf(".") == -1 /* IPV4 */) &&
  1394. (possibleHostOrPort.indexOf("::") == -1 /* IPV6 */)) {
  1395. port = possibleHostOrPort;
  1396. host = "localhost";
  1397. } else {
  1398. host = possibleHostOrPort;
  1399. }
  1400. }
  1401. if (st.hasMoreTokens()) {
  1402. port = st.nextToken();
  1403. }
  1404. if (host == null) {
  1405. host = "";
  1406. }
  1407. if (port == null) {
  1408. port = "3306";
  1409. }
  1410. StringBuffer newHostBuf = new StringBuffer();
  1411. newHostBuf.append(host);
  1412. if (port != null) {
  1413. newHostBuf.append(":");
  1414. newHostBuf.append(port);
  1415. }
  1416. newHostBuf.append(",");
  1417. //newHostBuf.append(host);
  1418. newHostBuf.append("192.0.2.1"); // non-exsitent machine from RFC3330 test network
  1419. newHostBuf.append(":65532"); // make sure the slave fails
  1420. props.remove("PORT");
  1421. props.remove("HOST");
  1422. Connection failoverConnection = null;
  1423. try {
  1424. failoverConnection = getConnectionWithProps("jdbc:mysql://"
  1425. + newHostBuf.toString() + "/", props);
  1426. String originalConnectionId = getSingleIndexedValueWithQuery(
  1427. failoverConnection, 1, "SELECT CONNECTION_ID()").toString();
  1428. System.out.println(originalConnectionId);
  1429. Connection nextConnection = getConnectionWithProps("jdbc:mysql://"
  1430. + newHostBuf.toString() + "/", props);
  1431. String nextId = getSingleIndexedValueWithQuery(
  1432. nextConnection, 1, "SELECT CONNECTION_ID()").toString();
  1433. System.out.println(nextId);
  1434. } finally {
  1435. if (failoverConnection != null) {
  1436. failoverConnection.close();
  1437. }
  1438. }
  1439. }
  1440. /**
  1441. * Tests to insure proper behavior for BUG#24706.
  1442. *
  1443. * @throws Exception if the test fails.
  1444. */
  1445. public void testBug24706() throws Exception {
  1446. if (!versionMeetsMinimum(6, 0)) {
  1447. return; // server status isn't there to support this feature
  1448. }
  1449. Properties props = new Properties();
  1450. props.setProperty("elideSetAutoCommits", "true");
  1451. props.setProperty("logger", "StandardLogger");
  1452. props.setProperty("profileSQL", "true");
  1453. Connection c = null;
  1454. StringBuffer logBuf = new StringBuffer();
  1455. StandardLogger.bufferedLog = logBuf;
  1456. try {
  1457. c = getConnectionWithProps(props);
  1458. c.setAutoCommit(true);
  1459. c.createStatement().execute("SELECT 1");
  1460. c.setAutoCommit(true);
  1461. c.setAutoCommit(false);
  1462. c.createS

Large files files are truncated, but you can click here to view the full file