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

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

http://cubbers-eqemu-utils.googlecode.com/
Java | 2317 lines | 1484 code | 423 blank | 410 comment | 147 complexity | 389c787fb48d8438c1c1a908618962de 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. All rights reserved. Use is subject to license terms.
  4. The MySQL Connector/J is licensed under the terms of the GPL,
  5. like most MySQL Connectors. There are special exceptions to the
  6. terms and conditions of the GPL as it is applied to this software,
  7. see the FLOSS License Exception available on mysql.com.
  8. This program is free software; you can redistribute it and/or
  9. modify it under the terms of the GNU General Public License as
  10. published by the Free Software Foundation; version 2 of the
  11. License.
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  19. 02110-1301 USA
  20. */
  21. package testsuite.regression;
  22. import java.io.ByteArrayInputStream;
  23. import java.io.ByteArrayOutputStream;
  24. import java.io.CharArrayReader;
  25. import java.io.File;
  26. import java.io.FileOutputStream;
  27. import java.io.FileWriter;
  28. import java.io.IOException;
  29. import java.io.InputStream;
  30. import java.io.PrintStream;
  31. import java.io.Reader;
  32. import java.io.StringReader;
  33. import java.io.UnsupportedEncodingException;
  34. import java.io.Writer;
  35. import java.math.BigDecimal;
  36. import java.math.BigInteger;
  37. import java.net.URL;
  38. import java.sql.Array;
  39. import java.sql.BatchUpdateException;
  40. import java.sql.Blob;
  41. import java.sql.CallableStatement;
  42. import java.sql.Clob;
  43. import java.sql.Connection;
  44. import java.sql.DataTruncation;
  45. import java.sql.Date;
  46. import java.sql.PreparedStatement;
  47. import java.sql.Ref;
  48. import java.sql.ResultSet;
  49. import java.sql.ResultSetMetaData;
  50. import java.sql.SQLException;
  51. import java.sql.SQLWarning;
  52. import java.sql.Statement;
  53. import java.sql.Time;
  54. import java.sql.Timestamp;
  55. import java.sql.Types;
  56. import java.text.SimpleDateFormat;
  57. import java.util.ArrayList;
  58. import java.util.Calendar;
  59. import java.util.List;
  60. import java.util.Locale;
  61. import java.util.Map;
  62. import java.util.Properties;
  63. import java.util.TimeZone;
  64. import testsuite.BaseTestCase;
  65. import testsuite.UnreliableSocketFactory;
  66. import com.mysql.jdbc.CachedResultSetMetaData;
  67. import com.mysql.jdbc.Field;
  68. import com.mysql.jdbc.NonRegisteringDriver;
  69. import com.mysql.jdbc.ParameterBindings;
  70. import com.mysql.jdbc.ResultSetInternalMethods;
  71. import com.mysql.jdbc.SQLError;
  72. import com.mysql.jdbc.ServerPreparedStatement;
  73. import com.mysql.jdbc.StatementImpl;
  74. import com.mysql.jdbc.StatementInterceptor;
  75. import com.mysql.jdbc.StatementInterceptorV2;
  76. import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;
  77. import com.mysql.jdbc.exceptions.MySQLTimeoutException;
  78. /**
  79. * Regression tests for the Statement class
  80. *
  81. * @author Mark Matthews
  82. */
  83. public class StatementRegressionTest extends BaseTestCase {
  84. class PrepareThread extends Thread {
  85. Connection c;
  86. PrepareThread(Connection cn) {
  87. this.c = cn;
  88. }
  89. public void run() {
  90. for (int i = 0; i < 20; i++) // force this to end eventually
  91. {
  92. try {
  93. this.c.prepareStatement("SELECT 1");
  94. StatementRegressionTest.this.testServerPrepStmtDeadlockCounter++;
  95. Thread.sleep(400);
  96. } catch (SQLException sqlEx) {
  97. throw new RuntimeException(sqlEx);
  98. } catch (InterruptedException e) {
  99. e.printStackTrace();
  100. }
  101. }
  102. }
  103. }
  104. static int count = 0;
  105. static int nextID = 1; // The next ID we expected to generate
  106. /*
  107. * Each row in this table is to be converted into a single REPLACE
  108. * statement. If the value is zero, a new record is to be created using then
  109. * autoincrement feature. If the value is non-zero, the existing row of that
  110. * value is to be replace with, obviously, the same key. I expect one
  111. * Generated Key for each zero value - but I would accept one key for each
  112. * value, with non-zero values coming back as themselves.
  113. */
  114. static final int[][] tests = { { 0 }, // generate 1
  115. { 1, 0, 0 }, // update 1, generate 2, 3
  116. { 2, 0, 0, }, // update 2, generate 3, 4
  117. };
  118. /**
  119. * Runs all test cases in this test suite
  120. *
  121. * @param args
  122. */
  123. public static void main(String[] args) {
  124. junit.textui.TestRunner.run(StatementRegressionTest.class);
  125. }
  126. private int testServerPrepStmtDeadlockCounter = 0;
  127. /**
  128. * Constructor for StatementRegressionTest.
  129. *
  130. * @param name
  131. * the name of the test to run
  132. */
  133. public StatementRegressionTest(String name) {
  134. super(name);
  135. }
  136. private void addBatchItems(Statement statement, PreparedStatement pStmt,
  137. String tableName, int i) throws SQLException {
  138. pStmt.setString(1, "ps_batch_" + i);
  139. pStmt.setString(2, "ps_batch_" + i);
  140. pStmt.addBatch();
  141. statement.addBatch("INSERT INTO " + tableName
  142. + " (strdata1, strdata2) VALUES " + "(\"s_batch_" + i
  143. + "\",\"s_batch_" + i + "\")");
  144. }
  145. private void createGGKTables() throws Exception {
  146. // Delete and recreate table
  147. dropGGKTables();
  148. this.stmt.executeUpdate("CREATE TABLE testggk ("
  149. + "id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,"
  150. + "val INT NOT NULL" + ")");
  151. }
  152. private void doGGKTestPreparedStatement(int[] values, boolean useUpdate)
  153. throws Exception {
  154. // Generate the the multiple replace command
  155. StringBuffer cmd = new StringBuffer("REPLACE INTO testggk VALUES ");
  156. int newKeys = 0;
  157. for (int i = 0; i < values.length; i++) {
  158. cmd.append("(");
  159. if (values[i] == 0) {
  160. cmd.append("NULL");
  161. newKeys += 1;
  162. } else {
  163. cmd.append(values[i]);
  164. }
  165. cmd.append(", ");
  166. cmd.append(count++);
  167. cmd.append("), ");
  168. }
  169. cmd.setLength(cmd.length() - 2); // trim the final ", "
  170. // execute and print it
  171. System.out.println(cmd.toString());
  172. PreparedStatement pStmt = this.conn.prepareStatement(cmd.toString(),
  173. Statement.RETURN_GENERATED_KEYS);
  174. if (useUpdate) {
  175. pStmt.executeUpdate();
  176. } else {
  177. pStmt.execute();
  178. }
  179. // print out what actually happened
  180. System.out.println("Expect " + newKeys
  181. + " generated keys, starting from " + nextID);
  182. this.rs = pStmt.getGeneratedKeys();
  183. StringBuffer res = new StringBuffer("Got keys");
  184. int[] generatedKeys = new int[newKeys];
  185. int i = 0;
  186. while (this.rs.next()) {
  187. if (i < generatedKeys.length) {
  188. generatedKeys[i] = this.rs.getInt(1);
  189. }
  190. i++;
  191. res.append(" " + this.rs.getInt(1));
  192. }
  193. int numberOfGeneratedKeys = i;
  194. assertTrue(
  195. "Didn't retrieve expected number of generated keys, expected "
  196. + newKeys + ", found " + numberOfGeneratedKeys,
  197. numberOfGeneratedKeys == newKeys);
  198. assertTrue("Keys didn't start with correct sequence: ",
  199. generatedKeys[0] == nextID);
  200. System.out.println(res.toString());
  201. // Read and print the new state of the table
  202. this.rs = this.stmt.executeQuery("SELECT id, val FROM testggk");
  203. System.out.println("New table contents ");
  204. while (this.rs.next())
  205. System.out.println("Id " + this.rs.getString(1) + " val "
  206. + this.rs.getString(2));
  207. // Tidy up
  208. System.out.println("");
  209. nextID += newKeys;
  210. }
  211. private void doGGKTestStatement(int[] values, boolean useUpdate)
  212. throws Exception {
  213. // Generate the the multiple replace command
  214. StringBuffer cmd = new StringBuffer("REPLACE INTO testggk VALUES ");
  215. int newKeys = 0;
  216. for (int i = 0; i < values.length; i++) {
  217. cmd.append("(");
  218. if (values[i] == 0) {
  219. cmd.append("NULL");
  220. newKeys += 1;
  221. } else {
  222. cmd.append(values[i]);
  223. }
  224. cmd.append(", ");
  225. cmd.append(count++);
  226. cmd.append("), ");
  227. }
  228. cmd.setLength(cmd.length() - 2); // trim the final ", "
  229. // execute and print it
  230. System.out.println(cmd.toString());
  231. if (useUpdate) {
  232. this.stmt.executeUpdate(cmd.toString(),
  233. Statement.RETURN_GENERATED_KEYS);
  234. } else {
  235. this.stmt.execute(cmd.toString(), Statement.RETURN_GENERATED_KEYS);
  236. }
  237. // print out what actually happened
  238. System.out.println("Expect " + newKeys
  239. + " generated keys, starting from " + nextID);
  240. this.rs = this.stmt.getGeneratedKeys();
  241. StringBuffer res = new StringBuffer("Got keys");
  242. int[] generatedKeys = new int[newKeys];
  243. int i = 0;
  244. while (this.rs.next()) {
  245. if (i < generatedKeys.length) {
  246. generatedKeys[i] = this.rs.getInt(1);
  247. }
  248. i++;
  249. res.append(" " + this.rs.getInt(1));
  250. }
  251. int numberOfGeneratedKeys = i;
  252. assertTrue(
  253. "Didn't retrieve expected number of generated keys, expected "
  254. + newKeys + ", found " + numberOfGeneratedKeys,
  255. numberOfGeneratedKeys == newKeys);
  256. assertTrue("Keys didn't start with correct sequence: ",
  257. generatedKeys[0] == nextID);
  258. System.out.println(res.toString());
  259. // Read and print the new state of the table
  260. this.rs = this.stmt.executeQuery("SELECT id, val FROM testggk");
  261. System.out.println("New table contents ");
  262. while (this.rs.next())
  263. System.out.println("Id " + this.rs.getString(1) + " val "
  264. + this.rs.getString(2));
  265. // Tidy up
  266. System.out.println("");
  267. nextID += newKeys;
  268. }
  269. private void dropGGKTables() throws Exception {
  270. this.stmt.executeUpdate("DROP TABLE IF EXISTS testggk");
  271. }
  272. /**
  273. * @param pStmt
  274. * @param catId
  275. * @throws SQLException
  276. */
  277. private void execQueryBug5191(PreparedStatement pStmt, int catId)
  278. throws SQLException {
  279. pStmt.setInt(1, catId);
  280. this.rs = pStmt.executeQuery();
  281. assertTrue(this.rs.next());
  282. assertTrue(this.rs.next());
  283. // assertTrue(rs.next());
  284. assertFalse(this.rs.next());
  285. }
  286. private String getByteArrayString(byte[] ba) {
  287. StringBuffer buffer = new StringBuffer();
  288. if (ba != null) {
  289. for (int i = 0; i < ba.length; i++) {
  290. buffer.append("0x" + Integer.toHexString(ba[i] & 0xff) + " ");
  291. }
  292. } else {
  293. buffer.append("null");
  294. }
  295. return buffer.toString();
  296. }
  297. /**
  298. * @param continueBatchOnError
  299. * @throws SQLException
  300. */
  301. private void innerBug6823(boolean continueBatchOnError) throws SQLException {
  302. Properties continueBatchOnErrorProps = new Properties();
  303. continueBatchOnErrorProps.setProperty("continueBatchOnError", String
  304. .valueOf(continueBatchOnError));
  305. this.conn = getConnectionWithProps(continueBatchOnErrorProps);
  306. Statement statement = this.conn.createStatement();
  307. String tableName = "testBug6823";
  308. createTable(tableName, "(id int not null primary key auto_increment,"
  309. + " strdata1 varchar(255) not null, strdata2 varchar(255),"
  310. + " UNIQUE INDEX (strdata1(100)))");
  311. PreparedStatement pStmt = this.conn.prepareStatement("INSERT INTO "
  312. + tableName + " (strdata1, strdata2) VALUES (?,?)");
  313. int c = 0;
  314. addBatchItems(statement, pStmt, tableName, ++c);
  315. addBatchItems(statement, pStmt, tableName, ++c);
  316. addBatchItems(statement, pStmt, tableName, ++c);
  317. addBatchItems(statement, pStmt, tableName, c); // duplicate entry
  318. addBatchItems(statement, pStmt, tableName, ++c);
  319. addBatchItems(statement, pStmt, tableName, ++c);
  320. int expectedUpdateCounts = continueBatchOnError ? 6 : 3;
  321. BatchUpdateException e1 = null;
  322. BatchUpdateException e2 = null;
  323. int[] updateCountsPstmt = null;
  324. try {
  325. updateCountsPstmt = pStmt.executeBatch();
  326. } catch (BatchUpdateException e) {
  327. e1 = e;
  328. updateCountsPstmt = e1.getUpdateCounts();
  329. }
  330. int[] updateCountsStmt = null;
  331. try {
  332. updateCountsStmt = statement.executeBatch();
  333. } catch (BatchUpdateException e) {
  334. e2 = e;
  335. updateCountsStmt = e1.getUpdateCounts();
  336. }
  337. assertNotNull(e1);
  338. assertNotNull(e2);
  339. assertEquals(expectedUpdateCounts, updateCountsPstmt.length);
  340. assertEquals(expectedUpdateCounts, updateCountsStmt.length);
  341. if (continueBatchOnError) {
  342. assertTrue(updateCountsPstmt[3] == Statement.EXECUTE_FAILED);
  343. assertTrue(updateCountsStmt[3] == Statement.EXECUTE_FAILED);
  344. }
  345. int psRows = 0;
  346. this.rs = this.stmt.executeQuery("SELECT * from " + tableName
  347. + " WHERE strdata1 like \"ps_%\"");
  348. while (this.rs.next()) {
  349. psRows++;
  350. }
  351. assertTrue(psRows > 0);
  352. int sRows = 0;
  353. this.rs = this.stmt.executeQuery("SELECT * from " + tableName
  354. + " WHERE strdata1 like \"s_%\"");
  355. while (this.rs.next()) {
  356. sRows++;
  357. }
  358. assertTrue(sRows > 0);
  359. assertTrue(psRows + "!=" + sRows, psRows == sRows);
  360. }
  361. /**
  362. * Tests fix for BUG#10155, double quotes not recognized when parsing
  363. * client-side prepared statements.
  364. *
  365. * @throws Exception
  366. * if the test fails.
  367. */
  368. public void testBug10155() throws Exception {
  369. this.conn.prepareStatement(
  370. "SELECT \"Test question mark? Test single quote'\"")
  371. .executeQuery().close();
  372. }
  373. /**
  374. * Tests fix for BUG#10630, Statement.getWarnings() fails with NPE if
  375. * statement has been closed.
  376. */
  377. public void testBug10630() throws Exception {
  378. Connection conn2 = null;
  379. Statement stmt2 = null;
  380. try {
  381. conn2 = getConnectionWithProps((Properties)null);
  382. stmt2 = conn2.createStatement();
  383. conn2.close();
  384. stmt2.getWarnings();
  385. fail("Should've caught an exception here");
  386. } catch (SQLException sqlEx) {
  387. assertEquals("08003", sqlEx.getSQLState());
  388. } finally {
  389. if (stmt2 != null) {
  390. stmt2.close();
  391. }
  392. if (conn2 != null) {
  393. conn2.close();
  394. }
  395. }
  396. }
  397. /**
  398. * Tests fix for BUG#11115, Varbinary data corrupted when using server-side
  399. * prepared statements.
  400. */
  401. public void testBug11115() throws Exception {
  402. String tableName = "testBug11115";
  403. if (versionMeetsMinimum(4, 1, 0)) {
  404. createTable(tableName,
  405. "(pwd VARBINARY(30)) DEFAULT CHARACTER SET utf8", "InnoDB");
  406. byte[] bytesToTest = new byte[] { 17, 120, -1, -73, -5 };
  407. PreparedStatement insStmt = this.conn
  408. .prepareStatement("INSERT INTO " + tableName
  409. + " (pwd) VALUES (?)");
  410. insStmt.setBytes(1, bytesToTest);
  411. insStmt.executeUpdate();
  412. this.rs = this.stmt.executeQuery("SELECT pwd FROM " + tableName);
  413. this.rs.next();
  414. byte[] fromDatabase = this.rs.getBytes(1);
  415. assertEquals(bytesToTest.length, fromDatabase.length);
  416. for (int i = 0; i < bytesToTest.length; i++) {
  417. assertEquals(bytesToTest[i], fromDatabase[i]);
  418. }
  419. this.rs = this.conn
  420. .prepareStatement("SELECT pwd FROM " + tableName)
  421. .executeQuery();
  422. this.rs.next();
  423. fromDatabase = this.rs.getBytes(1);
  424. assertEquals(bytesToTest.length, fromDatabase.length);
  425. for (int i = 0; i < bytesToTest.length; i++) {
  426. assertEquals(bytesToTest[i], fromDatabase[i]);
  427. }
  428. }
  429. }
  430. public void testBug11540() throws Exception {
  431. Locale originalLocale = Locale.getDefault();
  432. Connection thaiConn = null;
  433. Statement thaiStmt = null;
  434. PreparedStatement thaiPrepStmt = null;
  435. try {
  436. createTable("testBug11540", "(field1 DATE, field2 TIMESTAMP)");
  437. this.stmt
  438. .executeUpdate("INSERT INTO testBug11540 VALUES (NOW(), NOW())");
  439. Locale.setDefault(new Locale("th", "TH"));
  440. Properties props = new Properties();
  441. props.setProperty("jdbcCompliantTruncation", "false");
  442. thaiConn = getConnectionWithProps(props);
  443. thaiStmt = thaiConn.createStatement();
  444. this.rs = thaiStmt
  445. .executeQuery("SELECT field1, field2 FROM testBug11540");
  446. this.rs.next();
  447. Date origDate = this.rs.getDate(1);
  448. Timestamp origTimestamp = this.rs.getTimestamp(1);
  449. this.rs.close();
  450. thaiStmt.executeUpdate("TRUNCATE TABLE testBug11540");
  451. thaiPrepStmt = ((com.mysql.jdbc.Connection) thaiConn)
  452. .clientPrepareStatement("INSERT INTO testBug11540 VALUES (?,?)");
  453. thaiPrepStmt.setDate(1, origDate);
  454. thaiPrepStmt.setTimestamp(2, origTimestamp);
  455. thaiPrepStmt.executeUpdate();
  456. this.rs = thaiStmt
  457. .executeQuery("SELECT field1, field2 FROM testBug11540");
  458. this.rs.next();
  459. Date testDate = this.rs.getDate(1);
  460. Timestamp testTimestamp = this.rs.getTimestamp(1);
  461. this.rs.close();
  462. assertEquals(origDate, testDate);
  463. assertEquals(origTimestamp, testTimestamp);
  464. } finally {
  465. Locale.setDefault(originalLocale);
  466. }
  467. }
  468. /**
  469. * Tests fix for BUG#11663, autoGenerateTestcaseScript uses bogus parameter
  470. * names for server-side prepared statements.
  471. *
  472. * @throws Exception
  473. * if the test fails.
  474. */
  475. public void testBug11663() throws Exception {
  476. if (versionMeetsMinimum(4, 1, 0)
  477. && ((com.mysql.jdbc.Connection) this.conn)
  478. .getUseServerPreparedStmts()) {
  479. Connection testcaseGenCon = null;
  480. PrintStream oldErr = System.err;
  481. try {
  482. createTable("testBug11663", "(field1 int)");
  483. Properties props = new Properties();
  484. props.setProperty("autoGenerateTestcaseScript", "true");
  485. testcaseGenCon = getConnectionWithProps(props);
  486. ByteArrayOutputStream testStream = new ByteArrayOutputStream();
  487. PrintStream testErr = new PrintStream(testStream);
  488. System.setErr(testErr);
  489. this.pstmt = testcaseGenCon
  490. .prepareStatement("SELECT field1 FROM testBug11663 WHERE field1=?");
  491. this.pstmt.setInt(1, 1);
  492. this.pstmt.execute();
  493. System.setErr(oldErr);
  494. String testString = new String(testStream.toByteArray());
  495. int setIndex = testString.indexOf("SET @debug_stmt_param");
  496. int equalsIndex = testString.indexOf("=", setIndex);
  497. String paramName = testString.substring(setIndex + 4,
  498. equalsIndex);
  499. int usingIndex = testString.indexOf("USING " + paramName,
  500. equalsIndex);
  501. assertTrue(usingIndex != -1);
  502. } finally {
  503. System.setErr(oldErr);
  504. if (this.pstmt != null) {
  505. this.pstmt.close();
  506. this.pstmt = null;
  507. }
  508. if (testcaseGenCon != null) {
  509. testcaseGenCon.close();
  510. }
  511. }
  512. }
  513. }
  514. /**
  515. * Tests fix for BUG#11798 - Pstmt.setObject(...., Types.BOOLEAN) throws
  516. * exception.
  517. *
  518. * @throws Exception
  519. * if the test fails.
  520. */
  521. public void testBug11798() throws Exception {
  522. if (isRunningOnJdk131()) {
  523. return; // test not valid on JDK-1.3.1
  524. }
  525. try {
  526. this.pstmt = this.conn.prepareStatement("SELECT ?");
  527. this.pstmt.setObject(1, Boolean.TRUE, Types.BOOLEAN);
  528. this.pstmt.setObject(1, new BigDecimal("1"), Types.BOOLEAN);
  529. this.pstmt.setObject(1, "true", Types.BOOLEAN);
  530. } finally {
  531. if (this.pstmt != null) {
  532. this.pstmt.close();
  533. this.pstmt = null;
  534. }
  535. }
  536. }
  537. /**
  538. * Tests fix for BUG#13255 - Reconnect during middle of executeBatch()
  539. * should not happen.
  540. *
  541. * @throws Exception
  542. * if the test fails.
  543. */
  544. public void testBug13255() throws Exception {
  545. createTable("testBug13255", "(field_1 int)");
  546. Properties props = new Properties();
  547. props.setProperty("autoReconnect", "true");
  548. Connection reconnectConn = null;
  549. Statement reconnectStmt = null;
  550. PreparedStatement reconnectPStmt = null;
  551. try {
  552. reconnectConn = getConnectionWithProps(props);
  553. reconnectStmt = reconnectConn.createStatement();
  554. String connectionId = getSingleIndexedValueWithQuery(reconnectConn,
  555. 1, "SELECT CONNECTION_ID()").toString();
  556. reconnectStmt.addBatch("INSERT INTO testBug13255 VALUES (1)");
  557. reconnectStmt.addBatch("INSERT INTO testBug13255 VALUES (2)");
  558. reconnectStmt.addBatch("KILL " + connectionId);
  559. for (int i = 0; i < 100; i++) {
  560. reconnectStmt.addBatch("INSERT INTO testBug13255 VALUES (" + i
  561. + ")");
  562. }
  563. try {
  564. reconnectStmt.executeBatch();
  565. } catch (SQLException sqlEx) {
  566. // We expect this...we killed the connection
  567. }
  568. assertEquals(2, getRowCount("testBug13255"));
  569. this.stmt.executeUpdate("TRUNCATE TABLE testBug13255");
  570. reconnectConn.close();
  571. reconnectConn = getConnectionWithProps(props);
  572. connectionId = getSingleIndexedValueWithQuery(reconnectConn, 1,
  573. "SELECT CONNECTION_ID()").toString();
  574. reconnectPStmt = reconnectConn
  575. .prepareStatement("INSERT INTO testBug13255 VALUES (?)");
  576. reconnectPStmt.setInt(1, 1);
  577. reconnectPStmt.addBatch();
  578. reconnectPStmt.setInt(1, 2);
  579. reconnectPStmt.addBatch();
  580. reconnectPStmt.addBatch("KILL " + connectionId);
  581. for (int i = 3; i < 100; i++) {
  582. reconnectPStmt.setInt(1, i);
  583. reconnectPStmt.addBatch();
  584. }
  585. try {
  586. reconnectPStmt.executeBatch();
  587. } catch (SQLException sqlEx) {
  588. // We expect this...we killed the connection
  589. }
  590. assertEquals(2, getRowCount("testBug13255"));
  591. } finally {
  592. if (reconnectStmt != null) {
  593. reconnectStmt.close();
  594. }
  595. if (reconnectConn != null) {
  596. reconnectConn.close();
  597. }
  598. }
  599. }
  600. /**
  601. * Tests fix for BUG#15024 - Driver incorrectly closes streams passed as
  602. * arguments to PreparedStatements.
  603. *
  604. * @throws Exception
  605. * if the test fails.
  606. */
  607. public void testBug15024() throws Exception {
  608. createTable("testBug15024", "(field1 BLOB)");
  609. try {
  610. this.pstmt = this.conn
  611. .prepareStatement("INSERT INTO testBug15024 VALUES (?)");
  612. testStreamsForBug15024(false, false);
  613. Properties props = new Properties();
  614. props.setProperty("useConfigs", "3-0-Compat");
  615. Connection compatConn = null;
  616. try {
  617. compatConn = getConnectionWithProps(props);
  618. this.pstmt = compatConn
  619. .prepareStatement("INSERT INTO testBug15024 VALUES (?)");
  620. testStreamsForBug15024(true, false);
  621. } finally {
  622. if (compatConn != null) {
  623. compatConn.close();
  624. }
  625. }
  626. } finally {
  627. if (this.pstmt != null) {
  628. PreparedStatement toClose = this.pstmt;
  629. this.pstmt = null;
  630. toClose.close();
  631. }
  632. }
  633. }
  634. /**
  635. * PreparedStatement should call EscapeProcessor.escapeSQL?
  636. *
  637. * @throws Exception
  638. * if the test fails
  639. */
  640. public void testBug15141() throws Exception {
  641. try {
  642. createTable("testBug15141", "(field1 VARCHAR(32))");
  643. this.stmt.executeUpdate("INSERT INTO testBug15141 VALUES ('abc')");
  644. this.pstmt = this.conn
  645. .prepareStatement("select {d '1997-05-24'} FROM testBug15141");
  646. this.rs = this.pstmt.executeQuery();
  647. assertTrue(this.rs.next());
  648. assertEquals("1997-05-24", this.rs.getString(1));
  649. this.rs.close();
  650. this.rs = null;
  651. this.pstmt.close();
  652. this.pstmt = null;
  653. this.pstmt = ((com.mysql.jdbc.Connection) this.conn)
  654. .clientPrepareStatement("select {d '1997-05-24'} FROM testBug15141");
  655. this.rs = this.pstmt.executeQuery();
  656. assertTrue(this.rs.next());
  657. assertEquals("1997-05-24", this.rs.getString(1));
  658. this.rs.close();
  659. this.rs = null;
  660. this.pstmt.close();
  661. this.pstmt = null;
  662. } finally {
  663. if (this.rs != null) {
  664. ResultSet toCloseRs = this.rs;
  665. this.rs = null;
  666. toCloseRs.close();
  667. }
  668. if (this.pstmt != null) {
  669. PreparedStatement toClosePstmt = this.pstmt;
  670. this.pstmt = null;
  671. toClosePstmt.close();
  672. }
  673. }
  674. }
  675. /**
  676. * Tests fix for BUG#18041 - Server-side prepared statements don't cause
  677. * truncation exceptions to be thrown.
  678. *
  679. * @throws Exception
  680. * if the test fails
  681. */
  682. public void testBug18041() throws Exception {
  683. if (versionMeetsMinimum(4, 1)) {
  684. createTable("testBug18041", "(`a` tinyint(4) NOT NULL,"
  685. + "`b` char(4) default NULL)");
  686. Properties props = new Properties();
  687. props.setProperty("jdbcCompliantTruncation", "true");
  688. props.setProperty("useServerPrepStmts", "true");
  689. Connection truncConn = null;
  690. PreparedStatement stm = null;
  691. try {
  692. truncConn = getConnectionWithProps(props);
  693. stm = truncConn
  694. .prepareStatement("insert into testBug18041 values (?,?)");
  695. stm.setInt(1, 1000);
  696. stm.setString(2, "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
  697. stm.executeUpdate();
  698. fail("Truncation exception should have been thrown");
  699. } catch (DataTruncation truncEx) {
  700. // we expect this
  701. } finally {
  702. if (this.stmt != null) {
  703. this.stmt.close();
  704. }
  705. if (truncConn != null) {
  706. truncConn.close();
  707. }
  708. }
  709. }
  710. }
  711. private void testStreamsForBug15024(boolean shouldBeClosedStream,
  712. boolean shouldBeClosedReader) throws SQLException {
  713. IsClosedInputStream bIn = new IsClosedInputStream(new byte[4]);
  714. IsClosedReader readerIn = new IsClosedReader("abcdef");
  715. this.pstmt.setBinaryStream(1, bIn, 4);
  716. this.pstmt.execute();
  717. assertEquals(shouldBeClosedStream, bIn.isClosed());
  718. this.pstmt.setCharacterStream(1, readerIn, 6);
  719. this.pstmt.execute();
  720. assertEquals(shouldBeClosedReader, readerIn.isClosed());
  721. this.pstmt.close();
  722. }
  723. class IsClosedReader extends StringReader {
  724. boolean isClosed = false;
  725. public IsClosedReader(String arg0) {
  726. super(arg0);
  727. }
  728. public void close() {
  729. super.close();
  730. this.isClosed = true;
  731. }
  732. public boolean isClosed() {
  733. return this.isClosed;
  734. }
  735. }
  736. class IsClosedInputStream extends ByteArrayInputStream {
  737. boolean isClosed = false;
  738. public IsClosedInputStream(byte[] arg0, int arg1, int arg2) {
  739. super(arg0, arg1, arg2);
  740. }
  741. public IsClosedInputStream(byte[] arg0) {
  742. super(arg0);
  743. }
  744. public void close() throws IOException {
  745. super.close();
  746. this.isClosed = true;
  747. }
  748. public boolean isClosed() {
  749. return this.isClosed;
  750. }
  751. }
  752. /**
  753. * Tests fix for BUG#1774 -- Truncated words after double quote
  754. *
  755. * @throws Exception
  756. * if the test fails.
  757. */
  758. public void testBug1774() throws Exception {
  759. try {
  760. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1774");
  761. this.stmt
  762. .executeUpdate("CREATE TABLE testBug1774 (field1 VARCHAR(255))");
  763. PreparedStatement pStmt = this.conn
  764. .prepareStatement("INSERT INTO testBug1774 VALUES (?)");
  765. String testString = "The word contains \" character";
  766. pStmt.setString(1, testString);
  767. pStmt.executeUpdate();
  768. this.rs = this.stmt.executeQuery("SELECT * FROM testBug1774");
  769. this.rs.next();
  770. assertEquals(this.rs.getString(1), testString);
  771. } finally {
  772. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1774");
  773. }
  774. }
  775. /**
  776. * Tests fix for BUG#1901 -- PreparedStatement.setObject(int, Object, int,
  777. * int) doesn't support CLOB or BLOB types.
  778. *
  779. * @throws Exception
  780. * if this test fails for any reason
  781. */
  782. public void testBug1901() throws Exception {
  783. try {
  784. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1901");
  785. this.stmt
  786. .executeUpdate("CREATE TABLE testBug1901 (field1 VARCHAR(255))");
  787. this.stmt.executeUpdate("INSERT INTO testBug1901 VALUES ('aaa')");
  788. this.rs = this.stmt.executeQuery("SELECT field1 FROM testBug1901");
  789. this.rs.next();
  790. Clob valueAsClob = this.rs.getClob(1);
  791. Blob valueAsBlob = this.rs.getBlob(1);
  792. PreparedStatement pStmt = this.conn
  793. .prepareStatement("INSERT INTO testBug1901 VALUES (?)");
  794. pStmt.setObject(1, valueAsClob, java.sql.Types.CLOB, 0);
  795. pStmt.executeUpdate();
  796. pStmt.setObject(1, valueAsBlob, java.sql.Types.BLOB, 0);
  797. pStmt.executeUpdate();
  798. } finally {
  799. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1901");
  800. }
  801. }
  802. /**
  803. * Test fix for BUG#1933 -- Driver property 'maxRows' has no effect.
  804. *
  805. * @throws Exception
  806. * if the test fails.
  807. */
  808. public void testBug1933() throws Exception {
  809. if (versionMeetsMinimum(4, 0)) {
  810. Connection maxRowsConn = null;
  811. PreparedStatement maxRowsPrepStmt = null;
  812. Statement maxRowsStmt = null;
  813. try {
  814. Properties props = new Properties();
  815. props.setProperty("maxRows", "1");
  816. maxRowsConn = getConnectionWithProps(props);
  817. maxRowsStmt = maxRowsConn.createStatement();
  818. assertTrue(maxRowsStmt.getMaxRows() == 1);
  819. this.rs = maxRowsStmt.executeQuery("SELECT 1 UNION SELECT 2");
  820. this.rs.next();
  821. maxRowsPrepStmt = maxRowsConn
  822. .prepareStatement("SELECT 1 UNION SELECT 2");
  823. assertTrue(maxRowsPrepStmt.getMaxRows() == 1);
  824. this.rs = maxRowsPrepStmt.executeQuery();
  825. this.rs.next();
  826. assertTrue(!this.rs.next());
  827. props.setProperty("useServerPrepStmts", "false");
  828. maxRowsConn = getConnectionWithProps(props);
  829. maxRowsPrepStmt = maxRowsConn
  830. .prepareStatement("SELECT 1 UNION SELECT 2");
  831. assertTrue(maxRowsPrepStmt.getMaxRows() == 1);
  832. this.rs = maxRowsPrepStmt.executeQuery();
  833. this.rs.next();
  834. assertTrue(!this.rs.next());
  835. } finally {
  836. maxRowsConn.close();
  837. }
  838. }
  839. }
  840. /**
  841. * Tests the fix for BUG#1934 -- prepareStatement dies silently when
  842. * encountering Statement.RETURN_GENERATED_KEY
  843. *
  844. * @throws Exception
  845. * if the test fails
  846. */
  847. public void testBug1934() throws Exception {
  848. if (isRunningOnJdk131()) {
  849. return; // test not valid on JDK-1.3.1
  850. }
  851. try {
  852. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1934");
  853. this.stmt.executeUpdate("CREATE TABLE testBug1934 (field1 INT)");
  854. System.out.println("Before prepareStatement()");
  855. this.pstmt = this.conn.prepareStatement(
  856. "INSERT INTO testBug1934 VALUES (?)",
  857. java.sql.Statement.RETURN_GENERATED_KEYS);
  858. assertTrue(this.pstmt != null);
  859. System.out.println("After prepareStatement() - " + this.pstmt);
  860. } finally {
  861. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1934");
  862. }
  863. }
  864. /**
  865. * Tests fix for BUG#1958 - Improper bounds checking on
  866. * PreparedStatement.setFoo().
  867. *
  868. * @throws Exception
  869. * if the test fails.
  870. */
  871. public void testBug1958() throws Exception {
  872. PreparedStatement pStmt = null;
  873. try {
  874. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1958");
  875. this.stmt.executeUpdate("CREATE TABLE testBug1958 (field1 int)");
  876. pStmt = this.conn
  877. .prepareStatement("SELECT * FROM testBug1958 WHERE field1 IN (?, ?, ?)");
  878. try {
  879. pStmt.setInt(4, 1);
  880. } catch (SQLException sqlEx) {
  881. assertTrue(SQLError.SQL_STATE_ILLEGAL_ARGUMENT.equals(sqlEx
  882. .getSQLState()));
  883. }
  884. } finally {
  885. if (pStmt != null) {
  886. pStmt.close();
  887. }
  888. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1958");
  889. }
  890. }
  891. /**
  892. * Tests the fix for BUG#2606, server-side prepared statements not returning
  893. * datatype YEAR correctly.
  894. *
  895. * @throws Exception
  896. * if the test fails.
  897. */
  898. public void testBug2606() throws Exception {
  899. try {
  900. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug2606");
  901. this.stmt
  902. .executeUpdate("CREATE TABLE testBug2606(year_field YEAR)");
  903. this.stmt.executeUpdate("INSERT INTO testBug2606 VALUES (2004)");
  904. PreparedStatement yrPstmt = this.conn
  905. .prepareStatement("SELECT year_field FROM testBug2606");
  906. this.rs = yrPstmt.executeQuery();
  907. assertTrue(this.rs.next());
  908. assertEquals(2004, this.rs.getInt(1));
  909. } finally {
  910. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug2606");
  911. }
  912. }
  913. /**
  914. * Tests the fix for BUG#2671, nulls encoded incorrectly in server-side
  915. * prepared statements.
  916. *
  917. * @throws Exception
  918. * if an error occurs.
  919. */
  920. public void testBug2671() throws Exception {
  921. if (versionMeetsMinimum(4, 1)) {
  922. createTable("test3", "("
  923. + " `field1` int(8) NOT NULL auto_increment,"
  924. + " `field2` int(8) unsigned zerofill default NULL,"
  925. + " `field3` varchar(30) binary NOT NULL default '',"
  926. + " `field4` varchar(100) default NULL,"
  927. + " `field5` datetime NULL default '0000-00-00 00:00:00',"
  928. + " PRIMARY KEY (`field1`),"
  929. + " UNIQUE KEY `unq_id` (`field2`),"
  930. + " UNIQUE KEY (`field3`),"
  931. + " UNIQUE KEY (`field2`)"
  932. + " ) CHARACTER SET utf8", "InnoDB");
  933. this.stmt
  934. .executeUpdate("insert into test3 (field1, field3, field4) values (1,'blewis','Bob Lewis')");
  935. String query = " " + "UPDATE "
  936. + " test3 "
  937. + "SET "
  938. + " field2=? " + " ,field3=? "
  939. + " ,field4=? " + " ,field5=? "
  940. + "WHERE "
  941. + " field1 = ? ";
  942. java.sql.Date mydate = null;
  943. this.pstmt = this.conn.prepareStatement(query);
  944. this.pstmt.setInt(1, 13);
  945. this.pstmt.setString(2, "abc");
  946. this.pstmt.setString(3, "def");
  947. this.pstmt.setDate(4, mydate);
  948. this.pstmt.setInt(5, 1);
  949. int retval = this.pstmt.executeUpdate();
  950. assertTrue(retval == 1);
  951. }
  952. }
  953. /**
  954. * Tests fix for BUG#3103 -- java.util.Date not accepted as parameter to
  955. * PreparedStatement.setObject().
  956. *
  957. * @throws Exception
  958. * if the test fails
  959. *
  960. * @deprecated uses deprecated methods of Date class
  961. */
  962. public void testBug3103() throws Exception {
  963. try {
  964. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3103");
  965. this.stmt
  966. .executeUpdate("CREATE TABLE testBug3103 (field1 DATETIME)");
  967. PreparedStatement pStmt = this.conn
  968. .prepareStatement("INSERT INTO testBug3103 VALUES (?)");
  969. java.util.Date utilDate = new java.util.Date();
  970. pStmt.setObject(1, utilDate);
  971. pStmt.executeUpdate();
  972. this.rs = this.stmt.executeQuery("SELECT field1 FROM testBug3103");
  973. this.rs.next();
  974. java.util.Date retrUtilDate = new java.util.Date(this.rs
  975. .getTimestamp(1).getTime());
  976. // We can only compare on the day/month/year hour/minute/second
  977. // interval, because the timestamp has added milliseconds to the
  978. // internal date...
  979. assertTrue("Dates not equal", (utilDate.getMonth() == retrUtilDate
  980. .getMonth())
  981. && (utilDate.getDate() == retrUtilDate.getDate())
  982. && (utilDate.getYear() == retrUtilDate.getYear())
  983. && (utilDate.getHours() == retrUtilDate.getHours())
  984. && (utilDate.getMinutes() == retrUtilDate.getMinutes())
  985. && (utilDate.getSeconds() == retrUtilDate.getSeconds()));
  986. } finally {
  987. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3103");
  988. }
  989. }
  990. /**
  991. * Tests fix for BUG#3520
  992. *
  993. * @throws Exception
  994. * ...
  995. */
  996. public void testBug3520() throws Exception {
  997. try {
  998. this.stmt.executeUpdate("DROP TABLE IF EXISTS t");
  999. this.stmt.executeUpdate("CREATE TABLE t (s1 int,primary key (s1))");
  1000. this.stmt.executeUpdate("INSERT INTO t VALUES (1)");
  1001. this.stmt.executeUpdate("INSERT INTO t VALUES (1)");
  1002. } catch (SQLException sqlEx) {
  1003. System.out.println(sqlEx.getSQLState());
  1004. } finally {
  1005. this.stmt.executeUpdate("DROP TABLE IF EXISTS t");
  1006. }
  1007. }
  1008. /**
  1009. * Test fix for BUG#3557 -- UpdatableResultSet not picking up default values
  1010. *
  1011. * @throws Exception
  1012. * if test fails.
  1013. */
  1014. public void testBug3557() throws Exception {
  1015. boolean populateDefaults = ((com.mysql.jdbc.ConnectionProperties) this.conn)
  1016. .getPopulateInsertRowWithDefaultValues();
  1017. try {
  1018. ((com.mysql.jdbc.ConnectionProperties) this.conn)
  1019. .setPopulateInsertRowWithDefaultValues(true);
  1020. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");
  1021. this.stmt.executeUpdate("CREATE TABLE testBug3557 ( "
  1022. + "`a` varchar(255) NOT NULL default 'XYZ', "
  1023. + "`b` varchar(255) default '123', "
  1024. + "PRIMARY KEY (`a`(100)))");
  1025. Statement updStmt = this.conn
  1026. .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
  1027. ResultSet.CONCUR_UPDATABLE);
  1028. this.rs = updStmt.executeQuery("SELECT * FROM testBug3557");
  1029. assertTrue(this.rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE);
  1030. this.rs.moveToInsertRow();
  1031. assertEquals("XYZ", this.rs.getObject(1));
  1032. assertEquals("123", this.rs.getObject(2));
  1033. } finally {
  1034. ((com.mysql.jdbc.ConnectionProperties) this.conn)
  1035. .setPopulateInsertRowWithDefaultValues(populateDefaults);
  1036. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3557");
  1037. }
  1038. }
  1039. /**
  1040. * Tests fix for BUG#3620 -- Timezone not respected correctly.
  1041. *
  1042. * @throws SQLException
  1043. * if the test fails.
  1044. */
  1045. public void testBug3620() throws SQLException {
  1046. if (isRunningOnJRockit()) {
  1047. // bug with their timezones
  1048. return;
  1049. }
  1050. if (isRunningOnJdk131()) {
  1051. // bug with timezones, no update
  1052. // for new DST in USA
  1053. return;
  1054. }
  1055. long epsillon = 3000; // 3 seconds time difference
  1056. try {
  1057. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3620");
  1058. this.stmt
  1059. .executeUpdate("CREATE TABLE testBug3620 (field1 TIMESTAMP)");
  1060. PreparedStatement tsPstmt = this.conn
  1061. .prepareStatement("INSERT INTO testBug3620 VALUES (?)");
  1062. Calendar pointInTime = Calendar.getInstance();
  1063. pointInTime.set(2004, 02, 29, 10, 0, 0);
  1064. long pointInTimeOffset = pointInTime.getTimeZone().getRawOffset();
  1065. java.sql.Timestamp ts = new java.sql.Timestamp(pointInTime
  1066. .getTime().getTime());
  1067. tsPstmt.setTimestamp(1, ts);
  1068. tsPstmt.executeUpdate();
  1069. String tsValueAsString = getSingleValue("testBug3620", "field1",
  1070. null).toString();
  1071. System.out.println("Timestamp as string with no calendar: "
  1072. + tsValueAsString.toString());
  1073. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  1074. this.stmt.executeUpdate("DELETE FROM testBug3620");
  1075. Properties props = new Properties();
  1076. props.put("useTimezone", "true");
  1077. // props.put("serverTimezone", "UTC");
  1078. Connection tzConn = getConnectionWithProps(props);
  1079. Statement tsStmt = tzConn.createStatement();
  1080. tsPstmt = tzConn
  1081. .prepareStatement("INSERT INTO testBug3620 VALUES (?)");
  1082. tsPstmt.setTimestamp(1, ts, cal);
  1083. tsPstmt.executeUpdate();
  1084. tsValueAsString = getSingleValue("testBug3620", "field1", null)
  1085. .toString();
  1086. Timestamp tsValueAsTimestamp = (Timestamp) getSingleValue(
  1087. "testBug3620", "field1", null);
  1088. System.out.println("Timestamp as string with UTC calendar: "
  1089. + tsValueAsString.toString());
  1090. System.out.println("Timestamp as Timestamp with UTC calendar: "
  1091. + tsValueAsTimestamp);
  1092. this.rs = tsStmt.executeQuery("SELECT field1 FROM testBug3620");
  1093. this.rs.next();
  1094. Timestamp tsValueUTC = this.rs.getTimestamp(1, cal);
  1095. //
  1096. // We use this testcase with other vendors, JDBC spec
  1097. // requires result set fields can only be read once,
  1098. // although MySQL doesn't require this ;)
  1099. //
  1100. this.rs = tsStmt.executeQuery("SELECT field1 FROM testBug3620");
  1101. this.rs.next();
  1102. Timestamp tsValueStmtNoCal = this.rs.getTimestamp(1);
  1103. System.out
  1104. .println("Timestamp specifying UTC calendar from normal statement: "
  1105. + tsValueUTC.toString());
  1106. PreparedStatement tsPstmtRetr = tzConn
  1107. .prepareStatement("SELECT field1 FROM testBug3620");
  1108. this.rs = tsPstmtRetr.executeQuery();
  1109. this.rs.next();
  1110. Timestamp tsValuePstmtUTC = this.rs.getTimestamp(1, cal);
  1111. System.out
  1112. .println("Timestamp specifying UTC calendar from prepared statement: "
  1113. + tsValuePstmtUTC.toString());
  1114. //
  1115. // We use this testcase with other vendors, JDBC spec
  1116. // requires result set fields can only be read once,
  1117. // although MySQL doesn't require this ;)
  1118. //
  1119. this.rs = tsPstmtRetr.executeQuery();
  1120. this.rs.next();
  1121. Timestamp tsValuePstmtNoCal = this.rs.getTimestamp(1);
  1122. System.out
  1123. .println("Timestamp specifying no calendar from prepared statement: "
  1124. + tsValuePstmtNoCal.toString());
  1125. long stmtDeltaTWithCal = (ts.getTime() - tsValueStmtNoCal.getTime());
  1126. long deltaOrig = Math.abs(stmtDeltaTWithCal - pointInTimeOffset);
  1127. assertTrue(
  1128. "Difference between original timestamp and timestamp retrieved using java.sql.Statement "
  1129. + "set in database using UTC calendar is not ~= "
  1130. + epsillon + ", it is actually " + deltaOrig,
  1131. (deltaOrig < epsillon));
  1132. long pStmtDeltaTWithCal = (ts.getTime() - tsValuePstmtNoCal
  1133. .getTime());
  1134. System.out
  1135. .println(Math.abs(pStmtDeltaTWithCal - pointInTimeOffset)
  1136. + " < "
  1137. + epsillon
  1138. + (Math.abs(pStmtDeltaTWithCal - pointInTimeOffset) < epsillon));
  1139. assertTrue(
  1140. "Difference between original timestamp and timestamp retrieved using java.sql.PreparedStatement "
  1141. + "set in database using UTC calendar is not ~= "
  1142. + epsillon
  1143. + ", it is actually "
  1144. + pStmtDeltaTWithCal, (Math.abs(pStmtDeltaTWithCal
  1145. - pointInTimeOffset) < epsillon));
  1146. System.out
  1147. .println("Difference between original ts and ts with no calendar: "
  1148. + (ts.getTime() - tsValuePstmtNoCal.getTime())
  1149. + ", offset should be " + pointInTimeOffset);
  1150. } finally {
  1151. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3620");
  1152. }
  1153. }
  1154. /**
  1155. * Tests that DataTruncation is thrown when data is truncated.
  1156. *
  1157. * @throws Exception
  1158. * if the test fails.
  1159. */
  1160. public void testBug3697() throws Exception {
  1161. try {
  1162. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3697");
  1163. this.stmt
  1164. .executeUpdate("CREATE TABLE testBug3697 (field1 VARCHAR(255))");
  1165. StringBuffer updateBuf = new StringBuffer(
  1166. "INSERT INTO testBug3697 VALUES ('");
  1167. for (int i = 0; i < 512; i++) {
  1168. updateBuf.append("A");
  1169. }
  1170. updateBuf.append("')");
  1171. try {
  1172. this.stmt.executeUpdate(updateBuf.toString());
  1173. } catch (DataTruncation dtEx) {
  1174. // This is an expected exception....
  1175. }
  1176. SQLWarning warningChain = this.stmt.getWarnings();
  1177. System.out.println(warningChain);
  1178. } finally {
  1179. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3697");
  1180. }
  1181. }
  1182. /**
  1183. * Tests fix for BUG#3804, data truncation on server should throw
  1184. * DataTruncation exception.
  1185. *
  1186. * @throws Exception
  1187. * if the test fails
  1188. */
  1189. public void testBug3804() throws Exception {
  1190. if (versionMeetsMinimum(4, 1)) {
  1191. try {
  1192. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3804");
  1193. this.stmt
  1194. .executeUpdate("CREATE TABLE testBug3804 (field1 VARCHAR(5))");
  1195. boolean caughtTruncation = false;
  1196. try {
  1197. this.stmt
  1198. .executeUpdate("INSERT INTO testBug3804 VALUES ('1234567')");
  1199. } catch (DataTruncation truncationEx) {
  1200. caughtTruncation = true;
  1201. System.out.println(truncationEx);
  1202. }
  1203. assertTrue("Data truncation exception should've been thrown",
  1204. caughtTruncation);
  1205. } finally {
  1206. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3804");
  1207. }
  1208. }
  1209. }
  1210. /**
  1211. * Tests BUG#3873 - PreparedStatement.executeBatch() not returning all
  1212. * generated keys (even though that's not JDBC compliant).
  1213. *
  1214. * @throws Exception
  1215. * if the test fails
  1216. */
  1217. public void testBug3873() throws Exception {
  1218. if (isRunningOnJdk131()) {
  1219. return; // test not valid on JDK-1.3.1
  1220. }
  1221. PreparedStatement batchStmt = null;
  1222. try {
  1223. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3873");
  1224. this.stmt
  1225. .executeUpdate("CREATE TABLE testBug3873 (keyField INT NOT NULL PRIMARY KEY AUTO_INCREMENT, dataField VARCHAR(32))");
  1226. batchStmt = this.conn.prepareStatement(
  1227. "INSERT INTO testBug3873 (dataField) VALUES (?)",
  1228. Statement.RETURN_GENERATED_KEYS);
  1229. batchStmt.setString(1, "abc");
  1230. batchStmt.addBatch();
  1231. batchStmt.setString(1, "def");
  1232. batchStmt.addBatch();
  1233. batchStmt.setString(1, "ghi");
  1234. batchStmt.addBatch();
  1235. int[] updateCounts = batchStmt.executeBatch();
  1236. this.rs = batchStmt.getGeneratedKeys();
  1237. while (this.rs.next()) {
  1238. System.out.println(this.rs.getInt(1));
  1239. }
  1240. this.rs = batchStmt.getGeneratedKeys();
  1241. assertTrue(this.rs.next());
  1242. assertTrue(1 == this.rs.getInt(1));
  1243. assertTrue(this.rs.next());
  1244. assertTrue(2 == this.rs.getInt(1));
  1245. assertTrue(this.rs.next());
  1246. assertTrue(3 == this.rs.getInt(1));
  1247. assertTrue(!this.rs.next());
  1248. } finally {
  1249. if (batchStmt != null) {
  1250. batchStmt.close();
  1251. }
  1252. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug3873");
  1253. }
  1254. }
  1255. /**
  1256. * Tests fix for BUG#4119 -- misbehavior in a managed environment from
  1257. * MVCSoft JDO
  1258. *
  1259. * @throws Exception
  1260. * if the test fails.
  1261. */
  1262. public void testBug4119() throws Exception {
  1263. try {
  1264. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4119");
  1265. this.stmt.executeUpdate("CREATE TABLE `testBug4119` ("
  1266. + "`field1` varchar(255) NOT NULL default '',"
  1267. + "`field2` bigint(20) default NULL,"
  1268. + "`field3` int(11) default NULL,"
  1269. + "`field4` datetime default NULL,"
  1270. + "`field5` varchar(75) default NULL,"
  1271. + "`field6` varchar(75) default NULL,"
  1272. + "`field7` varchar(75) default NULL,"
  1273. + "`field8` datetime default NULL,"
  1274. + " PRIMARY KEY (`field1`(100))" + ")");
  1275. PreparedStatement pStmt = this.conn
  1276. .prepareStatement("insert into testBug4119 (field2, field3,"
  1277. + "field4, field5, field6, field7, field8, field1) values (?, ?,"
  1278. + "?, ?, ?, ?, ?, ?)");
  1279. pStmt.setString(1, "0");
  1280. pStmt.setString(2, "0");
  1281. pStmt.setTimestamp(3, new java.sql.Timestamp(System
  1282. .currentTimeMillis()));
  1283. pStmt.setString(4, "ABC");
  1284. pStmt.setString(5, "DEF");
  1285. pStmt.setString(6, "AA");
  1286. pStmt.setTimestamp(7, new java.sql.Timestamp(System
  1287. .currentTimeMillis()));
  1288. pStmt.setString(8, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
  1289. pStmt.executeUpdate();
  1290. } finally {
  1291. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4119");
  1292. }
  1293. }
  1294. /**
  1295. * Tests fix for BUG#4311 - Error in JDBC retrieval of mediumint column when
  1296. * using prepared statements and binary result sets.
  1297. *
  1298. * @throws Exception
  1299. * if the test fails.
  1300. */
  1301. public void testBug4311() throws Exception {
  1302. try {
  1303. int lowValue = -8388608;
  1304. int highValue = 8388607;
  1305. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4311");
  1306. this.stmt
  1307. .executeUpdate("CREATE TABLE testBug4311 (low MEDIUMINT, high MEDIUMINT)");
  1308. this.stmt.executeUpdate("INSERT INTO testBug4311 VALUES ("
  1309. + lowValue + ", " + highValue + ")");
  1310. PreparedStatement pStmt = this.conn
  1311. .prepareStatement("SELECT low, high FROM testBug4311");
  1312. this.rs = pStmt.executeQuery();
  1313. assertTrue(this.rs.next());
  1314. assertTrue(this.rs.getInt(1) == lowValue);
  1315. assertTrue(this.rs.getInt(2) == highValue);
  1316. } finally {
  1317. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4311");
  1318. }
  1319. }
  1320. /**
  1321. * Tests fix for BUG#4510 -- Statement.getGeneratedKeys() fails when key >
  1322. * 32767
  1323. *
  1324. * @throws Exception
  1325. * if the test fails
  1326. */
  1327. public void testBug4510() throws Exception {
  1328. if (isRunningOnJdk131()) {
  1329. return; // test not valid on JDK-1.3.1
  1330. }
  1331. try {
  1332. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4510");
  1333. this.stmt.executeUpdate("CREATE TABLE testBug4510 ("
  1334. + "field1 INT NOT NULL PRIMARY KEY AUTO_INCREMENT,"
  1335. + "field2 VARCHAR(100))");
  1336. this.stmt
  1337. .executeUpdate("INSERT INTO testBug4510 (field1, field2) VALUES (32767, 'bar')");
  1338. PreparedStatement p = this.conn.prepareStatement(
  1339. "insert into testBug4510 (field2) values (?)",
  1340. Statement.RETURN_GENERATED_KEYS);
  1341. p.setString(1, "blah");
  1342. p.executeUpdate();
  1343. ResultSet rs = p.getGeneratedKeys();
  1344. rs.next();
  1345. System.out.println("Id: " + rs.getInt(1));
  1346. rs.close();
  1347. } finally {
  1348. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4510");
  1349. }
  1350. }
  1351. /**
  1352. * Server doesn't accept everything as a server-side prepared statement, so
  1353. * by default we scan for stuff it can't handle.
  1354. *
  1355. * @throws SQLException
  1356. */
  1357. public void testBug4718() throws SQLException {
  1358. if (versionMeetsMinimum(4, 1, 0)
  1359. && ((com.mysql.jdbc.Connection) this.conn)
  1360. .getUseServerPreparedStmts()) {
  1361. this.pstmt = this.conn.prepareStatement("SELECT 1 LIMIT ?");
  1362. assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
  1363. this.pstmt = this.conn.prepareStatement("SELECT 1 LIMIT 1");
  1364. assertTrue(this.pstmt instanceof com.mysql.jdbc.ServerPreparedStatement);
  1365. this.pstmt = this.conn.prepareStatement("SELECT 1 LIMIT 1, ?");
  1366. assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
  1367. try {
  1368. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4718");
  1369. this.stmt
  1370. .executeUpdate("CREATE TABLE testBug4718 (field1 char(32))");
  1371. this.pstmt = this.conn
  1372. .prepareStatement("ALTER TABLE testBug4718 ADD INDEX (field1)");
  1373. assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
  1374. this.pstmt = this.conn.prepareStatement("SELECT 1");
  1375. assertTrue(this.pstmt instanceof ServerPreparedStatement);
  1376. this.pstmt = this.conn
  1377. .prepareStatement("UPDATE testBug4718 SET field1=1");
  1378. assertTrue(this.pstmt instanceof ServerPreparedStatement);
  1379. this.pstmt = this.conn
  1380. .prepareStatement("UPDATE testBug4718 SET field1=1 LIMIT 1");
  1381. assertTrue(this.pstmt instanceof ServerPreparedStatement);
  1382. this.pstmt = this.conn
  1383. .prepareStatement("UPDATE testBug4718 SET field1=1 LIMIT ?");
  1384. assertTrue(this.pstmt instanceof com.mysql.jdbc.PreparedStatement);
  1385. this.pstmt = this.conn
  1386. .prepareStatement("UPDATE testBug4718 SET field1='Will we ignore LIMIT ?,?'");
  1387. assertTrue(this.pstmt instanceof ServerPreparedStatement);
  1388. } finally {
  1389. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug4718");
  1390. }
  1391. }
  1392. }
  1393. /**
  1394. * Tests fix for BUG#5012 -- ServerPreparedStatements dealing with return of
  1395. * DECIMAL type don't work.
  1396. *
  1397. * @throws Exception
  1398. * if the test fails.
  1399. */
  1400. public void testBug5012() throws Exception {
  1401. PreparedStatement pStmt = null;
  1402. String valueAsString = "12345.12";
  1403. try {
  1404. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5012");
  1405. this.stmt
  1406. .executeUpdate("CREATE TABLE testBug5012(field1 DECIMAL(10,2))");
  1407. this.stmt.executeUpdate("INSERT INTO testBug5012 VALUES ("
  1408. + valueAsString + ")");
  1409. pStmt = this.conn
  1410. .prepareStatement("SELECT field1 FROM testBug5012");
  1411. this.rs = pStmt.executeQuery();
  1412. assertTrue(this.rs.next());
  1413. assertEquals(new BigDecimal(valueAsString), this.rs
  1414. .getBigDecimal(1));
  1415. } finally {
  1416. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5012");
  1417. if (pStmt != null) {
  1418. pStmt.close();
  1419. }
  1420. }
  1421. }
  1422. /**
  1423. * Tests fix for BUG#5133 -- PreparedStatement.toString() doesn't return
  1424. * correct value if no parameters are present in statement.
  1425. *
  1426. * @throws Exception
  1427. */
  1428. public void testBug5133() throws Exception {
  1429. String query = "SELECT 1";
  1430. String output = this.conn.prepareStatement(query).toString();
  1431. System.out.println(output);
  1432. assertTrue(output.indexOf(query) != -1);
  1433. }
  1434. /**
  1435. * Tests for BUG#5191 -- PreparedStatement.executeQuery() gives
  1436. * OutOfMemoryError
  1437. *
  1438. * @throws Exception
  1439. * if the test fails.
  1440. */
  1441. public void testBug5191() throws Exception {
  1442. PreparedStatement pStmt = null;
  1443. try {
  1444. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5191Q");
  1445. this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug5191C");
  1446. this.stmt.executeUpdate("CREATE TABLE testBug5191Q"
  1447. + "(QuestionId int NOT NULL AUTO_INCREMENT, "
  1448. + "Text VARCHAR(200), " + "PRIMARY KEY(QuestionId))");
  1449. this.stmt.executeUpdate("CREATE TABLE testBug519…

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