StatementsTest.java
68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
/*
Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package testsuite.simple;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Properties;
import com.mysql.jdbc.CharsetMapping;
import com.mysql.jdbc.MySQLConnection;
import com.mysql.jdbc.NotImplemented;
import com.mysql.jdbc.ParameterBindings;
import com.mysql.jdbc.SQLError;
import com.mysql.jdbc.StringUtils;
import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;
import com.mysql.jdbc.exceptions.MySQLTimeoutException;
import com.mysql.jdbc.interceptors.ServerStatusDiffInterceptor;
import testsuite.BaseTestCase;
public class StatementsTest extends BaseTestCase {
private static final int MAX_COLUMN_LENGTH = 255;
private static final int MAX_COLUMNS_TO_TEST = 40;
private static final int STEP = 8;
/**
* Runs all test cases in this test suite
*
* @param args
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(StatementsTest.class);
}
/**
* Creates a new StatementsTest object.
*
* @param name
*/
public StatementsTest(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
super.setUp();
this.stmt.executeUpdate("DROP TABLE IF EXISTS statement_test");
this.stmt.executeUpdate("DROP TABLE IF EXISTS statement_batch_test");
this.stmt.executeUpdate(
"CREATE TABLE statement_test (id int not null primary key auto_increment, strdata1 varchar(255) not null, strdata2 varchar(255))");
try {
this.stmt.executeUpdate("CREATE TABLE statement_batch_test (id int not null primary key auto_increment, "
+ "strdata1 varchar(255) not null, strdata2 varchar(255), UNIQUE INDEX (strdata1))");
} catch (SQLException sqlEx) {
if (sqlEx.getMessage().indexOf("max key length") != -1) {
createTable("statement_batch_test",
"(id int not null primary key auto_increment, strdata1 varchar(175) not null, strdata2 varchar(175), " + "UNIQUE INDEX (strdata1))");
}
}
for (int i = 6; i < MAX_COLUMNS_TO_TEST; i += STEP) {
this.stmt.executeUpdate("DROP TABLE IF EXISTS statement_col_test_" + i);
StringBuilder insertBuf = new StringBuilder("INSERT INTO statement_col_test_");
StringBuilder stmtBuf = new StringBuilder("CREATE TABLE IF NOT EXISTS statement_col_test_");
stmtBuf.append(i);
insertBuf.append(i);
stmtBuf.append(" (");
insertBuf.append(" VALUES (");
boolean firstTime = true;
for (int j = 0; j < i; j++) {
if (!firstTime) {
stmtBuf.append(",");
insertBuf.append(",");
} else {
firstTime = false;
}
stmtBuf.append("col_");
stmtBuf.append(j);
stmtBuf.append(" VARCHAR(");
stmtBuf.append(MAX_COLUMN_LENGTH);
stmtBuf.append(")");
insertBuf.append("'");
int numChars = 16;
for (int k = 0; k < numChars; k++) {
insertBuf.append("A");
}
insertBuf.append("'");
}
stmtBuf.append(")");
insertBuf.append(")");
this.stmt.executeUpdate(stmtBuf.toString());
this.stmt.executeUpdate(insertBuf.toString());
}
// explicitly set the catalog to exercise code in execute(), executeQuery() and executeUpdate()
// FIXME: Only works on Windows!
// this.conn.setCatalog(this.conn.getCatalog().toUpperCase());
}
@Override
public void tearDown() throws Exception {
try {
this.stmt.executeUpdate("DROP TABLE statement_test");
for (int i = 6; i < MAX_COLUMNS_TO_TEST; i += STEP) {
StringBuilder stmtBuf = new StringBuilder("DROP TABLE IF EXISTS statement_col_test_");
stmtBuf.append(i);
this.stmt.executeUpdate(stmtBuf.toString());
}
try {
this.stmt.executeUpdate("DROP TABLE statement_batch_test");
} catch (SQLException sqlEx) {
}
} finally {
super.tearDown();
}
}
public void testAccessorsAndMutators() throws SQLException {
assertTrue("Connection can not be null, and must be same connection", this.stmt.getConnection() == this.conn);
// Set max rows, to exercise code in execute(), executeQuery() and executeUpdate()
Statement accessorStmt = null;
try {
accessorStmt = this.conn.createStatement();
accessorStmt.setMaxRows(1);
accessorStmt.setMaxRows(0); // FIXME, test that this actually affects rows returned
accessorStmt.setMaxFieldSize(255);
assertTrue("Max field size should match what was set", accessorStmt.getMaxFieldSize() == 255);
try {
accessorStmt.setMaxFieldSize(Integer.MAX_VALUE);
fail("Should not be able to set max field size > max_packet_size");
} catch (SQLException sqlEx) {
// ignore
}
accessorStmt.setCursorName("undef");
accessorStmt.setEscapeProcessing(true);
accessorStmt.setFetchDirection(java.sql.ResultSet.FETCH_FORWARD);
int fetchDirection = accessorStmt.getFetchDirection();
assertTrue("Set fetch direction != get fetch direction", fetchDirection == java.sql.ResultSet.FETCH_FORWARD);
try {
accessorStmt.setFetchDirection(Integer.MAX_VALUE);
fail("Should not be able to set fetch direction to invalid value");
} catch (SQLException sqlEx) {
// ignore
}
try {
accessorStmt.setMaxRows(50000000 + 10);
fail("Should not be able to set max rows > 50000000");
} catch (SQLException sqlEx) {
// ignore
}
try {
accessorStmt.setMaxRows(Integer.MIN_VALUE);
fail("Should not be able to set max rows < 0");
} catch (SQLException sqlEx) {
// ignore
}
int fetchSize = this.stmt.getFetchSize();
try {
accessorStmt.setMaxRows(4);
accessorStmt.setFetchSize(Integer.MAX_VALUE);
fail("Should not be able to set FetchSize > max rows");
} catch (SQLException sqlEx) {
// ignore
}
try {
accessorStmt.setFetchSize(-2);
fail("Should not be able to set FetchSize < 0");
} catch (SQLException sqlEx) {
// ignore
}
assertTrue("Fetch size before invalid setFetchSize() calls should match fetch size now", fetchSize == this.stmt.getFetchSize());
} finally {
if (accessorStmt != null) {
try {
accessorStmt.close();
} catch (SQLException sqlEx) {
// ignore
}
accessorStmt = null;
}
}
}
public void testAutoIncrement() throws SQLException {
try {
this.stmt.setFetchSize(Integer.MIN_VALUE);
this.stmt.executeUpdate("INSERT INTO statement_test (strdata1) values ('blah')", Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1;
this.rs = this.stmt.getGeneratedKeys();
if (this.rs.next()) {
autoIncKeyFromApi = this.rs.getInt(1);
} else {
fail("Failed to retrieve AUTO_INCREMENT using Statement.getGeneratedKeys()");
}
this.rs.close();
int autoIncKeyFromFunc = -1;
this.rs = this.stmt.executeQuery("SELECT LAST_INSERT_ID()");
if (this.rs.next()) {
autoIncKeyFromFunc = this.rs.getInt(1);
} else {
fail("Failed to retrieve AUTO_INCREMENT using LAST_INSERT_ID()");
}
if ((autoIncKeyFromApi != -1) && (autoIncKeyFromFunc != -1)) {
assertTrue("Key retrieved from API (" + autoIncKeyFromApi + ") does not match key retrieved from LAST_INSERT_ID() " + autoIncKeyFromFunc
+ ") function", autoIncKeyFromApi == autoIncKeyFromFunc);
} else {
fail("AutoIncrement keys were '0'");
}
} finally {
if (this.rs != null) {
try {
this.rs.close();
} catch (Exception ex) {
// ignore
}
}
this.rs = null;
}
}
/**
* Tests all variants of numerical types (signed/unsigned) for correct
* operation when used as return values from a prepared statement.
*
* @throws Exception
*/
public void testBinaryResultSetNumericTypes() throws Exception {
/*
* TINYINT 1 -128 127 SMALLINT 2 -32768 32767 MEDIUMINT 3 -8388608
* 8388607 INT 4 -2147483648 2147483647 BIGINT 8 -9223372036854775808
* 9223372036854775807
*/
String unsignedMinimum = "0";
String tiMinimum = "-128";
String tiMaximum = "127";
String utiMaximum = "255";
String siMinimum = "-32768";
String siMaximum = "32767";
String usiMaximum = "65535";
String miMinimum = "-8388608";
String miMaximum = "8388607";
String umiMaximum = "16777215";
String iMinimum = "-2147483648";
String iMaximum = "2147483647";
String uiMaximum = "4294967295";
String biMinimum = "-9223372036854775808";
String biMaximum = "9223372036854775807";
String ubiMaximum = "18446744073709551615";
try {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testBinaryResultSetNumericTypes");
this.stmt.executeUpdate("CREATE TABLE testBinaryResultSetNumericTypes(rowOrder TINYINT, ti TINYINT,uti TINYINT UNSIGNED, si SMALLINT,"
+ "usi SMALLINT UNSIGNED, mi MEDIUMINT,umi MEDIUMINT UNSIGNED, i INT, ui INT UNSIGNED,bi BIGINT, ubi BIGINT UNSIGNED)");
PreparedStatement inserter = this.conn.prepareStatement("INSERT INTO testBinaryResultSetNumericTypes VALUES (?,?,?,?,?,?,?,?,?,?,?)");
inserter.setInt(1, 0);
inserter.setString(2, tiMinimum);
inserter.setString(3, unsignedMinimum);
inserter.setString(4, siMinimum);
inserter.setString(5, unsignedMinimum);
inserter.setString(6, miMinimum);
inserter.setString(7, unsignedMinimum);
inserter.setString(8, iMinimum);
inserter.setString(9, unsignedMinimum);
inserter.setString(10, biMinimum);
inserter.setString(11, unsignedMinimum);
inserter.executeUpdate();
inserter.setInt(1, 1);
inserter.setString(2, tiMaximum);
inserter.setString(3, utiMaximum);
inserter.setString(4, siMaximum);
inserter.setString(5, usiMaximum);
inserter.setString(6, miMaximum);
inserter.setString(7, umiMaximum);
inserter.setString(8, iMaximum);
inserter.setString(9, uiMaximum);
inserter.setString(10, biMaximum);
inserter.setString(11, ubiMaximum);
inserter.executeUpdate();
PreparedStatement selector = this.conn.prepareStatement("SELECT * FROM testBinaryResultSetNumericTypes ORDER by rowOrder ASC");
this.rs = selector.executeQuery();
assertTrue(this.rs.next());
assertTrue(this.rs.getString(2).equals(tiMinimum));
assertTrue(this.rs.getString(3).equals(unsignedMinimum));
assertTrue(this.rs.getString(4).equals(siMinimum));
assertTrue(this.rs.getString(5).equals(unsignedMinimum));
assertTrue(this.rs.getString(6).equals(miMinimum));
assertTrue(this.rs.getString(7).equals(unsignedMinimum));
assertTrue(this.rs.getString(8).equals(iMinimum));
assertTrue(this.rs.getString(9).equals(unsignedMinimum));
assertTrue(this.rs.getString(10).equals(biMinimum));
assertTrue(this.rs.getString(11).equals(unsignedMinimum));
assertTrue(this.rs.next());
assertTrue(this.rs.getString(2) + " != " + tiMaximum, this.rs.getString(2).equals(tiMaximum));
assertTrue(this.rs.getString(3) + " != " + utiMaximum, this.rs.getString(3).equals(utiMaximum));
assertTrue(this.rs.getString(4) + " != " + siMaximum, this.rs.getString(4).equals(siMaximum));
assertTrue(this.rs.getString(5) + " != " + usiMaximum, this.rs.getString(5).equals(usiMaximum));
assertTrue(this.rs.getString(6) + " != " + miMaximum, this.rs.getString(6).equals(miMaximum));
assertTrue(this.rs.getString(7) + " != " + umiMaximum, this.rs.getString(7).equals(umiMaximum));
assertTrue(this.rs.getString(8) + " != " + iMaximum, this.rs.getString(8).equals(iMaximum));
assertTrue(this.rs.getString(9) + " != " + uiMaximum, this.rs.getString(9).equals(uiMaximum));
assertTrue(this.rs.getString(10) + " != " + biMaximum, this.rs.getString(10).equals(biMaximum));
assertTrue(this.rs.getString(11) + " != " + ubiMaximum, this.rs.getString(11).equals(ubiMaximum));
assertTrue(!this.rs.next());
} finally {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testBinaryResultSetNumericTypes");
}
}
/**
* Tests stored procedure functionality
*
* @throws Exception
* if an error occurs.
*/
public void testCallableStatement() throws Exception {
if (versionMeetsMinimum(5, 0)) {
CallableStatement cStmt = null;
String stringVal = "abcdefg";
int intVal = 42;
try {
try {
this.stmt.executeUpdate("DROP PROCEDURE testCallStmt");
} catch (SQLException sqlEx) {
if (sqlEx.getMessage().indexOf("does not exist") == -1) {
throw sqlEx;
}
}
this.stmt.executeUpdate("DROP TABLE IF EXISTS callStmtTbl");
this.stmt.executeUpdate("CREATE TABLE callStmtTbl (x CHAR(16), y INT)");
this.stmt.executeUpdate("CREATE PROCEDURE testCallStmt(n INT, x CHAR(16), y INT) WHILE n DO SET n = n - 1;"
+ " INSERT INTO callStmtTbl VALUES (x, y); END WHILE;");
int rowsToCheck = 15;
cStmt = this.conn.prepareCall("{call testCallStmt(?,?,?)}");
cStmt.setInt(1, rowsToCheck);
cStmt.setString(2, stringVal);
cStmt.setInt(3, intVal);
cStmt.execute();
this.rs = this.stmt.executeQuery("SELECT x,y FROM callStmtTbl");
int numRows = 0;
while (this.rs.next()) {
assertTrue(this.rs.getString(1).equals(stringVal) && (this.rs.getInt(2) == intVal));
numRows++;
}
this.rs.close();
this.rs = null;
cStmt.close();
cStmt = null;
System.out.println(rowsToCheck + " rows returned");
assertTrue(numRows == rowsToCheck);
} finally {
try {
this.stmt.executeUpdate("DROP PROCEDURE testCallStmt");
} catch (SQLException sqlEx) {
if (sqlEx.getMessage().indexOf("does not exist") == -1) {
throw sqlEx;
}
}
this.stmt.executeUpdate("DROP TABLE IF EXISTS callStmtTbl");
if (cStmt != null) {
cStmt.close();
}
}
}
}
public void testCancelStatement() throws Exception {
if (versionMeetsMinimum(5, 0)) {
Connection cancelConn = null;
try {
cancelConn = getConnectionWithProps((String) null);
final Statement cancelStmt = cancelConn.createStatement();
cancelStmt.setQueryTimeout(1);
long begin = System.currentTimeMillis();
try {
cancelStmt.execute("SELECT SLEEP(30)");
} catch (SQLException sqlEx) {
assertTrue("Probably wasn't actually cancelled", System.currentTimeMillis() - begin < 30000);
}
for (int i = 0; i < 1000; i++) {
try {
cancelStmt.executeQuery("SELECT 1");
} catch (SQLException timedOutEx) {
break;
}
}
// Make sure we can still use the connection...
cancelStmt.setQueryTimeout(0);
this.rs = cancelStmt.executeQuery("SELECT 1");
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
cancelStmt.setQueryTimeout(0);
new Thread() {
@Override
public void run() {
try {
try {
sleep(5000);
} catch (InterruptedException iEx) {
// ignore
}
cancelStmt.cancel();
} catch (SQLException sqlEx) {
throw new RuntimeException(sqlEx.toString());
}
}
}.start();
begin = System.currentTimeMillis();
try {
cancelStmt.execute("SELECT SLEEP(30)");
} catch (SQLException sqlEx) {
assertTrue("Probably wasn't actually cancelled", System.currentTimeMillis() - begin < 30000);
}
for (int i = 0; i < 1000; i++) {
try {
cancelStmt.executeQuery("SELECT 1");
} catch (SQLException timedOutEx) {
break;
}
}
// Make sure we can still use the connection...
this.rs = cancelStmt.executeQuery("SELECT 1");
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
final PreparedStatement cancelPstmt = cancelConn.prepareStatement("SELECT SLEEP(30)");
cancelPstmt.setQueryTimeout(1);
begin = System.currentTimeMillis();
try {
cancelPstmt.execute();
} catch (SQLException sqlEx) {
assertTrue("Probably wasn't actually cancelled", System.currentTimeMillis() - begin < 30000);
}
for (int i = 0; i < 1000; i++) {
try {
cancelPstmt.executeQuery("SELECT 1");
} catch (SQLException timedOutEx) {
break;
}
}
// Make sure we can still use the connection...
this.rs = cancelStmt.executeQuery("SELECT 1");
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
cancelPstmt.setQueryTimeout(0);
new Thread() {
@Override
public void run() {
try {
try {
sleep(5000);
} catch (InterruptedException iEx) {
// ignore
}
cancelPstmt.cancel();
} catch (SQLException sqlEx) {
throw new RuntimeException(sqlEx.toString());
}
}
}.start();
begin = System.currentTimeMillis();
try {
cancelPstmt.execute();
} catch (SQLException sqlEx) {
assertTrue("Probably wasn't actually cancelled", System.currentTimeMillis() - begin < 30000);
}
for (int i = 0; i < 1000; i++) {
try {
cancelPstmt.executeQuery("SELECT 1");
} catch (SQLException timedOutEx) {
break;
}
}
// Make sure we can still use the connection...
this.rs = cancelStmt.executeQuery("SELECT 1");
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
final PreparedStatement cancelClientPstmt = ((com.mysql.jdbc.Connection) cancelConn).clientPrepareStatement("SELECT SLEEP(30)");
cancelClientPstmt.setQueryTimeout(1);
begin = System.currentTimeMillis();
try {
cancelClientPstmt.execute();
} catch (SQLException sqlEx) {
assertTrue("Probably wasn't actually cancelled", System.currentTimeMillis() - begin < 30000);
}
for (int i = 0; i < 1000; i++) {
try {
cancelStmt.executeQuery("SELECT 1");
} catch (SQLException timedOutEx) {
break;
}
}
// Make sure we can still use the connection...
this.rs = cancelStmt.executeQuery("SELECT 1");
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
cancelClientPstmt.setQueryTimeout(0);
new Thread() {
@Override
public void run() {
try {
try {
sleep(5000);
} catch (InterruptedException iEx) {
// ignore
}
cancelClientPstmt.cancel();
} catch (SQLException sqlEx) {
throw new RuntimeException(sqlEx.toString());
}
}
}.start();
begin = System.currentTimeMillis();
try {
cancelClientPstmt.execute();
} catch (SQLException sqlEx) {
assertTrue("Probably wasn't actually cancelled", System.currentTimeMillis() - begin < 30000);
}
for (int i = 0; i < 1000; i++) {
try {
cancelClientPstmt.executeQuery("SELECT 1");
} catch (SQLException timedOutEx) {
break;
}
}
// Make sure we can still use the connection...
this.rs = cancelStmt.executeQuery("SELECT 1");
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
Connection forceCancel = getConnectionWithProps("queryTimeoutKillsConnection=true");
Statement forceStmt = forceCancel.createStatement();
forceStmt.setQueryTimeout(1);
try {
forceStmt.execute("SELECT SLEEP(30)");
fail("Statement should have been cancelled");
} catch (MySQLTimeoutException timeout) {
// expected
}
int count = 1000;
for (; count > 0; count--) {
if (forceCancel.isClosed()) {
break;
}
Thread.sleep(100);
}
if (count == 0) {
fail("Connection was never killed");
}
try {
forceCancel.setAutoCommit(true); // should fail too
} catch (SQLException sqlEx) {
assertTrue(sqlEx.getCause() instanceof MySQLStatementCancelledException);
}
} finally {
if (this.rs != null) {
ResultSet toClose = this.rs;
this.rs = null;
toClose.close();
}
if (cancelConn != null) {
cancelConn.close();
}
}
}
}
public void testClose() throws SQLException {
Statement closeStmt = null;
boolean exceptionAfterClosed = false;
try {
closeStmt = this.conn.createStatement();
closeStmt.close();
try {
closeStmt.executeQuery("SELECT 1");
} catch (SQLException sqlEx) {
exceptionAfterClosed = true;
}
} finally {
if (closeStmt != null) {
try {
closeStmt.close();
} catch (SQLException sqlEx) {
/* ignore */
}
}
closeStmt = null;
}
assertTrue("Operations not allowed on Statement after .close() is called!", exceptionAfterClosed);
}
public void testEnableStreamingResults() throws Exception {
Statement streamStmt = this.conn.createStatement();
((com.mysql.jdbc.Statement) streamStmt).enableStreamingResults();
assertEquals(streamStmt.getFetchSize(), Integer.MIN_VALUE);
assertEquals(streamStmt.getResultSetType(), ResultSet.TYPE_FORWARD_ONLY);
}
public void testHoldingResultSetsOverClose() throws Exception {
Properties props = new Properties();
props.setProperty("holdResultsOpenOverStatementClose", "true");
Connection conn2 = getConnectionWithProps(props);
Statement stmt2 = null;
PreparedStatement pstmt2 = null;
ResultSet rs2 = null;
try {
stmt2 = conn2.createStatement();
this.rs = stmt2.executeQuery("SELECT 1");
this.rs.next();
this.rs.getInt(1);
stmt2.close();
this.rs.getInt(1);
stmt2 = conn2.createStatement();
stmt2.execute("SELECT 1");
this.rs = stmt2.getResultSet();
this.rs.next();
this.rs.getInt(1);
stmt2.execute("SELECT 2");
this.rs.getInt(1);
pstmt2 = conn2.prepareStatement("SELECT 1");
this.rs = pstmt2.executeQuery();
this.rs.next();
this.rs.getInt(1);
pstmt2.close();
this.rs.getInt(1);
pstmt2 = conn2.prepareStatement("SELECT 1");
this.rs = pstmt2.executeQuery();
this.rs.next();
this.rs.getInt(1);
rs2 = pstmt2.executeQuery();
this.rs.getInt(1);
pstmt2.execute();
this.rs.getInt(1);
rs2.close();
pstmt2 = ((com.mysql.jdbc.Connection) conn2).clientPrepareStatement("SELECT 1");
this.rs = pstmt2.executeQuery();
this.rs.next();
this.rs.getInt(1);
pstmt2.close();
this.rs.getInt(1);
pstmt2 = ((com.mysql.jdbc.Connection) conn2).clientPrepareStatement("SELECT 1");
this.rs = pstmt2.executeQuery();
this.rs.next();
this.rs.getInt(1);
rs2 = pstmt2.executeQuery();
this.rs.getInt(1);
pstmt2.execute();
this.rs.getInt(1);
rs2.close();
stmt2 = conn2.createStatement();
this.rs = stmt2.executeQuery("SELECT 1");
this.rs.next();
this.rs.getInt(1);
rs2 = stmt2.executeQuery("SELECT 2");
this.rs.getInt(1);
this.rs = stmt2.executeQuery("SELECT 1");
this.rs.next();
this.rs.getInt(1);
stmt2.executeUpdate("SET @var=1");
this.rs.getInt(1);
stmt2.execute("SET @var=2");
this.rs.getInt(1);
rs2.close();
} finally {
if (stmt2 != null) {
stmt2.close();
}
}
}
public void testInsert() throws SQLException {
try {
boolean autoCommit = this.conn.getAutoCommit();
// Test running a query for an update. It should fail.
try {
this.conn.setAutoCommit(false);
this.stmt.executeUpdate("SELECT * FROM statement_test");
} catch (SQLException sqlEx) {
assertTrue("Exception thrown for unknown reason", sqlEx.getSQLState().equalsIgnoreCase("01S03"));
} finally {
this.conn.setAutoCommit(autoCommit);
}
// Test running a update for an query. It should fail.
try {
this.conn.setAutoCommit(false);
this.rs = this.stmt.executeQuery("UPDATE statement_test SET strdata1='blah' WHERE 1=0");
} catch (SQLException sqlEx) {
assertTrue("Exception thrown for unknown reason", sqlEx.getSQLState().equalsIgnoreCase(SQLError.SQL_STATE_ILLEGAL_ARGUMENT));
} finally {
this.conn.setAutoCommit(autoCommit);
}
for (int i = 0; i < 10; i++) {
int updateCount = this.stmt.executeUpdate("INSERT INTO statement_test (strdata1,strdata2) values ('abcdefg', 'poi')");
assertTrue("Update count must be '1', was '" + updateCount + "'", (updateCount == 1));
}
int insertIdFromGeneratedKeys = Integer.MIN_VALUE;
this.stmt.executeUpdate("INSERT INTO statement_test (strdata1, strdata2) values ('a', 'a'), ('b', 'b'), ('c', 'c')",
Statement.RETURN_GENERATED_KEYS);
this.rs = this.stmt.getGeneratedKeys();
if (this.rs.next()) {
insertIdFromGeneratedKeys = this.rs.getInt(1);
}
this.rs.close();
this.rs = this.stmt.executeQuery("SELECT LAST_INSERT_ID()");
int insertIdFromServer = Integer.MIN_VALUE;
if (this.rs.next()) {
insertIdFromServer = this.rs.getInt(1);
}
assertEquals(insertIdFromGeneratedKeys, insertIdFromServer);
} finally {
if (this.rs != null) {
try {
this.rs.close();
} catch (Exception ex) {
// ignore
}
}
this.rs = null;
}
}
/**
* Tests multiple statement support
*
* @throws Exception
*/
public void testMultiStatements() throws Exception {
if (versionMeetsMinimum(4, 1)) {
Connection multiStmtConn = null;
Statement multiStmt = null;
try {
Properties props = new Properties();
props.setProperty("allowMultiQueries", "true");
multiStmtConn = getConnectionWithProps(props);
multiStmt = multiStmtConn.createStatement();
multiStmt.executeUpdate("DROP TABLE IF EXISTS testMultiStatements");
multiStmt.executeUpdate("CREATE TABLE testMultiStatements (field1 VARCHAR(255), field2 INT, field3 DOUBLE)");
multiStmt.executeUpdate("INSERT INTO testMultiStatements VALUES ('abcd', 1, 2)");
multiStmt.execute("SELECT field1 FROM testMultiStatements WHERE field1='abcd';UPDATE testMultiStatements SET field3=3;"
+ "SELECT field3 FROM testMultiStatements WHERE field3=3");
this.rs = multiStmt.getResultSet();
assertTrue(this.rs.next());
assertTrue("abcd".equals(this.rs.getString(1)));
this.rs.close();
// Next should be an update count...
assertTrue(!multiStmt.getMoreResults());
assertTrue("Update count was " + multiStmt.getUpdateCount() + ", expected 1", multiStmt.getUpdateCount() == 1);
assertTrue(multiStmt.getMoreResults());
this.rs = multiStmt.getResultSet();
assertTrue(this.rs.next());
assertTrue(this.rs.getDouble(1) == 3);
// End of multi results
assertTrue(!multiStmt.getMoreResults());
assertTrue(multiStmt.getUpdateCount() == -1);
} finally {
if (multiStmt != null) {
multiStmt.executeUpdate("DROP TABLE IF EXISTS testMultiStatements");
multiStmt.close();
}
if (multiStmtConn != null) {
multiStmtConn.close();
}
}
}
}
/**
* Tests that NULLs and '' work correctly.
*
* @throws SQLException
* if an error occurs
*/
public void testNulls() throws SQLException {
try {
this.stmt.executeUpdate("DROP TABLE IF EXISTS nullTest");
this.stmt.executeUpdate("CREATE TABLE IF NOT EXISTS nullTest (field_1 CHAR(20), rowOrder INT)");
this.stmt.executeUpdate("INSERT INTO nullTest VALUES (null, 1), ('', 2)");
this.rs = this.stmt.executeQuery("SELECT field_1 FROM nullTest ORDER BY rowOrder");
this.rs.next();
assertTrue("NULL field not returned as NULL", (this.rs.getString("field_1") == null) && this.rs.wasNull());
this.rs.next();
assertTrue("Empty field not returned as \"\"", this.rs.getString("field_1").equals("") && !this.rs.wasNull());
this.rs.close();
} finally {
if (this.rs != null) {
try {
this.rs.close();
} catch (Exception ex) {
// ignore
}
}
this.stmt.executeUpdate("DROP TABLE IF EXISTS nullTest");
}
}
public void testParsedConversionWarning() throws Exception {
if (versionMeetsMinimum(4, 1)) {
try {
Properties props = new Properties();
props.setProperty("useUsageAdvisor", "true");
Connection warnConn = getConnectionWithProps(props);
this.stmt.executeUpdate("DROP TABLE IF EXISTS testParsedConversionWarning");
this.stmt.executeUpdate("CREATE TABLE testParsedConversionWarning(field1 VARCHAR(255))");
this.stmt.executeUpdate("INSERT INTO testParsedConversionWarning VALUES ('1.0')");
PreparedStatement badStmt = warnConn.prepareStatement("SELECT field1 FROM testParsedConversionWarning");
this.rs = badStmt.executeQuery();
assertTrue(this.rs.next());
this.rs.getFloat(1);
} finally {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testParsedConversionWarning");
}
}
}
public void testPreparedStatement() throws SQLException {
this.stmt.executeUpdate("INSERT INTO statement_test (id, strdata1,strdata2) values (999,'abcdefg', 'poi')");
this.pstmt = this.conn.prepareStatement("UPDATE statement_test SET strdata1=?, strdata2=? where id=999");
this.pstmt.setString(1, "iop");
this.pstmt.setString(2, "higjklmn");
int updateCount = this.pstmt.executeUpdate();
assertTrue("Update count must be '1', was '" + updateCount + "'", (updateCount == 1));
this.pstmt.clearParameters();
this.pstmt.close();
this.rs = this.stmt.executeQuery("SELECT id, strdata1, strdata2 FROM statement_test");
assertTrue(this.rs.next());
assertTrue(this.rs.getInt(1) == 999);
assertTrue("Expected 'iop', received '" + this.rs.getString(2) + "'", "iop".equals(this.rs.getString(2)));
assertTrue("Expected 'higjklmn', received '" + this.rs.getString(3) + "'", "higjklmn".equals(this.rs.getString(3)));
}
public void testPreparedStatementBatch() throws SQLException {
this.pstmt = this.conn.prepareStatement("INSERT INTO statement_batch_test (strdata1, strdata2) VALUES (?,?)");
for (int i = 0; i < 1000; i++) {
this.pstmt.setString(1, "batch_" + i);
this.pstmt.setString(2, "batch_" + i);
this.pstmt.addBatch();
}
int[] updateCounts = this.pstmt.executeBatch();
for (int i = 0; i < updateCounts.length; i++) {
assertTrue("Update count must be '1', was '" + updateCounts[i] + "'", (updateCounts[i] == 1));
}
}
public void testRowFetch() throws Exception {
if (versionMeetsMinimum(5, 0, 5)) {
createTable("testRowFetch", "(field1 int)");
this.stmt.executeUpdate("INSERT INTO testRowFetch VALUES (1)");
Connection fetchConn = null;
Properties props = new Properties();
props.setProperty("useCursorFetch", "true");
try {
fetchConn = getConnectionWithProps(props);
PreparedStatement fetchStmt = fetchConn.prepareStatement("SELECT field1 FROM testRowFetch WHERE field1=1");
fetchStmt.setFetchSize(10);
this.rs = fetchStmt.executeQuery();
assertTrue(this.rs.next());
this.stmt.executeUpdate("INSERT INTO testRowFetch VALUES (2), (3)");
fetchStmt = fetchConn.prepareStatement("SELECT field1 FROM testRowFetch ORDER BY field1");
fetchStmt.setFetchSize(1);
this.rs = fetchStmt.executeQuery();
assertTrue(this.rs.next());
assertEquals(1, this.rs.getInt(1));
assertTrue(this.rs.next());
assertEquals(2, this.rs.getInt(1));
assertTrue(this.rs.next());
assertEquals(3, this.rs.getInt(1));
assertEquals(false, this.rs.next());
this.rs = fetchStmt.executeQuery();
} finally {
if (fetchConn != null) {
fetchConn.close();
}
}
}
}
public void testSelectColumns() throws SQLException {
for (int i = 6; i < MAX_COLUMNS_TO_TEST; i += STEP) {
long start = System.currentTimeMillis();
this.rs = this.stmt.executeQuery("SELECT * from statement_col_test_" + i);
if (this.rs.next()) {
}
long end = System.currentTimeMillis();
System.out.println(i + " columns = " + (end - start) + " ms");
}
}
/**
* Tests for PreparedStatement.setObject()
*
* @throws Exception
*/
public void testSetObject() throws Exception {
Properties props = new Properties();
props.put("noDatetimeStringSync", "true"); // value=true for #5
Connection conn1 = getConnectionWithProps(props);
Statement stmt1 = conn1.createStatement();
createTable("t1",
" (c1 DECIMAL," // instance of String
+ "c2 VARCHAR(255)," // instance of String
+ "c3 BLOB," // instance of byte[]
+ "c4 DATE," // instance of java.util.Date
+ "c5 TIMESTAMP," // instance of String
+ "c6 TIME," // instance of String
+ "c7 TIME)"); // instance of java.sql.Timestamp
this.pstmt = conn1.prepareStatement("INSERT INTO t1 VALUES (?, ?, ?, ?, ?, ?, ?)");
long currentTime = System.currentTimeMillis();
this.pstmt.setObject(1, "1000", Types.DECIMAL);
this.pstmt.setObject(2, "2000", Types.VARCHAR);
this.pstmt.setObject(3, new byte[] { 0 }, Types.BLOB);
this.pstmt.setObject(4, new java.util.Date(currentTime), Types.DATE);
this.pstmt.setObject(5, "2000-01-01 23-59-59", Types.TIMESTAMP);
this.pstmt.setObject(6, "11:22:33", Types.TIME);
this.pstmt.setObject(7, new java.sql.Timestamp(currentTime), Types.TIME);
this.pstmt.execute();
this.rs = stmt1.executeQuery("SELECT * FROM t1");
this.rs.next();
assertEquals("1000", this.rs.getString(1));
assertEquals("2000", this.rs.getString(2));
assertEquals(1, ((byte[]) this.rs.getObject(3)).length);
assertEquals(0, ((byte[]) this.rs.getObject(3))[0]);
assertEquals(new java.sql.Date(currentTime).toString(), this.rs.getDate(4).toString());
if (versionMeetsMinimum(4, 1)) {
assertEquals("2000-01-01 23:59:59", this.rs.getString(5));
} else {
assertEquals("20000101235959", this.rs.getString(5));
}
assertEquals("11:22:33", this.rs.getString(6));
assertEquals(new java.sql.Time(currentTime).toString(), this.rs.getString(7));
}
public void testStatementRewriteBatch() throws Exception {
for (int j = 0; j < 2; j++) {
Properties props = new Properties();
if (j == 0) {
props.setProperty("useServerPrepStmts", "true");
}
props.setProperty("rewriteBatchedStatements", "true");
Connection multiConn = getConnectionWithProps(props);
createTable("testStatementRewriteBatch", "(pk_field INT PRIMARY KEY NOT NULL AUTO_INCREMENT, field1 INT)");
Statement multiStmt = multiConn.createStatement();
multiStmt.addBatch("INSERT INTO testStatementRewriteBatch(field1) VALUES (1)");
multiStmt.addBatch("INSERT INTO testStatementRewriteBatch(field1) VALUES (2)");
multiStmt.addBatch("INSERT INTO testStatementRewriteBatch(field1) VALUES (3)");
multiStmt.addBatch("INSERT INTO testStatementRewriteBatch(field1) VALUES (4)");
multiStmt.addBatch("UPDATE testStatementRewriteBatch SET field1=5 WHERE field1=1");
multiStmt.addBatch("UPDATE testStatementRewriteBatch SET field1=6 WHERE field1=2 OR field1=3");
int[] counts = multiStmt.executeBatch();
ResultSet genKeys = multiStmt.getGeneratedKeys();
for (int i = 1; i < 5; i++) {
genKeys.next();
assertEquals(i, genKeys.getInt(1));
}
assertEquals(counts.length, 6);
assertEquals(counts[0], 1);
assertEquals(counts[1], 1);
assertEquals(counts[2], 1);
assertEquals(counts[3], 1);
assertEquals(counts[4], 1);
assertEquals(counts[5], 2);
this.rs = multiStmt.executeQuery("SELECT field1 FROM testStatementRewriteBatch ORDER BY field1");
assertTrue(this.rs.next());
assertEquals(this.rs.getInt(1), 4);
assertTrue(this.rs.next());
assertEquals(this.rs.getInt(1), 5);
assertTrue(this.rs.next());
assertEquals(this.rs.getInt(1), 6);
assertTrue(this.rs.next());
assertEquals(this.rs.getInt(1), 6);
createTable("testStatementRewriteBatch", "(pk_field INT PRIMARY KEY NOT NULL AUTO_INCREMENT, field1 INT)");
props.clear();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("maxAllowedPacket", "1024");
multiConn = getConnectionWithProps(props);
multiStmt = multiConn.createStatement();
for (int i = 0; i < 1000; i++) {
multiStmt.addBatch("INSERT INTO testStatementRewriteBatch(field1) VALUES (" + i + ")");
}
multiStmt.executeBatch();
genKeys = multiStmt.getGeneratedKeys();
for (int i = 1; i < 1000; i++) {
genKeys.next();
assertEquals(i, genKeys.getInt(1));
}
createTable("testStatementRewriteBatch", "(pk_field INT PRIMARY KEY NOT NULL AUTO_INCREMENT, field1 INT)");
props.clear();
props.setProperty("useServerPrepStmts", j == 0 ? "true" : "false");
props.setProperty("rewriteBatchedStatements", "true");
multiConn = getConnectionWithProps(props);
PreparedStatement pStmt = null;
pStmt = multiConn.prepareStatement("INSERT INTO testStatementRewriteBatch(field1) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < 1000; i++) {
pStmt.setInt(1, i);
pStmt.addBatch();
}
pStmt.executeBatch();
genKeys = pStmt.getGeneratedKeys();
for (int i = 1; i < 1000; i++) {
genKeys.next();
assertEquals(i, genKeys.getInt(1));
}
createTable("testStatementRewriteBatch", "(pk_field INT PRIMARY KEY NOT NULL AUTO_INCREMENT, field1 INT)");
props.setProperty("useServerPrepStmts", j == 0 ? "true" : "false");
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("maxAllowedPacket", j == 0 ? "10240" : "1024");
multiConn = getConnectionWithProps(props);
pStmt = multiConn.prepareStatement("INSERT INTO testStatementRewriteBatch(field1) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < 1000; i++) {
pStmt.setInt(1, i);
pStmt.addBatch();
}
pStmt.executeBatch();
genKeys = pStmt.getGeneratedKeys();
for (int i = 1; i < 1000; i++) {
genKeys.next();
assertEquals(i, genKeys.getInt(1));
}
Object[][] differentTypes = new Object[1000][14];
createTable("rewriteBatchTypes",
"(internalOrder int, f1 tinyint null, " + "f2 smallint null, f3 int null, f4 bigint null, "
+ "f5 decimal(8, 2) null, f6 float null, f7 double null, " + "f8 varchar(255) null, f9 text null, f10 blob null, f11 blob null, "
+ (versionMeetsMinimum(5, 6, 4) ? "f12 datetime(3) null, f13 time(3) null, f14 date null)"
: "f12 datetime null, f13 time null, f14 date null)"));
for (int i = 0; i < 1000; i++) {
differentTypes[i][0] = Math.random() < .5 ? null : new Byte((byte) (Math.random() * 127));
differentTypes[i][1] = Math.random() < .5 ? null : new Short((short) (Math.random() * Short.MAX_VALUE));
differentTypes[i][2] = Math.random() < .5 ? null : new Integer((int) (Math.random() * Integer.MAX_VALUE));
differentTypes[i][3] = Math.random() < .5 ? null : new Long((long) (Math.random() * Long.MAX_VALUE));
differentTypes[i][4] = Math.random() < .5 ? null : new BigDecimal("19.95");
differentTypes[i][5] = Math.random() < .5 ? null : new Float(3 + ((float) (Math.random())));
differentTypes[i][6] = Math.random() < .5 ? null : new Double(3 + (Math.random()));
differentTypes[i][7] = Math.random() < .5 ? null : randomString();
differentTypes[i][8] = Math.random() < .5 ? null : randomString();
differentTypes[i][9] = Math.random() < .5 ? null : randomString().getBytes();
differentTypes[i][10] = Math.random() < .5 ? null : randomString().getBytes();
differentTypes[i][11] = Math.random() < .5 ? null : new Timestamp(System.currentTimeMillis());
differentTypes[i][12] = Math.random() < .5 ? null : new Time(System.currentTimeMillis());
differentTypes[i][13] = Math.random() < .5 ? null : new Date(System.currentTimeMillis());
}
props.setProperty("useServerPrepStmts", j == 0 ? "true" : "false");
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("maxAllowedPacket", j == 0 ? "10240" : "1024");
multiConn = getConnectionWithProps(props);
pStmt = multiConn.prepareStatement(
"INSERT INTO rewriteBatchTypes(internalOrder,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14) VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
for (int i = 0; i < 1000; i++) {
pStmt.setInt(1, i);
for (int k = 0; k < 14; k++) {
if (k == 8) {
String asString = (String) differentTypes[i][k];
if (asString == null) {
pStmt.setObject(k + 2, null);
} else {
pStmt.setCharacterStream(k + 2, new StringReader(asString), asString.length());
}
} else if (k == 9) {
byte[] asBytes = (byte[]) differentTypes[i][k];
if (asBytes == null) {
pStmt.setObject(k + 2, null);
} else {
pStmt.setBinaryStream(k + 2, new ByteArrayInputStream(asBytes), asBytes.length);
}
} else {
pStmt.setObject(k + 2, differentTypes[i][k]);
}
}
pStmt.addBatch();
}
pStmt.executeBatch();
this.rs = this.stmt
.executeQuery("SELECT f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14 FROM rewriteBatchTypes ORDER BY internalOrder");
int idx = 0;
// We need to format this ourselves, since we have to strip the nanos off of TIMESTAMPs, so .equals() doesn't really work...
SimpleDateFormat sdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss''", Locale.US);
while (this.rs.next()) {
for (int k = 0; k < 14; k++) {
if (differentTypes[idx][k] == null) {
assertTrue("On row " + idx + " expected NULL, found " + this.rs.getObject(k + 1) + " in column " + (k + 1),
this.rs.getObject(k + 1) == null);
} else {
String className = differentTypes[idx][k].getClass().getName();
if (className.equals("java.io.StringReader")) {
StringReader reader = (StringReader) differentTypes[idx][k];
StringBuilder buf = new StringBuilder();
int c = 0;
while ((c = reader.read()) != -1) {
buf.append((char) c);
}
String asString = this.rs.getString(k + 1);
assertEquals("On row " + idx + ", column " + (k + 1), buf.toString(), asString);
} else if (differentTypes[idx][k] instanceof java.io.InputStream) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] buf = new byte[128];
InputStream in = (InputStream) differentTypes[idx][k];
while ((bytesRead = in.read(buf)) != -1) {
bOut.write(buf, 0, bytesRead);
}
byte[] expected = bOut.toByteArray();
byte[] actual = this.rs.getBytes(k + 1);
assertEquals("On row " + idx + ", column " + (k + 1), StringUtils.dumpAsHex(expected, expected.length),
StringUtils.dumpAsHex(actual, actual.length));
} else if (differentTypes[idx][k] instanceof byte[]) {
byte[] expected = (byte[]) differentTypes[idx][k];
byte[] actual = this.rs.getBytes(k + 1);
assertEquals("On row " + idx + ", column " + (k + 1), StringUtils.dumpAsHex(expected, expected.length),
StringUtils.dumpAsHex(actual, actual.length));
} else if (differentTypes[idx][k] instanceof Timestamp) {
assertEquals("On row " + idx + ", column " + (k + 1), sdf.format(differentTypes[idx][k]), sdf.format(this.rs.getObject(k + 1)));
} else if (differentTypes[idx][k] instanceof Double) {
assertEquals("On row " + idx + ", column " + (k + 1), ((Double) differentTypes[idx][k]).doubleValue(), this.rs.getDouble(k + 1),
.1);
} else if (differentTypes[idx][k] instanceof Float) {
assertEquals("On row " + idx + ", column " + (k + 1), ((Float) differentTypes[idx][k]).floatValue(), this.rs.getFloat(k + 1), .1);
} else if (className.equals("java.lang.Byte")) {
// special mapping in JDBC for ResultSet.getObject()
assertEquals("On row " + idx + ", column " + (k + 1), new Integer(((Byte) differentTypes[idx][k]).byteValue()),
this.rs.getObject(k + 1));
} else if (className.equals("java.lang.Short")) {
// special mapping in JDBC for ResultSet.getObject()
assertEquals("On row " + idx + ", column " + (k + 1), new Integer(((Short) differentTypes[idx][k]).shortValue()),
this.rs.getObject(k + 1));
} else {
assertEquals("On row " + idx + ", column " + (k + 1) + " (" + differentTypes[idx][k].getClass() + "/"
+ this.rs.getObject(k + 1).getClass(), differentTypes[idx][k].toString(), this.rs.getObject(k + 1).toString());
}
}
}
idx++;
}
}
}
public void testBatchRewriteErrors() throws Exception {
createTable("rewriteErrors", "(field1 int not null primary key) ENGINE=MyISAM");
Properties props = new Properties();
Connection multiConn = null;
for (int j = 0; j < 2; j++) {
props.setProperty("useServerPrepStmts", "false");
if (j == 1) {
props.setProperty("continueBatchOnError", "false");
} else {
props.setProperty("continueBatchOnError", "true");
}
props.setProperty("maxAllowedPacket", "4096");
props.setProperty("rewriteBatchedStatements", "true");
multiConn = getConnectionWithProps(props);
this.pstmt = multiConn.prepareStatement("INSERT INTO rewriteErrors VALUES (?)");
Statement multiStmt = multiConn.createStatement();
for (int i = 0; i < 4096; i++) {
multiStmt.addBatch("INSERT INTO rewriteErrors VALUES (" + i + ")");
this.pstmt.setInt(1, i);
this.pstmt.addBatch();
}
multiStmt.addBatch("INSERT INTO rewriteErrors VALUES (2048)");
this.pstmt.setInt(1, 2048);
this.pstmt.addBatch();
try {
this.pstmt.executeBatch();
} catch (BatchUpdateException bUpE) {
int[] counts = bUpE.getUpdateCounts();
for (int i = 4059; i < counts.length; i++) {
assertEquals(counts[i], Statement.EXECUTE_FAILED);
}
// this depends on max_allowed_packet, only a sanity check
assertTrue(getRowCount("rewriteErrors") >= 4000);
}
this.stmt.execute("TRUNCATE TABLE rewriteErrors");
try {
multiStmt.executeBatch();
} catch (BatchUpdateException bUpE) {
int[] counts = bUpE.getUpdateCounts();
for (int i = 4094; i < counts.length; i++) {
assertEquals(counts[i], Statement.EXECUTE_FAILED);
}
// this depends on max_allowed_packet, only a sanity check
assertTrue(getRowCount("rewriteErrors") >= 4000);
}
if (versionMeetsMinimum(5, 0)) {
this.stmt.execute("TRUNCATE TABLE rewriteErrors");
createProcedure("sp_rewriteErrors", "(param1 INT)\nBEGIN\nINSERT INTO rewriteErrors VALUES (param1);\nEND");
CallableStatement cStmt = multiConn.prepareCall("{ CALL sp_rewriteErrors(?)}");
for (int i = 0; i < 4096; i++) {
cStmt.setInt(1, i);
cStmt.addBatch();
}
cStmt.setInt(1, 2048);
cStmt.addBatch();
try {
cStmt.executeBatch();
} catch (BatchUpdateException bUpE) {
int[] counts = bUpE.getUpdateCounts();
for (int i = 4093; i < counts.length; i++) {
assertEquals(counts[i], Statement.EXECUTE_FAILED);
}
// this depends on max_allowed_packet, only a sanity check
assertTrue(getRowCount("rewriteErrors") >= 4000);
}
}
}
}
public void testStreamChange() throws Exception {
createTable("testStreamChange", "(field1 varchar(32), field2 int, field3 TEXT, field4 BLOB)");
this.pstmt = this.conn.prepareStatement("INSERT INTO testStreamChange VALUES (?, ?, ?, ?)");
try {
this.pstmt.setString(1, "A");
this.pstmt.setInt(2, 1);
char[] cArray = { 'A', 'B', 'C' };
Reader r = new CharArrayReader(cArray);
this.pstmt.setCharacterStream(3, r, cArray.length);
byte[] bArray = { 'D', 'E', 'F' };
ByteArrayInputStream bais = new ByteArrayInputStream(bArray);
this.pstmt.setBinaryStream(4, bais, bArray.length);
assertEquals(1, this.pstmt.executeUpdate());
this.rs = this.stmt.executeQuery("SELECT field3, field4 from testStreamChange where field1='A'");
this.rs.next();
assertEquals("ABC", this.rs.getString(1));
assertEquals("DEF", this.rs.getString(2));
char[] ucArray = { 'C', 'E', 'S', 'U' };
this.pstmt.setString(1, "CESU");
this.pstmt.setInt(2, 3);
Reader ucReader = new CharArrayReader(ucArray);
this.pstmt.setCharacterStream(3, ucReader, ucArray.length);
this.pstmt.setBinaryStream(4, null, 0);
assertEquals(1, this.pstmt.executeUpdate());
this.rs = this.stmt.executeQuery("SELECT field3, field4 from testStreamChange where field1='CESU'");
this.rs.next();
assertEquals("CESU", this.rs.getString(1));
assertEquals(null, this.rs.getString(2));
} finally {
if (this.rs != null) {
this.rs.close();
this.rs = null;
}
if (this.pstmt != null) {
this.pstmt.close();
this.pstmt = null;
}
}
}
public void testStubbed() throws SQLException {
try {
this.stmt.getResultSetHoldability();
} catch (NotImplemented notImplEx) {
}
}
public void testTruncationOnRead() throws Exception {
this.rs = this.stmt.executeQuery("SELECT '" + Long.MAX_VALUE + "'");
this.rs.next();
try {
this.rs.getByte(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getShort(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getInt(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
this.rs = this.stmt.executeQuery("SELECT '" + Double.MAX_VALUE + "'");
this.rs.next();
try {
this.rs.getByte(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getShort(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getInt(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getLong(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getLong(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
PreparedStatement pStmt = null;
System.out.println("Testing prepared statements with binary result sets now");
try {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testTruncationOnRead");
this.stmt.executeUpdate("CREATE TABLE testTruncationOnRead(intField INTEGER, bigintField BIGINT, doubleField DOUBLE)");
this.stmt.executeUpdate("INSERT INTO testTruncationOnRead VALUES (" + Integer.MAX_VALUE + ", " + Long.MAX_VALUE + ", " + Double.MAX_VALUE + ")");
this.stmt.executeUpdate("INSERT INTO testTruncationOnRead VALUES (" + Integer.MIN_VALUE + ", " + Long.MIN_VALUE + ", " + Double.MIN_VALUE + ")");
pStmt = this.conn.prepareStatement("SELECT intField, bigintField, doubleField FROM testTruncationOnRead ORDER BY intField DESC");
this.rs = pStmt.executeQuery();
this.rs.next();
try {
this.rs.getByte(1);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getInt(2);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
try {
this.rs.getLong(3);
fail("Should've thrown an out-of-range exception");
} catch (SQLException sqlEx) {
assertTrue(SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE.equals(sqlEx.getSQLState()));
}
} finally {
this.stmt.executeUpdate("DROP TABLE IF EXISTS testTruncationOnRead");
}
}
public void testStatementInterceptors() throws Exception {
Connection interceptedConn = null;
/*
* try {
* Properties props = new Properties();
* props.setProperty("statementInterceptors", "com.mysql.jdbc.interceptors.ResultSetScannerInterceptor");
* props.setProperty("resultSetScannerRegex", ".*");
* interceptedConn = getConnectionWithProps(props);
* this.rs = interceptedConn.createStatement().executeQuery("SELECT 'abc'");
* this.rs.next();
* this.rs.getString(1);
* } finally {
* closeMemberJDBCResources();
*
* if (interceptedConn != null) {
* interceptedConn.close();
* }
* }
*/
try {
Properties props = new Properties();
props.setProperty("statementInterceptors", ServerStatusDiffInterceptor.class.getName());
interceptedConn = getConnectionWithProps(props);
this.rs = interceptedConn.createStatement().executeQuery("SELECT 'abc'");
} finally {
if (interceptedConn != null) {
interceptedConn.close();
}
}
}
public void testParameterBindings() throws Exception {
// Need to check character set stuff, so need a new connection
Connection utfConn = getConnectionWithProps("characterEncoding=utf-8,treatUtilDateAsTimestamp=false,autoDeserialize=true");
java.util.Date now = new java.util.Date();
Object[] valuesToTest = new Object[] { new Byte(Byte.MIN_VALUE), new Short(Short.MIN_VALUE), new Integer(Integer.MIN_VALUE), new Long(Long.MIN_VALUE),
new Double(Double.MIN_VALUE), "\u4E2D\u6587", new BigDecimal(Math.PI), null, // to test isNull
now // to test serialization
};
StringBuilder statementText = new StringBuilder("SELECT ?");
for (int i = 1; i < valuesToTest.length; i++) {
statementText.append(",?");
}
this.pstmt = utfConn.prepareStatement(statementText.toString());
for (int i = 0; i < valuesToTest.length; i++) {
this.pstmt.setObject(i + 1, valuesToTest[i]);
}
ParameterBindings bindings = ((com.mysql.jdbc.PreparedStatement) this.pstmt).getParameterBindings();
for (int i = 0; i < valuesToTest.length; i++) {
Object boundObject = bindings.getObject(i + 1);
if (boundObject == null || valuesToTest[i] == null) {
continue;
}
Class<?> boundObjectClass = boundObject.getClass();
Class<?> testObjectClass = valuesToTest[i].getClass();
if (boundObject instanceof Number) {
assertEquals("For binding #" + (i + 1) + " of class " + boundObjectClass + " compared to " + testObjectClass, boundObject.toString(),
valuesToTest[i].toString());
} else if (boundObject instanceof Date) {
} else {
assertEquals("For binding #" + (i + 1) + " of class " + boundObjectClass + " compared to " + testObjectClass, boundObject, valuesToTest[i]);
}
}
}
public void testLocalInfileHooked() throws Exception {
createTable("localInfileHooked", "(field1 int, field2 varchar(255))");
String streamData = "1\tabcd\n2\tefgh\n3\tijkl";
InputStream stream = new ByteArrayInputStream(streamData.getBytes());
try {
((com.mysql.jdbc.Statement) this.stmt).setLocalInfileInputStream(stream);
this.stmt.execute("LOAD DATA LOCAL INFILE 'bogusFileName' INTO TABLE localInfileHooked CHARACTER SET "
+ CharsetMapping.getMysqlCharsetForJavaEncoding(((MySQLConnection) this.conn).getEncoding(), (com.mysql.jdbc.Connection) this.conn));
assertEquals(-1, stream.read());
this.rs = this.stmt.executeQuery("SELECT field2 FROM localInfileHooked ORDER BY field1 ASC");
this.rs.next();
assertEquals("abcd", this.rs.getString(1));
this.rs.next();
assertEquals("efgh", this.rs.getString(1));
this.rs.next();
assertEquals("ijkl", this.rs.getString(1));
} finally {
((com.mysql.jdbc.Statement) this.stmt).setLocalInfileInputStream(null);
}
}
}