File: BlobClob4BlobTest.java

package info (click to toggle)
derby 10.14.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 78,896 kB
  • sloc: java: 691,930; sql: 42,686; xml: 20,511; sh: 3,373; sed: 96; makefile: 60
file content (3706 lines) | stat: -rw-r--r-- 133,335 bytes parent folder | download | duplicates (4)
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
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
/*
 *
 * Derby - Class BlobClob4BlobTest
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.apache.derbyTesting.functionTests.tests.jdbcapi;

import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.CRC32;
import junit.framework.Test;
import org.apache.derbyTesting.functionTests.util.Formatters;
import org.apache.derbyTesting.functionTests.util.streams.ByteAlphabet;
import org.apache.derbyTesting.functionTests.util.streams.CharAlphabet;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.Decorator;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;
import org.apache.derbyTesting.junit.Utilities;

/**
 * Test of JDBC blob and clob
 */
public class BlobClob4BlobTest extends BaseJDBCTestCase {

    /** Creates a new instance of BlobClob4BlobTest */
    public BlobClob4BlobTest(String name) {
        super(name);
    }

    /**
     * Set up the conection to the database.
     */
    public void setUp() throws  Exception {
        getConnection().setAutoCommit(false);

        // creating small tables then add large column - that way forcing table
        // to have default small page size, but have large rows.

        Statement stmt = createStatement();
        stmt.executeUpdate("CREATE TABLE testClob (b INT, c INT)");
        stmt.executeUpdate("ALTER TABLE testClob ADD COLUMN a CLOB(300K)");

        // multiple tests depend on small page size, make sure size is 4k
        checkSmallPageSize(stmt, "TESTCLOB");

        stmt.executeUpdate("CREATE TABLE testBlob (b INT)");
        stmt.executeUpdate("ALTER TABLE testBlob ADD COLUMN a blob(300k)");
        stmt.executeUpdate("ALTER TABLE testBlob ADD COLUMN crc32 BIGINT");

        // multiple tests depend on small page size, make sure size is 4k
        checkSmallPageSize(stmt, "TESTBLOB");

        stmt.close();
        commit();
    }

    protected void tearDown() throws Exception {
        rollback();
        Statement stmt = createStatement();
        stmt.executeUpdate("DROP TABLE testClob");
        stmt.executeUpdate("DROP TABLE testBlob");
        stmt.close();
        commit();
        super.tearDown();
    }

    /***                TESTS               ***/

    /**
     * DERBY-3085.  Test update where streamed parameter is not 
     * consumed by the server. Network Server needs to clean-up 
     * after execution.
     * 
     */
    public void testUnconsumedParameter() throws SQLException
    {
        Connection conn = getConnection();
        conn.setAutoCommit(false);
        Statement s = conn.createStatement();
        // Test table with no rows.
        s.executeUpdate("create table testing(num int, addr varchar(40), contents blob(16M))");
        // no rows inserted so there is no match.
        byte[] data = new byte[ 38000];
        for (int i = 0; i < data.length; i++)
            data[i] = 'a';
        ByteArrayInputStream is = new ByteArrayInputStream( data);           
        String sql = "UPDATE testing SET Contents=? WHERE num=1";
        
        PreparedStatement ps = prepareStatement( sql);
        ps.setBinaryStream( 1, is,data.length);
        //DERBY-4312 Make sure commit() doesn't interfere here
        commit();
        ps.executeUpdate();          
        // Make sure things still work ok when we have a parameter that does get consumed.
        // insert a matching row.
        s.executeUpdate("insert into testing values (1,null,null)");
        is = new ByteArrayInputStream(data);
        ps.setBinaryStream( 1, is,data.length);
        ps.executeUpdate();
        // Check update occurred
        ResultSet rs = s.executeQuery("select length(contents) from testing where num = 1");
        JDBC.assertSingleValueResultSet(rs, "38000");
        ps.close();
        conn.commit();
        // Check the case where there are rows inserted but there is no match.
        is = new ByteArrayInputStream( data);           
        sql = "UPDATE testing SET Contents=? WHERE num=2";
        ps = prepareStatement( sql);
        ps.setBinaryStream( 1, is,data.length);
        ps.executeUpdate();
        ps.close();
        s.executeUpdate("drop table testing");
        conn.commit();
        
        // Test with multiple parameters
        s.executeUpdate("create table testing(num int, addr varchar(40), contents blob(16M),contents2 blob(16M))");
        
        is = new ByteArrayInputStream( data);
        ByteArrayInputStream is2 = new ByteArrayInputStream(data);
        sql = "UPDATE testing SET Contents=?, contents2=?  WHERE num=1";

        ps = prepareStatement( sql);
        ps.setBinaryStream( 1, is,data.length);
        ps.setBinaryStream(2, is2,data.length);
        ps.executeUpdate();
        
        
        // multiple parameters and matching row
        s.executeUpdate("insert into testing values (1,'addr',NULL,NULL)");
        is = new ByteArrayInputStream( data);
        is2 = new ByteArrayInputStream(data);
        ps.setBinaryStream( 1, is,data.length);
        ps.setBinaryStream(2, is2,data.length);
        ps.executeUpdate();
        rs = s.executeQuery("select length(contents), length(contents2) from testing where num = 1");
        JDBC.assertFullResultSet(rs, new String[][] {{"38000","38000"}});
        rs.close();
        s.executeUpdate("drop table testing");
        
        // With Clob
        s.executeUpdate("create table testing(num int, addr varchar(40), contents Clob(16M))");
        char[] charData = new char[ 38000];
        for (int i = 0; i < data.length; i++)
       data[i] = 'a';
        CharArrayReader reader = new CharArrayReader( charData);            
        sql = "UPDATE testing SET Contents=? WHERE num=1";

       ps = prepareStatement( sql);
       ps.setCharacterStream( 1, reader,charData.length);
       ps.executeUpdate();
       // with a matching row
       s.executeUpdate("insert into testing values (1,null,null)");
       reader = new CharArrayReader(charData);
       ps.setCharacterStream( 1, reader,data.length);
       ps.executeUpdate();
       // Check update occurred
       rs = s.executeQuery("select length(contents) from testing where num = 1");
       JDBC.assertSingleValueResultSet(rs, "38000");
       s.executeUpdate("drop table testing");
       ps.close();
       
       conn.commit();
        
    }

    /**
     * Test that it is possible to change the isolation level after reading a
     * BLOB (DERBY-3427).
     */
    public void testIsolationLevelChangeAfterRead() throws SQLException {
        ResultSet rs =
            createStatement().executeQuery("VALUES CAST(X'FFFF' AS BLOB)");
        JDBC.assertDrainResults(rs);
        getConnection().setTransactionIsolation(
            Connection.TRANSACTION_SERIALIZABLE);
    }

    /**
     * Tests PreparedStatement.setCharacterStream
     */
    public void testSetCharacterStream() throws Exception {
        int clobLength = 5009;

        // insert a streaming column
        PreparedStatement ps = prepareStatement(
                "insert into testClob (a) values(?)");
        Reader streamReader = new LoopingAlphabetReader(
                clobLength, CharAlphabet.tamil());
        ps.setCharacterStream(1, streamReader, clobLength);
        //DERBY-4312 make sure commit() doesn't interfere
        commit();
        ps.executeUpdate();
        streamReader.close();
        ps.close();
        commit();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("SELECT a FROM testClob");
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            assertEquals("FAIL - wrong clob length", clobLength, clob.length());
            Reader clobValue = clob.getCharacterStream();
            Reader origValue = new LoopingAlphabetReader(
                    clobLength, CharAlphabet.tamil());

            assertTrue("New clob value did not match",
                    compareReaders(origValue, clobValue));
            origValue.close();
            clobValue.close();
        }
        rs.close();
        stmt.close();

        commit();

    }

    /**
     *  basic test of getAsciiStream also tests length
     */
    public void testGetAsciiStream() throws Exception {
        byte[] buff = new byte[1024];

        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("SELECT a, b FROM testClob");

        // fetch row back, get the column as a clob.
        Clob clob;
        int clobLength;
        while (rs.next()) {
            // get the first column in select as a clob
            clob = rs.getClob(1);
            clobLength = rs.getInt(2);

            if (clob != null) {
                assertEquals("FAIL - wrong clob.length()",
                        clobLength, clob.length());

                InputStream fin = clob.getAsciiStream();
                int columnSize = 0;
                int size = -1;
                do {
                    size = fin.read(buff);
                    columnSize += (size > 0) ? size : 0;
                } while (size >= 0);

                assertEquals("FAIL - wrong column size",
                        clobLength, columnSize);
            } else {
                assertTrue("Clob was null but length was not 0",
                        (clobLength == 0));
            }
        }
        rs.close();
        stmt.close();

        commit();
    }

    /**
     * basic test of getCharacterStream also tests length
     */
    public void testGetCharacterStream() throws Exception {

        char[] buff = new char[128];

        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a , b from testClob");
        ResultSetMetaData met = rs.getMetaData();

        // fetch row back, get the column as a clob.
        int clobLength = 0;
        while (rs.next()) {
            // get the first column as a clob
            Clob clob = rs.getClob(1);
            clobLength = rs.getInt(2);
            if (clob != null) {
                assertEquals("FAIL - wrong clob.length()",
                        clobLength, clob.length());

                Reader reader = clob.getCharacterStream();
                int columnSize = 0;
                int size = -1;
                do {
                    size = reader.read(buff);
                    columnSize += (size >= 0) ? size : 0;
                } while (size >= 0);

                assertEquals("FAIL - wrong column size",
                        clobLength, columnSize);
            } else {
                assertTrue("Clob was null but length was not 0",
                        (clobLength == 0));
            }
        }
        rs.close();
        stmt.close();

        commit();
    }

    /**
     * test of getCharacterStream on a table containing unicode characters
     */
    public void testGetCharacterStreamWithUnicode() throws Exception {
        String[] unicodeStrings = {
            "\u0061\u0062\u0063",
            "\u0370\u0371\u0372",
            "\u05d0\u05d1\u05d2"};
        insertUnicodeData(unicodeStrings);

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM testClob");

        int clobLength = 0, arrayIndex = 0;
        while (rs.next()) {
            clobLength = rs.getInt(2);
            arrayIndex = rs.getInt(3);
            Clob clob = rs.getClob(1);
            if (clob != null) {
                assertEquals("FAIL - wrong clob.length()",
                        clobLength, clob.length());

                Reader clobValue = clob.getCharacterStream();
                if (arrayIndex > 0) {
                    char[] buff = new char[3];
                    clobValue.read(buff);
                    assertEquals("Clob value does not match unicodeString",
                            unicodeStrings[arrayIndex],
                            new String(buff));
                    assertEquals("Expected end of stream",
                            -1, clobValue.read());
                } else {
                    Reader origValue = new LoopingAlphabetReader(
                            clobLength, CharAlphabet.tamil());
                    compareReaders(origValue, clobValue);
                }
            } else {
                assertTrue("Clob was null but length was not 0",
                        (clobLength == 0));
            }
        }
        rs.close();
        stmt.close();

        commit();
    }

    /**
     * Test triggers on CLOB columns.
     */
    public void baseTestTriggersWithClobColumn(boolean useOrderBy) 
        throws Exception {

        insertDefaultData();

        Statement stmt = createStatement();
        stmt.executeUpdate(
                "CREATE TABLE testClobTriggerA (a CLOB(400k), b int)");
        stmt.executeUpdate(
                "CREATE TABLE testClobTriggerB (a CLOB(400k), b int)");
        stmt.executeUpdate(
                "create trigger T13A after update on testClob " +
                "referencing new as n old as o " +
                "for each row "+
                "insert into testClobTriggerA(a, b) values (n.a, n.b)");
        stmt.executeUpdate(
                "create trigger T13B after INSERT on testClobTriggerA " +
                "referencing new table as n " +
                "for each statement "+
                "insert into testClobTriggerB(a, b) select n.a, n.b from n");

        commit();

        // Fire the triggers
        stmt.executeUpdate("UPDATE testClob SET b = b + 0");
        commit();

        // Verify the results
        Statement origSt = createStatement();
        Statement trigASt = createStatement();
        Statement trigBSt = createStatement();

        ResultSet origRS  = null;
        ResultSet trigARS = null;
        ResultSet trigBRS = null;

        if (useOrderBy) {
            origRS = 
                origSt.executeQuery(
                    "select a, length(a), b  from testClob order by b");
            trigARS = 
                trigASt.executeQuery(
                    "select a, length(a), b from testClobTriggerA order by b");
            trigBRS = 
                trigBSt.executeQuery(
                    "select a, length(a), b from testClobTriggerB order by b");

        } else {
            origRS = 
                origSt.executeQuery(
                        "select a, length(a), b  from testClob");
            trigARS = 
                trigASt.executeQuery(
                        "select a, length(a), b from testClobTriggerA");
            trigBRS = 
                trigBSt.executeQuery(
                        "select a, length(a), b from testClobTriggerB");
        }

        int count = 0;
        while (origRS.next()) {
            count ++;
            assertTrue("row trigger produced less rows " +
                    count, trigARS.next());
            assertTrue("statement trigger produced less rows " +
                    count, trigBRS.next());

            Clob origClob = origRS.getClob(1);
            if (origClob != null) {
                assertEquals("FAIL - Invalid checksum for row trigger",
                        getStreamCheckSum(origClob.getAsciiStream()),
                        getStreamCheckSum(trigARS.getClob(1).getAsciiStream()));
                assertEquals("FAIL - Invalid checksum for statement trigger",
                        getStreamCheckSum(origClob.getAsciiStream()),
                        getStreamCheckSum(trigBRS.getClob(1).getAsciiStream()));
            }

            assertEquals("FAIL - Invalid length in row trigger",
                    origRS.getInt(2), trigARS.getInt(2));
            assertEquals("FAIL - Invalid length in statement trigger",
                    origRS.getInt(2), trigBRS.getInt(2));

            assertEquals("FAIL - Length not updated on row trigger",
                    origRS.getInt(3), trigARS.getInt(3));
            assertEquals("FAIL - Length not updated on statement trigger",
                    origRS.getInt(3), trigBRS.getInt(3));
        }

        origRS.close();
        trigARS.close();
        trigBRS.close();
        origSt.close();
        trigASt.close();
        trigBSt.close();

        stmt.executeUpdate("DROP TRIGGER T13A");
        stmt.executeUpdate("DROP TRIGGER T13B");
        stmt.executeUpdate("DROP TABLE testClobTriggerB");
        stmt.executeUpdate("DROP TABLE testClobTriggerA");

        stmt.close();
        commit();
    }

    /**
     * Test triggers on CLOB columns.
     * <p>
     * Call with order by in the query, this causes a path through the
     * sorter.
     **/
    public void testTriggersWithClobColumnOrderBy() 
        throws Exception {

        baseTestTriggersWithClobColumn(true);
    }

    /**
     * Test triggers on CLOB columns.
     * <p>
     * Call with no order by in the query, thus a code path not through
     * the sorter.
     **/
    public void testTriggersWithClobColumn() 
        throws Exception {

        baseTestTriggersWithClobColumn(false);
    }


    /**
     * test Clob.getSubString() method
     */
    public void testGetSubString() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");
        int clobLength = 0;
        Clob clob;
        while (rs.next()) {
            clob = rs.getClob(1);
            if (clob == null)
                continue;
            clobLength = rs.getInt(2);
            verifyInterval(clob, 9905, 50, 0, clobLength);
            verifyInterval(clob, 5910, 150, 1, clobLength);
            verifyInterval(clob, 5910, 50, 2, clobLength);
            verifyInterval(clob, 204, 50, 3, clobLength);
            verifyInterval(clob, 68, 50, 4, clobLength);
            verifyInterval(clob, 1, 50, 5, clobLength);
            verifyInterval(clob, 1, 1, 6, clobLength);
            verifyInterval(clob, 1, 0, 7, clobLength); // length 0 at start
            verifyInterval(clob, clobLength + 1, 0, 8, clobLength); // and end
            if (clobLength > 100) {
                String res = clob.getSubString(clobLength-99,200);
                assertEquals("FAIL - wrong length of substring",
                        100, res.length());
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * test getSubString with unicode
     */
    public void testGetSubStringWithUnicode() throws Exception {
        String[] unicodeStrings = {
            "\u0061\u0062\u0063",
            "\u0370\u0371\u0372",
            "\u05d0\u05d1\u05d2"};
        insertUnicodeData(unicodeStrings);

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b, c from testClob");
        int clobLength = 0, arrayIndex = 0;
        Clob clob;
        while (rs.next()) {
            clob = rs.getClob(1);
            clobLength = rs.getInt(2);
            arrayIndex = rs.getInt(3);
            if (clob != null) {
                if (arrayIndex >= 0) {
                    assertEquals("FAIL - wrong substring returned",
                            unicodeStrings[arrayIndex],
                            clob.getSubString(1, 3));
                } else {
                    if (clob.length() > 0) {
                        long charsToRead = Math.min((clob.length() / 3), 2048);
                        char[] charValue = new char[(int)charsToRead];
                        Reader clobReader = clob.getCharacterStream();
                        clobReader.read(charValue);
                        clobReader.read(charValue);
                        String subString = clob.getSubString(charsToRead + 1,
                                (int)charsToRead);
                        assertEquals("FAIL - wrong substring length",
                                charValue.length, subString.length());
                        for (int i=0; i< charValue.length; i++) {
                            assertEquals("FAIL - wrong substring returned at " +
                                    i, charValue[i], subString.charAt(i));
                        }
                    }
                }
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * test position with a String argument
     */
    public void testPositionString() throws Exception {
        insertDefaultData();

        runPositionStringTest();
    }

    /**
     * test position with a String argument and unicode data.
     */
    public void testPositionStringWithUnicode() throws Exception {
        String[] unicodeStrings = {
            "\u0061\u0062\u0063",
            "\u0370\u0371\u0372",
            "\u05d0\u05d1\u05d2"};
        insertUnicodeData(unicodeStrings);

        runPositionStringTest();
    }

    private void runPositionStringTest() throws Exception {
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");
        int clobLength = 0;
        Clob clob;
        Random random = new Random();
        String searchString;
        int start, length, startSearchPos;
        int distance, maxStartPointDistance;
        long foundAt;
        // clobs are generated with looping alphabet streams
        maxStartPointDistance = CharAlphabet.MODERNLATINLOWER.length;
        while (rs.next()) {
            clob = rs.getClob(1);
            clobLength = rs.getInt(2);
            if (clob != null && clobLength > 0) {
                println("\n\nclobLength: " + clobLength);
                for (int i=0; i<10; i++) {
                    // find a random string to search for
                    start = Math.max(random.nextInt(clobLength - 1), 1);
                    length = random.nextInt(clobLength - start) + 1;
                    println("start:" + start + " length:" + length);
                    searchString = clob.getSubString(start, length);
                    // get random position to start the search from
                    distance = random.nextInt(maxStartPointDistance);
                    startSearchPos = Math.max((start - distance), 1);
                    // make sure that the searched string does not happen
                    // before the expected position
                    String tmp = clob.getSubString(startSearchPos, start);
                    if (tmp.indexOf(searchString) != -1) {
                        startSearchPos = start;
                    }
                    println("startSearchPos: " + startSearchPos +
                            "searchString: " + searchString);
                    foundAt = clob.position(searchString, startSearchPos);
                    assertEquals("FAIL - wrong match found for " +
                            searchString + " start at " + startSearchPos +
                            " with length " + searchString.length(),
                            start, foundAt);
                }
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * test position with a Clob argument
     */
    public void testPositionClob() throws Exception {
        insertDefaultData();

        runPositionClobTest();
    }

    /**
     * test position with a Clob argument containing unicode characters
     */
    public void testPositionClobWithUnicode() throws Exception {
        String[] unicodeStrings = {
            "\u0061\u0062\u0063",
            "\u0370\u0371\u0372",
            "\u05d0\u05d1\u05d2"};
        insertUnicodeData(unicodeStrings);

        runPositionClobTest();
    }

    private void runPositionClobTest() throws Exception {
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");
        int clobLength = 0;
        Clob clob;
        Statement stmt2 = createStatement();
        Random random = new Random();
        String searchString;
        int start, length, startSearchPos;
        int distance, maxStartPointDistance;
        long foundAt;
        // clobs are generated with looping alphabet streams
        maxStartPointDistance = CharAlphabet.MODERNLATINLOWER.length;
        while (rs.next()) {
            clob = rs.getClob(1);
            clobLength = rs.getInt(2);
            if (clob != null && clobLength > 0) {
                println("\n\nclobLength: " + clobLength);
                // Create a table with clobs to search
                stmt2.executeUpdate("CREATE TABLE searchClob " +
                        "(a clob(300K), start int, position int)");
                // insert clobs into the table
                PreparedStatement ps = prepareStatement(
                        "INSERT INTO searchClob values (?, ?, ?) ");
                for (int i=0; i<10; i++) {
                    // find a random string to search for
                    start = Math.max(random.nextInt(clobLength - 1), 1);
                    length = random.nextInt(clobLength - start) + 1;
                    println("start:" + start + " length:" + length);
                    searchString = clob.getSubString(start, length);
                    // get random position to start the search from
                    distance = random.nextInt(maxStartPointDistance);
                    startSearchPos = Math.max((start - distance), 1);
                    // make sure that the searched string does not happen
                    // before the expected position
                    String tmp = clob.getSubString(startSearchPos, start);
                    if (tmp.indexOf(searchString) != -1) {
                        startSearchPos = start;
                    }

                    ps.setString(1, searchString);
                    ps.setInt(2, startSearchPos);
                    ps.setInt(3, start);
                    ps.executeUpdate();
                }

                ps.close();

                ResultSet rs2 = stmt2.executeQuery(
                        "SELECT a, start, position FROM searchClob");
                while (rs2.next()) {
                    Clob searchClob = rs2.getClob(1);
                    startSearchPos = rs2.getInt(2);
                    start = rs2.getInt(3);

                    searchString = searchClob.getSubString(1L,
                            (int)searchClob.length());
                    println("startSearchPos: " + startSearchPos +
                            "searchString: " + searchString);
                    foundAt = clob.position(searchClob, startSearchPos);
                    assertEquals("FAIL - wrong match found for " +
                            searchString + " starting at " + startSearchPos +
                            " with length " + searchString.length(),
                            start, foundAt);
                }
                rs2.close();
                stmt2.executeUpdate("DROP TABLE searchClob");
            }
        }
        rs.close();
        stmt.close();
        stmt2.close();
    }

    /**
     * make sure clobs work for small CLOB fields also test length method
     */
    public void testSmallClobFields() throws Exception {
        Statement stmt = createStatement();
        stmt.executeUpdate(
                "ALTER TABLE testClob ADD COLUMN smallClob CLOB(10)");

        PreparedStatement ps = prepareStatement(
                "insert into testClob (smallClob) values(?)");
        String val = "";
        for (int i = 0; i < 10; i++) {
            // insert a string
            ps.setString(1, val);
            ps.executeUpdate();
            val += "x";
        }

        ResultSet rs = stmt.executeQuery("select a from testClob");
        byte[] buff = new byte[128];
        int j = 0;
        // fetch all rows back, get the columns as clobs.
        while (rs.next()) {
            // get the first column as a clob
            Clob clob = rs.getClob(1);
            if (clob != null) {
                InputStream fin = clob.getAsciiStream();
                int columnSize = 0, size = 0;
                do
                {
                    size = fin.read(buff);
                    columnSize += (size > 0) ? size : 0;
                } while (size != -1);
                assertEquals("FAIL - wrong clob size", j, columnSize);
                assertEquals("FAIL - wrong clob length", j, clob.length());
                j++;
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * make sure cannot get a clob from an int column
     */
    public void testGetClobFromIntColumn() throws Exception{

        insertDefaultData();

        Statement stmt = createStatement();

        ResultSet rs = stmt.executeQuery("select b from testClob");
        while (rs.next()) {
            try {
                Clob clob = rs.getClob(1);

                rs.close(); // Cleanup on fail
                stmt.close();

                fail("FAIL - getClob on column type int should throw " +
                        "an exception");
            } catch (SQLException se) {
                checkException(LANG_DATA_TYPE_GET_MISMATCH, se);
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * make sure setClob doesn't work on an int column
     */
    public void testSetClobToIntColumn() throws Exception {
        insertDefaultData();

        PreparedStatement ps = prepareStatement(
                "insert into testClob (b, c) values (?, ?)");
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");
        Clob clob;
        int clobLength;
        while (rs.next()) {
            // get the first ncolumn as a clob
            clob = rs.getClob(1);
            clobLength = rs.getInt(2);
            if (clob != null) {
                try {
                    ps.setClob(1,clob);
                    ps.setInt(2, clobLength);
                    ps.executeUpdate();

                    rs.close(); // Cleanup on fail
                    stmt.close();

                    fail("FAIL - can not use setClob on int column");
                } catch (SQLException se) {
                    checkException(LANG_DATA_TYPE_GET_MISMATCH, se);
                }
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * test raising of exceptions
     */
    public void testRaisingOfExceptionsClob() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery(
                "select a, b from testClob WHERE a is not NULL");
        int i = 0, clobLength = 0;
        Clob clob;
        rs.next();
        clob = rs.getClob(1);
        clobLength = rs.getInt(2);
        rs.close();
        assertFalse("FAIL - clob can not be null", clob == null);

        // 0 or negative position value
        try {
            clob.getSubString(0,5);
            fail("FAIL - getSubString with 0 as position should have " +
                    "caused an exception");
        } catch (SQLException e) {
            checkException(BLOB_BAD_POSITION, e);
        }

        // negative length value
        try {
            clob.getSubString(1,-76);
            fail("FAIL - getSubString with negative length should have " +
                    "caused an exception");
        } catch (SQLException e) {
            checkException(BLOB_NONPOSITIVE_LENGTH, e);
        }
        // boundary negative 1 length
        try {
            clob.getSubString(1,-1);
            fail("FAIL - getSubString with negative length should have " +
                    "caused an exception");
        } catch (SQLException e) {
            checkException(BLOB_NONPOSITIVE_LENGTH, e);
        }
        // before start with length zero
        try {
            clob.getSubString(0,0);
            fail("FAIL - getSubString with 0 as position should have " +
                    "caused an exception");
        } catch (SQLException e) {
            checkException(BLOB_BAD_POSITION, e);
        }
        // 2 past end with length 0
        try {
            clob.getSubString(clobLength + 2,0);
            fail("FAIL - getSubString with position bigger than clob " +
                    "should have caused an exception");
        }  catch (SQLException e) {
            checkException(BLOB_POSITION_TOO_LARGE, e);
        }
        // 0 or negative position value
        try {
            clob.position("xx",-4000);
            fail("FAIL - position with negative as position should " +
                    "have caused an exception");
        } catch (SQLException e) {
            checkException(BLOB_BAD_POSITION, e);
        }
        // null pattern
        try {
            clob.position((String) null,5);
            fail("FAIL = position((String) null,5)");
        } catch (SQLException e) {
            checkException(BLOB_NULL_PATTERN_OR_SEARCH_STR, e);
        }
        // 0 or negative position value
        try {
            clob.position(clob,-42);
            fail("FAIL = position(clob,-42)");
        } catch (SQLException e) {
            checkException(BLOB_BAD_POSITION, e);
        }
        // null pattern
        try {
            clob.position((Clob) null,5);
            fail("FAIL = pposition((Clob) null,5)");
        } catch (SQLException e) {
            checkException(BLOB_NULL_PATTERN_OR_SEARCH_STR, e);
        }
    }

    /**
     * test setClob
     */
    public void testSetClob() throws Exception {
        insertDefaultData();
        ResultSet rs, rs2;
        Statement stmt = createStatement();
        stmt.execute("create table testSetClob (a CLOB(300k), b integer)");
        PreparedStatement ps = prepareStatement(
                "insert into testSetClob values(?,?)");
        rs = stmt.executeQuery("select a, b from testClob");
        Clob clob;
        int clobLength;
        while (rs.next()) {
            // get the first column as a clob
            clob = rs.getClob(1);
            clobLength = rs.getInt(2);
            if (clob != null && clobLength != 0) {
                ps.setClob(1,clob);
                ps.setInt(2,clobLength);
                ps.executeUpdate();
            }
        }
        rs.close();

        rs = stmt.executeQuery("select a, b from testSetClob");
        Clob clob2;
        int clobLength2, nullClobs = 0;
        while (rs.next()) {
            clob2 = rs.getClob(1);
            clobLength2 = rs.getInt(2);
            assertFalse("FAIL - Clob is NULL", clob2 == null);
            assertEquals("FAIL - clob.length() != clobLength",
                    clobLength2, clob2.length());
        }
        rs.close();
        stmt.executeUpdate("DROP TABLE testSetClob");
        stmt.close();
    }

    /**
     * Test Clob.position()
     */
    public void testPositionAgressiveUseOrderBy() 
        throws Exception {
            baseTestPositionAgressive(true);
    }
    public void testPositionAgressiveDoNotUseOrderBy() 
        throws Exception {
            baseTestPositionAgressive(false);
    }

    public void baseTestPositionAgressive(boolean useOrderBy) 
        throws Exception {
        Statement s = createStatement();

        s.execute("CREATE TABLE C8.T8POS" +
                "(id INT NOT NULL PRIMARY KEY, DD CLOB(1m), pos INT, L INT)");
        s.execute("CREATE TABLE C8.T8PATT(PATT CLOB(300k))");

        // characters used to fill the String
        char[] fill = new char[4];
        fill[0] = 'd';          // 1 byte UTF8 character (ASCII)
        fill[1] = '\u03a9';     // 2 byte UTF8 character (Greek)
        fill[2] = '\u0e14';     // 3 byte UTF8 character (Thai)
        fill[3] = 'j';          // 1 byte UTF8 character (ASCII)

        char[] base = new char[256 * 1024];

        for (int i = 0; i < base.length; i += 4) {

            base[i] = fill[0];
            base[i+1] = fill[1];
            base[i+2] = fill[2];
            base[i+3] = fill[3];

        }

        char[]  patternBase = new char[2 * 1024];
        for (int i = 0; i < patternBase.length; i += 8) {

            patternBase[i] = 'p';
            patternBase[i+1] = 'a';
            patternBase[i+2] = 't';
            patternBase[i+3] = '\u03aa';
            patternBase[i+4] = (char) i;// changed value to keep pattern varying
            patternBase[i+5] = 'b';
            patternBase[i+6] = 'm';
            patternBase[i+7] = '\u0e15';

        }

        PreparedStatement ps = prepareStatement(
                "INSERT INTO C8.T8POS VALUES (?, ?, ?, ?)");
        PreparedStatement psp = prepareStatement(
                "INSERT INTO C8.T8PATT VALUES (?)");

        T8insert(ps, 1, base, 256, patternBase, 8, 100, true);
        T8insert(ps, 2, base, 3988, patternBase, 8, 2045, true);
        T8insert(ps, 3, base, 16321, patternBase, 8, 4566, true);
        T8insert(ps, 4, base, 45662, patternBase, 8, 34555, true);
        T8insert(ps, 5, base, 134752, patternBase, 8, 67889, true);
        T8insert(ps, 6, base, 303, patternBase, 8, 80, false);
        T8insert(ps, 7, base, 4566, patternBase, 8, 2086, false);
        T8insert(ps, 8, base, 17882, patternBase, 8, 4426, false);
        T8insert(ps, 9, base, 41567, patternBase, 8, 31455, false);
        String pstr =
                T8insert(ps, 10, base, 114732, patternBase, 8, 87809, false);

        commit();

        psp.setString(1, pstr);
        psp.executeUpdate();

        checkClob8(s, pstr, useOrderBy);
        commit();

        ResultSet rsc = s.executeQuery("SELECT PATT FROM C8.T8PATT");
        rsc.next();
        checkClob8(s, rsc.getClob(1), useOrderBy);

        rsc.close();


        commit();

        s.execute("DELETE FROM C8.T8POS");
        s.execute("DELETE FROM C8.T8PATT");


        T8insert(ps, 1, base, 256, patternBase, 134, 100, true);
        T8insert(ps, 2, base, 3988, patternBase, 134, 2045, true);
        T8insert(ps, 3, base, 16321, patternBase, 134, 4566, true);
        T8insert(ps, 4, base, 45662, patternBase, 134, 34555, true);
        T8insert(ps, 5, base, 134752, patternBase, 134, 67889, true);
        T8insert(ps, 6, base, 303, patternBase, 134, 80, false);
        T8insert(ps, 7, base, 4566, patternBase, 134, 2086, false);
        T8insert(ps, 8, base, 17882, patternBase, 134, 4426, false);
        T8insert(ps, 9, base, 41567, patternBase, 134, 31455, false);
        pstr = T8insert(ps, 10, base, 114732, patternBase, 134, 87809, false);

        commit();
        psp.setString(1, pstr);
        psp.executeUpdate();
        commit();


        checkClob8(s, pstr, useOrderBy);
        commit();

        rsc = s.executeQuery("SELECT PATT FROM C8.T8PATT");
        rsc.next();
        checkClob8(s, rsc.getClob(1), useOrderBy);

        s.execute("DELETE FROM C8.T8POS");
        s.execute("DELETE FROM C8.T8PATT");

        T8insert(ps, 1, base, 256, patternBase, 679, 100, true);
        T8insert(ps, 2, base, 3988, patternBase, 679, 2045, true);
        T8insert(ps, 3, base, 16321, patternBase, 679, 4566, true);
        T8insert(ps, 4, base, 45662, patternBase, 679, 34555, true);
        T8insert(ps, 5, base, 134752, patternBase, 679, 67889, true);
        T8insert(ps, 6, base, 303, patternBase, 679, 80, false);
        T8insert(ps, 7, base, 4566, patternBase, 679, 2086, false);
        T8insert(ps, 8, base, 17882, patternBase, 679, 4426, false);
        T8insert(ps, 9, base, 41567, patternBase, 679, 31455, false);
        pstr = T8insert(ps, 10, base, 114732, patternBase, 679, 87809, false);

        commit();
        psp.setString(1, pstr);
        psp.executeUpdate();
        commit();


        checkClob8(s, pstr, useOrderBy);
        commit();

        rsc = s.executeQuery("SELECT PATT FROM C8.T8PATT");
        rsc.next();
        checkClob8(s, rsc.getClob(1), useOrderBy);

        s.execute("DELETE FROM C8.T8POS");
        s.execute("DELETE FROM C8.T8PATT");
        ps.close();
        psp.close();

        s.execute("DROP TABLE C8.T8POS");
        s.execute("DROP TABLE C8.T8PATT");

        s.close();

        commit();
    }

    private static String T8insert(PreparedStatement ps, int id, char[] base,
            int bl, char[] pattern, int pl, int pos, boolean addPattern)
            throws SQLException
    {

        StringBuffer sb = new StringBuffer();
        sb.append(base, 0, bl);

        // Assume the pattern looks like Abcdefgh
        // put together a block of misleading matches such as
        // AAbAbcAbcdAbcde

        int last = addPatternPrefix(sb, pattern, pl, 5, 10);

        if (last >= (pos / 2))
            pos = (last + 10) * 2;

        // now a set of misleading matches up to half the pattern width
        last = addPatternPrefix(sb, pattern, pl, pl/2, pos/2);

        if (last >= pos)
            pos = last + 13;

        // now a complete set of misleading matches
        pos = addPatternPrefix(sb, pattern, pl, pl - 1, pos);

        if (addPattern) {
            // and then the pattern
            sb.insert(pos, pattern, 0, pl);
        } else {
            pos = -1;
        }


        String dd = sb.toString();
        String pstr = new String(pattern, 0, pl);

        assertEquals("FAIL - test confused pattern not at expected location",
                pos, dd.indexOf(pstr));

        // JDBC uses 1 offset for first character
        if (pos != -1)
            pos = pos + 1;

        ps.setInt(1, id);
        ps.setString(2, dd);
        ps.setInt(3, pos);
        ps.setInt(4, dd.length());
        ps.executeUpdate();

        return pstr;

    }

    private static int addPatternPrefix(
            StringBuffer sb, char[] pattern, int pl, int fakeCount, int pos) {

        for (int i = 0; i < fakeCount && i < (pl - 1); i++) {

            sb.insert(pos, pattern, 0, i + 1);
            pos += i + 1;
        }

        return pos;
    }

    private static void checkClob8(
    Statement   s, 
    String      pstr,
    boolean     useOrderBy) 
        throws SQLException
    {
        ResultSet rs = null;

        if (useOrderBy)
        {
            rs = s.executeQuery(
                    "SELECT ID, DD, POS, L FROM C8.T8POS ORDER BY 1");
        }
        else
        {
            rs = s.executeQuery(
                    "SELECT ID, DD, POS, L FROM C8.T8POS");
        }

        while (rs.next()) {

            int id = rs.getInt(1);

            java.sql.Clob cl = rs.getClob(2);

            int pos = rs.getInt(3);
            int len = rs.getInt(4);

            long clobPosition = cl.position(pstr, 1);
            assertEquals("FAIL - position did not match",
                    (long) pos, clobPosition);
        }
        rs.close();
    }

    private static void checkClob8(
    Statement   s, 
    Clob        pstr,
    boolean     useOrderBy) 
        throws SQLException {


        ResultSet rs = null;

        if (useOrderBy)
        {
            rs = s.executeQuery(
                "SELECT ID, DD, POS, L FROM C8.T8POS ORDER BY 1");
        }
        else
        {
            rs = s.executeQuery(
                "SELECT ID, DD, POS, L FROM C8.T8POS");
        }

        while (rs.next()) {

            int id = rs.getInt(1);

            java.sql.Clob cl = rs.getClob(2);

            int pos = rs.getInt(3);
            int len = rs.getInt(4);

            long clobPosition = cl.position(pstr, 1);
            assertEquals("FAIL - position did not match",
                    (long) pos, clobPosition);

        }
        rs.close();
    }

    /**
     * make sure clob is still around after we go to the next row,
     * after we close the result set, and after we close the statement
     */
    public void testClobAfterClose() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");
        byte[] buff = new byte[128];
        Clob[] clobArray = new Clob[10];
        int[] clobLengthArray = new int[10];
        int j = 0;
        while (rs.next()) {
            clobArray[j] = rs.getClob(1);
            clobLengthArray[j++] = rs.getInt(2);
        }
        rs.close();
        stmt.close();

        for (int i = 0; i < 10; i++) {
            if (clobArray[i] != null) {
                InputStream fin = clobArray[i].getAsciiStream();
                int columnSize = 0;
                for (;;) {
                    int size = fin.read(buff);
                    if (size == -1)
                        break;
                    columnSize += size;
                }
                assertEquals("FAIL - wrong column size",
                        columnSize, clobLengthArray[i]);
                assertEquals("FAIL - wrong column size",
                        columnSize, clobArray[i].length());
            }
        }
    }

    /**
     * test locking
     */
    public void testLockingClob() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");
        // fetch row back, get the column as a clob.
        Clob clob = null, shortClob = null;
        int clobLength;
        while (rs.next()) {
            clobLength = rs.getInt(2);
            if (clobLength == 10000)
                clob = rs.getClob(1);
            if (clobLength == 26)
                shortClob = rs.getClob(1);
        }
        rs.close();
        stmt.close();

        assertTrue("shortClob is null", shortClob != null);
        assertTrue("clob is null", clob != null);

        Connection conn2 = openDefaultConnection();
        // turn off autocommit, otherwise blobs/clobs cannot hang around
        // until end of transaction
        conn2.setAutoCommit(false);
        // update should go through since we don't get any locks on clobs
        // that are not long columns
        Statement stmt2 = conn2.createStatement();
        stmt2.executeUpdate("update testClob set a = 'foo' where b = 26");
        assertEquals("FAIL: clob length changed", 26, shortClob.length());
        // should timeout waiting for the lock to do this
        try {
            stmt2.executeUpdate(
                    "update testClob set b = b + 1 where b = 10000");
            stmt2.close(); // Cleanup on fail
            conn2.rollback();
            conn2.close();
            fail("FAIL: row should be locked");
        } catch (SQLException se) {
            checkException(LOCK_TIMEOUT, se);
        }

        // DERBY-3740, the reference below to clob must remain after the above
        // expected lock timeout, otherwise GC might run on the clob and
        // cause intermittent problems if the GC causes lock to be released
        // early.
        assertEquals("FAIL: clob length changed", 10000, clob.length());
        
        // Test that update goes through after the transaction is committed
        commit();
        stmt2.executeUpdate("update testClob set b = b + 1 where b = 10000");
        
        stmt2.close();
        conn2.rollback();
        conn2.close();
    }

    /**
     * test locking with a long row + long column
     */
    public void testLockingWithLongRowClob() throws Exception
    {
        ResultSet rs;
        Statement stmt, stmt2;
        stmt = createStatement();
        stmt.execute("alter table testClob add column al varchar(2000)");
        stmt.execute("alter table testClob add column bl varchar(3000)");
        stmt.execute("alter table testClob add column cl varchar(2000)");
        stmt.execute("alter table testClob add column dl varchar(3000)");
        stmt.execute("alter table testClob add column el CLOB(400k)");
        PreparedStatement ps = prepareStatement(
            "insert into testClob (al, bl, cl, dl, el, b) values(?,?,?,?,?,?)");
        ps.setString(1,Formatters.padString("blaaa",2000));
        ps.setString(2,Formatters.padString("tralaaaa",3000));
        ps.setString(3,Formatters.padString("foodar",2000));
        ps.setString(4,Formatters.padString("moped",3000));
        InputStream streamIn = new LoopingAlphabetStream(10000);
        ps.setAsciiStream(5, streamIn, 10000);
        ps.setInt(6, 1);
        // DERBY-4312 make sure commit() doesn't interfere here.
        commit();
        ps.executeUpdate();
        streamIn.close();
        ps.close();
        commit();

        stmt = createStatement();
        rs = stmt.executeQuery("select el from testClob");
        // fetch row back, get the column as a clob.
        Clob clob = null;
        assertTrue("FAIL - row not found", rs.next());
        clob = rs.getClob(1);
        assertTrue("FAIL - clob is null", clob != null);
        rs.close();
        stmt.close();

        Connection conn2 = openDefaultConnection();
        // turn off autocommit, otherwise blobs/clobs cannot hang around
        // until end of transaction
        conn2.setAutoCommit(false);
        // the following should timeout
        stmt2 = conn2.createStatement();
        try {
            stmt2.executeUpdate(
                    "update testClob set el = 'smurfball' where b = 1");
            stmt2.close(); // Cleanup on fail
            conn2.rollback();
            conn2.close();
            fail("FAIL - statement should timeout");
        } catch (SQLException se) {
            checkException(LOCK_TIMEOUT, se);
        }
                
        // Test that update goes through after the transaction is committed
        commit();
        stmt2.executeUpdate("update testClob set el = 'smurfball' where b = 1");
        
        stmt2.close();
        conn2.commit();
        conn2.close();
    }

    /**
     * test accessing clob after commit
     */
    public void testClobAfterCommit() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a,b from testClob");
        // fetch row back, get the column as a clob.
        Clob clob = null, shortClob = null;
        int clobLength;
        int i = 0;
        while (rs.next()) {
            clobLength = rs.getInt(2);
            if (clobLength == 10000)
                clob = rs.getClob(1);
            if (clobLength == 26)
                shortClob = rs.getClob(1);
        }
        
        /*
        * We call it before the commit(); to cache the result
        * DERBY-3574
        */
        clob.length();
        shortClob.length();
        
        rs.close();
        stmt.close();
        commit();
        assertTrue("FAIL - shortClob is NULL", shortClob != null);
        // this should give blob/clob unavailable exceptions on client
        try {
            shortClob.length();
            //Should have thrown an SQLException in the
            fail("FAIL - should not be able to access Clob after commit");
        } catch (SQLException e) {
            //The same SQLState String INVALID_LOB
            //is used for LOB's(Both Clob and Blob). Ensure that
            //we get the expected exception by comparing the SQLState.
            checkException(INVALID_LOB, e);
        }

        // these should all give blob/clob data unavailable exceptions
        try {
            clob.length();
            //Large Clobs not accessible after commit. 
            //Should have thrown an SQLException here.
            fail("FAIL - should not be able to access large Clob after commit");
        } catch (SQLException e) {
            //The same SQLState String INVALID_LOB
            //is used for LOB's(Both Clob and Blob). Ensure that
            //we get the expected exception by comparing the SQLState.
            checkException(INVALID_LOB, e);
        }
        try {
            clob.getSubString(2,3);
            //Large Clobs are not accessible after commit. 
            //Should have thrown an SQLException here.
            fail("FAIL - should not be able to access large Clob after commit");
        } catch (SQLException e) {
            //The same SQLState String INVALID_LOB
            //is used for LOB's(Both Clob and Blob). Ensure that
            //we get the expected exception by comparing the SQLState.
            checkException(INVALID_LOB, e);
        }
        try {
            clob.getAsciiStream();
            //Large Clobs are not accessible after commit. 
            //Should have thrown an SQLException here.
            fail("FAIL - should not be able to access large Clob after commit");
        } catch (SQLException e) {
            //The same SQLState String INVALID_LOB
            //is used for LOB's(Both Clob and Blob). Ensure that
            //we get the expected exception by comparing the SQLState.
            checkException(INVALID_LOB, e);
        }
        try {
            clob.position("foo",2);
            //Large Clobs are not accessible after commit. 
            //Should have thrown an SQLException here.
            fail("FAIL - should not be able to access large Clob after commit");
        } catch (SQLException e) {
            //The same SQLState String INVALID_LOB
            //is used for LOB's(Both Clob and Blob). Ensure that
            //we get the expected exception by comparing the SQLState.
            checkException(INVALID_LOB, e);
        }
        try {
            clob.position(clob,2);
            //Large Clobs are not accessible after commit. 
            //Should have thrown an SQLException here.
            fail("FAIL - should not be able to access large Clob after commit");
        } catch (SQLException e) {
            //The same SQLState String INVALID_LOB
            //is used for LOB's(Both Clob and Blob). Ensure that
            //we get the expected exception by comparing the SQLState.
            checkException(INVALID_LOB, e);
        }
    }

    /**
     * test accessing clob after closing the connection
     */
    public void testClobAfterClosingConnection() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a,b from testClob");
        // fetch row back, get the column as a clob.
        Clob clob = null, shortClob = null;
        int clobLength;
        while (rs.next()) {
            clobLength = rs.getInt(2);
            if (clobLength == 10000)
                clob = rs.getClob(1);
            if (clobLength == 26)
                shortClob = rs.getClob(1);
        }
		
        /*
         * We call it before the commit(); to cache the result
         * DERBY-3574
         */
        clob.length();
        shortClob.length();
		
        rs.close();
        stmt.close();
        commit();
        getConnection().close();

        try {
            long len = shortClob.length();
            //Clobs on the Embedded side and the NetworkClient
            //side are not accessible after closing the
            //connection. Should have thrown an SQLException here.
            fail("FAIL - should not be able to access Clob after " +
                    "Connection Close");
        }
        catch (SQLException e) {
            //Ensure that we get the expected exception by comparing
            //the SQLState.
            checkException(NO_CURRENT_CONNECTION, e);
        }

        // these should all give blob/clob data unavailable exceptions
        try {
            clob.length();
            //Large Clobs on the Embedded side and the NetworkClient
            //side are not accessible after Connection Close. Should
            //have thrown an SQLException here.
            fail("FAIL - should not be able to access large " +
                    "Clob after Connection Close");
        } catch (SQLException e) {
            //Ensure that we get the expected exception by comparing
            //the SQLState.
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            clob.getSubString(2,3);
            //Large Clobs on the Embedded side and the NetworkClient
            //side are not accessible after Connection Close. Should
            //have thrown an SQLException here.
            fail("FAIL - should not be able to access large " +
                    "Clob after Connection Close");
        } catch (SQLException e) {
            //Ensure that we get the expected exception by comparing
            //the SQLState.
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            clob.getAsciiStream();
            //Large Clobs on the Embedded side and the NetworkClient
            //side are not accessible after Connection Close. Should
            //have thrown an SQLException here.
            fail("FAIL - should not be able to access large " +
                    "Clob after Connection Close");
        } catch (SQLException e) {
            //Ensure that we get the expected exception by comparing
            //the SQLState.
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            clob.position("foo",2);
            //Large Clobs on the Embedded side and the NetworkClient
            //side are not accessible after Connection Close. Should
            //have thrown an SQLException here.
            fail("FAIL - should not be able to access large " +
                    "Clob after Connection Close");
        } catch (SQLException e) {
            //Ensure that we get the expected exception by comparing
            //the SQLState.
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            clob.position(clob,2);
            //Large Clobs on the Embedded side and the NetworkClient
            //side are not accessible after Connection Close. Should
            //have thrown an SQLException here.
            fail("FAIL - should not be able to access large " +
                    "Clob after Connection Close");
        } catch (SQLException e) {
            //Ensure that we get the expected exception by comparing
            //the SQLState.
            checkException(NO_CURRENT_CONNECTION, e);
        }
    }

    /**
     * Make sure we get an error attempting to access the 
     * lob after commit.
     */
    public void testClobAfterCommitWithSecondClob() throws SQLException
    {
        getConnection().setAutoCommit(false);
        Statement s1 = createStatement();
        ResultSet rs1 = s1.executeQuery("values cast('first' as clob)");
        rs1.next();
        Clob first = rs1.getClob(1);
        rs1.close(); 
        commit();
        Statement s2 = createStatement();
        ResultSet rs2 = s2.executeQuery("values cast('second' as clob)");
        rs2.next();
        Clob second = rs2.getClob(1);
        try {
            first.getSubString(1,100);
            fail("first.getSubString should have failed because after the commit");
        } catch (SQLException se){
            assertSQLState(INVALID_LOB,se);
        }
        assertEquals("second",second.getSubString(1, 100));        
        rs2.close(); 
    }
    /**
     * Test fix for derby-1382.
     *
     * Test that the getClob() returns the correct value for the clob before and
     * after updating the clob when using result sets of type
     * TYPE_SCROLL_INSENSITIVE.
     *
     * @throws SQLException
     */
    public void testGetClobBeforeAndAfterUpdate() throws SQLException {
        String clobData = "initial clob ";
        PreparedStatement ps = prepareStatement("insert into " +
                "testClob (b, a) values (?, ?)");
        for (int i=0; i<10; i++) {
            ps.setInt(1, i);
            ps.setString(2, clobData + i);
            ps.execute();
        }
        ps.close();

        Statement scrollStmt = createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = scrollStmt.executeQuery("SELECT b, a FROM testClob");

        String value;
        Clob c;

        rs.first();
        checkContentsBeforeAndAfterUpdatingClob(rs);
        rs.next();
        checkContentsBeforeAndAfterUpdatingClob(rs);
        rs.relative(3);
        checkContentsBeforeAndAfterUpdatingClob(rs);
        rs.absolute(7);
        checkContentsBeforeAndAfterUpdatingClob(rs);
        rs.previous();
        checkContentsBeforeAndAfterUpdatingClob(rs);
        rs.last();
        checkContentsBeforeAndAfterUpdatingClob(rs);
        rs.previous();
        checkContentsBeforeAndAfterUpdatingClob(rs);

        rs.close();
        scrollStmt.close();
    }

    private void checkContentsBeforeAndAfterUpdatingClob(ResultSet rs)
    throws SQLException {
        Clob c;
        String value, expectedValue;
        String clobData = "initial clob ";
        String updatedClobData = "updated clob ";

        c = rs.getClob(2);
        // check contents
        value = c.getSubString(1, (int)c.length());
        expectedValue = clobData + rs.getInt(1);
        assertEquals("FAIL - wrong clob value", expectedValue, value);
        // update contents
        value = updatedClobData + rs.getInt(1);
        c.setString(1, value);
        rs.updateClob(2, c);
        rs.updateRow();
        // check update values
        rs.next(); // leave the row
        rs.previous(); // go back to updated row
        c = rs.getClob(2);
        // check contents
        value = c.getSubString(1, (int)c.length());
        expectedValue = updatedClobData + rs.getInt(1);
        assertEquals("FAIL - wrong clob value", expectedValue, value);
    }

    /**
     * Test fix for derby-1421.
     *
     * Test that the getClob() returns the correct value for the blob before and
     * after updating the Clob using the method updateCharacterStream().
     *
     * @throws SQLException
     */
    public void testGetClobBeforeAndAfterUpdateStream() throws SQLException {
        String clobData = "initial clob ";
        PreparedStatement ps = prepareStatement("insert into " +
                "testClob (b, a) values (?, ?)");
        for (int i=0; i<10; i++) {
            ps.setInt(1, i);
            ps.setString(2, clobData + i);
            ps.execute();
        }
        ps.close();

        Statement scrollStmt = createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = scrollStmt.executeQuery("SELECT b, a FROM testClob");

        rs.first();
        updateClobWithUpdateCharacterStream(rs);
        rs.next();
        updateClobWithUpdateCharacterStream(rs);
        rs.relative(3);
        updateClobWithUpdateCharacterStream(rs);
        rs.absolute(7);
        updateClobWithUpdateCharacterStream(rs);
        rs.previous();
        updateClobWithUpdateCharacterStream(rs);
        rs.last();
        updateClobWithUpdateCharacterStream(rs);
        rs.previous();
        updateClobWithUpdateCharacterStream(rs);

        rs.close();
        scrollStmt.close();
    }

    private void updateClobWithUpdateCharacterStream(ResultSet rs)
    throws SQLException {
        Clob c;
        String value, expectedValue;
        String clobData = "initial clob ";
        String updatedClobData = "updated clob ";

        c = rs.getClob(2);
        // check contents
        value = c.getSubString(1, (int)c.length());
        expectedValue = clobData + rs.getInt(1);
        assertEquals("FAIL - wrong clob value", expectedValue, value);

        // update contents
        value = (updatedClobData + rs.getInt(1));
        Reader updateValue = new StringReader(value);
        rs.updateCharacterStream(2, updateValue, value.length());
        rs.updateRow();
        // check update values
        rs.next(); // leave the row
        rs.previous(); // go back to updated row
        c = rs.getClob(2);
        // check contents
        value = c.getSubString(1, (int)c.length());
        expectedValue = updatedClobData + rs.getInt(1);
        assertEquals("FAIL - wrong clob value", expectedValue, value);
    }

    /**
     * test clob finalizer closes the container (should only release table and
     * row locks that are read_committed)
     * NOTE: this test does not produce output since it needs to call the
     * garbage collector whose behaviour is unreliable. It is in the test run to
     * exercise the code (most of the time).
     */
    public void testClobFinalizer() throws Exception {
        insertDefaultData();
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testClob");

        Clob[] clobArray = new Clob[10];
        int[] clobLengthArray = new int[10];
        int j = 0;
        while (rs.next()) {
            clobArray[j] = rs.getClob(1);
            clobLengthArray[j++] = rs.getInt(2);
        }
        rs.close();
        stmt.close();

        for (int i = 0; i < 10; i++) {
            clobArray[i] = null;
        }

        System.gc();
        System.gc();
    }


    /**
     * basic test of getBinaryStream also tests length
     */
    public void testGetBinaryStream() throws Exception {
        insertDefaultData();
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b, crc32 from testBlob");
        testBlobContents(rs);
        stmt.close();
        commit();
    }

    /**
     * test getBytes
     */
    public void testGetBytes() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a,b from testBlob");
        int blobLength = 0;
        Blob blob;
        while (rs.next()) {
            blob = rs.getBlob(1);
            blobLength = rs.getInt(2);
            if (blob != null) {
                verifyInterval(blob, 9905, 50, 0, blobLength);
                verifyInterval(blob, 5910, 150, 1, blobLength);
                verifyInterval(blob, 5910, 50, 2, blobLength);
                verifyInterval(blob, 204, 50, 3, blobLength);
                verifyInterval(blob, 68, 50, 4, blobLength);
                verifyInterval(blob, 1, 50, 5, blobLength);
                verifyInterval(blob, 1, 1, 6, blobLength);
                verifyInterval(blob, 1, 0, 7, blobLength);
                verifyInterval(blob, blobLength + 1, 0, 8, blobLength);
                if (blobLength > 100) {
                    byte[] res = blob.getBytes(blobLength-99,200);
                    assertEquals("FAIL - wrong length in bytes",
                            100, res.length);
                    // Get expected value
                    InputStream inStream = blob.getBinaryStream();
                    long left = blobLength - 100;
                    long read = 0;
                    while (left > 0 && read != -1) {
                        read = inStream.skip(Math.min(1024, left));
                        left -= read > 0? read : 0;
                    }
                    byte[] expected = new byte[100];
                    read = inStream.read(expected);
                    inStream.close();
                    assertEquals("FAIL - wrong value",
                            new String(expected),new String(res));
                }
            } else {
                assertTrue("FAIL - blob was NULL but length != 0",
                        blobLength == 0);
            }
        }
        stmt.close();
        commit();
    }

    /**
     * test position with a byte[] argument
     */
    public void testPositionBytes() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testBlob");
        int blobLength = 0;
        Blob blob;
        Random random = new Random();
        byte[] searchBytes;
        int start, length, startSearchPos;
        int distance, maxStartPointDistance;
        long foundAt;
        // clobs are generated with looping alphabet streams
        maxStartPointDistance = CharAlphabet.MODERNLATINLOWER.length;
        while (rs.next()) {
            blob = rs.getBlob(1);
            blobLength = rs.getInt(2);
            if (blob != null && blobLength > 0) {
                println("\n\nblobLength: " + blobLength);
                for (int i=0; i<10; i++) {
                    // find a random string to search for
                    start = Math.max(random.nextInt(blobLength - 1), 1);
                    length = random.nextInt(blobLength - start) + 1;
                    println("start:" + start + " length:" + length);
                    searchBytes = blob.getBytes(start, length);
                    String searchString = new String(searchBytes, "US-ASCII");
                    // get random position to start the search from
                    distance = random.nextInt(maxStartPointDistance);
                    startSearchPos = Math.max((start - distance), 1);
                    // make sure that the searched string does not happen
                    // before the expected position
                    byte[] tmp = blob.getBytes(startSearchPos, start);
                    if (new String(tmp,"US-ASCII").indexOf(searchString) != -1)
                    {
                        startSearchPos = start;
                    }
                    println("startSearchPos: " + startSearchPos +
                            "searchString: " + new String(searchBytes));
                    foundAt = blob.position(searchBytes, startSearchPos);
                    assertEquals("FAIL - wrong match found for " +
                            searchString + " starting at " + startSearchPos +
                            " and length of " + searchBytes.length,
                            start, foundAt);

                }
            }
        }
        rs.close();
        stmt.close();
    }

    /**
     * Tests the {@code Blob.position} using a deterministic sequence of
     * actions and arguments.
     */
    public void testPositionBlobDeterministic()
            throws IOException, SQLException {
        getConnection().setAutoCommit(false);
        final int size = 100000;
        PreparedStatement ps = prepareStatement(
                "INSERT INTO testBlob (a, b) VALUES (?, ?)");
        ps.setBinaryStream(1, new LoopingAlphabetStream(size), size);
        ps.setInt(2, size);
        ps.executeUpdate();
        ps.close();
        ps = prepareStatement("select a from testBlob where b = ?");
        ps.setInt(1, size);
        ResultSet rs = ps.executeQuery();
        assertTrue("No data found", rs.next());
        Blob blob = rs.getBlob(1);
        // Try with a one-byte pattern.
        byte[] pattern = new byte[] {(byte)'k'}; // k number 11 in the alphabet
        assertEquals(11, blob.position(pattern, 1));
        // Try with a non-existing pattern.
        pattern = new byte[] {(byte)'p', (byte)'o'};
        assertEquals(-1, blob.position(pattern, size / 3));

        // Loop through all matches 
        pattern = new byte[] {(byte)'d', (byte)'e'};
        long foundAtPos = 1;
        int index = 0;
        int stepSize = ByteAlphabet.modernLatinLowercase().byteCount();
        while ((foundAtPos = blob.position(pattern, foundAtPos +1)) != -1) {
            assertEquals((stepSize * index++) + 4, foundAtPos);
            byte[] fetchedPattern = blob.getBytes(foundAtPos, pattern.length);
            assertTrue(Arrays.equals(pattern, fetchedPattern));
        }

        // Try a longer pattern.
        int pSize = 65*1024; // 65 KB
        pattern = new byte[pSize];
        assertEquals(pSize, new LoopingAlphabetStream(pSize).read(pattern));
        assertEquals(1, blob.position(pattern, 1));
        assertEquals(stepSize * 100 +1,
                blob.position(pattern, stepSize * 99 + 7));
        // Try again after getting the length.
        assertEquals(size, blob.length());
        assertEquals(stepSize * 100 +1,
                blob.position(pattern, stepSize * 99 + 7));

        // Try specifing a starting position that's too big.
        try {
            blob.position(pattern, size*2);
            fail("Accepted position after end of Blob");
        } catch (SQLException sqle) {
            assertSQLState("XJ076", sqle);
        }

        // Fetch the last 5 bytes, try with a partial match at the end.
        byte[] blobEnd = blob.getBytes(size - 4, 5);
        pattern = new byte[6];
        System.arraycopy(blobEnd, 0, pattern, 0, blobEnd.length);
        pattern[5] = 'X'; // Only lowercase in the looping alphabet stream.
        assertEquals(-1, blob.position(pattern, size - 10));

        // Get the very last byte, try with a partial match at the end.
        blobEnd = blob.getBytes(size, 1);
        pattern = new byte[] {blobEnd[0], 'X'};
        assertEquals(-1, blob.position(pattern, size - 5));
    }

    /**
     * Test Blob.position() with blob argument
     */
    public void testPositionBlob() throws Exception {
        insertDefaultData();
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testBlob");
        int blobLength = 0;
        Blob blob;
        Statement stmt2 = createStatement();
        Random random = new Random();
        String searchString;
        int start, length, startSearchPos;
        int distance, maxStartPointDistance;
        long foundAt;
        // clobs are generated with looping alphabet streams
        maxStartPointDistance = CharAlphabet.MODERNLATINLOWER.length;
        while (rs.next()) {
            blob = rs.getBlob(1);
            blobLength = rs.getInt(2);
            if (blob != null && blobLength > 0) {
                println("\n\nblobLength: " + blobLength);
                // Create a table with clobs to search
                stmt2.executeUpdate("CREATE TABLE searchBlob " +
                        "(a Blob(300K), start int, position int)");
                // insert clobs into the table
                PreparedStatement ps = prepareStatement(
                        "INSERT INTO searchBlob values (?, ?, ?) ");
                for (int i=0; i<10; i++) {
                    // find a random string to search for
                    start = Math.max(random.nextInt(blobLength - 1), 1);
                    length = random.nextInt(blobLength - start) + 1;
                    println("start:" + start + " length:" + length);
                    searchString = new String(blob.getBytes(start, length),"US-ASCII");
                    // get random position to start the search from
                    distance = random.nextInt(maxStartPointDistance);
                    startSearchPos = Math.max((start - distance), 1);
                    // make sure that the searched string does not happen
                    // before the expected position
                    String tmp = new String(
                            blob.getBytes(startSearchPos, start),"US-ASCII");
                    if (tmp.indexOf(searchString) != -1) {
                        startSearchPos = start;
                    }

                    ps.setBytes(1, searchString.getBytes("US-ASCII"));
                    ps.setInt(2, startSearchPos);
                    ps.setInt(3, start);
                    ps.executeUpdate();
                }

                ps.close();

                ResultSet rs2 = stmt2.executeQuery(
                        "SELECT a, start, position FROM searchBlob");
                while (rs2.next()) {
                    Blob searchBlob = rs2.getBlob(1);
                    startSearchPos = rs2.getInt(2);
                    start = rs2.getInt(3);

                    searchString = new String(
                            searchBlob.getBytes(1L, (int)searchBlob.length()),"US-ASCII");
                    println("startSearchPos: " + startSearchPos +
                            "searchString: " + searchString);
                    foundAt = blob.position(searchBlob, startSearchPos);
                    assertEquals("FAIL - wrong match found for " +
                            searchString + " starting at " + startSearchPos +
                            " and length of " + searchString.length(),
                            start, foundAt);
                }
                rs2.close();
                stmt2.executeUpdate("DROP TABLE searchBlob");
            }
        }
        rs.close();
        stmt.close();
        stmt2.close();
    }

    /**
     * Test triggers on BLOB columns.
     */
    public void testTriggerWithBlobColumn() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        stmt.executeUpdate("CREATE TABLE blobTest8TriggerA " +
                "(a BLOB(400k), b int, crc32 BIGINT)");
        stmt.executeUpdate("CREATE TABLE blobTest8TriggerB " +
                "(a BLOB(400k), b int, crc32 BIGINT)");
        stmt.executeUpdate(
                "create trigger T8A after update on testBlob " +
                "referencing new as n old as o " +
                "for each row "+
                "insert into blobTest8TriggerA(a, b, crc32) " +
                "values (n.a, n.b, n.crc32)");
        stmt.executeUpdate(
                "create trigger T8B after INSERT on blobTest8TriggerA " +
                "referencing new table as n " +
                "for each statement "+
                "insert into blobTest8TriggerB(a, b, crc32) " +
                "select n.a, n.b, n.crc32 from n");

        commit();
        ResultSet rs = stmt.executeQuery(
                "select a,b,crc32 from blobTest8TriggerA");
        assertFalse("FAIL - Table blobTest8TriggerA should contain no rows",
                rs.next());
        rs.close();
        commit();
        stmt.executeUpdate("UPDATE testBlob set b = b + 0");
        commit();
        rs = stmt.executeQuery(
                "select a,b,crc32 from blobTest8TriggerA");
        testBlobContents(rs);
        rs.close();
        commit();

        rs = stmt.executeQuery(
                "select a,b,crc32 from blobTest8TriggerB");
        testBlobContents(rs);
        rs.close();
        commit();
        stmt.executeUpdate("DROP TRIGGER T8A");
        stmt.executeUpdate("DROP TRIGGER T8B");
        stmt.executeUpdate("DROP TABLE blobTest8TriggerB");
        stmt.executeUpdate("DROP TABLE blobTest8TriggerA");

        stmt.close();
        commit();

    }

    /**
     * tests small blob abd length method
     */
    public void testVarbinary() throws Exception{

        Statement stmt = createStatement();
        stmt.execute("ALTER TABLE testBlob ADD COLUMN smallBlob blob(13)");

        PreparedStatement ps = prepareStatement(
                "insert into testBlob (smallBlob) values (?)");
        String val = "";

        for (int i = 0; i < 10; i++) {
            // insert a string
            ps.setBytes(1, val.getBytes("US-ASCII"));
            ps.executeUpdate();
            val = val.trim() + "x";
        }

        ResultSet rs = stmt.executeQuery("select smallBlob from testBlob");
        byte[] buff = new byte[128];
        int j = 0;
        // fetch all rows back, get the columns as clobs.
        while (rs.next()) {
            // get the first column as a clob
            Blob blob = rs.getBlob(1);
            assertTrue("FAIL - blob is null", blob != null);
            InputStream fin = blob.getBinaryStream();
            int columnSize = 0;
            for (;;) {
                int size = fin.read(buff);
                if (size == -1)
                    break;
                columnSize += size;
            }
            assertEquals("FAIL - unexpected blob size", j, columnSize);
            assertEquals("FAIL - unexpected blob length", j, blob.length());
            j++;
        }
        ps.close();
        stmt.close();
        commit();
    }

    /**
     * make sure cannot get a blob from an int column
     */
    public void testGetBlobFromIntColumn() throws Exception {

        insertDefaultData();
        Statement stmt = createStatement();

        ResultSet rs = stmt.executeQuery("select b from testClob");
        while (rs.next()) {
            // get the first column as a clob
            try {
                Blob blob = rs.getBlob(1);
                rs.close();
                stmt.close();
                fail("FAIL - getBlob on int column should throw an " +
                        "exception");
            } catch (SQLException se) {
                checkException(LANG_DATA_TYPE_GET_MISMATCH, se);
            }
        }
        rs.close();
        stmt.close();
        commit();

    }

    /**
     * make sure setBlob doesn't work for an int column
     */
    public void testSetBlobOnIntColumn() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        PreparedStatement ps = prepareStatement(
                "insert into testBlob (b) values(?)");
        ResultSet rs = stmt.executeQuery("select a,b from testBlob");
        Blob blob;
        int blobLength;
        while (rs.next()) {
            // get the first column as a blob
            blob = rs.getBlob(1);
            if (blob != null) {
                try {
                    ps.setBlob(1,blob);
                    ps.executeUpdate();
                    rs.close();
                    stmt.close();
                    ps.close();
                    fail("FAIL - setBlob worked on INT column");
                } catch (SQLException se) {
                    checkException(LANG_DATA_TYPE_GET_MISMATCH, se);
                }
            }
        }
        rs.close();
        stmt.close();
        ps.close();
        commit();
    }

    /**
     * test raising of exceptions
     */
    public void testRaisingOfExceptionsBlob() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a,b from testBlob");

        int blobLength = 0;
        Blob blob;
        while (rs.next()) {
            blob = rs.getBlob(1);
            blobLength = rs.getInt(2);
            if (blob != null) {

                // 0 or negative position value
                try {
                    blob.getBytes(0, 5);
                    fail("FAIL - getBytes with 0 as position should " +
                            "have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_BAD_POSITION, e);
                }
                // negative length value
                try {
                    blob.getBytes(1, -76);
                    fail("FAIL - getBytes with negative length should " +
                            "have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_NONPOSITIVE_LENGTH, e);
                }
                // zero length value
                try {
                    blob.getBytes(1, -1);
                    fail("FAIL - getBytes with negative length should " +
                            "have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_NONPOSITIVE_LENGTH, e);
                }
                // before begin length 0
                try {
                    blob.getBytes(0, 0);
                    fail("FAIL - getBytes with 0 position and length " +
                            "should have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_BAD_POSITION, e);
                }
                // after end length 0
                try {
                    blob.getBytes(blobLength + 2, 0);
                    fail("FAIL - getBytes with position larger than " +
                            "the length of the blob should have caused an " +
                            "exception");
                } catch (SQLException e) {
                    checkException(BLOB_POSITION_TOO_LARGE, e);
                }
                // 0 or negative position value
                try {
                    blob.position(new byte[0], -4000);
                    fail("FAIL - position with negative start " +
                            "position should have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_BAD_POSITION, e);
                }
                // null pattern
                try {
                    blob.position((byte[]) null, 5);
                    fail("FAIL - position with null pattern should " +
                            "have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_NULL_PATTERN_OR_SEARCH_STR, e);
                }
                // 0 or negative position value
                try {
                    blob.position(blob, -42);
                    fail("FAIL - position with negative start " +
                            "position should have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_BAD_POSITION, e);
                }
                // null pattern
                try {
                    blob.position((Blob) null, 5);
                    fail("FAIL - position with null pattern should " +
                            "have caused an exception");
                } catch (SQLException e) {
                    checkException(BLOB_NULL_PATTERN_OR_SEARCH_STR, e);
                }
            }
        }
        rs.close();
        stmt.close();
        commit();
    }

    /**
     * test setBlob
     */
    public void testSetBlob() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        stmt.execute("create table testBlobX (a blob(300K), b integer)");
        PreparedStatement ps = prepareStatement(
                "insert into testBlobX values(?,?)");
        ResultSet rs = stmt.executeQuery("select a, b from testBlob");
        Blob blob;
        int blobLength;
        while (rs.next()) {
            // get the first column as a blob
            blob = rs.getBlob(1);
            blobLength = rs.getInt(2);
            if (blob != null) {
                ps.setBlob(1,blob);
                ps.setInt(2,blobLength);
                ps.executeUpdate();
            }
        }
        rs.close();
        commit();

        rs = stmt.executeQuery("select a,b from testBlobX");
        Blob blob2;
        int blobLength2;
        while (rs.next()) {
            // get the first column as a blob
            blob2 = rs.getBlob(1);
            blobLength2 = rs.getInt(2);
            assertTrue("FAIL - blob is NULL", blob2 != null);
            assertEquals("FAIL - wrong blob length",
                    blob2.length(), blobLength2);
        }
        rs.close();

        stmt.executeUpdate("DROP TABLE testBlobX");
        stmt.close();
        commit();
    }

    /**
     * make sure blob is still around after we go to the next row,
     * after we close the result set, and after we close the statement
     */
    public void testBlobAfterClose() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a,b from testBlob");
        byte[] buff = new byte[128];
        Blob[] blobArray = new Blob[10];
        int[] blobLengthArray = new int[10];
        int j = 0;
        while (rs.next()) {
            blobArray[j] = rs.getBlob(1);
            blobLengthArray[j++] = rs.getInt(2);
        }
        rs.close();
        stmt.close();

        for (int i = 0; i < 10; i++) {
            if (blobArray[i] != null) {
                InputStream fin = blobArray[i].getBinaryStream();
                int columnSize = 0;
                for (;;) {
                    int size = fin.read(buff);
                    if (size == -1)
                        break;
                    columnSize += size;
                }
                assertEquals("FAIL - invalid length",
                        blobLengthArray[i], columnSize);
                assertEquals("FAIL - invalid length",
                        columnSize, blobArray[i].length());
            }
        }
    }

    /**
     * test locking
     */
    public void testLockingBlob() throws Exception {

        Statement stmt = createStatement();

        insertDefaultData();

        // for blob lock to remain, autocommit must be false.
        assertFalse(getConnection().getAutoCommit());

        // test depends on small page size, make sure size is 4k
        checkSmallPageSize(stmt, "TESTBLOB");

        ResultSet rs = stmt.executeQuery("select a,b from testBlob");
        // fetch row back, get the column as a blob.
        Blob blob = null, shortBlob = null;
        int blobLength;
        while (rs.next()) {
            blobLength = rs.getInt(2);
            if (blobLength == 10000)
                blob = rs.getBlob(1);
            if (blobLength == 26)
                shortBlob = rs.getBlob(1);
        }
        rs.close();


        Connection conn2 = openDefaultConnection();
        // turn off autocommit, otherwise blobs/clobs cannot hang around
        // until end of transaction
        conn2.setAutoCommit(false);
        // Update should go through since we don't get any locks on blobs
        // that are not long columns
        Statement stmt2 = conn2.createStatement();
        stmt2.executeUpdate("update testBlob set a = null where b = 26");
        assertEquals("FAIL - blob was updated", 26, shortBlob.length());

        // should timeout waiting for the lock to do this
        try {
            
            stmt2.executeUpdate(
                    "update testBlob set b = b + 1 where b = 10000");
            stmt.close();
            stmt2.close();
            conn2.rollback();
            conn2.close();
            fail("FAIL - should have gotten lock timeout");
        } catch (SQLException se) {
            checkException(LOCK_TIMEOUT, se);
        }

        // DERBY-3740, add a reference to the retrieved blobs that is used
        // after the expected lock timeout in conn2.  Before this change 
        // this test would intermittently fail.  I believe that a smart
        // JVM/JIT recognized that the blob reference was no longer used
        // after the above while loop, and allowed gc on it before the routine
        // could get to the expected conflicting lock.  Upon GC the blob's
        // finalize code closes the internal stream and releases the lock in
        // read committed mode.

        // make sure we got the 10000 byte blob which should be a stream.
        assertTrue(blob != null);

        // make sure we got the 26 byte blob which should be materialized.
        assertTrue(shortBlob != null);
        
        // Test that update goes through after the transaction is committed
        commit();
        stmt2.executeUpdate("update testBlob set b = b + 1 where b = 10000");
        
        stmt.close();
        stmt2.close();
        conn2.commit();
        conn2.close();
    }

    /**
     * test locking with a long row + long column
     */
    public void testLockingWithLongRowBlob() throws Exception
    {
        ResultSet rs;
        Statement stmt, stmt2;

        // for blob lock to remain, autocommit must be false.
        assertFalse(getConnection().getAutoCommit());

        stmt = createStatement();

        // test depends on small page size, make sure size is 4k
        checkSmallPageSize(stmt, "TESTBLOB");

        stmt.execute("alter table testBlob add column al varchar(2000)");
        stmt.execute("alter table testBlob add column bl varchar(3000)");
        stmt.execute("alter table testBlob add column cl varchar(2000)");
        stmt.execute("alter table testBlob add column dl varchar(3000)");
        stmt.execute("alter table testBlob add column el BLOB(400k)");
        PreparedStatement ps = prepareStatement(
            "insert into testBlob (al, bl, cl, dl, el, b) values(?,?,?,?,?,?)");
        ps.setString(1,Formatters.padString("blaaa",2000));
        ps.setString(2,Formatters.padString("tralaaaa",3000));
        ps.setString(3,Formatters.padString("foodar",2000));
        ps.setString(4,Formatters.padString("moped",3000));
        InputStream streamIn = new LoopingAlphabetStream(10000);
        ps.setBinaryStream(5, streamIn, 10000);
        ps.setInt(6, 1);
        ps.executeUpdate();
        streamIn.close();
        ps.close();
        commit();

        stmt = createStatement();
        rs = stmt.executeQuery("select el from testBlob");
        // fetch row back, get the column as a clob.
        Blob blob = null;
        assertTrue("FAIL - row not found", rs.next());
        blob = rs.getBlob(1);
        assertTrue("FAIL - blob is null", blob != null);
        rs.close();
        stmt.close();

        Connection conn2 = openDefaultConnection();
        // turn off autocommit, otherwise blobs/clobs cannot hang around
        // until end of transaction
        conn2.setAutoCommit(false);
        // the following should timeout
        stmt2 = conn2.createStatement();
        try {
            stmt2.executeUpdate("update testBlob set el = null where b = 1");
            stmt2.close();
            stmt.close();
            conn2.rollback();
            conn2.close();
            fail("FAIL - statement should timeout");
        } catch (SQLException se) {
            checkException(LOCK_TIMEOUT, se);
        }
        // Test that update goes through after the transaction is committed
        commit();

        // DERBY-3740, add a reference to the retrieved blobs that is used
        // after the expected lock timeout in conn2.  Before this change 
        // this test would intermittently fail.  I believe that a smart
        // JVM/JIT recognized that the blob reference was no longer used
        // after the above while loop, and allowed gc on it before the routine
        // could get to the expected conflicting lock.  Upon GC the blob's
        // finalize code closes the internal stream and releases the lock in
        // read committed mode.
        assertTrue(
            "FAIL - blob is null after expected lock timeout", blob != null);

        stmt2.executeUpdate("update testBlob set el = null where b = 1");
        
        stmt2.close();
        conn2.commit();
        stmt.close();
        conn2.close();
    }

    /**
     * test accessing blob after commit
     */
    public void testBlobAfterCommit() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testBlob");
        // fetch row back, get the column as a blob.
        Blob blob = null, shortBlob = null;
        int blobLength;
        while (rs.next()) {
            blobLength = rs.getInt(2);
            if (blobLength == 10000)
                blob = rs.getBlob(1);
            if (blobLength == 26)
                shortBlob = rs.getBlob(1);
        }
		
        /*
         * We call it before the commit(); to cache the result
         * DERBY-3574
         */
        blob.length();
        shortBlob.length();
		
        rs.close();
        stmt.close();
        commit();


        assertTrue("FAIL - shortBlob is NULL", shortBlob != null);
        // This should give blob/clob unavailable exceptions with both
        // client and embedded driver.
        try {
            shortBlob.length();
            fail("FAIL - should not be able to access Blob after commit");
        } catch (SQLException e) {
            checkException(INVALID_LOB, e);
        }

        assertTrue("FAIL - blob is NULL", blob != null);
        // these should all give blob/clob data unavailable exceptions
        try {
            blob.length();
            fail("FAIL - should not be able to access large Blob after commit");
        } catch (SQLException e) {
            checkException(INVALID_LOB, e);
        }
        try {
            blob.getBytes(2,3);
            fail("FAIL - should not be able to access large Blob after commit");
        } catch (SQLException e) {
            checkException(INVALID_LOB, e);
        }
        try {
            blob.getBinaryStream();
            fail("FAIL - should not be able to access large Blob after commit");
        } catch (SQLException e) {
            checkException(INVALID_LOB, e);
        }
        try {
            blob.position("foo".getBytes("US-ASCII"),2);
            fail("FAIL - should not be able to access large Blob after commit");
        } catch (SQLException e) {
            checkException(INVALID_LOB, e);
        }
        try {
            blob.position(blob,2);
            fail("FAIL - should not be able to access large Blob after commit");
        } catch (SQLException e) {
            checkException(INVALID_LOB, e);
        }
    }

    /**
     * test accessing blob after closing the connection
     */
    public void testBlobAfterClosingConnection() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a, b from testBlob");
        // fetch row back, get the column as a blob.
        Blob blob = null, shortBlob = null;
        int blobLength;
        while (rs.next()) {
            blobLength = rs.getInt(2);
            if (blobLength == 10000)
                blob = rs.getBlob(1);
            if (blobLength == 26)
                shortBlob = rs.getBlob(1);
        }
		
        /*
         * We call it before the commit(); to cache the result
         * DERBY-3574
         */
        blob.length();
        shortBlob.length();
		
        rs.close();
        rollback();
        getConnection().close();

        try {
            long length = shortBlob.length();                        
            fail("FAIL - should get an exception, connection is closed");
        } catch (SQLException e) {
            checkException(NO_CURRENT_CONNECTION, e);            
        }

        // these should all give blob/clob data unavailable exceptions
        try {
            blob.length();
            fail("FAIL - should not be able to access large lob " +
                    "after the connection is closed");
        } catch (SQLException e) {
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            blob.getBytes(2,3);
            fail("FAIL - should not be able to access large lob " +
                    "after the connection is closed");
        } catch (SQLException e) {
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            blob.getBinaryStream();
            fail("FAIL - should not be able to access large lob " +
                    "after the connection is closed");
        } catch (SQLException e) {
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            blob.position("foo".getBytes("US-ASCII"),2);
            fail("FAIL - should not be able to access large lob " +
                    "after the connection is closed");
        } catch (SQLException e) {
            checkException(NO_CURRENT_CONNECTION, e);
        }
        try {
            blob.position(blob,2);
            fail("FAIL - should not be able to access large lob " +
                    "after the connection is closed");
        } catch (SQLException e) {
            checkException(NO_CURRENT_CONNECTION, e);
        }

        // restart the connection
        getConnection().setAutoCommit(false);
    }

    /**
     * test blob finalizer closes the container
     * (should only release table and row locks that are read_committed)
     * NOTE: this test does not produce output since it needs to call the
     * garbage collector whose behaviour is unreliable. It is in the test run to
     * exercise the code (most of the time).
     */
    public void testBlobFinalizer() throws Exception {
        insertDefaultData();
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("select a,b from testBlob");

        Blob[] blobArray = new Blob[10];
        int[] blobLengthArray = new int[10];
        int j = 0;
        while (rs.next()) {
            blobArray[j] = rs.getBlob(1);
            blobLengthArray[j++] = rs.getInt(2);
        }
        rs.close();
        stmt.close();

        for (int i = 0; i < 10; i++) {
            blobArray[i] = null;
        }

        System.gc();
        System.gc();

    }

    /**
     * Test fix for derby-1382.
     *
     * Test that the getBlob() returns the correct value for the blob before and
     * after updating the blob when using result sets of type
     * TYPE_SCROLL_INSENSITIVE.
     *
     * @throws Exception
     */
    public void testGetBlobBeforeAndAfterUpdate() throws Exception {
        String blobData = "initial blob ";
        PreparedStatement ps =
                prepareStatement(
                "insert into testBlob (b, a) values (?, ?)");
        for (int i=0; i<10; i++) {
            ps.setInt(1, i);
            ps.setBytes(2, (blobData + i).getBytes("US-ASCII"));
            ps.execute();
        }
        ps.close();

        Statement scrollStmt = createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = scrollStmt.executeQuery("SELECT b, a FROM testBlob");

        rs.first();
        checkContentsBeforeAndAfterUpdatingBlob(rs);
        rs.next();
        checkContentsBeforeAndAfterUpdatingBlob(rs);
        rs.relative(3);
        checkContentsBeforeAndAfterUpdatingBlob(rs);
        rs.absolute(7);
        checkContentsBeforeAndAfterUpdatingBlob(rs);
        rs.previous();
        checkContentsBeforeAndAfterUpdatingBlob(rs);
        rs.last();
        checkContentsBeforeAndAfterUpdatingBlob(rs);
        rs.previous();
        checkContentsBeforeAndAfterUpdatingBlob(rs);

        rs.close();
        scrollStmt.close();

    }

    private void checkContentsBeforeAndAfterUpdatingBlob(ResultSet rs)
    throws SQLException, UnsupportedEncodingException {
        Blob b;
        byte[] value, expectedValue;
        String blobData = "initial blob ";
        String updatedBlobData = "updated blob ";

        b = rs.getBlob(2);
        // check contents
        value = b.getBytes(1, blobData.length() + 1);
        expectedValue = (blobData + rs.getInt(1)).getBytes("US-ASCII");
        assertTrue("FAIL - wrong blob value",
                Arrays.equals(value, expectedValue));

        // update contents
        value = (updatedBlobData + rs.getInt(1)).getBytes("US-ASCII");
        b.setBytes(1, value);
        rs.updateBlob(2, b);
        rs.updateRow();
        // check update values
        rs.next(); // leave the row
        rs.previous(); // go back to updated row
        b = rs.getBlob(2);
        // check contents
        value = b.getBytes(1, updatedBlobData.length() + 1);
        expectedValue = (updatedBlobData + rs.getInt(1)).getBytes("US-ASCII");
        assertTrue("FAIL - wrong blob value",
                Arrays.equals(value, expectedValue));
    }

    /**
     * Test fix for derby-1421.
     *
     * Test that the getBlob() returns the correct value for the blob before and
     * after updating the blob using the method updateBinaryStream().
     *
     * @throws Exception
     */
    public void testGetBlobBeforeAndAfterUpdateStream() throws Exception {

        String blobData = "initial blob ";
        PreparedStatement ps =
                prepareStatement(
                "insert into testBlob (b, a) values (?, ?)");
        for (int i=0; i<10; i++) {
            ps.setInt(1, i);
            ps.setBytes(2, (blobData + i).getBytes("US-ASCII"));
            ps.execute();
        }
        ps.close();

        Statement scrollStmt = createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = scrollStmt.executeQuery("SELECT b, a FROM testBlob");

        rs.first();
        updateBlobWithUpdateBinaryStream(rs);
        rs.next();
        updateBlobWithUpdateBinaryStream(rs);
        rs.relative(3);
        updateBlobWithUpdateBinaryStream(rs);
        rs.absolute(7);
        updateBlobWithUpdateBinaryStream(rs);
        rs.previous();
        updateBlobWithUpdateBinaryStream(rs);
        rs.last();
        updateBlobWithUpdateBinaryStream(rs);
        rs.previous();
        updateBlobWithUpdateBinaryStream(rs);

        rs.close();
        scrollStmt.close();
    }

    private void updateBlobWithUpdateBinaryStream(ResultSet rs)
    throws SQLException, UnsupportedEncodingException {
        Blob b;
        byte[] value, expectedValue;
        String blobData = "initial blob ";
        String updatedBlobData = "updated blob ";

        b = rs.getBlob(2);
        // check contents
        value = b.getBytes(1, blobData.length() + 1);
        expectedValue = (blobData + rs.getInt(1)).getBytes("US-ASCII");
        
        assertTrue("FAIL - wrong blob value",
                Arrays.equals(value, expectedValue));

        // update contents
        value = (updatedBlobData + rs.getInt(1)).getBytes("US-ASCII");
        InputStream updateValue = new ByteArrayInputStream(value);
        rs.updateBinaryStream(2, updateValue, value.length);
        rs.updateRow();
        // check update values
        rs.next(); // leave the row
        rs.previous(); // go back to updated row
        b = rs.getBlob(2);
        // check contents
        value = b.getBytes(1, updatedBlobData.length() + 1);
        expectedValue = (updatedBlobData + rs.getInt(1)).getBytes("US-ASCII");
        assertTrue("FAIL - wrong blob value",
                Arrays.equals(value, expectedValue));
    }

    /**
     * test behaviour of system with self destructive user
     * update a long column underneath a clob
     */
    public void testSelfDestructiveClob() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery(
                "select a, b from testClob where b = 10000");
        byte[] buff = new byte[128];
        // fetch row back, get the column as a clob.
        Clob clob = null;
        InputStream fin;
        int clobLength = 0, i = 0;
        assertTrue("FAIL - row not found", rs.next());
        i++;
        clobLength = rs.getInt(2);
        // get the first column as a clob
        clob = rs.getClob(1);
        assertEquals("FAIL - wrong clob length", 10000, clobLength);
        fin = clob.getAsciiStream();
        int columnSize = 0;

        PreparedStatement ps = prepareStatement(
                "update testClob set a = ? where b = 10000");
        StringBuffer foo = new StringBuffer();
        for (int k = 0; k < 1000; k++)
            foo.append('j');
        ps.setString(1,foo.toString());
        ps.executeUpdate();

        rs = stmt.executeQuery("select a from testClob where b = 10000");
        while (rs.next()) {
            int j = 1;
            String val = rs.getString(1);
            assertEquals("FAIL - invalid blob value", foo.substring(0, 50),
                    val.substring(0,50));
            j++;
        }

        while (columnSize < 11000) {
            int size = fin.read(buff);
            if (size == -1)
                break;
            columnSize += size;
        }
        assertEquals("FAIL - invalid column size", 10000, columnSize);

        assertEquals("FAIL - invalid column size", clobLength, columnSize);
        assertEquals("FAIL - invalid column size", columnSize, clob.length());

        rs.close();
        stmt.close();
    }

    /**
     * test behaviour of system with self destructive user
     * drop table and see what happens to the clob
     * expect an IOException when moving to a new page of the long column
     */
    public void testSelfDestructiveClob2() throws Exception {
        insertDefaultData();

        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery(
                "select a,b from testClob where b = 10000");
        byte[] buff = new byte[128];
        // fetch row back, get the column as a clob.
        Clob clob = null;
        InputStream fin;
        int clobLength = 0, i = 0;
        assertTrue("FAIL - row not found", rs.next());
        i++;
        clobLength = rs.getInt(2);
        // get the first column as a clob
        clob = rs.getClob(1);
        assertEquals("FAIL - wrong clob length", 10000, clobLength);
        fin = clob.getAsciiStream();
        int columnSize = 0;

        stmt.executeUpdate("drop table testClob");

        try {
            while (columnSize < 11000) {
                int size = fin.read(buff);
                if (size == -1)
                    break;
                columnSize += size;
            }
            fail("FAIL - should have got an IOException");
        } catch (java.io.IOException ioe) {
            if(usingEmbedded()) {
                assertEquals("FAIL - wrong exception",
                        "ERROR 40XD0: Container has been closed.",
                        ioe.getMessage());
            }
        }

        rollback();
    }

    /**
     * Test fix for derby-265.
     * Test that if getBlob is called after the transaction
     * in which it was created is committed, a proper user error
     * is thrown instead of an NPE.
     * Basically per the spec, getBlob is valid only for the duration of
     * the transaction it was created in
     * Updated for DERBY-1511: The test case wasn't supposed to fail in the
     * first place (neither with NPE nor with "proper user error") since none
     * of the BLOBs are accessed after the transaction that created them was
     * completed.
     * @throws Exception
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void testNegativeTestDerby265Blob() throws Exception {
        getConnection().setAutoCommit(false);

        PreparedStatement ps = prepareStatement(
                "insert into testBlob(b, a) values(?,?)");
        for (int i = 0; i < 3; i++) {
            InputStream fis = new LoopingAlphabetStream(300000);
            ps.setInt(1, i);
            ps.setBinaryStream(2, fis, 300000);
            ps.executeUpdate();
            fis.close();
        }
        commit();

        getConnection().setAutoCommit(true);

        Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        s.execute("SELECT b, a FROM testBlob");
        ResultSet rs1 = s.getResultSet();
        Statement s2 = createStatement(ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        s2.executeQuery("SELECT b, a FROM testBlob");
        ResultSet rs2 = s2.getResultSet();
        rs2.next();

        Blob b2 = rs2.getBlob(2);
        rs1.next();
        Blob b1 = rs1.getBlob(2);
        rs1.close();

        // DERBY-1511: Fetching the next BLOB here used to fail because it
        // had been pre-fetched before the commit and was closed in the commit.
        // Now, we don't pre-fetch BLOBs anymore, so expect to get a working
        // object here.
        assertTrue(rs2.next());
        assertNotNull(rs2.getBlob(2));
        rs2.close();
    }

    /**
     * Test fix for derby-265.
     * Test that if getClob is called after the transaction
     * in which it was created is committed, a proper user error
     * is thrown instead of an NPE.
     * Basically per the spec, getClob is valid only for the duration of
     * the transaction in it was created in
     * Updated for DERBY-1511: The test case wasn't supposed to fail in the
     * first place (neither with NPE nor with "proper user error") since none
     * of the CLOBs are accessed after the transaction that created them was
     * completed.
     * @throws Exception
     */
    public void testNegativeTestDerby265Clob() throws Exception {

        getConnection().setAutoCommit(false);

        PreparedStatement ps = prepareStatement(
                "insert into testClob(b, a) values(?,?)");
        for (int i = 0; i < 3; i++) {
            Reader fis = new LoopingAlphabetReader(300000);
            ps.setInt(1, i);
            ps.setCharacterStream(2, fis, 300000);
            ps.executeUpdate();
            fis.close();
        }
        commit();

        getConnection().setAutoCommit(true);

        Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        s.execute("SELECT b, a FROM testClob");
        ResultSet rs1 = s.getResultSet();
        Statement s2 = createStatement(ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        s2.executeQuery("SELECT b, a FROM testClob");
        ResultSet rs2 = s2.getResultSet();
        rs2.next();

        Clob b2 = rs2.getClob(2);
        rs1.next();
        Clob b1 = rs1.getClob(2);
        rs1.close();

        // DERBY-1511: Fetching the next CLOB here used to fail because it
        // had been pre-fetched before the commit and was closed in the commit.
        // Now, we don't pre-fetch CLOBs anymore, so expect to get a working
        // object here.
        assertTrue(rs2.next());
        assertNotNull(rs2.getClob(2));
        rs2.close();
    }

    public static Test suite() {
        BaseTestSuite suite = new BaseTestSuite("BlobClob4BlobTest");
        suite.addTest(baseSuite("embedded"));
        suite.addTest(
                TestConfiguration.clientServerDecorator(baseSuite("client")));

        // JSR169 does not have encryption support
        if (JDBC.vmSupportsJDBC3())
        {
            Test encSuite = baseSuite("encrypted");
            suite.addTest(Decorator.encryptedDatabase (encSuite));
        }

        return suite;
    }

    private static Test baseSuite(String name) {
        BaseTestSuite suite = new BaseTestSuite(
                BlobClob4BlobTest.class, "BlobClob4BlobTest:" + name);
        return new CleanDatabaseTestSetup(
                DatabasePropertyTestSetup.setLockTimeouts(suite, 2, 4));
    }


    private void insertDefaultData() throws Exception {
        PreparedStatement ps = prepareStatement(
                "INSERT INTO testClob (a, b, c) VALUES (?, ?, ?)");

        String clobValue = "";
        ps.setString(1, clobValue);
        ps.setInt(2, clobValue.length());
        ps.setLong(3, 0);
        ps.addBatch();
        clobValue = "you can lead a horse to water but you can't form it " +
                "into beverage";
        ps.setString(1, clobValue);
        ps.setInt(2, clobValue.length());
        ps.setLong(3, 0);
        ps.addBatch();
        clobValue = "a stitch in time says ouch";
        ps.setString(1, clobValue);
        ps.setInt(2, clobValue.length());
        ps.setLong(3, 0);
        ps.addBatch();
        clobValue = "here is a string with a return \n character";
        ps.setString(1, clobValue);
        ps.setInt(2, clobValue.length());
        ps.setLong(3, 0);
        ps.addBatch();

        ps.executeBatch();
        ps.clearBatch();

        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.modernLatinLowercase(), 0);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.modernLatinLowercase(), 56);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.modernLatinLowercase(), 5000);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.modernLatinLowercase(), 10000);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.modernLatinLowercase(), 300000);

        ps.setNull(1, Types.CLOB);
        ps.setInt(2, 0);
        ps.setLong(3, 0);
        ps.executeUpdate();

        ps.close();

        ps = prepareStatement(
                "INSERT INTO testBlob (a, b, crc32) VALUES (?, ?, ?)");

        byte[] blobValue = "".getBytes("US-ASCII");
        ps.setBytes(1, blobValue);
        ps.setInt(2, blobValue.length);
        ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
        ps.addBatch();
        blobValue = ("you can lead a horse to water but you can't form it " +
                "into beverage").getBytes("US-ASCII");
        ps.setBytes(1, blobValue);
        ps.setInt(2, blobValue.length);
        ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
        ps.addBatch();
        blobValue = "a stitch in time says ouch".getBytes("US-ASCII");
        ps.setBytes(1, blobValue);
        ps.setInt(2, blobValue.length);
        ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
        ps.addBatch();
        blobValue = "here is a string with a return \n character".
                getBytes("US-ASCII");
        ps.setBytes(1, blobValue);
        ps.setInt(2, blobValue.length);
        ps.setLong(3, getStreamCheckSum(new ByteArrayInputStream(blobValue)));
        ps.addBatch();

        ps.executeBatch();
        ps.clearBatch();

        insertLoopingAlphabetStreamData(
                ps, 0);
        insertLoopingAlphabetStreamData(
                ps, 56);
        insertLoopingAlphabetStreamData(
                ps, 5000);
        insertLoopingAlphabetStreamData(
                ps, 10000);
        insertLoopingAlphabetStreamData(
                ps, 300000);

        ps.setNull(1, Types.BLOB);
        ps.setInt(2, 0);
        ps.setNull(3, Types.BIGINT);
        ps.executeUpdate();

        ps.close();

        commit();
    }


    private void insertUnicodeData(String[] unicodeString) throws Exception {
        PreparedStatement ps = prepareStatement(
                "INSERT INTO testClob (a, b, c) VALUES (?, ?, ?)");

        for (int i=0; i<unicodeString.length; i++) {
            ps.setString(1, unicodeString[i]);
            ps.setInt(2, unicodeString[i].length());
            ps.setInt(3, i);
            ps.addBatch();
        }
        ps.executeBatch();
        ps.clearBatch();

        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.tamil(), 0);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.tamil(), 56);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.tamil(), 5000);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.tamil(), 10000);
        insertLoopingAlphabetStreamData(
                ps, CharAlphabet.tamil(), 300000);

        ps.setNull(1, Types.CLOB);
        ps.setInt(2, 0);
        ps.setInt(3, -1);
        ps.executeUpdate();

        ps.close();
        commit();
    }

    private void insertLoopingAlphabetStreamData(
            PreparedStatement ps,
            int lobLength)
        throws Exception
    {
        ps.setBinaryStream(1, new LoopingAlphabetStream(lobLength), lobLength);
        ps.setInt(2, lobLength);
        ps.setLong(3, getStreamCheckSum(new LoopingAlphabetStream(lobLength)));
        ps.executeUpdate();
    }

    private void insertLoopingAlphabetStreamData(
            PreparedStatement ps,
            CharAlphabet alphabet,
            int lobLength)
        throws Exception
    {
        ps.setCharacterStream(1, new LoopingAlphabetReader(lobLength, alphabet),
                lobLength);
        ps.setInt(2, lobLength);
        ps.setLong(3, -1);
        ps.executeUpdate();
    }

    private boolean compareReaders(Reader origValue, Reader newValue)
    throws Exception {
        char[] origBuff = new char[1024];
        char[] newBuff = new char[1024];
        int countOrig = -1;
        int countNew = -1;
        do {
            countOrig = origValue.read(origBuff);
            countNew = newValue.read(newBuff);
            if (countOrig != countNew) {
                return false;
            }
            if (!java.util.Arrays.equals(origBuff, newBuff)) {
                return false;
            }
        } while (countOrig != -1);
        return true;
    }

    /**
     * Get the CRC32 checksum of a stream, reading
     * its contents entirely and closing it.
     */
    private long getStreamCheckSum(InputStream in)
    throws Exception {
        CRC32 sum = new CRC32();

        byte[] buf = new byte[32*1024];

        for (;;) {
            int read = in.read(buf);
            if (read == -1)
                break;
            sum.update(buf, 0, read);
        }
        in.close();
        return sum.getValue();
    }

    /**
     * Verifies the value returned by the method Clob.getSubstring()
     */
    private void verifyInterval(Clob clob, long pos, int length,
            int testNum, int clobLength) throws Exception {
        try {
            String subStr = clob.getSubString(pos, length);
            assertEquals("FAIL - getSubString returned wrong length",
                    Math.min((clob.length() - pos) + 1, length),
                    subStr.length());
            assertEquals("FAIL - clob has mismatched lengths",
                    clobLength, clob.length());
            assertFalse("FAIL - NO ERROR ON getSubString POS TOO LARGE",
                    (pos > clobLength + 1));

            // Get expected value usign Clob.getAsciiStream()
            char[] value = new char[length];
            String valueString;
            Reader reader = clob.getCharacterStream();
            long left = pos - 1;
            long skipped = 0;
            if (clobLength > 0) {
                println("clobLength: " + clobLength);
                while (left > 0 && skipped >= 0) {
                    skipped = reader.skip(Math.min(1024, left));
                    left -= skipped > 0 ? skipped : 0;
                }
            }
            int numBytes = reader.read(value);

            // chech the the two values match
            if (numBytes >= 0) {
                char[] readBytes = new char[numBytes];
                System.arraycopy(value, 0, readBytes, 0, numBytes);
                valueString = new String(readBytes);
                assertEquals("FAIL - wrong substring value",
                        valueString, subStr);
            } else {
                assertTrue("FAIL - wrong length", subStr.length() == 0);
            }
        } catch (SQLException e) {
            if (pos <= 0) {
                checkException(BLOB_BAD_POSITION, e);
            } else {
                if (pos > clobLength + 1) {
                    checkException(BLOB_POSITION_TOO_LARGE, e);
                } else {
                    throw e;
                }
            }
        }
    }

    /**
     * Verifies the value returned by the method Blob.getBytes()
     */
    private void verifyInterval(Blob blob, long pos, int length,
            int testNum, int blobLength) throws Exception {
        try {
            String subStr = new String(blob.getBytes(pos,length), "US-ASCII");
            assertEquals("FAIL - getSubString returned wrong length ",
                    Math.min((blob.length() - pos) + 1, length),
                    subStr.length());
            assertEquals("FAIL - clob has mismatched lengths",
                    blobLength, blob.length());
            assertFalse("FAIL - NO ERROR ON getSubString POS TOO LARGE",
                    (pos > blobLength + 1));

            // Get expected value usign Blob.getBinaryStream()
            byte[] value = new byte[length];
            String valueString;
            InputStream inStream = blob.getBinaryStream();
            inStream.skip(pos - 1);
            int numBytes = inStream.read(value);
            // check that the two values match
            if (numBytes >= 0) {
                byte[] readBytes = new byte[numBytes];
                System.arraycopy(value, 0, readBytes, 0, numBytes);
                valueString = new String(readBytes, "US-ASCII");
                assertEquals("FAIL - wrong substring value",
                        valueString, subStr);
            } else {
                assertTrue("FAIL - wrong length", subStr.length() == 0);
            }
        } catch (SQLException e) {
            if (pos <= 0) {
                checkException(BLOB_BAD_POSITION, e);
            } else {
                if (pos > blobLength + 1) {
                    checkException(BLOB_POSITION_TOO_LARGE, e);
                } else {
                    throw e;
                }
            }
        }
    }


    /**
     * Test the contents of the testBlob table or ResultSet
     * with identical shape.
     * @param rs
     * @throws Exception
     */
    public void testBlobContents(ResultSet rs) throws Exception {
        int nullCount = 0;
        int rowCount = 0;
        byte[] buff = new byte[128];
        // fetch row back, get the long varbinary column as a blob.
        Blob blob;
        int blobLength = 0, i = 0;
        while (rs.next()) {
            i++;
            // get the first column as a clob
            blob = rs.getBlob(1);
            long crc32 = rs.getLong(3);
            boolean crc2Null = rs.wasNull();
            if (blob == null) {
                assertTrue("FAIL - NULL BLOB but non-NULL checksum", crc2Null);
                nullCount++;
            } else {
                rowCount++;

                long blobcrc32 = getStreamCheckSum(blob.getBinaryStream());
                assertEquals("FAIL - mismatched checksums for blob with " +
                        "length " + blob.length(), blobcrc32, crc32);

                InputStream fin = blob.getBinaryStream();
                int columnSize = 0;
                for (;;) {
                    int size = fin.read(buff);
                    if (size == -1)
                        break;
                    columnSize += size;
                }
                blobLength = rs.getInt(2);
                assertEquals("FAIL - wrong column size",
                        blobLength, columnSize);
                assertEquals("FAIL - wrong column length",
                        blobLength, blob.length());
            }
        }
        assertEquals("FAIL - wrong not null row count null:" + nullCount,
                9, rowCount);
        assertEquals("FAIL - wrong null blob count", 1, nullCount);
    }

    /**
     * From LobTest.java, test various inserts on a BLOB column
     * 
     * @throws SQLException
     */
    public void testBlobInsert() throws SQLException {
        String[] typeNames = { "int", "char(10)", "varchar(80)", "long varchar",
                "char(10) for bit data", "long varchar for bit data", "blob(80)" };

        Connection conn = getConnection();
        Statement s = conn.createStatement();

        // create table for testing

        s.execute("create table blobCheck (bl blob(80)) ");

        int columns = typeNames.length;
        // test insertion of literals.
        for (int i = 0; i < columns; i++) {

            if (typeNames[i].indexOf("blob") == -1)
                continue;

            // Check char literals.
            // (fail)
            String insert = "insert into blobCheck (bl"
                    + " ) values ('string' )";
            assertStatementError("42821",s,insert);
            // (succeed)
            insert = "insert into blobCheck (bl" + " ) values (cast ("
                    + Utilities.stringToHexLiteral("string") + " as blob(80)) )";
            s.execute(insert);
            // Check bit literals.
            // (fail)
            insert = "insert into blobCheck (bl" + " ) values (X'48' )";
           assertStatementError("42821",s,insert);
            // old CS compatible value: ( b'01001' )
            // (succeed)
            insert = "insert into blobCheck (bl"
                    + " ) values (cast (X'C8' as blob(80)) )";
            s.execute(insert);
            // Check hex literals.
            // (fail)
            insert = "insert into blobCheck (bl" + " ) values ( X'a78a' )";
            assertStatementError("42821",s,insert);
            // (succeed)
            insert = "insert into blobCheck (bl"
                    + " ) values (cast (X'a78a' as blob(80)) )";
            s.execute(insert);
        }
        s.execute("drop table blobCheck");
    }

     
    private void checkException(String SQLState, SQLException se)
            throws Exception
    {
         assertSQLState(SQLState, se);
    }


    /**
     * DERBY-3243 Fix ArrayIndexOutOfBounds Exception
     * if we retrieve more than 32K lobs
     * 
     */
    public void testRetrieveMoreThan32KLobs() throws SQLException
    {
        int numRows = 34000;
        // Load the database
        Connection conn = getConnection();
        conn.setAutoCommit(false);
        Statement s = createStatement();
        
        PreparedStatement ps = prepareStatement("INSERT INTO TESTCLOB VALUES(?,?,?)");
        for (int i = 0 ; i < numRows;i++)
        {
            ps.setInt(1,i);
            ps.setInt(2,i);
            ps.setString(3,"" + i);
            ps.executeUpdate();
            if (i % 1000 == 0) {
                commit();
            }
        }
        commit();
        
        // retrieve the data
        
        ResultSet rs = s.executeQuery("SELECT * from TESTCLOB");
        while (rs.next()) {
            rs.getInt(1);
            Clob c = rs.getClob(3);
            c.getSubString(1,100);
        }
        rs.close();
        
        conn.commit();
        
        
    }

    /**
     * Test that Blob.truncate() resets the position before copying the first
     * N bytes into a new holder object. The bug is only triggered if the
     * BLOB returned as a stream from store. That is, it must be larger than
     * one page so that it's not materialized. Regression test for DERBY-5113.
     */
    public void testDerby5113() throws Exception {
        setAutoCommit(false);

        // Insert a BLOB larger than one page. Normally, this means larger
        // than 32K, but the test tables use smaller pages, see comment in
        // setUp().
        PreparedStatement insert = prepareStatement(
                "insert into testblob(a) values ?");
        insert.setBinaryStream(1, new LoopingAlphabetStream(5000), 5000);
        insert.executeUpdate();

        // Retrieve the BLOB.
        Statement s = createStatement();
        ResultSet rs = s.executeQuery("select a from testblob");
        rs.next();
        Blob blob = rs.getBlob(1);

        // Now call getBytes() so that the position in the underlying stream
        // is changed.
        byte[] bytes = blob.getBytes(1, 3000);
        assertEquals(new LoopingAlphabetStream(3000),
                     new ByteArrayInputStream(bytes));

        // Truncate the BLOB. This used to fail with "Reached EOF prematurely"
        // because truncate() didn't move the position in the underlying stream
        // back to the beginning.
        blob.truncate(4000);

        // Verify that the BLOB was truncated correctly.
        assertEquals(4000, blob.length());
        bytes = blob.getBytes(1, 4000);
        assertEquals(new LoopingAlphabetStream(4000),
                     new ByteArrayInputStream(bytes));

        rs.close();
    }

    private void checkSmallPageSize(Statement st, String tblName)
        throws SQLException
    {
        ResultSet rs = st.executeQuery(
            "select * from TABLE(SYSCS_DIAG.SPACE_TABLE('"+tblName+"')) T");

        int found_rows = 0;
        while (rs.next())
        {
            found_rows++;
            assertEquals(4096, rs.getInt("pagesize"));
        }
        assertTrue(found_rows == 1);
        rs.close();
    }
        
    
    private static final String BLOB_BAD_POSITION = "XJ070";
    private static final String BLOB_NONPOSITIVE_LENGTH = "XJ071";
    private static final String BLOB_POSITION_TOO_LARGE = "XJ076";
    private static final String LANG_DATA_TYPE_GET_MISMATCH = "22005";
    private static final String BLOB_NULL_PATTERN_OR_SEARCH_STR = "XJ072";
    private static final String LOCK_TIMEOUT = "40XL1";
    private static final String NO_CURRENT_CONNECTION = "08003";
    private static final String INVALID_LOB = "XJ215";

}