File: manual.tex

package info (click to toggle)
apq 3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,772 kB
  • ctags: 406
  • sloc: ada: 2,943; ansic: 2,053; sh: 676; makefile: 204
file content (11061 lines) | stat: -rw-r--r-- 378,140 bytes parent folder | download
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
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
% APQ-2.2 Manual

\documentclass[english,letterpaper]{book}
\usepackage{times}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage{longtable}
\usepackage{amsmath}
\usepackage{amssymb}

\usepackage{floatflt}
\usepackage{fancyhdr}

\pagestyle{fancy}

%\lhead{}
%\chead{}
\rhead{}

\lfoot{}
\cfoot{\thepage}
\rfoot{APQ 3.0}


\newcommand\Ref[1]{\textsection\ref{#1} (page~\pageref{#1})}

\usepackage{fancyvrb}
\usepackage{listings}

\usepackage{makeidx}
\makeindex

\IfFileExists{url.sty}{\usepackage{url}}
                      {\newcommand{\url}{\texttt}}

\makeatletter

\usepackage{babel}
\makeatother



%==========%
% HYPERREF %
%==========%
\usepackage[dvipdfm, bookmarks, colorlinks, breaklinks, pdftitle={APQ User Manual},
    pdfauthor={KOW Framework Project}]{hyperref}
\hypersetup{
	linkcolor=DarkSkyBlue,
	citecolor= DarkSkyBlue,
	filecolor= DarkSkyBlue,
	urlcolor= DarkSkyBlue
}



%========================%
% Listings Package Setup %
%========================%
\usepackage{xcolor}
\usepackage{listings}


% COLORS (Tango)
\definecolor{LightButter}{rgb}{0.98,0.91,0.31}
\definecolor{LightOrange}{rgb}{0.98,0.68,0.24}
\definecolor{LightChocolate}{rgb}{0.91,0.72,0.43}
\definecolor{LightChameleon}{rgb}{0.54,0.88,0.20}
\definecolor{LightSkyBlue}{rgb}{0.45,0.62,0.81}
\definecolor{LightPlum}{rgb}{0.68,0.50,0.66}
\definecolor{LightScarletRed}{rgb}{0.93,0.16,0.16}
\definecolor{Butter}{rgb}{0.93,0.86,0.25}
\definecolor{Orange}{rgb}{0.96,0.47,0.00}
\definecolor{Chocolate}{rgb}{0.75,0.49,0.07}
\definecolor{Chameleon}{rgb}{0.45,0.82,0.09}
\definecolor{SkyBlue}{rgb}{0.20,0.39,0.64}
\definecolor{Plum}{rgb}{0.46,0.31,0.48}
\definecolor{ScarletRed}{rgb}{0.80,0.00,0.00}
\definecolor{DarkButter}{rgb}{0.77,0.62,0.00}
\definecolor{DarkOrange}{rgb}{0.80,0.36,0.00}
\definecolor{DarkChocolate}{rgb}{0.56,0.35,0.01}
\definecolor{DarkChameleon}{rgb}{0.30,0.60,0.02}
\definecolor{DarkSkyBlue}{rgb}{0.12,0.29,0.53}
\definecolor{DarkPlum}{rgb}{0.36,0.21,0.40}
\definecolor{DarkScarletRed}{rgb}{0.64,0.00,0.00}
\definecolor{Aluminium1}{rgb}{0.93,0.93,0.92}
\definecolor{Aluminium2}{rgb}{0.82,0.84,0.81}
\definecolor{Aluminium3}{rgb}{0.73,0.74,0.71}
\definecolor{Aluminium4}{rgb}{0.53,0.54,0.52}
\definecolor{Aluminium5}{rgb}{0.33,0.34,0.32}
\definecolor{Aluminium6}{rgb}{0.18,0.20,0.21}




\lstset{
	keywordstyle=[1]{\color{DarkSkyBlue}},
	keywordstyle=[2]{\color{DarkScarletRed}},
	keywordstyle=[3]{\bfseries},
	keywordstyle=[4]{\color{DarkPlum}},
	keywordstyle=[5]{\color{SkyBlue}},
	commentstyle={\color{Aluminium4}\small},
	stringstyle={\color{Chocolate}},
	tabsize=4,
	breaklines=true,
	basicstyle={\ttfamily\small},
	xleftmargin=21pt,
	xrightmargin=11pt,
	frame=single,
	rulecolor=\color{black!30},
	captionpos=b,
	framesep=10pt,
	framexleftmargin=18pt,
	numbers=none,
	numberstyle={\tiny},
	stepnumber=1,
	numbersep=15pt
}



\lstdefinelanguage{Ada}{%
	morekeywords={alfa,and,array,begin,boolean,byte,case,char,const,div,%
	do,downto,else,end,false,file,for,function,get,goto,if,in,%
	integer,label,maxint,mod,new,not,of,or,pack,packed,page,program,%
	procedure,put,read,readln,real,record,repeat,reset,rewrite,set,%
	text,then,to,true,type,unpack,until,var,while,with,write,writeln},%
	sensitive=false,%
	morecomment=[s]{(*}{*)},%
	morecomment=[s]{\{}{\}},%
	morestring=[d]{'}%
}
\lstdefinelanguage{SQL}{%
	morekeywords={select,insert,table,from,into,create,delete,alfa,and,array,begin,boolean,byte,case,char,const,div,%
	do,downto,else,end,false,file,for,function,get,goto,if,in,%
	integer,label,maxint,mod,new,not,of,or,pack,packed,page,program,%
	procedure,put,read,readln,real,record,repeat,reset,rewrite,set,%
	text,then,to,true,type,unpack,until,var,while,with,write,writeln},%
	sensitive=false,%
	morecomment=[s]{(*}{*)},%
	morecomment=[s]{\{}{\}},%
	morestring=[d]{'},%
	caption=SQL%
}




\lstnewenvironment{SQL}{\lstset{language=SQL}}{}

\lstnewenvironment{Code}{\lstset{language=Ada}}{}

\lstnewenvironment{Example}{\lstset{language=Ada,title=Example}}{}
\lstnewenvironment{NumberedExample}{\lstset{language=Ada,label=Example}}{}



%\DefineVerbatimEnvironment{SQL}{Verbatim}%
%   {frame=single,fontsize=\small,label={SQL},labelposition=topline}
%\DefineVerbatimEnvironment{Code}{Verbatim}%
%   {frame=single,fontsize=\small}
%\DefineVerbatimEnvironment{Example}{Verbatim}%
%   {frame=single,fontsize=\small,label={Example},labelposition=topline}
%\DefineVerbatimEnvironment{NumberedExample}{Verbatim}%
%   {frame=single,numbers=left,fontsize=\small,label={Example},labelposition=topline,commandchars=\\\{\}}


%==============%
% The document %
%==============%


\begin{document}

\title{APQ Ada95 Database Binding}
\author{%
Copyright (c) 2002-2004, Warren W. Gay VE3WWG\\%
Copyright (c) 2007-2009, KOW Framework Project
}
\date{\today}
\maketitle

\tableofcontents{}
\listoftables
%\listoffigures

\chapter{Introduction}


\section{APQ Version 2.2}

This manual documents APQ Version 2.2, which is released under a dual
ACL\index{ACL} and GPL\index{GPL} (GNU Public License)\index{GNU Public
License} arrangement. The dual license arrangement is designed to give
both the \index{distributor} and user the necessary freedoms to enjoy
the fair use and distribution of the sources \index{distribution of
sources} contained in this project. See file COPYING\index{copying} for
more details.


\section{Supported Databases}

The APQ binding\index{binding} was initially created to satisfy the simple need to
allow Ada\index{Ada} programs to use a PostgreSQL\index{PostgreSQL} database. However, as open
sourced database technologies continue to advance, the need to allow
other databases to be used, becomes greater. Rather than write a unique
Ada binding for each one, it was conceptualized that a common API\index{API}
could emerge from the APQ framework\index{framework}. To this end, the APQ binding
has been reworked rather extensively for version 2.1, to permit increasing
levels of general support of other database technologies, including
MySQL\index{MySQL}.

In the fall of 2003 the foundation was laid for Sybase\index{Sybase} support in
the unreleased APQ 2.2 software using Sybase on a trial download\index{download} basis.
Sybase highlighted some new APQ design \index{design, APQ} wrinkles, which required a
few new adjustments and API additions. However, this development ground
to a halt for a spell, until September 9, 2004 when it was announced
on www.slashdot.org\index{www.slashdot.org} that ``Sybase Releases Free Enterprise Database
on Linux''\index{Linux}.

\begin{quote}
``Sybase announced today that they are releasing a free (as in
beer) version of their flagship database for Linux. The free version
is limited to 1 CPU, 2 GB of RAM, and 5 GB of data, which is more
than adequate for all but the most demanding applications. This release
provides a very attractive alternative to Microsoft SQL Server\index{Microsoft SQL Server}, and
gives developers and DBAs an extremely powerful argument to use against
the adoption of Microsoft-based solutions.''%
\footnote{Posted by ``Tassach'' (tassach@rapiertech.com)}
\end{quote}

Now there was greater reason to put enterprise class database support
into an Ada thick binding\index{thick binding} for databases. Sybase support in APQ would
allow developers to develop real applications in using Ada, without
trial software expiring. Once developed, these same Ada applications
could be deployed within the enterprise and on a large scale.

\begin{floatingtable}{
   \begin{tabular}{lccc}
   Database       &  As of APQ Version &  SQL   &  Blob \\
   \hline
   PostgreSQL     &  1.x               &  Yes   &  Yes  \\
   MySQL          &  2.x               &  Yes   &  No   \\
   Sybase 12.52   &  2.2               &  Yes   &  No   \\
   SQL Server     &  3.0               &  Yes   &  No   \\
   \end{tabular}}
   \caption{Database Product Support}\label{t:DBSupport}
\end{floatingtable}


Thanks in part to the generosity of Sybase to developers, APQ 3.0
now supports the following list of database\index{list of database technologies} technologies:
Table \ref{t:DBSupport} is further described as follows:

\begin{description}
   \item [As of APQ Version]is the version where the database was first supported.
   \item [SQL]indicates whether the common SQL functions are supported (sans blob).
   \item [Blob]indicates whether blob support is present.
\end{description}

As the reader can observe in the table above, the support for MySQL
is incomplete in APQ 2.1. The blob support\index{blob support} is lacking in APQ for MySQL,
because MySQL's blob interface is not as complete as provided by PostgreSQL.
Where PostgreSQL provides the facility for virtually limitless sized
blobs, a MySQL blob must fit within a ``column'', very much like
a text field. For this reason, the facility to perform stream oriented\index{stream oriented}
I/O is lacking on a blob in APQ for MySQL.\\

Also, there han't been time or interest in developing Blob support in Sybase and SQL Server
so far. This implementation should take quite a while to be done and for now the focus of 
the project is in providing a stable solution for database connectivity.


\subsection{The Future of Blob Support for MySQL}

Much investigation and research\index{research, APQ} is required to adequately resolve
the blob issue in APQ. Rather than hold back the binding from general
use, where blob functionality may have limited use anyway, it was
decided to release APQ 2.0 with the common API for the two databases,
and leaving the resolution of the blob API for a future release.

If you are a developer, who hopes to write portable database\index{portable database code} code,
then please be aware that the PostgreSQL\index{PostgreSQL} blob\index{blob} API is subject to future
revision. Potentially, this could be fairly extensively revised, but
every attempt will be made to leave a migration path open to the developer.


APQ 3.0 inhertis


\section{Generic Database Support}

One of the main goals of the APQ version 2.0 release, was to develop
a common API\index{API, common}, that does not discriminate based upon the database technology
being selected. The ideal was to allow a developer to write a procedure
that would accept a classwide\index{classwide} database objects, and perform database
operations without needing to be concerned whether the database being
used was PostgreSQL\index{PostgreSQL}, MySQL\index{MySQL} or Sybase\index{Sybase}.
To a large extent, the author believes that this goal has been achieved.


\subsection{Generic Limitations}

It must be admited however, there are some areas where the database
technologies were very different. Consequently, some exceptions and
work-arounds will be required by the programmer. An example of this
is that MySQL\index{MySQL} requires that all rows be fetched from a SELECT\index{SELECT} query.
A failure to do this, corrupts the communication between the server\index{communication, server}
and the client. Consequently, APQ works around this by defaulting
to use the C library call mysql\_store\_result()\index{mysql\_store\_result()} instead of the alternative,
which is mysql\_use\_result()\index{mysql\_use\_result()}. However, if the result set is large,\index{large result sets}
then receiving all of the rows into the clients memory\index{memory, client} is not a suitable
choice. Consequently, APQ does provide some MySQL specific ways to
manage this setting. 

The MySQL database software also provides the special ``LIMIT n''\index{LIMIT n}
extension, if the client program is only interested in the first n
rows of the result. If for example, you have a price file containing
stock price history, you may want to query the most recent price for
it. The simplest way to do this would be to perform a SELECT\index{SELECT} on the
table with a descending price date sort sequence (or index). But if
you only want the first (most recent) row \index{most recent row} returned, you do not want
to retrieve the entire price history into the memory of your client!
This is what mysql\_store\_result()\index{mysql\_store\_result()} implies (APQ default). So the
application programmer will need to plan for this, when MySQL is used.
He will need to do one of the following:

\begin{itemize}
   \item Cause mysql\_use\_result() to be used instead (change the APQ default),
         and then fetch all of the rows, one by one.
   \item Use the MySQL ``LIMIT 1''\index{LIMIT n} SQL extension to limit the results to
         1 row.
\end{itemize}

The problem of course, is that this type of handling must only be
done for MySQL\index{MySQL} databases. Consequently, APQ also provides an API so
that the application may query which database is being used.


\section{The APQ Database Binding}

This software represents a binding\index{binding to objects} to objects and procedures that
enable the Ada95\index{Ada95}%
\footnote{Hereafter, we'll just refer to the language as Ada, even though the
version of the language implied is Ada95.%
} programmer to manipulate or query a relational database.\index{relational database} This document
describes the design principles and goals\index{goals of APQ} of this APQ binding. It
also supplies reference documentation\index{reference documentation} to the programmer, enabling
the reader to write applications using the PostgreSQL\index{PostgreSQL}, MySQL\index{MySQL} 
or Sybase\index{Sybase}  databases,
in the Ada programming language.

The APQ binding\index{binding} was initially developed using GNAT
3.13p\index{GNAT} under FreeBSD 4.4\index{FreeBSD} release.
APQ version 2.0 was developed using Debian\index{Debian Linux} Linux\index{Linux} and GNAT 3.14p. The
examples presented will be tested under the same development environments.

The source code avoids any use of GNAT\index{GNAT} specific language extensions\index{language extensions}.
The possible exception to this rule is that the gnatprep\index{gnatprep} tool may
be used to precompile\index{precompile} optional support of optional databases\index{optional databases}. There
is some C\index{C language} language source\index{source code} code used, to facilitate Ada\index{Ada} and database
C language library linkages.

\begin{table}
   \begin{center}
   \begin{tabular}{ll}
   Library           &  Database\\
   \hline 
   libpq             &  PostgreSQL\\
   libmysqlclient    &  MySQL\\
   OCS-12\_5         &  Sybase\\
   \end{tabular}
   \end{center}
\caption{Client Libraries}\label{t:ClientLib}
\end{table}

Table \ref{t:ClientLib} 
lists the C language libraries\index{libraries, C} that are
used in addition to the APQ client\index{library, APQ client} library, while linking\index{linking} your
application:

GNAT specific features are avoided where possible. The exception
however, is the use of the GNAT\index{GNAT} specific pragma\index{pragma} statements of the form:

\index{Linker\_Options}
\begin{Code}

   pragma Linker_Options("-lapq");

\end{Code}

is used for example, to save the programmer from having to specify
linking\index{linking} arguments. Therefore those using non-ACT\index{non-ACT} vendor
supplied Ada compilers\index{Ada compilers} might be able to compile and use this binding\index{binding}
without a huge investment.

A 32-bit\index{32-bit Windows} Windows library for APQ can be built for use with the PostgreSQL\index{PostgreSQL},
MySQL\index{MySQL} or Sybase\index{Sybase} DLL\index{DLL} client libraries. APQ release 2.1 included the
win32 build instructions necessary, but was omitted in the 2.0 release.


\subsection{General Features}

This binding\index{binding} supports all of the normal database functions that a
programmer would want to use. Additionally blob\index{blob} support
is included%
\footnote{For PostgreSQL only, at release 2.0.%
}, and implemented using the Ada streams\index{streams, Ada} interface\index{interface}.
This provides the programmer with the Ada convenience and safety of
the streams interface\index{streams interface} when working with blobs.

This binding includes the following general features:

\begin{enumerate}
   \item Open and Close one or more concurrent database connections\index{connections}
   \item Create and Execute one or more concurrent SQL queries\index{queries, concurrent} on a selected
         database connection\index{connection, database}
   \item Begin work\index{begin work}, Commit work\index{commit work} or Rollback work\index{rollback work}
   \item Access error message\index{error messages} text
   \item Generic functions and procedures to support specialized application
         types
   \item The NULL indicator\index{NULL indicator} is supported
   \item Blob\index{blob} support using the Ada streams\index{streams, Ada} facility
   \item A wide range of native\index{native types} and builtin\index{builtin data types} data types are supported
   \item Database neutral API\index{neutral API, database} is now supported for most functions
\end{enumerate}

\subsection{Binding Type}

This library represents a thick Ada binding\index{thick binding} to the PostgreSQL C\index{C programmer}  programmer's
libpq\index{libpq} library %
\footnote{C++ programs can also make use of this library but there exists the
library libpq++ for C++ native support.%
}, and with version 2.0, MySQL's\index{MySQL} C programming library. As a thick
binding, there are consequently Ada objects\index{objects, Ada} and data types that are
tailored specifically to the Ada programmer. Some data types and objects
exist to mirror those used in the C language, while others are provided
to make the binding easier or safer to apply.

A thin binding\index{thin binding} would have required the Ada programmer to be continually
dealing with C language\index{C language data types} data type issues. Conversions to and from
various types and pointers\index{pointers} would be necessary making the use of the
binding rather tedious. Furthermore, the resulting Ada\index{Ada} program would
be much harder to read and understand.

A thick binding\index{thick binding} introduces new objects and types in order to provide
an API to the programmer. This approach however, fully insulates the
Ada\index{Ada} programmer from interfacing with C programs\index{C programs}, pointers\index{pointers} and strings\index{strings}.
The design goal\index{design goal} has additionally been to keep the number of new objects
and types to a minimum. This has been done without sacrificing convenience
and safety\index{safety}. Readability\index{readability} of the resulting Ada\index{Ada} program was also considered
to be important.

The objects and data types involved in the use of this binding can
be classified into the following main groups:

\begin{enumerate}
   \item Native\index{native data types} data types and objects
   \item Database \index{database objects} manipulation objects
   \item New database related objects and types for holding data
\end{enumerate}

Native data types need no explanation in this document. The database
manipulation objects will be described in 
\Ref{Database_Objects:Section}.
The following section will introduce the Ada types\index{Ada types} that are used to
hold data.


\section{Binding Data Types}

The PostgreSQL\index{PostgreSQL} database supports many standard SQL\index{SQL data types} data types as well
as a few exotic ones. This section documents the database base types\index{data types, database}
that are supported by the Ada\index{Ada binding} binding to the database. This list is
expected to grow with time as the Ada binding continues to mature
in its own software development.

The ``Data Type Name'' column in the following table refers to
a binding type\index{binding type} if the type name is prefixed with ``APQ\_''%
\footnote{Formerly, the PostgreSQL specific types had used a PG\_ prefix.%
}. These data types were designed to mimic common database data types
in use. They can be used as they are provided, or you may subtype
from them or even derive new types from them in typical Ada\index{Ada} fashion.
All other data types are references to native Ada data types (for
some of these, the package where they are defined are shown in the
``Notes'' column).

The column labelled ``Root Type''\index{root types} documents the data type that
the APQ\_ data type was derived\index{derived} from. Where they represent an Ada\index{subtype, Ada}
subtype, the column ``Subtype'' indicates a ``Y''. For type
derivations a ``N'' is shown in this column, indicating that the
APQ\_ type \index{APQ\_ types} listed is made ``unique''.


\subsection{PostgreSQL Data Types\label{PostgreSQL SQL Data Types}}

The ``Notes'' column of Table \ref{t:pqtypes} provides PostgreSQL notes, package names\index{package names} and
PostgreSQL\index{data types, PostgreSQL} data type names where the name is given in all capitals.

\begin{longtable}{|l|c|c|l|}
\hline 
Data Type Name    &  Root Type   &  Subtype  &  PostgreSQL Notes\\
\hline \hline 
Row\_ID\_Type     &  -           &  N        &  Used for blobs and rows\\
\hline 
String(<>)        &  -           &  -        &  Native Strings\\
\hline 
String(a..b)      &  -           &  -        &  Fixed length strings\\
\hline 
Unbounded\_String &  -           &  -        &  Ada.Strings.Unbounded\\
\hline 
Bounded\_String   &  -           &  -        &  Ada.Strings.Bounded\\
\hline 
APQ\_Smallint     &  -           &  N        &  SMALLINT\\
\hline 
APQ\_Integer      &  -           &  N        &  INTEGER\\
\hline 
APQ\_Bigint       &  -           &  N        &  BIGINT\\
\hline 
APQ\_Real         &  -           &  N        &  REAL\\
\hline 
APQ\_Double       &  -           &  N        &  DOUBLE PRECISION\\
\hline 
APQ\_Serial       &  -           &  N        &  SERIAL\\
\hline 
APQ\_Bigserial    &  -           &  N        &  BIGSERIAL\\
\hline 
APQ\_Boolean      &  Boolean     &  Y        &  BOOLEAN\\
\hline 
APQ\_Date         &  Ada.Calendar.Time & Y   &  DATE\\
\hline 
APQ\_Time         &  Ada.Calendar.Day\_Duration & Y & TIME\footnote{No timezone information}\\
\hline 
APQ\_Timestamp    &  Ada.Calendar.Time & N   & TIMESTAMP\footnote{No timezone information}\\
\hline 
APQ\_Timezone     &  Integer     &  N        &  range -23..23\\
\hline 
APQ\_Bitstring    &  -           &  N        &  BIT or BIT VARYING\\
\hline 
Decimal\_Type     &  -           &  -        &  PostgreSQL.Decimal\\
\hline 
range <>          &  -           &  -        &  Native Integers\\
\hline 
delta <>          &  -           &  -        &  Native Fixed Point\\
\hline 
digits <>         &  -           &  -        &  Native Floating Point\\
\hline 
delta <> digits <> & -           &  -        &  Native Decimal\\
\hline
\caption{PostgreSQL Data Types}\label{t:pqtypes}
\end{longtable}

The data type shown as ``Decimal\_Type''\index{Decimal\_Type}
is special, in that it is supported from a child package APQ\-.PostgreSQL\-.Decimal\index{APQ.PostgreSQL.Decimal}.
It represents a tagged\index{tagged type} type that provides an interface to the C routines\index{C routines}
used by the PostgreSQL database server, for arbitrary precision decimal\index{precision, arbitrary}
values.


\subsection{MySQL Data Types\label{MySQL Data Types}}

Table \ref{t:mytypes} summarizes the MySQL\index{data types, MySQL} specific data types and the
corresponding APQ data types.

\begin{longtable}{|l|c|c|l|}
\hline 
APQ Data Type        &  Ada Spec                   &  Subtype     &  Comments\\
\hline
\hline 
Row\_ID\_Type        &  unsigned 64 bits           &  N           &  For all databases\\
\hline 
APQ\_Smallint        &  signed 16 bits             &  N           &  SMALLINT\\
\hline 
APQ\_Integer         &  signed 32 bits             &  N           &  INTEGER\\
\hline 
APQ\_Bigint          &  signed 64 bits             &  N           &  BIGINT\\
\hline 
APQ\_Real            &  digits 6                   &  N           &  REAL\\
\hline 
APQ\_Double          &  digits 15                  &  N           &  DOUBLE PRECISION\\
\hline 
APQ\_Serial          &  range 1..2147483647        &  N           &  \emph{INTEGER}\\
\hline 
APQ\_Bigserial       &  range 1..2{*}{*}63         &  N           &  \emph{BIGINT}\\
\hline 
APQ\_Boolean         &  Boolean                    &  Y           &  BOOLEAN\\
\hline 
APQ\_Date            &  Ada.Calendar.Time          &  Y           &  DATE\\
\hline 
APQ\_Time            &  Ada.Calendar.Day\_Duration &  Y           &  TIME\\
\hline 
APQ\_Timestamp       &  Ada.Calendar.Time          &  N           &  TIMESTAMP\\
\hline 
APQ\_Timezone        &  range -23..23              &  N           &  \emph{Not in MySQL}\\
\hline 
APQ\_Bitstring       &  array(Positive) of APQ\_Boolean & N       &  \emph{Not in MySQL}\\
\hline
\caption{MySQL Data Types}\label{t:mytypes}
\end{longtable}

Notice the italicized SQL keywords\index{keywords, SQL} in the table. They identify the
SQL keywords that differ from PostgreSQL\index{PostgreSQL}. However, the programmer
only needs to be concerned with these SQL\index{keywords, SQL} keywords when creating new
tables or temporary tables. For example a column of type SERIAL\index{SERIAL} in
a PostgreSQL table, should be declared as a INTEGER\index{INTEGER} type in MySQL.


\section{Sybase Data Types}

The chart below outlines the mappings between APQ data types and Sybase
server data types\index{data types, Sybase}. The italicized SQL keywords
\index{keywords, SQL} in the table identify
the keywords that differ from PostgreSQL\index{PostgreSQL}. The following notes are
particular to Sybase\index{Sybase}:

\begin{itemize}	
   \item APQ\_Bigint is not completely range compatible with Sybase's \emph{NUMERIC}
         \index{APQ\_Bigint}\index{NUMERIC}\index{DECIMAL}
         (or \emph{DECIMAL}) server types. APQ\_Bigint will always accept Sybase server
         values, but the server will not be able to accept the full APQ\_Bigint range of values.
         To comply with the database server's range,
         the application designer should use:
\end{itemize}

\index{Sybase\_Bigint}
\begin{Code}
subtype Sybase_Bigint is APQ_Bigint
   range -10**38..10**38-1;
\end{Code}

\begin{itemize}
   \item APQ\_Bigserial\index{APQ\_Bigserial} is not supported.
   \item APQ\_Boolean\index{APQ\_Boolean}  maps to Sybase's data type \emph{BIT.}
   \item APQ\_Timezone\index{APQ\_Timezone} is not supported by any Sybase data type.
   \item APQ\_Bitstring\index{APQ\_Bitstring} is not supported.
\end{itemize}

Table \ref{t:sytypes} lists the APQ types supported for Sybase.

\begin{longtable}{|l|c|c|l|}
\hline 
APQ Data Type        &  Ada Spec          &  Subtype           &  Comments\\
\hline
\hline 
Row\_ID\_Type        &  unsigned 64 bits  &  N                 &  For all databases\\
\hline 
APQ\_Smallint        &  signed 16 bits    &  N                 &  SMALLINT\\
\hline 
APQ\_Integer         &  signed 32 bits    &  N                 &  INTEGER/INT\\
\hline 
APQ\_Bigint          &  signed 64 bits ($-10^{38}..$$10^{38}\textrm{-1}$) & N & \emph{NUMERIC/DECIMAL}\\
\hline 
APQ\_Real            &  digits 6          &  N                 &  REAL\\
\hline 
APQ\_Double          &  digits 15         &  N                 &  DOUBLE PRECISION\\
\hline 
APQ\_Serial          &  range 1..2147483647 & N                &  \emph{INTEGER}\\
\hline 
APQ\_Bigserial       &  range 1..$2^{63}$ &  N                 &  ???\\
\hline 
APQ\_Boolean         &  Boolean           &  Y                 &  \emph{BIT}\\
\hline 
APQ\_Date            &  Ada.Calendar.Time &  Y                 &  DATE\\
\hline 
APQ\_Time            &  Ada.Calendar.Day\_Duration & Y         &  TIME\\
\hline 
APQ\_Timestamp       &  Ada.Calendar.Time &  N                 &  \emph{DATETIME}\\
\hline 
APQ\_Timezone        &  range -23..23     &  N                 &  \emph{Not in Sybase}\\
\hline 
APQ\_Bitstring       &  array(Positive) of APQ\_Boolean & N    &  \emph{Not in Sybase}\\
\hline
\caption{Sybase Data Types}\label{t:sytypes}
\end{longtable}


\section{Database Objects\label{Database_Objects:Section}}

Much of the binding between Ada\index{Ada} and the database server is provided
through the use of tagged\index{tagged record} record types. Presently the APQ binding
operates through three object types\index{object types, APQ} listed in Table \ref{t:APQObj}.

\begin{table}
   \begin{center}
   \begin{tabular}{lll}
   Derived From            &  Object Type       &  Purpose\\
   \hline
   Root\_Connection\_Type  &  Connection\_Type  & Database connection\\
   Root\_Query\_Type       &  Query\_Type       & SQL interface\\
   N/A                     &  Blob\_Type        & Blob operations\\
   \end{tabular}
   \end{center}
   \caption{APQ Object Types}\label{t:APQObj}
\end{table}

The APQ objects from Table \ref{t:APQObj} are described more fully as follows:

\begin{description}
   \item[Connection\_Type] object is used with Query\_Type and Blob\_Type objects
         to perform SQL queries and blob operations respectively. This object
         maintains the connection to the database server.
   \item[Query\_Type] objects are used with one Connection\_Type object
         to perform SQL query operations. This object holds the text of the
         SQL query, some query state and result information. To execute a 
         query, it must be used in conjunction with a Connection\_Type object.
   \item[Blob\_Type] objects are used with one Connection\_Type object to 
         perform blob operations. This is currently only supported for PostgreSQL
         by APQ. All blob operations must occur within a transaction.
\end{description}

\begin{floatingtable}{
      \begin{tabular}{lc}
      Object            & Finalized \\
      \hline 
      Connection\_Type  & Yes \\
      Query\_Type       & Yes \\
      Blob\_Type        & No \\
      \end{tabular}}
\caption{Object Finalization Behavior}\label{t:Finalization}
\end{floatingtable}

Table \ref{t:Finalization} lists the three APQ objects and their finalization
behaviour.
While the Connection\_Type\index{Connection\_Type}
and Query\_Type\index{Query\_Type} objects are subject to
finalization, the Blob\_Type\index{Blob\_Type} is not.
This is because it represents an access type to
a Blob\_Object. This is similar in concept to an open a file, using
the File\_Type data type. This design approach was necessary
to support Ada\index{Ada} Streams\index{streams, Ada} oriented access for blobs.

\subsection{Object Hierarchy}

Before multiple database products were supported, the APQ object hierarchy\index{hierarchy}
was simple. To provide generic level support however, there are now
root\index{root objects} objects and derived objects\index{derived objects}. In most programming
contexts, the application writer does not need to be concerned with this fact.
However, if you frequently inspect the spec files\index{spec files} instead of the documentation\index{documentation},
you must be aware that primitives\index{primitives} for a given object may be declared
in multiple places. Examine Table \ref{t:pkghier} to review the APQ package hierarchy.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Package Name            & Description \\
         \hline 
         APQ                     & Root objects and primitives \\
         APQ.PostgreSQL          & Declarations and constants unique to PostgreSQL \\
         APQ.PostgreSQL.Client   & Derived objects and added primitives \\
         APQ.MySQL               & Declarations and constants unique to MySQL \\
         APQ.MySQL.Client        & Derived objects and added primitives \\
         APQ.Sybase              & Declarations and constants unique to Sybase \\
         APQ.Sybase.Client       & Derived objects and added primitves for Sybase \\
      \end{tabular}
   \end{center}
   \caption{APQ Package Hierarchy}\label{t:pkghier}
\end{table}

Table \ref{t:pkghier} illustrates that support for a given database is derived\index{derived}
from the APQ top level\index{top level package} package. Root objects\index{root level} are declared in APQ,
with common functionality. Some primitives must be overridden\index{overridden} by the
derived object in database specific packages. For example, APQ.Root\_Query\_Type
declares a primitive named Value (\emph{APQ.Value)} to return a string
column result. If this particular method is called, the exception
\emph{Is\_Abstract}\index{Is\_Abstract} will be raised to indicate that it must be overriden
with code to handle the specific database being used. Normally the
user would invoke APQ\-.MySQL\-.Client\-.Value when using the MySQL\index{MySQL} database,
for example. The programmer normally need not be aware of these details,
since object dispatching\index{dispatching} takes care of these details.

For this reason, the APQ\-.MySQL\-.Query\_Type object for example, is
derived from the APQ\-.Root\_Query\_Type\index{Root\_Query\_Type} object. This Query\_Type\index{Query\_Type} object
will provide its own implementation of the Value\index{Value} function to return
a column result, and will work as required.

Consequently, when looking for primitives\index{primitives} available to the Query\_Type
object, don't forget that many common primitives\index{common primitives} will be inherited\index{inherited}
from the APQ\-.Root\-\_Query\-\_Type object. The same is true for Connection\-\_Type\index{Connection\_Type}
objects. A number of common primitives are inherited from the APQ\-.Root\_Connection\_Type
object.


\chapter{Connecting to the Database}

Before any useful work can be accomplished by a database client program,
a connection must be established between the Ada program and the database
server. This chapter will demonstrate how to use the APQ binding\index{binding} to
enable a program to connect\index{connect} and disconnect\index{disconnect}
from the database server.

\section{The Connection\_Type}

The Connection\_Type\index{Connection\_Type} object holds everything that is needed to maintain
a connection\index{connection} to the database server. There are seven groups of primitive\index{primitive}
operations for this object:

\begin{enumerate}
   \item Context\index{Context} setting operations
   \item Connection\index{Connection} operations
   \item Connection Information functions\index{information functions}
   \item General Information operations
   \item Implicit operations (Finalization\index{Finalization})
   \item Trace Facilities\index{trace facilities}
   \item Generic Database Operations
\end{enumerate}

\section{Context Setting Operations}\label{Context_Setting_Operations}

These primitives ``configure''\index{configure} the connection\index{connection} that is
to be made later. When the object is initially created, it is in the
disconnected\index{disconnected state} state. While disconnected, configuration changes can be
made in to affect the next connection attempt. With the exception of the
database name\index{database name}, the application should not make configuration\index{configuration} changes
while the object is in the connected state\index{connected state}.
\footnote{This is not yet enforced by APQ.}

The configuration primitives\index{primitives} are listed in Table \ref{t:ctxops}.
\footnote{The items marked ``Root'' are primitives from APQ.Root\_Query\_Type.
The items marked {}``Derived'' are those overrides that are declared
on the APQ.{*}.Query\_Type object.}

\begin{table}
   \begin{center}
      \begin{tabular}{ccll}
      Type & Derivation & Name                  & Purpose \\
      \hline 
      proc & Root       & Set\_Host\_Name       & Set server host name \\
      proc & Root       & Set\_Host\_Address    & Set server host IP address \\
      proc & Root       & Set\_Port             & Set server port number \\
      proc & Root       & Set\_DB\_Name         & Set database name \\
      proc & Root       & Set\_User\_Password   & Set userid and password \\
      proc & Root       & Set\_Instance         & Set instance name to use \\
      proc & Root       & Set\_Options          & Set userid and password \\
      \end{tabular}
   \end{center}
\caption{Context Setting Primitives}\label{t:ctxops}
\end{table}

It would be nice if all database software products worked the same
way but the reality is very different. Table \ref{t:ctxdiffs} indicates how
the primitives apply by database product.\label{Set_Instance Support Chart}
In the table you can see that PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL} establish their
connection by specifying the host, port and database name. Sybase
on the other hand, specifies this information in their \emph{interface}
file. To access the appropriate Sybase\index{Sybase interface entry} interface entry requires only
the \emph{instance}\index{instance} information supplied by the Set\_Instance\index{Set\_Instance} call.

\begin{table}
   \begin{center}
      \begin{tabular}{lccc}
      Primitive            & PostgreSQL   & MySQL  & Sybase \\
      \hline 
      Set\_Host\_Name      & Yes          & Yes    & Ignored \\
      Set\_Host\_Address   & Yes          & Yes    & Ignored \\
      Set\_Port            & Yes          & Yes    & Ignored \\
      Set\_DB\_Name        & Yes          & Yes    & See Note %
      \footnote{Set\_DB\_Name is useful after the connection is made.}\\
      Set\_User\_Password  & Yes          & Yes    & Yes \\
      Set\_Instance        & No           & No     & Yes \\
      Set\_Options         & Yes          & Yes    & Yes \\
      \end{tabular}
   \end{center}
\caption{Context Setting Differences}\label{t:ctxdiffs}
\end{table}

\subsection{PostgreSQL Defaults}

The PostgreSQL database defines certain environment\index{environment, PostgreSQL} variables that
can specify defaults. These and the fallback\index{fallback values} values are documented
in Table \ref{t:pqdef}.

\begin{table}
   \begin{center}
      \begin{tabular}{cclll}
      Type & Derivation    & Name               & Default      & Fallback \\
      \hline 
      proc & Root          & Set\_Host\_Name    & PGHOST       & localhost\\
      proc & Root          & Set\_Host\_Address & PGHOST       & localhost\\
      proc & Root          & Set\_Port          & PGPORT       & 5432\\
      proc & Root          & Set\_DB\_Name      & PGDATABASE   & LOGNAME\\
      proc & Root          & Set\_User\_Password &
         \begin{tabular}{l}
            PGUSER\\
            PGPASSWORD\\
         \end{tabular}
        & LOGNAME\\
      proc & Root          & Set\_Options       & PGOPTIONS    & ""\\
      \end{tabular}
   \end{center}
   \caption{PostgreSQL Context Defaults}\label{t:pqdef}
\end{table}

The capitalized names in the table for the ``Default'' and ``Fallback''
columns represent environment\index{environment} variable names.
When any of the environment\index{environment variables} variables are undefined in the ``Default''
column, the value used is determined by the ``Fallback'' value
listed. The fallback\index{fallback} variable name LOGNAME\index{LOGNAME}
is simply used to represent the current user's userid\index{userid}.%
\footnote{The PostgreSQL libpq library may in fact, completely ignore the LOGNAME
environment variable, and simply look up the userid in the /etc/password
file.%
} When no password\index{password} value is provided and no PGPASSWORD\index{PGPASSWORD}
environment variable exists, then no password is assumed.


\subsection{Procedure Set\_Host\_Name}

The Set\_Host\_Name\index{Set\_Host\_Name} procedure accepts the following arguments

\begin{Code}
procedure Set_Host_Name(
   C :         in out Connection_Type;
   Host_Name : in     String
);
\end{Code}

The following example configures the Connection\_Type object to connect
to host\index{host name} ``witherspoon'':

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_Host_Name(C,"witherspoon");
\end{Example}

\begin{description}
\item [Note:]Sybase ignores this API call.
\end{description}

\subsection{Procedure Set\_Host\_Address}

The procedure takes two arguments, in the same fashion as Set\_Host\_Name\index{Set\_Host\_Address}:

\begin{Code}
procedure Set_Host_Address(
   C :            in out Connection_Type;
   Host_Address : in     String
);
\end{Code}

The following example configures the Connection\_Type object to connect
to IP address\index{IP address} 10.0.0.7:

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_Host_Address(C,"10.0.0.7");
\end{Example}

\begin{description}
\item [Note:]Sybase ignores this API call.
\end{description}

\subsection{Procedure Set\_Port (IP)}

This procedure configures the port\index{port} where the database
server\index{server} is listening\index{listening} (when using TCP/IP\index{TCP/IP}
as the transport\index{transport}):

\begin{Code}
procedure Set_Port(
   C :           in out Connection_Type;
   Port_Number : in     Integer
);
\end{Code}

\begin{floatingtable}{
   \begin{tabular}{ccc}
   Database                &  Default  &  Port\\
   \hline 
   PostgreSQL              &  IP       &  5432\\
   MySQL                   &  UNIX     &  ?\\
   Sybase                  &  N/A      &  Ignored\\
   \end{tabular}}
   \caption{Default Database Connections}\label{t:defdb}
\end{floatingtable}

Table \ref{t:defdb} shows the connection defaults by database product. Some of these
are influenced by APQ. For example, APQ defaults to using a TCP/IP connection for the
PostgreSQL standard port of 5432.

The next example
shows how the port\index{port} number is configured.
The example configures APQ to use TCP/IP 
port number 5432\index{port 5432} to connect to
a PostgreSQL database.

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_Port(C,5432);
\end{Example}

\begin{description}
\item [Note:]Sybase ignores this API call.
\end{description}

\subsection{Procedure Set\_Port (UNIX)}

To create a local UNIX socket connection to the database, there is
an overloaded version of Set\_Port\index{Set\_Port} that accepts a string\index{string} parameter
instead of an integer\index{port, integer} port number.

\begin{Code}
procedure Set_Port(
   C :           in out Connection_Type;
   Port_Number : in     String
);
\end{Code}

Specify a null string\index{null string} for the connection\index{connection} 
to use the local\index{local socket} UNIX\index{UNIX socket} socket default.

This parameter has changed somewhat as PostgreSQL\index{PostgreSQL} evolves. If you
are experiencing trouble getting a UNIX\index{UNIX socket} socket connection to work,
check the database documentation for PostgreSQL carefully. The following
example has been tested to work on PostgreSQL version 7.3.5.

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_Port(C,"5432");
\end{Example}

See the troubleshooting chapter for tips.

\subsection{Procedure Set\_DB\_Name}

This procedure call configures the name of the database that the server
is to use \emph{prior} to the connection being established. Once
the connection has been established, calling Set\_DB\_Name\index{Set\_DB\_Name} switches the 
connection\index{connection} to use the named database.
The calling signature for this primitive is as follows:

\begin{Code}
procedure Set_DB_Name(
   C :       in out Connection_Type;
   DB_Name : in     String
);
\end{Code}

The following code fragment shows how the database name\index{database name} is configured
to be ``production'':

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_DB_Name(C,"production");
\end{Example}

The Set\_DB\_Name \emph{always} acts as a configuration setting \emph{prior}
to connecting to the database server. Calling Set\_DB\_Name on a Connection\_Type\index{Connection\_Type}
object that has an open server connection to the database, can result
in hidden SQL commands for some databases.%
\footnote{For PostgreSQL and Sybase, a USE <database> command must be executed.%
} Table \ref{t:setdb} summarizes the behaviour according to database product.

\begin{table}
   \begin{center}
      \begin{tabular}{llll}
      Database Vendor   &  Before Connecting &  While Connecting           &  After Connected\\
      \hline 
      PostgreSQL        &  Configuration     &  uses config     &  ``USE'' Executed\\
      MySQL             &  Configuration     &  uses config.    &  MySQL Client Call\\
      Sybase            &  Pending SQL       &  ``USE'' executed   &  ``USE'' Executed\\
      \end{tabular}
   \end{center}
   \caption{Set\_DB\_Name Behaviour}\label{t:setdb}
\end{table}

From the table you can see that PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL} configure the
database prior to connecting\index{connecting} (connecting also establishes the database
to be used). When Set\_\-DB\_\-Name is called after a connection has been
established, the database server will switch\index{switch database} to the requested database.
For some databases, this happens through the native\index{native client API} client API library\index{library}
(MySQL), but for others, a ``USE~<database>''\index{USE database} SQL\index{SQL} command must
be executed (internally within APQ).

\begin{floatingtable}{
   \begin{tabular}{ll}
   Exception Name    &  Reason\\
   \hline 
   Use\_Error        &  Unsuccessful doing a ``USE <database>''\\
   \end{tabular}}
   \caption{Set\_DB\_Name Exceptions}\label{t:sdbx}
\end{floatingtable}

Sybase\index{Sybase} is different again, because does not establish the database
at connect time\index{connect time} (Sybase will use the configured default database).
So a call to Set\_DB\_Name will queue a ``USE <database>''\index{USE database} SQL\index{SQL}
statement, to be executed by APQ, once the connection succeeds. If
another Set\_DB\_Name is performed while connected, new ``USE <database>''
SQL statements are executed on the Sybase server\index{Sybase server} connection provided.

The exceptions listed in Table \ref{t:sdbx}\index{exception} are possible when
using a new database name.

The case of the database name used is affected according to the case policy\index{case policy}
that is in effect for the connection\index{connection}. This is summarized in Table \ref{t:cpol}
for each database vendor product.

\begin{table}
   \begin{center}
      \begin{tabular}{llll}
      Database Product  &  Case Policy          &  Effect on DB\_Name      &  DB Name Sensitive\\
      \hline 
      PostgreSQL        &  Ignored              &  Case preserved          &  Yes\\
      MySQL             &  Ignored              &  Case preserved          &  Yes\\
      Sybase            &  Ignored              &  Case preserved          &  Yes\\
      \end{tabular}
   \end{center}
   \caption{Case Policy by Product}\label{t:cpol}
\end{table}

\subsection{Procedure Set\_User\_Password}

This procedure call configures both the userid\index{userid} and the password\index{password} together.
If there is no password, then supply the null string\index{null string}:

\begin{Code}
procedure Set_User_Password(
   C :             in out Connection_Type;
   User_Name :     in     String;
   User_Password : in     String
);
\end{Code}

The following code fragment illustrates how the userid and
password is configured:

\begin{Example}
declare
   C :   Connection_Type;
begin
   Set_User_Password(C,"myuserid","xyzzy");
\end{Example}

\subsection{Procedure Set\_Case}

One of the goals of APQ was to make writing of portable database\index{portable database code} code
possible. While this isn't completely possible, the goal remains to
reduce database differences. Until the introduction of Sybase\index{Sybase} within
APQ, there was little concern for the case of SQL query\index{SQL query code} code used. 

This APQ manual has always used examples where SQL code is uppercased\index{uppercased SQL code},
with Ada\index{Ada} code using normal Ada95\index{Ada95} conventions. This helps to make the
SQ\index{SQL}L code standout, and separate it from the other code. Sybase introduces
a problem however, since the Sybase server is case sensitive\index{case sensitive} when
referring to tables\index{tables} and column\index{column names} names. This feature cannot be disabled
for a Sybase server%
\footnote{MySQL databases can be configured to be caseless or case sensitive.%
}. Since users of Sybase\index{Sybase} tend to use lowercase\index{lowercase names} names, this creates
a bit of a problem for portable\index{portable SQL} SQL text within APQ.

The approach that APQ 2.2 uses for Sybase\index{Sybase} (and future databases where
this matters), all SQL\index{SQL} code is changed to lowercase\index{lowercase} before being
sent to the server. Before the reader panics thinking that this won't
work, it should be made clear that APQ does not change the case\index{case of SQL} of
any string\index{string} that is quoted\index{quoted} (using the Append\_Quoted\index{Append\_Quoted} functions for
example). A WHERE\index{WHERE clause} clause such as the following will preserve the text
within quotes\index{quotes}:

\begin{SQL}

   where part_no = "XZ98-307"

\end{SQL}

APQ keeps track of what parts of the SQL\index{SQL query} query were quoted\index{quoted} and which
parts were not. This is \emph{not} done by parsing\index{parsing} the SQL text. That
would be prone to error and would require intimate knowledge of every
SQL dialect supported in APQ. Instead, the string\index{string} fragments are marked
for ``preserve''\index{preserve case} case or ``not preserve''\index{preserved, not} as the Query\_Type\index{Query\_Type}
object collects text. When the full SQL text\index{SQL text} is require by a routine
like To\_String\index{To\_String}, then the standing case policy\index{case policy} is applied to each
string\index{string fragment} fragment that has ``not preserve''\index{preserved, not}.

You can change this APQ case policy\index{case policy} for Sybase (or any other database).
The Set\_Case\index{Set\_Case} function gives you complete control over what the policy
to use for SQL case\index{SQL case}. You can choose one of the SQL\_Case\_Type\label{SQL_Case_Type Choices}
\index{SQL\_Case\_Type} options, which are listed in Table~\ref{t:cpolicies}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Case Policy    &  Description\\
         \hline 
         Preserve\_Case &  Do not make any case changes to the SQL text\\
         Lower\_Case    &  Force unquoted SQL text to lowercase\\
         Upper\_Case    &  Force unquoted SQL text to uppercase\\
      \end{tabular}
   \end{center}
   \caption{Case Policies for SQL Text}\label{t:cpolicies}
\end{table}

\begin{floatingtable}{
   \begin{tabular}{ll}
   Database       &  Default SQL Case Policy\\
   \hline 
   PostgreSQL     &  Upper\_Case\\
   MySQL          &  Lower\_Case\\
   Sybase         &  Lower\_Case\\
   \end{tabular}}
\caption{Default Case Policies}\label{t:dfcpol}
\end{floatingtable}

Table~\ref{t:dfcpol} summarizes the default case policies\index{case policies} used in APQ 2.2
for the different database vendor products supported.

MySQL\index{MySQL} joins Sybase\index{Sybase} in this case policy because by default, MySQL is
case sensitive. If you have configured your MySQL server to be case
insenstive, then any setting will do (Upper\_Case\index{Upper\_Case} is suggested for
the benefit of the trace log displays). Most users of Sybase\index{Sybase} will
likely prefer either the Lower\_Case\index{Lower\_Case} or Preserve\_Case\index{Preserve\_Case}
policies instead.

The Set\_Case\index{Set\_Case} API procedure for the Connection\_Type object is defined
as follows:

\begin{Code}
procedure Set_Case(
   C :        in out Connection_Type;
   SQL_Case : in     SQL_Case_Type
);
\end{Code}

You may also use the Get\_Case\index{Get\_Case} function primitive to find out what
the current policy in effect is. Please note that a change in policy
only affects the outcome of the next call to the following
pimitives of the Query\_Type\index{Query\_Type} object:

\begin{itemize}
   \item To\_String
   \item Execute
   \item Execute\_Checked
\end{itemize}

The Set\_Case\index{Set\_Case} call will not actually change the SQL text\index{SQL text} stored within
the Query\_Type object. It only sets the policy\index{case policy} mode.

The following example shows how to undo the Sybase default of lowercasing
the SQL text:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   ...
   Set_Case(C,Preserve_Case);
   ...
   Append(Q,"from table Mixed_Case");
   Execute(Q,C); -- SQL case is preserved here
\end{Example}

\subsubsection{The Viral Nature of Connection\_Type}

Note that APQ does permit altering the case policy\index{case policy} for Query\_Type\index{Query\_Type}
objects in addition to the Connection\_Type\index{Connection\_Type} object being described
here. It should be noted however, that the setting held by the Connection\_Type
is viral\index{viral nature} in nature. Whenever a Query\_Type object is used in conjunction
with a Connection\_Type object, in a \emph{Execute}\index{Execute} 
or \emph{Execute\_Checked}\index{Execute\_Checked}
call for example, the Query\_Type object will inherit the setting
held by the corresponding Connection\_Type object. For this reason,
the best application practice is to establish your application case
policy\index{case policy} in all Connection\_Type objects used by your application. It
is also best practice to use one Connection\_Type object wherever
possible, since many queries can share one connection\index{shared connection}.

The only reason you should consider applying a case policy\index{case policy} directly
to a Query\_Object, is perhaps for application specific uses of the
SQL text\index{SQL text}. For example, you could build a query\index{query, build a} in a Query\_Type object,
set the case policy to Upper\_Case\index{Upper\_Case}, and then use the To\_String\index{To\_String} function
primitive to extract out the SQL text for logging\index{logging} or user display\index{display}
purposes. Once however the Query\_Type is used with a Connection\_Type
however, (in \emph{Execute}) the Connection\_Type's setting will not
only prevail for the primitive, but will also force the Query\_Type's
policy to agree upon return from the call.


\subsection{Procedure Set\_Options\label{Procedure Set_Options}}

This procedure call permits the caller to specify any specialized
database server options. The options are specified in string form
with this API call. The specific options, and the format\index{format} of those
options\index{options} will vary according to the database being used. See the following
subsections for additional information about the database engine\index{engine, database} specifics.

The procedure Set\_Options\index{Set\_Options} is documented as follows:

\begin{Code}
procedure Set_Options(
   C :       in out Connection_Type;
   Options : in     String
);
\end{Code}

Exceptions\index{exceptions} can be raised if the options are being set on a connection
that is already connected. Table \ref{t:soopts} lists the exceptions that may be
raised by Set\_Options.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
      Exception Name    &  Reason\\
      \hline 
      Failed            &  The option is either unsupported or setting was rejected\\
      \end{tabular}
   \end{center}
   \caption{Set\_Options Exceptions}\label{t:soopts}
\end{table}

If the options are configured for an unconnected\index{unconnected} Connection\_Type
object, the exceptions if any, will be raised at the time of connection
(See the Connect primitive).

The following PostgreSQL\index{PostgreSQL} code fragment illustrates how two options\index{options}
may be configured:

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_Options(C,"requiressl=1 dbname=test");
\end{Example}

Note that in this example, the option string has been used to declare
the database name to be used. Standard values should be set through
the primitive functions provided (ie. use Set\_DB\_Name\index{Set\_DB\_Name} instead).
Otherwise, when information primitives are added, you may not get
correct results. Any non-standard options like the ``requiressl''\index{requiressl}
option, should be configured as shown in this procedure call.

MySQL\index{MySQL} and Sybase\index{Sybase}, use a comma delimited list\index{delimited list} of options\index{options}.
The following example shows how to get Sybase I/O\index{statistics, Sybase I/O} 
and time statistics\index{statistics, time} recorded in your APQ trace\index{trace log} log:

\begin{Example}
declare
  C : Connection_Type;
begin
   Set_Options(C,"STATS_IO=TRUE,STATS_TIME=TRUE");
\end{Example}

Option parsing\index{parsing} is rather limited. Everything between the '=' sign
and the next comma is the value for the parameter. Different database
products will use different parameter types\index{paramater types}. For example, MySQL\index{MySQL} will
use 0 to represent False\index{false}, and 1 to represent True\index{true}. For Sybase\index{Sybase}, use
F or False, and T or True for Boolean\index{Boolean} values.


\subsubsection{PostgreSQL Options}

The documentation is not very clear about the format\index{format} of these options,
but it appears that keyword=value\index{keyword value pairs}  pairs\index{keyword=value pairs}
separated by \emph{spaces} for multiple options\index{options} are
accepted. If you must include spaces or other special characters within
the value component, then you must follow PostgreSQL\index{PostgreSQL} escaping rules\index{escaping rules}.
Refer to the database server documentation for these details.


\subsubsection{MySQL Options}

MySQL's\index{MySQL} C interface\index{C interface} is much different than PostgreSQL's C interface
for options. MySQL uses an enumerated value\index{enumerated value} and argument pair\index{argument pair} when
setting an option\index{option}.%
\footnote{Although, some options do not use the argument.%
} To keep the APQ interface friendly and consistent, APQ will accept
all options and arguments in a string\index{string} form as documented in
\Ref{Procedure Set_Options}. However, these string options\index{string options} must be
processed by APQ and digested into arguments usable by the MySQL C
client interface. Consequently, APQ must anticipate these options
and the option format in advance. For these reasons, the MySQL options
and their arguments will be partially documented here.

The format\index{format of option string} of the option string should be one or more option names
and arguments, separated by commas. Option names\index{option names} are treated as caseless\index{caseless}
(internally upcased\index{upcased}).

\begin{Example}

   Set\_Options(C,"CONNECT_TIMEOUT=3,COMPRESS,LOCAL_INFIL=1");

\end{Example}

Each option should be separated by a comma. APQ processes each option
in left to right fashion, making multiple MySQL C API calls for each
one. Table~\ref{t:myopts} lists the APQ supported options for MySQL.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Option Name          &  Argument Type           &  Comments\\
         \hline 
         CONNECT\_TIMEOUT     &  Unsigned                &  Seconds\\
         COMPRESS             &  None                    &  Compressed comm link\\
         NAMED\_PIPE          &  None                    &  Windows: use a named pipe\\
         INIT\_COMMAND        &  String                  &  Initialization command\\
         READ\_DEFAULT\_FILE  &  String                  &  See MySQL\\
         READ\_DEFAULT\_GROUP &  String                  &  See MySQL\\
         SET\_CHARSET\_DIR    &  String                  &  See MySQL\\
         SET\_CHARSET\_NAME   &  String                  &  See MySQL\\
         LOCAL\_INFIL         &  Boolean                 &  See MySQL\\
      \end{tabular}
   \end{center}
   \caption{MySQL Options}\label{t:myopts}
\end{table}

It is important to observe that any option that requires an argument\index{argument, option},
must have one. Any argument that requires an unsigned integer\index{unsigned}, must
have an unsigned integer (otherwise an exception\index{exception} is raised). A MySQL\index{MySQL}
Boolean\index{Boolean} argument should be the value 0 or 1. At the present time,
APQ gathers string\index{string} data up until the next comma or the end of the
string. Currently an option argument string cannot contain a comma
character.
\footnote{This needs to be corrected in a future release of APQ.}


\subsubsection{Sybase Options}

Sybase documents several options\index{options, Sybase} in their ``Open Client C Programmer's
Reference'' manual. All documented options are made available to
the APQ developer, although some options are not recommended. 

\begin{floatingtable}{
   \begin{tabular}{ll}
   Option Value   &  Meaning\\
   \hline 
   TRUE           &  True\\
   T              &  True\\
   FALSE          &  False\\
   F              &  False\\
   \end{tabular}}
   \caption{Boolean Option Values}\label{t:boolarg}
\end{floatingtable}

Each Sybase option value must conform to certain data type format\index{format, option}
and/or restrictions. Table~\ref{t:boolarg} lists
acceptable argument values for Boolean\index{Boolean} options, within APQ. The
case is not significant, but uppercase is recommended to make it stand out from
the surrounding Ada code.

The following is an example of a Boolean option setting for the Sybase option STATS\_IO:

\begin{Example}

   "STATS_IO=TRUE"

\end{Example}

Some Sybase options require an integer\index{unsigned integer} (actually unsigned). Those
options listed in the option table\index{option table} as requiring an Unsigned value,
should be simply an unsigned value. The following is an example:

\begin{Example}

   "ROWCOUNT=1"

\end{Example}

String value arguments\index{string value arguments} are simply textual values that are placed between
the equal sign and the next comma (or end of string). The following
example illustrates:

\begin{Example}

   "AUTHOFF=sa"

\end{Example}

Some options are identified as taking ``String/NULL''. These options
will take normal string values or simply the word NULL\index{NULL options}. The value
NULL allows the system default to be used. The following is an example:

\begin{Example}

   "CHARSET=NULL"

\end{Example}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Value             &  Sybase Option\\
         \hline 
         SUNDAY            &  CS\_OPT\_SUNDAY\\
         MONDAY            &  CS\_OPT\_MONDAY\\
         TUESDAY           &  CS\_OPT\_TUESDAY\\
         WEDNESDAY         &  CS\_OPT\_WEDNESDAY\\
         THURSDAY          &  CS\_OPT\_THURSDAY\\
         FRIDAY            &  CS\_OPT\_FRIDAY\\
         SATURDAY          &  CS\_OPT\_SATURDAY\\
      \end{tabular}
   \end{center}
   \caption{Weekday Option Argument Values}\label{t:wkday}
\end{table}

The DATEFIRST option\index{DATEFIRST option} accepts an argument Weekday argument. The valid
range of values are listed in Table~\ref{t:wkday}.

The following example shows how the DATEFIRST option is used:

\begin{Example}

   "DATEFIRST=SUNDAY"

\end{Example}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
      Value    &  Sybase Option\\
      \hline 
      MDY      &  CS\_OPT\_FMTMDY\\
      DMY      &  CS\_OPT\_FMTDMY\\
      YMD      &  CS\_OPT\_FMTYMD\\
      YDM      &  CS\_OPT\_FMTYDM\\
      MYD      &  CS\_OPT\_FMTMYD\\
      DYM      &  CS\_OPT\_FMTDYM\\
      \end{tabular}
   \end{center}
   \caption{Date Format Argument Values}\label{t:dtfmt}
\end{table}

One last category of Sybase option arguments is the DATEFORMAT argument\index{DATEFORMAT option}
type. The valid list of values for this type of argument are given in Table~\ref{t:dtfmt}.

The following is an example of such an option:

\begin{Example}

   "DATEFORMAT=YMD"

\end{Example}

Table~\ref{t:syonames} lists all of the options that APQ is able to recognize for Sybase.
Each of the option names\index{option names} listed is equivalent to the 
Sybase C macro\index{C macro, Sybase}
constant if the prefix CS\_OPT\_\index{CS\_OPT\_{*}} is added to the option name. Consult
the Sybase documentation for descriptions of the purpose of these
options and when to apply them.

\begin{longtable}{lll}
Option Name       &  Data Type            &  Notes\\
\hline 
ANSINULL          &  Boolean              &\\
ANSIPERM          &  Boolean              &\\
ARITHABORT        &  Boolean              &\\
ARITHIGNORE       &  Boolean              &\\
AUTHOFF           &  String               &\\
AUTHON            &  String               &\\
CHAINXACTS        &  Boolean              &\\
CHARSET           &  String/NULL          &  Use NULL for default\\
CURCLOSEONXACT    &  Boolean              &\\
DATEFIRST         &  Weekday              &\\
DATEFORMAT        &  YMD/MDY/etc.         &  May interfere with APQ\\
FIPSFLAG          &  Boolean              &\\
FORCEPLAN         &  Boolean              &\\
FORMATONLY        &  Boolean              &\\
GETDATA           &  Boolean              &\\
IDENTITYOFF       &  String               &\\
IDENTITYON        &  String               &\\
IDENTITYUPD\_OFF  &  String               &\\
IDENTITYUPD\_ON   &  String               &\\
ISOLATION         &  Unsigned             &  0, 1 or 3\\
NATLANG           &  String/NULL          &  Use NULL for default\\
NOCOUNT           &  Boolean              &\\
NOEXEC            &  Boolean              &\\
PARSEONLY         &  Boolean              &\\
QUOTED\_IDENT     &  Boolean              &\\
RESTREES          &  Boolean              &\\
ROWCOUNT          &  Unsigned             &\\
SHOWPLAN          &  Boolean              &  Use at your own risk\\
STATS\_IO         &  Boolean              &\\
STATS\_TIME       &  Boolean              &\\
STR\_RTRUNC       &  Boolean              &\\
TEXTSIZE          &  Unsigned             &\\
TRUNCIGNORE       &  Boolean              &\\
\caption{Sybase Option Names}\label{t:syonames}
\end{longtable}

Keep in mind that not all option settings will be compatible for use
with APQ. Changing server date formats\index{date formats} to anything other than year-month-day
format, is likely to cause problems within APQ, for example.


\subsection{Procedure Set\_Notice\_Proc}

The PostgreSQL\index{PostgreSQL} database
\footnote{The Set\_Notice\_Proc procedure is not available with MySQL.}
server sends notice\index{notice messages} messages back to the libpq\index{libpq} C library\index{library}, that the
APQ binding uses. These are received by a callback\index{callback}, after certain
database operations have been completed. While the messages are saved
in the Connection\_Type object (see also \Ref{Function Notice_Message}),
they overwrite each other as each new message comes in. For this reason,
it may be desireable for some applications to also receive a callback,
so that they can process the messages without losing them. The most
common reason to do this is to simply display them on standard error\index{standard error}.

The callback\index{callback}\index{Set\_Notice\_Proc} procedure must be defined as follows:
\marginpar{The default setting for any new Connection\_Type object is No\_Notify.}

\begin{Code}
procedure Notice_Callback(
   C :       in out Connection_Type;
   Message : in     String
);
\end{Code}

The Set\_Notice\_Proc takes an argument named Notify\_Proc\index{Notify\_Proc} that is
of the following type:

\begin{Code}
type Notify_Proc_Type is access
   procedure(
      C :       in out Connection_Type;
      Message : in     String
   );
\end{Code}

Finally, the Set\_Notice\_Proc procedure has the following calling signature:
\marginpar{Note that the Reset or Disconnect call will clear any
registered Notify procedure.}

\begin{Code}
procedure Set_Notice_Proc(
   C :           in out Connection_Type;
   Notify_Proc : in     Notify_Proc_Type
);
\end{Code}

This call can be made at any time to change the Notify\index{notify procedure} procedure.
The object may or may not be connected\index{connected}. The new procedure takes effect
immediately upon return, and will be used when the object is connected.
The present implementation only maintains one such procedure.%
\footnote{Note that the replaced procedure is not returned. A future implementation
of APQ may address this.%
}


\subsubsection{Disabling Notify}

The APQ\-.PostgreSQL\-.Client\index{APQ\-.PostgreSQL\-.Client} package 
provides the special constant No\_Notify\index{No\_Notify}
for the application programmer to use. An example of disabling notification\index{disabling notification}
follows:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   -- Enable notify processing
   Set_Notify_Proc(C,My_Notify'Access);
   ...
   -- Disable notification
   Set_Notify_Proc(C,No_Notify);
\end{Example}

\subsubsection{Using Standard\_Error\_Notify}

During the debugging\index{debugging} phase of a database application, it may be useful
to simply have the notice messages\index{notice messages} printed on Standard\_Error\index{Standard\_Error}. To
do this, simply provide the access constant Standard\_Error\_Notify\index{Standard\_Error\_Notify}
as the second argument:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   -- Send notices to stderr
   Set_Notify_Proc(C,Standard_Error_Notify);
   ...
\end{Example}

\section{Connection Operations}

The APQ binding provides three primitives for connecting\index{connecting} and disconnecting\index{disconnecting}
from the database server. They are summarized in Table~\ref{t:conprims}.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Type     &  Name              &  Purpose\\
         \hline
         proc     &  Connect           &  Connect to the database server\\
         proc     &  Disconnect        &  Disconnect from the database server\\
         proc     &  Reset             &  Disconnect if connected\\
      \end{tabular}
   \end{center}
   \caption{APQ Connection Primitives}\label{t:conprims}
\end{table}

\subsection{Procedure Connect}

This primitive initiates a connection attempt with the database server
as configured by the \Ref{Context_Setting_Operations} primitives.
If the connection succeeds, the procedure call returns\index{Connect}
successfully, leaving the Connection\_Type object in a connected state.


\begin{Code}
procedure Connect(
   C : in out Connection_Type
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name       &  Reason\\
         \hline 
         Not\_Connected       &  The connection attempt failed\\
         Already\_Connected   &  There is already a connection\\
         Failed               &  One or more configured options failed\\
         Use\_Error           &  Connection OK, but USE database failed\\
      \end{tabular}
   \end{center}
   \caption{Connect Exceptions}\label{t:conx}
\end{table}

Table~\ref{t:conx} summarizes the exceptions that Connect may raise.

The Already\_Connected\index{Already\_Connected} exception indicates that you need to disconnect
first, or use another Connection\_Type object if you are maintaining
multiple connections\index{connections, multiple}. Failed will be raised if a pending option setting
is unsupported or its setting has been rejected. The exception Use\_Error\index{Use\_Error}
indicates that the connection itself succeeded, but the selection
of the database failed. The connection will be returned in an unconnected\index{unconnected}
state when Use\_Error is raised.

\begin{description}
   \item[PostgreSQL Note:] \index{PostgreSQL}The Connect primitive as of APQ 1.91 automatically executes a 'SET
      DATESTYLE TO ISO' \index{ISO}\index{DATESTYLE} command to guarantee that the APQ date routines
      will function correctly, even when the PGDATESTYLE\index{PGDATESTYLE} environment variable
      may choose something other than ISO. This implies however, that APQ
      applications should always format date information in the ISO format.
   \item[MySQL Note:]When MySQL\index{MySQL} returns dates in YYYYMMDD\index{YYYYMMDD} format, APQ
      will automatically make the necessary adjustment, based upon the length
      of the result.
\end{description}

The following is an example call:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   begin
      Connect(C);
   exception
      when No_Connection =>
         -- Handle connection failure
      when Already_Connected =>
         ...; -- Indicates program logic problem
      when others =>
         raise;
   end;
\end{Example}

\subsection{Connection Cloning\label{Connection Cloning}}

Application writers may want additional connections cloned\index{cloning connections} from a
given connection. A web server may want to do this for example. This
could be performed by obtaining all of the connection information
from the given connection and then proceed to configure a new connection,
but this is tedious and error prone. To clone a new connection from
an existing connection, simply use the Connect\index{Connect} primitive with the
following calling signature (argument Same\_As is added):

\begin{Code}
procedure Connect(
   C :       in out Connection_Type;
   Same_As : in     Connection_Type
);
\end{Code}

This primitive configures object C to use the same parameters as object
Same\_As\index{Same\_As}. It then creates a connection to the database using these cloned\index{cloned}
parameters. The exceptions that may be raised are listed in Table~\ref{t:cclonx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name       &  Reason\\
         \hline 
         Not\_Connected       &  The connection attempt failed\\
         Already\_Connected   &  There is already a connection\\
      \end{tabular}
   \end{center}
   \caption{Connection Cloning Exceptions}\label{t:cclonx}
\end{table}

The Not\_Connected\index{Not\_Connected} exception can be raised if the Same\_As connection
is not connected (it must be connected). This same exception can be
raised if the new connection fails (this should rarely happen unless
your database is suddenly taken down or a network failure occurs).
The Already\_Connected\index{Already\_Connected} exception is raised if \emph{C} is already
connected.

\begin{description}
   \item[Note:] Note that the trace settings of the Same\_As object are not
      carried to the new object C. You must manually configure any trace
      settings you require in the newly connected object C.
\end{description}

The following example shows how a procedure My\_Subr can clone
a new connection:

\begin{Example}
procedure My_Subr(C : Connection_Type) is
   C2 : Connection_Type;
begin
   Connect(C2,C); -- Clone a connection
\end{Example}

\subsection{Procedure Disconnect}

The Disconnect\index{Disconnect} primitive closes the connection that was previously
established in the Connection\_Type\index{Connection\_Type} object. The Disconnect primitive
uses the following arguments:

\begin{Code}
procedure Disconnect(
   C : in out Connection_Type
);
\end{Code}

The list of possible exceptions for Disconnect are illustrated in Table~\ref{t:dconx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name       &  Reason\\
         \hline 
         No\_Connection       &  There is no connection to disconnect\index{No\_Connection}\\
      \end{tabular}
   \end{center}
   \caption{Disconnect Exceptions}\label{t:dconx}
\end{table}

The following code fragment shows the procedure call in action:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   begin
      Disconnect(C);
   exception
      when No_Connection =>
         ...; -- Indicates program logic problem
      when others =>
         raise;
   end;
\end{Example}

\subsection{Procedure Reset}

The Reset\index{Reset} primitive is provided so that the programmer can recycle
the Connection\_Type object for use in a subsequent connection. Without
this primitive, the user would need to destroy the original and create
a new Connection\_Type. The Reset primitive accepts the following
arguments:

\begin{Code}
procedure Reset(
   C : in out Connection_Type
);
\end{Code}

In addition to closing the current connection, if it is open, the
notification procedure is also deregistered (if there was a Set\_Notify\_Proc\index{Set\_Notify\_Proc}
performed).

No exceptions should occur. If there is a connection pending\index{pending connection}, it is
disconnected\index{disconnected}. If there is no connection pending, the call is ignored.
The following shows an example of its use:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   Reset(C);  -- C is now ready for re-use
\end{Example}

\section{Connection Information Operations}

A modular\index{modular software} piece of software may get handed a Connection\_Type object
as a parameter, and have a need to inquire about the details of the
provided connection. The function primitives that return information
about the connection are listed in Table~\ref{t:cinfp}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Function Name     &  Information Returned\\
         \hline 
         Host\_Name        &  Host name of the connection\\
         Port              &  Port Number or Port Pathname\\
         DB\_Name          &  Database name\\
         User              &  User name for the database\\
         Password          &  Password for the database\\
         Instance          &  Instance name for the database\\
         Options           &  Database option parameters\\
      \end{tabular}
   \end{center}
   \caption{Connection Information Primitives}\label{t:cinfp}
\end{table}

These function primitive specifications are listed below:

\begin{Code}
function Host_Name(
   C : Connection_Type;
) return String;
\end{Code}

\begin{Code}
function Port(
   C : Connection_Type;
) return String;  -- UNIX path
\end{Code}

\begin{Code}
function Port(
   C : Connection_Type;
) return Integer; -- TCP/IP port
\end{Code}

\begin{Code}
function DB_Name(
   C : Connection_Type;
) return String;
\end{Code}

\begin{Code}
function User(
   C : Connection_Type;
) return String;
\end{Code}

\begin{Code}
function Password(
   C : Connection_Type;
) return String;
\end{Code}

\begin{Code}
function Instance(
   C : Connection_Type;
) return String;
\end{Code}

\begin{Code}
function Options(
   C : Connection_Type;
) return String;
\end{Code}

The Port\index{Port} primitive that returns a String is for use with database
connections using a UNIX socket\index{UNIX socket}\index{local socket}. The socket
pathname\index{pathname} is returned in this case.
\footnote{or at least a fragment of the pathname.}

When called on Connection\_Type objects without a current connection,
an empty string\index{string, empty} is returned for any value that has not been configured
(for example if Set\-\_Host\-\_Name\index{Set\_Host\_Name} has not been called, Host\-\_Name\index{Host\_Name} will
return ""). If the value has been set, then that value is returned
as expected. Once the Connection\-\_Type object is connected to the
database however, the values will be values fetched from the library\index{library}
libpq\index{libpq} instead.
\footnote{Normally, these values should agree with what was configured.}

The following code sample shows how to extract the host name\index{host name} and database
name for the current connection.

\begin{Example}
procedure My_Code(C : in out Connection_Type) is
   Host_Name :     String := Host_Name(C);
   Database_Name : String := DB_Name(C);
begin
   ...
\end{Example}

\begin{description}
\item [Sybase Note:]The Instance function primitive was added to APQ support Sybase.
   See the support level chart for Set\_Instance\index{Set\_Instance} on page \pageref{Set_Instance Support Chart}
   and other information primitives. Note also that setting and retrieving
   other parameters is possible in some cases, even though the information
   is ignored by Sybase.
\end{description}

\section{General Information Operations}

Due to the modular construction of software, it is sometimes necessary
to query an object for its present state. The primitives listed in Table~\ref{t:gifc}
for the Connection\_Type object are available for querying the state\index{query the state}
of the object. These are discussed in the next subsections.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Type  &  Name              &  Purpose\\
         \hline 
         func  &  Is\_Connected     &  Indicates connected state\\
         func  &  Error\_Message    &  Returns a error message text\\
      \end{tabular}
   \end{center}
   \caption{General Information for Connections}\label{t:gifc}
\end{table}

\subsection{Function Is\_Connected}

The Is\_Connected\index{Is\_Connected} function returns a Boolean result that indicates
the present state of the Connection\_Type object. The arguments are
as follows:

\begin{Code}
function Is_Connected(
   C : Connection_Type
) return Boolean;
\end{Code}

There are no exceptions raised by this primitive.

The following example shows how to test if the object C is currently
supporting a connection. The example disconnects from the server,
if it determines that C is connected.

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   if Is_Connected(C) then
      Disconnect(C);
      ...
\end{Example}

\subsection{Function Error\_Message}

The Error\_Message\index{Error\_Message} function makes it possible for the application
to report why the connection failed. This information is often crucial
to the user of a failed application. The arguments accepted are as
follows:

\begin{Code}
function Error_Message(
   C : Connection_Type
) return String;
\end{Code}

There are no exceptions raised by this function. If there is no present
connection or no present error to report, the null string is returned.
The following example shows how the connection failure is reported:

\begin{Example}
with Ada.Text_IO;
...
declare
   use Ada.Text_IO;

   C : Connection_Type;
begin
   ...
   begin
      Connect(C);
   exception
      when No_Connection =>
         Put_Line(Standard_Error,"Connection Failed!");
         Put_Line(Standard_Error,Error_Message(C));
         ...
      when Already_Connected =>
         ...;  -- Program logic error here
      when others =>
         raise;
   end;
\end{Example}

\subsection{Function Notice\_Message\label{Function Notice_Message}}

The C libpq\index{libpq} interface library\index{library}\footnote{The Notice\_Message function is
not available for MySQL.} provides the APQ binding with certain
notification messages\index{notification messages} during some calls, by means of a callback\index{callback}. Each
time one of these notifications is received from the database server,
the notification message is saved in the Connection\_Type object
(replacing any former notice message). The last notification message
received can be retreived using the Notice\_Message\index{Notice\_Message} function:

\begin{Code}
function Notice_Message(
   C : Connection_Type
) return String;
\end{Code}

No exception is raised, and the null string\index{null string} is returned if no notice
message has been registered.

The following example illustrates one example of the Notice\_Message
function:

\begin{Example}
with Ada.Text_IO;
...
declare
   use Ada.Text_IO;

   C : Connection_Type;
begin
   ...
   declare
      Msg : String := Notice_Message(C);
   begin
      if Msg'Length > 0 then
         Put_Line(Standard_Error,Msg);
         ...
\end{Example}

\subsection{In\_Abort\_State Function\label{In_Abort_State Function}}

\Ref{Abort_State exception} documents the Abort\_State\index{Abort\_State}
exception, which is unique to PostgreSQL\index{PostgreSQL}. This exception is raised in
response to a status flag stored in the
APQ\-.PostgreSQL\-.Client\-.Connection\_Type object. When a transaction is
started, any SQL error\index{SQL error} will put the PostgreSQL database server into an
``\emph{abort state}'', where all current and future commands will be
ignored, for the connection \footnote{MySQL does not support this
concept, and so it does not go into an abort state.}. To permit the
application programmer to query this status, the In\_Abort\_State\index{In\_Abort\_State}
function can be used. It returns True, if an error has occurred within a
transaction, which requires a Rollback\_Work (\Ref{Begin, Commit and Rollback Work functions})
call to clear this state. The calling
requirements are summarized in the following table:

\begin{Code}
function In_Abort_State(
   C : Connection_Type
) return Boolean;
\end{Code}

Exceptions for In\_Abort\_State are summarized in Table~\ref{t:iasx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Not\_Connected    &  There is no connection to query\\
      \end{tabular}
   \end{center}
   \caption{In\_Abort\_State Exceptions}\label{t:iasx}
\end{table}

The following example shows how this function might be used:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   ...
   Begin_Work(Q,C);
   ...
   Execute(Q,C);
   ...
   if In_Abort_State(C) then
      Rollback(Q,C);
      ...
   end if;
\end{Example}

\section{Implicit Operations}

There are a few implicit operations\index{implicit operations} that are performed that the programmer
should be aware of. They are:

\begin{itemize}
   \item The Connection\_Type is subject to Finalization
   \item A default Commit/Rollback operation can occur at Finalization
\end{itemize}

The programmer is encouraged to call Commit\_Work\index{Commit\_Work} or Rollback\_Work\index{Rollback\_Work}
explicitly, whenever possible. This way, the programmer is in complete
control of the transaction outcome.

If a transaction has not been committed or rolled back, and the connected
Connection\_Type object is finalized\index{finalization}%
\footnote{Usually because the Connection\_Type object has fallen out of scope.%
}, then the default action for commit or rollback occurs. The default
for the APQ binding is to rollback the transaction, when the connection
is still active. If the programmer has disconnected\index{disconnected} from the database
prior to finalization, then no further action occurs. To change or
control the default action, use the Set\_Rollback\_On\_Finalize\index{Set\_Rollback\_On\_Finalize} procedure
described in the next section.


\subsection{Set\_Rollback\_On\_Finalize Procedure\label{Set_Rollback_On_Finalize Procedure}}

The Set\_Rollback\_On\_Finalize primitive allows the programmer to
change the default action for the Connection\_Type object. The calling
requirements are summarized in the following table:%

\begin{Code}
procedure Set_Rollback_On_Finalize(
   C :        in out Connection_Type;
   Rollback : in     Boolean
);
\end{Code}

To change the default to COMMIT WORK\index{COMMIT WORK} when the Connection\_Type object
finalizes, peform the following call:

\begin{Example}
declare
   C : Connection_Type;
begin
   Set_Rollback_On_Finalize(C,False); -- Commit on Finalize
\end{Example}

\subsection{Will\_Rollback\_On\_Finalize Function\label{Will_Rollback_On_Finalize Function}}

Programs sometimes need to inquire about the state of the Connection\_Type
object that they may have been passed. To inquire about the commit
or rollback default, the Will\_Rollback\_On\_Finalize\index{Will\_Rollback\_On\_Finalize} function can
be called. The following table summarizes the calling requirements:

\begin{Code}
function Will_Rollback_On_Finalize(
   C : Connection_Type
) return Boolean;
\end{Code}

\section{Trace Facilities\label{Trace Facilities}}

No matter how carefully a programmer writes a new program, problems
develop that are often difficult to understand. Good tracing facilities\index{trace facilities}
allow the problem to be quickly understood and corrected.

To gain trace support using APQ, it is only necessary to perform the
following steps:

\begin{enumerate}
   \item Open a trace capture file with Open\_DB\_Trace
   \item Optionally enable/disable tracing at various points in the program
      with Set\_Trace%
      \footnote{Tracing is enabled by default after a Open\_DB\_Trace call.}
   \item Perform your SQL operations
   \item Close the trace capture file with Close\_DB\_Trace%
      \footnote{Or allow it to be closed when the Connection\_Type object is finalized.}
\end{enumerate}

The Open\_DB\_Trace\index{Open\_DB\_Trace} procedure takes a Trace\_Mode\_Type\index{Trace\_Mode\_Type} parameter
that decides what trace content is being collected. The valid enumerated
choices are listed in Table~\ref{t:tmchoic}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Value           & Description\\
         \hline
         APQ.Trace\_None & Collect no trace information (no file is written/created)\\
         APQ.Trace\_DB   & Collect only C library trace information%
            \footnote{Prior to APQ 2.0, this was Trace\_libpq.}\\
         APQ.Trace\_APQ  & Collect only APQ SQL trace information\\
         APQ.Trace\_Full & Collect both database library and Trace\_APQ information\\
      \end{tabular}
   \end{center}
   \caption{Trace\_Mode\_Type Choices}\label{t:tmchoic}
\end{table}

The Trace\_None\index{Trace\_None} value is provided so that the Open\_DB\_Trace procedure
does not need to be coded around if a trace variable is supplied,
which may or may not request tracing. Close\_DB\_Trace\index{Close\_DB\_Trace} can be called
on a Connection\_Type\index{Connection\_Type} for which Trace\_None is in effect, without
any exception being thrown (the call is ignored).

Trace\_DB\index{Trace\_DB} provides only what the C library (libpq\index{libpq} for PostgreSQL\index{PostgreSQL})
provides. This may be useful to the database software maintainers,
if they want a trace of the activity that you are reporting problems
with.

Trace\_APQ\index{Trace\_APQ} is what the author considers to be the most useful output
format to an APQ developer. The trace output in this mode is such
that the extra trace information is provided in SQL comment\index{SQL comment} form.
The actual queries that are executed are in their natural SQL form.
The captured Trace\_APQ trace then, is in a format that can be played
back, reproducing exactly what the application performed.%
\footnote{There are limitations however, since the blob functions are not traced
at the present release.%
} The full trace or portions of it then can be used to help debug SQL
related problems. 

The following shows a sample of what the Trace\_APQ output looks like:

\begin{SQL}
-- Start of Trace, Mode=TRACE_APQ
-- SQL QUERY:
BEGIN~WORK}
;
-- Result: 'BEGIN'

-- SQL QUERY:
INSERT INTO DOCUMENT
       (NAME,DOCDATE,BLOBID,CREATED,MODIFIED,ACCESSED)
VALUES ('compile.adb','2002-08-12~21:09:25',3339004,
        '2002-08-12~21:59:48','2002-08-12~21:09:25',
        '2002-08-19~22:11:36')
;
-- Result: 'INSERT 3339005 1'

-- SQL QUERY:
SELECT DOCID
FROM DOCUMENT
WHERE OID = 3339005
;
-- Result: 'SELECT'
...
-- SQL QUERY:
COMMIT WORK
;
-- Result: 'COMMIT'
-- End of Trace.
\end{SQL}

The following subsections describe the primitives that provide support
for trace facilities.


\subsection{Procedure Open\_DB\_Trace}

To start any capture of trace\index{trace capture} information, you must specify the name
of the text file to be written to. The file must be writable to the
current process. The Connection\_Type object must be connected prior
to calling Open\_DB\_Trace\index{Open\_DB\_Trace}:

\begin{Code}
procedure Open_DB_Trace(
   C :        in out Connection_Type;
   Filename : in     String;
   Mode :     in     Trace_Mode_Type := Trace_APQ
);
\end{Code}

Table \ref{t:odbtx} lists the possible exceptions for Open\_DB\_Trace.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name & Reason\\
         \hline 
         Not\_Connected & There is no connection\\
         Tracing\_State & Trace is already enabled\\
      \end{tabular}
   \end{center}
   \caption{Open\_DB\_Trace Exceptions}\label{t:odbtx}
\end{table}

Upon return from the Open\_DB\_Trace procedure, a text file will be
created and ready to have trace entries written to it.%
\footnote{Note that trace entries are buffered by C standard I/O routines, so
trace information may be held in memory buffers before it is flushed
out or closed.%
}

The following example shows how a call might be coded:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   Open_DB_Trace(C,"./bugs.sql",Trace_APQ);
\end{Example}

\subsection{Procedure Close\_DB\_Trace}

Closing the tracing facility for a connection, suspends all further
trace writes. Once this has been done, the effect of Set\_Trace\index{Set\_Trace} is
superceeded, preventing any further trace information being written.
The calling requirements are outlined in the following table:

\begin{Code}
procedure Close_DB_Trace(
   C : in out Connection_Type
);
\end{Code}

If the Open\_DB\_Trace call was made with the Mode parameter set to
Trace\_None, then the call to Close\_DB\_Trace\index{Close\_DB\_Trace} has no effect and is
ignored for programmer convenience.

No exceptions are raised.

An example call is shown below:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   Open_DB_Trace(C,"./bugs.sql",Trace_APQ);
   ...
   Close_DB_Trace(C);
\end{Example}

\subsection{Procedure Set\_Trace}

In large applications where large numbers of SQL statements are executed,
it may be desirable to trace only certain parts of its execution in
a dynamic fashion. The Set\_Trace\index{Set\_Trace} primitive gives the programmer a
way to disable and re-enable tracing at strategic\index{strategic tracing} points within the
application. The calling requirements are summarized as follows:

\begin{Code}
procedure Set_Trace(
   C :        in out Connection_Type;
   Trace_On : in     Boolean := True
);
\end{Code}

Tracing is enabled by default, after a successful call to Open\_DB\_Trace
is made (unless Mode was Trace\_None\index{Trace\_None}).

There are no exceptions raised.

Note that it is considered safe to invoke Set\_Trace, even if a former
Open\_DB\_Trace call was not successfully performed, or the trace
mode was Trace\_None. This allows the application to retain strategic
Set\_Trace calls without having to remove them, when the Open\_DB\_Trace
call is disabled%
\footnote{Setting Mode to Trace\_None effectively disables the trace facility
without requiring any code changes.%
} or commented out.


\subsection{Function Is\_Trace}

It may be helpful to the developer that is tracking down a problem
to know when tracing is enabled or not. The Is\_Trace\index{Is\_Trace} function returns
true when the trace collection file is receiving trace information.
The calling arguments are listed below:%

Note that the returned value tracks the last value provided by
Set\_Trace, whether or not an open trace file has been created/opened.

\begin{Code}
function Is_Trace(
   C : Connection_Type;
) return Boolean;
\end{Code}

Note that the initial state of the Connection\_Type object is to have
Is\_Trace to return True. Also after a successful Open\_DB\_Trace,
Is\_Trace will return True.

An example showing its use is given below:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   Open_DB_Trace(C,"./bugs.sql",Trace_APQ);
   ...
   if Is_Trace(C) then
      -- We are collecting trace info..
\end{Example}

\section{Generic Database Operations}

APQ 2.0 and later is designed so that all but the most specialized
database operations, can be performed, given only a Root\_Connection\_Type'Class\index{Root\_Connection\_Type'Class}
object (declared in top level package APQ). The following sections
describe some generic database related primitives that are necessary
for successful generic database support.


\subsection{Package APQ}

Root object support\index{root object support} is provided in the package APQ\index{APQ, package}. Generic database
code will normally only use this package:

\begin{Code}
   with APQ;

   use APQ;  -- Optional use clause
\end{Code}

The data types that will be used will be:

\begin{itemize}
   \item APQ.Root\_Connection\_Type'Class
   \item APQ.Root\_Query\_Type'Class\index{Root\_Query\_Type'Class}
\end{itemize}

The generic primitives that will be covered in the next section are:

\begin{itemize}
   \item APQ.Engine\_Of
   \item APQ.New\_Query
\end{itemize}

\subsection{Predicate Engine\_Of\label{Generic Database Engine_Of}}

Given a Root\_Connection\_Type'Class object, generic database code
sometimes needs to determine which specific database is being used.
This allows the code to make special SQL syntax changes, depending
upon the technology being used (for example, MySQL\index{MySQL} permits the use
of a \emph{LIMIT}\index{LIMIT} keyword in queries).

The Engine\_Of\index{Engine\_Of} primitive (dispatching) will identify the
database technology that is being used:

\begin{Code}
type Database_Type is (
   Engine_PostgreSQL,
   Engine_MySQL,
   Engine_Sybase
);

function Engine_Of(
   C : Connection_Type
) return Database_Type;
\end{Code}

The following example code shows how to test if a PostgreSQL\index{PostgreSQL} database
is being used:

\begin{Example}
with APQ; use APQ;
...
procedure App(C : Root_Connection_Type'Class) is
begin
   ...
   if Engine_Of(C) = Engine_PostgreSQL then
      ...
\end{Example}

\subsection{Primitive New\_Query\label{Query_Type Factories}}

Normally, an application database procedure will receive a connection
object as one of its input parameters. Generally, this connection
is established in the main program and then used by the program components
as required. However, to pass the parameter in a generic way (allowing
for polymorphism), you would declare the procedure's argument as receiving
data type Root\_Connection\_Type'Class.

Within the called procedure however, you will need a Query\_Type object.
This too could be passed in as an argument, but this is unnecessary.
At other times, you may need additional Query\_Type objects for temporary
use. What you need is a convenient way to create a Query\_Type object
that matches the connection that you have received as a parameter. This
is done by the New\_Query function\index{New\_Query}.

If your connection object is a:

\begin{Code}

   APQ.PostgreSQL.Client.Connection_Type

\end{Code}

object, then your application will want to create a:

\begin{Code}

   APQ.PostgreSQL.Client.Query_Type

\end{Code}

object. You want to avoid tests like:

\begin{Example}

if Connection is in APQ.PostgreSQL.Client.Connection_Type then
   ...
elsif Connection is in APQ.MySQL.Client.Connection_Type then
   ...
elsif Connection is in APQ.Sybase.Client.Connection_Type then
   ...

\end{Example}

The above example code would force your portable code to also ``with''\index{with}
the following packages:

\begin{Example}
with APQ.PostgreSQL.Client;
with APQ.MySQL.Client;
...
\end{Example}

which would be very inconvenient and unnecessary.

To make portable\index{portable} database programming easier, APQ provides a dispatching\index{dispatching}
Query\_Type object factory primitive that can be used for this purpose.
For example:

\begin{NumberedExample}
with APQ;
use APQ;

procedure My_Generic_App(C : Root_Connection_Type'Class) is
   Q : Root_Query_Type'Class := New_Query(C);\label{Ex:New_Query_Assgn}
begin
   Prepare(Q,"SELECT NAME,INCOME");
   Append_Line(Q,"FROM~SALARIES");
\end{NumberedExample}

The assignment to Q in line~\ref{Ex:New_Query_Assgn}, shows the
application of the primitive New\_Query. This dispatching
primitive returns the correct Query\_Type object that matches the
connection that was given. The primitive New\_Query is more formally
presented as follows:

\begin{Code}
function New_Query(
   C : Root_Connection_Type
) return Root_Query_Type'Class;
\end{Code}

\subsection{Query\_Type Assignment\label{Query_Type Cloning}}

Prior to APQ version 2.0, the Query\_Type object was a \emph{limited}\index{limited tagged type}
tagged type. This meant that the Query\_Type object was never able
to be assigned to another Query\_Type object. With the need for a
factory\index{factory} primitive like \textbf{New\_Query} it was necessary to lift
that restriction (otherwise the factory was unable to return the created
object). So the Root\_Query\_Type and derived forms, permit assignment
as of APQ version 2.0 and later.

When a Query\_Type is assigned in APQ, nothing spectacular happens.
In fact, the contents of the object on the right hand side are effectively
ignored, leaving a new object on the left side. The following example
shows how Q1 and Q2 are essentially the same:

\begin{NumberedExample}
declare
   Q0 : Query_Type;
   Q1 : Query_Type;
   Q2 : Query_Type;
begin
   ...
   Q1 := Q0;   -- Q1 becomes initialized (Q0 ignored)\label{Ex:Q1}
   Clear(Q2);  -- Initialize Q2\label{Ex:Q2}
\end{NumberedExample}

In this example, both Q1~(line~\ref{Ex:Q1}) and Q2~(line~\ref{Ex:Q2})
end up in the same state, and no state information is taken from Q0. You
might wonder why this would be implemented. The following example code
fragment illustrates why this is convenient and useful:

\begin{NumberedExample}
with APQ;
usse APQ;

procedure My_Generic_App(C : Root_Connection_Type'Class) is
   Q : Root_Query_Type'Class := New_Query(C);
begin
   Prepare(Q,"SELECT NAME, INCOME");
   Append(Q, "FROM~SALARIES");
   Execute(Q,C);
   ...
   declare
      Q2 : Root_Query_Type'Class := Q;\label{Ex:Q_Clone}
   begin
      ...
   end;
\end{NumberedExample}

The example illustrates that the assignment (line~\ref{Ex:Q_Clone}) is
simply a convenient factory of its own kind. It is also likely to be
slightly more efficient than the New\_Query primitive on the
connection. Think of assignment of Query\_Type objects as cloning\index{cloning}
operations. The assigned object becomes a fresh initialized clone of the
Query\_Type object on the right hand side of the assignment.

\chapter{SQL Query Support}

Once a database connection has been established, the application is
ready to invoke operations on the database server. To ease the programmer's
burden in keeping track of the various components involved in these
transactions, the Query\_Type object is provided. The Query\_Type\index{Query\_Type}
object and the Connection\_Type object are used together when it comes
time to execute the query. Some operations require the connection
object, while others do not.

There are a large number of primitives associated with the Query\_Type
object. Most of them are related to the large number of data types
that are supported. These Query\_Type primitives fall into the following
basic categories:

\begin{enumerate}
   \item Object initialization
   \item SQL Query building
   \item SQL Execution on the Database server
   \item Transaction operations
   \item Fetch operations
   \item Column information functions
   \item Value fetching functions
   \item Value and Indicator fetching procedures
   \item Information operations
\end{enumerate}

In addition to these, are a number of generic functions and procedures
that permit the APQ user to custom tailor the API to his own specialized
Ada data types. This allows applications to continue the follow the
healthy tradition of using strong data types. There is no need for
a database application to take a back seat to safety\index{safety}.

\section{Initialization \label{SQL Initialization}}

The Query\_Type object is initialized when the object is created.
However, the Query\-\_Type object can be re-used as various SQL\index{SQL}
operations are performed by the program. To re-use the Query\_Type
object, one of the primitives in Table~\ref{t:qinit} may be used to recycle it for
re-use.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Type  &  Name     &  Purpose\\
         \hline
         proc  &  Clear    &  Clear object and re-initialize\\
         proc  &  Prepare  &  Reinitialize with start of new SQL query\\
      \end{tabular}
   \end{center}
   \caption{Query Initialization}\label{t:qinit}
\end{table}

The Clear\index{Clear} procedure does the initialization of the Query\_Type object.
The Prepare primitive implicitly invokes Clear
\footnote{Consequently, your application need not invoke Clear() prior to calling
Prepare().} and additionally starts the building of an SQL query. Very short
SQL statements may comletely specified by the Prepare API call. Longer
queries can be completed with some of the other primitives to be discussed
in this section.

\subsection{Procedure Clear}

With one exception, the Clear\index{Clear} primitive completely resets the state
of the Query\_Type object. This function primitive serves to basic
purposes:

\begin{enumerate}
\item Resets the object to its initial state so that it can be reused for a new query.
\item Releases any results of the current query (close cursors etc.)
\end{enumerate}

When performed after a query has been executed, this primitive releases
all results from the query. For Sybase, this can include issuing a
cancel back to the server and flushing all pending row results that
have not been retrieved by the APQ client program.

Clear accepts the Query\_Type object as its only argument:

\begin{Code}
procedure Clear(
   Q : in out Query_Type
);
\end{Code}

The one exception to clearing state however, is that the SQL case\index{case policy}
policy remains unchanged. If prior to the clear, the SQL case policy
is set to Preserve\_Case\index{Preserve\_Case}, it will remain so after the Clear call.

There are no exceptions raised by this call.

The use of the Clear primitive is recommended after all SQL processing
related to the query has been completed. This permits any database
server results to be released. Think of it as ``closing''\index{closing a query} the
query. Note however, that object finalization\index{finalization} will take care of this,
if the job is left unfinished by the programmer.

The following example illustrates it's use:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   ...
   Clear(Q);
\end{Example}

\subsubsection{Performance Issue}

There is one particular case where calling Clear is vitally important
for some database products. Let's use an example where you are fetching
the most recent stock price from a price history file. Here is the
table declaration:

\begin{SQL}
CREATE TABLE PRICE_HIST (
   SECURITY    CHAR(10) NOT NULL,
   PRICE_DATE  DATE NOT NULL,
   PRICE       REAL,
   PRIMARY KEY (SECURITY,PRICE_DATE)
);
\end{SQL}

With this table holding price history, keyed by the security name
and date, we can lookup the most recent price with a subroutine something
like the following:

\begin{NumberedExample}
procedure Last_Price(
   C :        in out Root_Connection_Type'Class;
   Security : in     String;
   Price :       out APQ_Double
) is
   function Value is new Float_Value(APQ_Double);

   Q : Root_Query_Type'Class := New_Query(C);\label{Ex:TheQ}
begin

   Begin_Work(Q,C);

   Prepare(Q,    "SELECT SECURITY,PRICE_DATE,PRICE");
   Append_Line(Q,"FROM PRICE_HIST");
   Append(Q,     "WHERE SECURITY = ");
   Append_Quoted(Q,C,Security,Line_Feed);
   Append_Line(Q,"ORDER BY SECURITY,PRICE_DATE DESC");\label{Ex:OrderBy}

   if Engine_Of(C) = Engine_MySQL then
      Append_Line(Q,"LIMIT 1");\label{Ex:Limit1}
   end if;

   Execute(Q,C);

   begin
      Fetch(Q);
   exception
      when No_Tuple =>
         raise;   -- No price found!
   end;

   Price := Value(Q,3);
   Clear(Q);\label{Ex:Clear}

end Last_Price;
\end{NumberedExample}

In this example, you can see that MySQL\index{MySQL} is covered by adding the "LIMIT 1"\index{LIMIT}
clause in line~\ref{Ex:Limit1}.\footnote{MySQL will limit the results to 1 row, if any.}
PostgreSQL\index{PostgreSQL} does not have a problem with this type of query because each row is
fetched on demand. Sybase\index{Sybase} however, will start returning all the rows
that it has available, in the order specified by the "ORDER BY"\index{ORDER BY} clause
(line~\ref{Ex:OrderBy}).

Given that the routine Last\_Price only calls Fetch\index{Fetch}
once, there is no point in the Sybase server producing and sending
more row data down the connection to the APQ client program. For this
reason, a call to Clear\index{Clear} (line~\ref{Ex:Clear}) will send a cancel notice to the Sybase server
to stop producing additional rows. It will also clear out any row data on
the connection that has not been fetched by the client program.

In this particular example, the Query\_Type object Q (line~\ref{Ex:TheQ}) would have been
finalized\index{finalized} anyway upon return from Last\_Price. Finalized Query\_Type
objects always perform the equivalent of a call to Clear prior to
releasing the object storage. However, it is important to explicitly
call Clear\index{Clear} if you have many other operations that follow the query
performed in order to allow a timely cancel if necessary and to release
any pending query results.


\subsection{Procedure Prepare\label{Procedure Prepare}}

The Prepare\index{Prepare} primitive goes one step further than Clear
in that it readies the object for the start of an SQL\index{SQL} statement build.
If the query is short, this will be the only building step required.
As in the case of Clear, the SQL case policy\index{case policy} is unchanged however.

The Prepare procedure takes the following arguments:

\begin{Code}
procedure Prepare(
   Q :     in out Query_Type;
   SQL :   in     String;
   After : in     String := Line_Feed
);
\end{Code}

The SQL argument defines the start of your SQL\index{SQL} statement. The
After argument may supply either the default (line feed)\index{line feed} or
some other text to append to the SQL text\index{SQL text}.
It is provided as a programmer convenience, since many times the
programmer will need to append a comma for example.

There are no exceptions raised by this call.

The following code shows an example of building a query to drop a
table:

\begin{Example}
declare
   Q : Query_Type;
begin
   ...
   Prepare(Q,"DROP TABLE DEAD_WEIGHT");
\end{Example}

\section{SQL Query Building \label{SQL Query Building}}

The previous section primitives ``cleared'' the Query\_Type for
a new query. The primitives provided in this section help to build
a new SQL query or to continue (append to)\index{append} the one started by the
Prepare call in \Ref{Procedure Prepare}. The programmer may
start\index{start} with a Prepare call and follow it by a number of ``append''
calls, or call Clear and build upon an empty query\index{empty query} and skip the
Prepare. ``PREPARE''\index{PREPARE} however, is a traditional first step
in embedded SQL\index{embedded SQL} software, so this tradition comes recommended
by the author.

There are two broad categories of support for creating SQL queries\index{SQL queries}.
They are:

\begin{enumerate}
   \item Append\index{Append} a value to the SQL query
   \item Encode\index{Encode} a value or NULL\index{NULL}, to the SQL query.
\end{enumerate}

Both of these categories append to the current query. Primitives in
category 2 , are prefixed with Encode and will be described
later in the present chapter. 

The Append category of support is useful for values that are never
\emph{NULL} (in SQL terms these columns that are declared as ``NOT
NULL''\index{NOT NULL}). The Encode category of support is provided for values in
your application that may be in the NULL\index{NULL} state. It is not absolutely
required that the Encode support be used, since it is possible for
the application to test for a NULL value. However, the programmer
will find that the Encode support provides application coding convenience
and economy of expression. With compact code, better readability\index{readability} and
safety\index{safety} is normally obtained.

Within category 1, there are five groups of primitives%
\footnote{The generic procedures have been lumped in with the primitives.%
} that build on the present query. They are:

\begin{enumerate}
   \item Append a string
   \item Append a string and a \emph{{}``newline''}
   \item Append a quoted string%
      \footnote{Quoted values are always spared from any automatic case conversions,
      if any are applied.}
   \item Append non string types
   \item Append using generic procedures for custom types
\end{enumerate}

Encode\index{Encode} support on the other hand, only provides for the needs of variables
that must be communicated to the database server. As a result, the
encode procedures consist only of the following two groups:

\begin{enumerate}
   \item Encode non-string\index{non-string types} types
   \item Encode using generic procedures for custom types\index{custom types}
\end{enumerate}

Presently only the second group is provided for by the APQ binding.%
\footnote{The reasoning is that most of the time, the user will want to instantiate
the generic procedures anyway. This permits both the data type and
the null indicator\index{null indicator} type to be a custom application type.%
} A future release may expand on category 1 support.

The append procedures (category 1) will be described first and then
followed by the encode procedures (category 2).


\subsection{Append SQL String}

The Append\index{Append} procedure permits the programmer to append text to the
SQL query being saved in the Query\_Type object. Unlike Prepare\index{Prepare},
Append does not clear the object. Append continues to add
SQL text\index{SQL text} to the query already gathered by the object Q (below):

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   SQL :   in     String;
   After : in     String := ""
);
\end{Code}

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   SQL :   in     Ada.Strings.Unbounded.Unbounded_String;
   After : in     String := ""
);
\end{Code}

There are no exceptions raised by this call.

The following example shows how Append is used:

\begin{Example}
declare
   Q : Query_Type;
begin
   ...
   Prepare(Q,"SELECT CUSTNO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
\end{Example}

Note that the Prepare\index{Prepare} call uses a default argument After=New\_Line\index{After}\index{New\_Line},
while Append uses a null string\index{null string} default.
You can put a line break in the SQL query by supplying the
value New\_Line in the argument "After" if you like.
The following example illustrates the use of Prepare and Append:

\begin{Example}
declare
   Q : Query_Type;
   Col_Name_1 : constant String := "CUSTNO";
   Col_Name_2 : constant String := "CUST_NAME";
begin
   ...
   Prepare(Q,"SELECT ");
   Append(Q,Col_Name_1,",");
   Append(Q,Col_Name_2,Line_Feed);
   Append(Q,"FROM CUSTOMER");
\end{Example}

This example builds up the same query that the previous example did,
except that the column names were provided by string variables\index{string variables}.

\subsection{Append SQL Line\label{Append SQL Line}}

The Append\_Line\index{Append\_Line} procedure is provided for added convenience and program
readability\index{readability}. The same effect can be had with a string Append call,
using string APQ.Line\_Feed supplied as the After\index{After} argument.
The Append\_Line procedure has the following specification:

\begin{Code}
procedure Append_Line(
   Q :   in out Query_Type;
   SQL : in     String;
);
\end{Code}

The Append\_Line procedure is one of the few that does not sport an
\emph{After} argument.


\subsection{Append Quoted SQL String}

Don't quote\index{quoted strings} your own strings at home. There are several reasons why
supplying your own quotes to a call to the normal Append call is a
bad idea:

\begin{enumerate}
   \item Some characters must be encoded\index{encoded} or escaped\index{escaped}, if they occur in the string.
   \item SQL portability\index{portability} is enhanced, since encoding and escaping\index{escaping} varies from
      database vendor to vendor.
   \item Internationalization\index{Internationalization} chosen by the user may require different processing.
   \item Quoted\index{quoted strings} strings should not be changed to upper or lowercase\index{lowercase} (by APQ).
\end{enumerate}

The Append\_Quoted\index{Append\_Quoted} procedure call is designed to make it easier for
the programmer to supply a string value that may contain special characters
within it. Since a string value is already supplied by APQ with outer\index{outer quotes}
quotes, any quote\index{quote} appearing within the string must be quoted. The
Append\_Quoted procedure provides the necessary outer quotes\index{quotes}
for the sring value and escapes\index{escapes} any special characters\index{special characters}
occuring within it as well. 

Another very important reason for using this API call for quoted strings
is that this will prevent the APQ library from changing the case of\index{case of SQL}
any SQL text that is created. This is true no matter what the current
SQL case policy\index{case policy} is (see type APQ\-.SQL\-\_Case\-\_Type on page \pageref{SQL_Case_Type Choices}).
Any string segment\index{string segment} that was added to the query with this API call
will not have its case changed when the query is executed or the text
of the SQL is returned in a call to the To\_String\index{To\_String} function.

There are two Append\_Quoted procedures, which differ only in the data
type of the \emph{SQL} argument:

\begin{Code}
procedure Append_Quoted(
   Q :          in out Query_Type;
   Connection : in out Root_Connection_Type'Class;
   SQL :        in     String;
   After :      in     String := ""
);
\end{Code}

\begin{Code}
procedure Append_Quoted(
   Q :          in out Query_Type;
   Connection : in out Root_Connection_Type'Class;
   SQL :        in     Ada.Strings.Unbounded.Unbounded_String;
   After :      in     String := ""
);
\end{Code}

Notice that this particular API call requires a connection\index{connection}. The reason
for this is that some databases require the server to make the appropriate
choices dealing with internationalized\index{internationalized} character sets\index{character sets}. The quoting\index{quoting}
conventions also vary from database to database, so APQ relies upon
the database vendor software to perform the quoting for you.

The following example illustrates the use of this call (using the
String type):

\begin{Example}
declare
   C :               Connection_Type;
   Q :               Query_Type;
   Freds_Emporium :  String := "Fred's Emporium";
begin
   ...
   Prepare(Q,    "SELECT COMPNO,COMPANY_NAME");
   Append_Line(Q,"FROM SUPPLIER");
   Append(Q,     "WHERE COMPANY_NAME = ");
   Append_Quoted(Q,C,Freds_Emporium,New_Line);
\end{Example}

The effect of these calls is to build an SQL query\index{SQL} that looks as follows
(for PostgreSQL\index{PostgreSQL}):

\begin{SQL}
SELECT COMPNO,COMPANY_NAME
FROM SUPPLIER
WHERE COMPANY_NAME = 'Fred\'s Emporium'
\end{SQL}

Notice how the quote character was escaped for use by the PostgreSQL\index{PostgreSQL}
database server. Note also that even though the SQL case policy\index{case policy} was to
use Upper\_Case\index{Upper\_Case}, the case of the quoted text was preserved.

APQ will automatically adjust the quoting conventions\index{quoting conventions} to match the
database being used. The same example above when used for Sybase\index{Sybase},
would produce the following SQL text\index{SQL text} instead:

\begin{SQL}
SELECT COMPNO,COMPANY_NAME
FROM SUPPLIER
WHERE COMPANY_NAME = 'Fred''s Emporium'
\end{SQL}

Sybase uses a doubled-up quote\index{doubled-up quote} instead.

Using APQ's Append\_Quoted frees the programmer from worrying about
quoting conventions and guarantees that the case of the text will be
preserved.

\subsection{Append Non-String Types to SQL Query}

A fairly large set of builtin non-string\index{non-string types} data types are supported by varied
Append calls that differ in the second argument V. The following
is a list of their specifications:

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     APQ_Boolean;
   After : in     String := ""
);
\end{Code}

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     APQ_Date;
   After : in     String := ""
);
\end{Code}

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     APQ_Time;
   After : in     String := ""
);
\end{Code}

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     APQ_Timestamp;
   After : in     String := ""
);
\end{Code}

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     APQ_Bitstring;
   After : in     String := ""
);
\end{Code}

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     Row_ID_Type;
   After : in     String := ""
);
\end{Code}

These Append\index{Append} procedure calls automatically convert\index{convert} the supplied data
type in argument V, internally into a string\index{string} using the To\_String\index{To\_String} function
appropriate to the data type. Internally, the string Append procedure
is then utilized to perform the remaining work. The following example
illustrates their use:

\begin{Example}
declare
   Q :         Query_Type;
   Ship_Date : APQ_Date;
begin
   ...
   Prepare(Q,    "SELECT COMPNO,COMPANY_NAME,SHIP_DATE");
   Append_Line(Q,"FROM SUPPLIER");
   Append(Q,     "WHERE SHIP_DATE = ");
   Append(Q,Ship_Date,New_Line);
\end{Example}

The example presented builds an SQL query that looks like this:

\begin{SQL}
SELECT COMPNO,COMPANY_NAME,SHIP_DATE
FROM SUPPLIER
WHERE SHIP_DATE = '2002-07-21'
\end{SQL}

Notice that the Append call for APQ\_Date\index{APQ\_Date} automatically supplies the
necessary quotes to the SQL query\index{SQL query} (if needed for the database being
used). All of the data types supported are molded into a format that
is acceptable in the native database SQL syntax\index{SQL syntax}. 

There is one additional Append procedure call that has a special set
of arguments in order to support dates\index{dates} with time zones\index{time zones}. The arguments
for this procedure call are as follows:

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   TS :    in     APQ_Timestamp;
   TZ :    in     APQ_Timezone;
   After : in     String := ""
);
\end{Code}

Apart from the different argument names TS and TZ, this
procedure works in the same fashion as the former Append\index{Append} procedure
call. The TZ argument simply supplies the additional time zone\index{time zone}
information to be added to the timestamp\index{timestamp}.

\begin{description}
\item [Note:] Not all databases support the use of timezone values.
\end{description}

\subsection{Generic Append SQL Procedures}

Ada programmers often take advantage of the strong typing \index{strong typing}that
is available in the language. To accomodate this programming aspect,
generic procedures are available so that type conversions\index{type conversions}
are unnecessary. The following table documents the generic procedures
that accept one generic argument named Val\_Type and the data
types that they support:

\begin{Code}
generic
   type Val_Type is new Boolean;
procedure Append_Boolean(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is range <>;
procedure Append_Integer(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is mod <>;
procedure Append_Modular(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is digits <>;
procedure Append_Float(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <>;
procedure Append_Fixed(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <> digits <>;
procedure Append_Decimal(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
procedure Append_Date(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Day_Duration;
procedure Append_Time(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Timestamp;
procedure Append_Timestamp(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Bitstring;
procedure Append_Bitstring(
   Q :     in out Root_Query_Type'Class;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

Each of the resulting instantiated procedures provide the following
calling signature:

\begin{Code}
procedure Append(
   Q :     in out Query_Type;
   V :     in     Val_Type;
   After : in     String := ""
);
\end{Code}

The following code fragment illustrates how these are instantiated\index{instantiated} and used:

\begin{NumberedExample}
declare
   type Price_Type is delta 0.01 digits 12;\label{Ex:TypeDef}
   procedure Append is new Append_Decimal(Price_Type);\label{Ex:Inst}

   Q :             Query_Type;
   Selling_Price : Price_Type;
begin
   ...
   Prepare(Q,"UPDATE SUPPL_ORDER");
   Append(Q."SET SELLING_PRICE = ");
   Append(Q,Selling_Price,New_Line);\label{Ex:InstUse}
   Append_Line(Q,"WHERE ...");
\end{NumberedExample}

In this example, the application defines its own type Price\_Type
in line~\ref{Ex:TypeDef}. After instantiating the Append\_Decimal
generic procedure as Append\index{Append} (line~\ref{Ex:Inst}), the application is
free to neatly append a price value from Selling\_Price in
line~\ref{Ex:InstUse}, as if it were natively supported.


\subsection{Generic Append\_Timezone}

The Append\_Timezone\index{Append\_Timezone} has an additional generic paramter. The instantiated\index{instantiated}
procedure also has a slightly different set of calling arguments. The generic
parameters are specified as follows:

\begin{Code}
generic
   type Date_Type is new Ada.Claendar.Time;
   type Zone_Type is new APQ_Timezone;
procedure Append_Timezone(
   Q :     in out Root_Query_Type'Class;
   V :     in     Date_Type;
   Z :     in     Zone_Type;
   After : in     String := ""
);
\end{Code}

The instantiated procedure has the following calling signature:

\begin{Code}
procedure Append(
   Q :     in out Root_Query_Type'Class;
   V :     in     Date_Type;
   Z :     in     Zone_Type;
   After : in     String := ""
);
\end{Code}

The following shows an example of its use:

\begin{NumberedExample}
declare
   type Ship_Date_Type is new APQ_Timestamp;
   type Ship_Zone_Type is new APQ_Timezone;

   procedure Append is new Append_Timezone(\label{Ex:InstTZ}
      Ship_Date_Type,Ship_Zone_Type);

   Q :         Query_Type;
   Ship_Date : Ship_Date_Type;
   Ship_Zone : Ship_Zone_Type;
begin
   ...
   Prepare(Q,"SELECT COUNT(*)");
   Append_Line(Q,"FROM ORDER");
   Append(Q,"WHERE SHIP_DATE = ");
   Append(Q,Ship_Date,Ship_Zone,New_Line);\label{Ex:UseInstTZ}
   ...
\end{NumberedExample}

The example shows how the application's types Ship\_Date\_Type
and Ship\_Zone\_Type are accomodated by the Append\index{Append} instantiation\index{instantiation}
of the generic procedure (line~\ref{Ex:InstTZ}). The instantiated
Append routine is applied in line~\ref{Ex:UseInstTZ}.


\subsection{Generic Append of Bounded SQL Text}

To accomodate the use of the package Ada\-.Strings\-.Bounded\index{Ada.Strings.Bounded},
the generic procedure Append\_Bounded\index{Append\_Bounded} was provided. Its instantiation
requirements differ from the preceeding ones because the instantiation
of the Bounded\_String\index{Bounded\_String} type must be provided to the Append\_Bounded
generic procedure. The generic procedure is defined as follows:

\begin{Code}
generic
   with package P 
      is new Ada.Strings.Bounded.Generic_Bounded_Length(<>);
procedure Append_Bounded(
   Q :     in out Query_Type;
   SQL :   in     P.Bounded_String;
   After : in     String
);
\end{Code}

In other words, Append\_Bounded can be instantiated from any instantiation
of the Ada.Strings.Bounded.Generic\_Bounded\_Length package. The following
example makes this easier to understand:

\begin{NumberedExample}
with Ada.Strings.Bounded;
...
declare
   package B80 
      is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
   package B20 
      is new Ada.Strings.Bounded.Generic_Bounded_Length(20);

   procedure Append is new Append_Bounded(B80);\label{Ex:B80}
   procedure Append is new Append_Bounded(B20);\label{Ex:B20}

   Q :         Query_Type;
   Item_Code : B20;
   Item_Name : B80;
begin
   ...
   Prepare(Q,    "SELECT COUNT(*)");
   Append_Line(Q,"FROM ORDER");
   Append(Q,     "WHERE ITEM_CODE = ","'");
   Append(Q,Item_Code,"' AND ITEM_NAME = '");\label{Ex:UseB20}
   Append(Q,Item_Name,"'" & New_Line);\label{Ex:UseB80}
   ...
\end{NumberedExample}

The example shows how two different generic procedures named Append
are instantiated from the Bounded\_String instantiations B80 (line~\ref{Ex:B80})
and B20 (line~\ref{Ex:B20}). Note that the Append\_Bounded procedure does not escape
special characters, nor provide the outer quotes (this is a poor example of its
use actually).

The Append\index{Append} call used in line~\ref{Ex:UseB20} is the one that was
instantiated on line~\ref{Ex:B20}. The other Append used on
line~\ref{Ex:UseB80} was instantiated on line~\ref{Ex:B80}. These
are matched according to the normal Ada95\index{Ada95} argument type matching
rules.

\subsection{Generic Append\_Bounded\_Quoted Procedure}

To accomodate the quoting needs of Bounded\_Strings, the Append\_Bounded\_Quoted\index{Append\_Bounded\_Quoted}
generic procedure may be used:

\begin{Code}
generic
   with package P
      is new Ada.Strings.Bounded.Generic_Bounded_Length(<>);
procedure Append_Bounded_Quoted(
   Q :     in out Query_Type;
   C :     in     Connection_Type;
   SQL :   in     P.Bounded_String;
   After : in     String
);
\end{Code}

It is otherwise very similar to the previous Append\_Unbounded\index{Append\_Unbounded} procedure.
The following example illustrates a safer\index{safer} version of the prior example:

\begin{Example}
with Ada.Strings.Bounded;
...
declare
   package B80 
      is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
   package B20 
      is new Ada.Strings.Bounded.Generic_Bounded_Length(20);

   procedure Append_Quoted is new Append_Bounded_Quoted(B80);
   procedure Append_Quoted is new Append_Bounded_Quoted(B20);

   C :         Connection_Type;
   Q :         Query_Type;
   Item_Code : B20;
   Item_Name : B80;
begin
   ...
   Prepare(Q,    "SELECT COUNT(*)");
   Append_Line(Q,"FROM ORDER");
   Append(Q,     "WHERE ITEM_CODE = ");
   Append_Quoted(Q,C,Item_Code," AND ITEM_NAME = ");
   Append_Quoted(Q,C,Item_Name,New_Line);
   ...
\end{Example}

The instantiations of Append\_Quoted\index{Append\_Quoted}%
\footnote{It is not necessary to instantiate these procedures as
Append\_Quoted, but it is recommended for readability.} here will
properly escape\index{escape} any special\index{special characters} characters that may appear in the program's
string variables Item\_Code and Item\_Name. Additionally, note that the
outer quotes\index{quotes} are provided automatically, easing the programmer's burden
in building up the SQL query. Like other Append\_Quoted API calls within
APQ, the case\index{case within quoted strings} within quoted strings is always preserved.


\subsection{Encoding Quoted Strings}

While strings are well covered by the category 1 support, it is necessary
to encode a NULL\index{NULL} in place of a quoted string\index{quoted string},
when the value is null. The generic specification for 
Encode\-\_String\-\_Quoted\index{Encode\_String\_Quoted} is as follows:

\begin{Code}
generic
   type Ind_Type is new Boolean;
procedure Encode_String_Quoted(
   Q :          in out Root_Query_Type'Class;
   Connection : in     Root_Connection_Type'Class;
   SQL :        in     String;
   Indicator :  in     Ind_Type;
   After :      in     String := ""
);
\end{Code}

An example of its instantiation and use is shown below:

\begin{Example}
declare
   type Cust_Name_Ind_Type is new Boolean;

   procedure Encode_Quoted 
      is new Encode_String_Quoted(Cust_Name_Ind_Type);

   Q :             Query_Type;
   Cust_Name :     String(1..30);
   Cust_Name_Ind : Cust_Name_Ind_Type; -- Indicator
begin
   ...
   Prepare(Q,"UPDATE CUSTOMER");
   Append_Line(Q,"SET CUST_NAME = ");
   Encode_Quoted(Q,Cust_Name,Cust_Name_Ind);
\end{Example}

In this example, the String Cust\_Name is given outer quotes
and any special characters are escaped before the value is appended
to the current SQL query being collected in object Q. If however,
the indicator Cust\_Name\_Ind is True (indicating that the
value Cust\_Name should be interpreted as NULL\index{NULL}), then the string
``NULL'' is appended instead. When NULL is supplied, no outer
quotes are supplied. The following two SQL statements are possible,
depending upon Cust\_Name\_Ind. When the indicator is false,
a quoted\index{quoted value} value is supplied:

\begin{SQL}
UPDATE CUSTOMER
SET CUST_NAME = 'Fred Willard'
...
\end{SQL}

When the indicator is true (the value is null), the resulting query
becomes the following:

\begin{SQL}
UPDATE CUSTOMER
SET CUST_NAME = NULL
...
\end{SQL}

\subsection{Encoding Quoted Unbounded\_String}

To provide quoting\index{quoting support} support for Unbounded\-\_Strings\index{Ada.Strings.Unbounded},
the Encode\-\_Bounded\-\_Quoted gen\-eric procedure is provided by APQ.
The specifications for this procedure is given below:

\begin{Code}
generic
   type Ind_Type is new Boolean;
procedure Encode_Unbounded_Quoted(
   Q :          in out Root_Query_Type'Class;
   Connection : in     Root_Connection_Type'Class;
   SQL :        in     Ada.Strings.Unbounded.Unbounded_String;
   Indicator :  in     Ind_Type;
   After :      in     String := ""
);
\end{Code}

An example of its use is illustrated as follows:

\begin{Example}
declare
   use Ada.Strings.Bounded;

   type Cust_Name_Ind_Type is new Boolean;

   procedure Encode_Quoted 
      is new Encode_Unbounded_Quoted(Cust_Name_Ind_Type);

   C :             Connection_Type;
   Q :             Query_Type;
   Cust_Name :     Unbounded_String;
   Cust_Name_Ind : Cust_Name_Ind_Type;
begin
   ...
   Prepare(Q,"UPDATE CUSTOMER");
   Append_Line(Q,"SET CUST_NAME = ");
   Encode_Quoted(Q,C,Cust_Name,Cust_Name_Ind);
\end{Example}

In this example, the Unbounded\_String Cust\_Name is given
outer quotes and any special characters are escaped before the value
is appended to the current SQL query\index{SQL query} being collected in object Q.
If however, the indicator\index{indicator, null} Cust\_Name\_Ind is True (indicating
that the value \emph{Cust\_Name} should be interpreted as NULL), then
the string ``NULL''\index{NULL} is appended\index{appended} instead. When NULL is supplied,
no outer\index{outer quotes} quotes are supplied. The following two SQL statements are
possible, depending upon \emph{Cust\_Name\_Ind}. When the indicator
is false, a quoted value\index{quoted value} is supplied:

\begin{SQL}
UPDATE CUSTOMER
SET CUST_NAME = 'Fred Willard'
...
\end{SQL}

When the indicator is true, the resulting query becomes the following:

\begin{SQL}
UPDATE CUSTOMER
SET CUST_NAME = NULL
...
\end{SQL}

\subsection{Encoding Bounded Quoted Strings}

Bounded strings\index{bounded strings} require instantiations of
Ada\-.Strings\-.Bounded\-.Gen\-eric\-\_Bound\-ed\-\_Len\-gth
\index{Ada.Strings.Bounded}with a specific length. The instantiated
package\index{package} reference must be provided as an argment to the
Encode\-\_Bounded\-\_Quoted\index{Encode\_Bounded\_Quoted} instantiation:

\begin{Code}
generic
   type Ind_Type is new Boolean;
   with package P 
      is new Ada.Strings.Bounded.Generic_Bounded_Length(<>);
procedure Encode_Bounded_Quoted(
   Q :          in out Root_Query_Type'Class;
   Connection : in     Root_Connection_Type'Class;
   SQL :        in     P.Bounded_String;
   Indicator :  in     Ind_Type;
   After :      in     String := ""
);
\end{Code}

An example showing its use is given below:

\begin{Example}
with Ada.Strings.Bounded;

declare
   package B80 is new 
      Ada.Strings.Bounded.Generic_Bounded_Length(80);

   type Cust_Name_Ind_Type is new Boolean;

   procedure Encode_Quoted is new
      Encode_Bounded_Quoted(Cust_Name_Ind_Type,B80);

   C :             Connection_Type;
   Q :             Query_Type;
   Cust_Name :     B80.Bounded_String;
   Cust_Name_Ind : Cust_Name_Ind_Type; -- Indicator
begin
   ...
   Prepare(Q,"UPDATE CUSTOMER");
   Append_Line(Q,"SET CUST_NAME = ");
   Encode_Quoted(Q,C,Cust_Name,Cust_Name_Ind);
   ...
\end{Example}

In this example, the Bounded\_String Cust\_Name is given outer
quotes and any special characters are escaped before the value is
appended to the current SQL query being collected in object Q.
If however, the indicator\index{indicator} Cust\_Name\_Ind is True (indicating
that the value Cust\_Name should be interpreted as NULL), then
the string ``NULL''\index{NULL} is appended instead. When NULL is supplied,
no outer quotes are supplied. The following two SQL\index{SQL} statements are
possible, depending upon Cust\_Name\_Ind. When the indicator is false,
a quoted value\index{quoted value} is supplied:

\begin{SQL}
UPDATE CUSTOMER
SET CUST_NAME = 'Fred Willard'
...
\end{SQL}

When the indicator is true, the resulting query becomes the following:

\begin{SQL}
UPDATE CUSTOMER
SET CUST_NAME = NULL
...
\end{SQL}

\subsection{Encoding Non-String Values}

There are a large number of generic\index{generic} encoding procedures that 
allow encoding of non-string\index{non-string values} values into SQL queries. They are
listed below:

\begin{Code}
generic
   type Val_Type is new Boolean;
   type Ind_Type is new Boolean;
procedure Encode_Boolean(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is range <>;
   type Ind_Type is new Boolean;
procedure Encode_Integer(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is mod <>;
   type Ind_Type is new Boolean;
procedure Encode_Modular(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is digits <>;
   type Ind_Type is new Boolean;
procedure Encode_Float(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <>;
   type Ind_Type is new Boolean;
procedure Encode_Fixed(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <> digits <>;
   type Ind_Type is new Boolean;
procedure Encode_Decimal(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Date;
   type Ind_Type is new Boolean;
procedure Encode_Date(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Time;
   type Ind_Type is new Boolean;
procedure Encode_Time(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Timestamp;
   type Ind_Type is new Boolean;
procedure Encode_Timestamp(
   Q :         in out Root_Query_Type'Class;
   V :         in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Bitstring;
   type Ind_Type is new Boolean;
procedure Encode_Bitstring(
   Q :         in out Root_Query_Type'Class;
   V:          in     Val_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

The following example shows the application of one of these generic
procedures:

\begin{Example}
declare
   type Cust_No_Type is new Integer range 1000..100_000;
   type Cust_Age_Type is new Integer range 0..200;

   procedure Append is new Append_Integer(Cust_No_Type);
   procedure Encode is new 
      Encode_Integer(Cust_No_Type,Boolean);

   Q :            Query_Type;
   Cust_No :      Cust_No_Type;  -- Customer # NOT NULL
   Cust_Age :     Cust_Age_Type; -- Can be NULL
   Cust_Age_Ind : Boolean;       -- Indicator
   Cust_Name :    String(1..30); -- Customer Name NOT NULL
begin
   ...
   Prepare(Q,"INSERT INTO CUSTOMER (CUST_NO,AGE,CUST_NAME)");
   Append(Q, "VALUES ( ");
   Append(Q,Cust_No,",");
   Encode(Q,Cust_Age,Cust_Age_Ind,",");
   Append_Quoted(Q,Cust_Name," )" & New_Line);
   ...
\end{Example}

From the example, if variable Cust\_Name holds the value ``Martin Mull'',
and Cust\_No holds 12345, two possible SQL queries are possible,
depending upon the value of Cust\_Age\_Ind, the null indicator\index{indicator, null}. When
Cust\_Age\_Ind is false (not null), then the SQL query would be formed as
follows:

\begin{SQL}
INSERT INTO CUSTOMER (CUST_NO,AGE,CUST_NAME)
VALUES (12345,52,'Martin Mull')
\end{SQL}

When the indicator\index{indicator} Cust\_Age\_Ind is true (representing null), then the
query would be constructed as follows:

\begin{SQL}
INSERT INTO CUSTOMER (CUST_NO,AGE,CUST_NAME)
VALUES (12345,NULL,'Martin Mull')
\end{SQL}

Notice how Append\index{Append} procedures are used for values that can never be
null (no null indicator is involved). Encode routines are only necessary
when a null indicator may need to be encoded into the result.


\subsection{Encoding Timezone}

Encoding\index{encoding} APQ\_Timezone\index{APQ\_Timezone} values requires a special generic procedure
named Encode\-\_Timezone\index{Encode\_Timezone}. Its generic parameters are described by the
following table:

\begin{Code}
generic
   type Date_Type is new APQ_Timestamp;
   type Zone_Type is new APQ_Timezone;
   type Ind_Type is new Boolean;
procedure Encode_Timezone(
   Q :         in out Root_Query_Type'Class;
   D :         in     Date_Type;
   Z :         in     Zone_Type;
   Indicator : in     Ind_Type;
   After :     in     String := ""
);
\end{Code}

The following example demonstrates the instantiation and use of the
procedure:\label{Birthday Timezone Example}

\begin{Example}
declare
   type Cust_No_Type is new Integer range 1000..100_000;
   type Birthday_Type is new APQ_Timestamp;

   procedure Append is new Append_Integer(Cust_No_Type);
   procedure Encode is new
      Encode_Integer(Cust_No_Type,Boolean);
   procedure Encode is new
      Encode_Timezone(Birthday_Type,APQ_Timezone,Boolean);

   Q :            Query_Type;
   Cust_No :      Cust_No_Type;  -- Customer # NOT NULL
   Birthday :     Birthday_Type; -- Customer birthday
   Birthday_TZ :  APQ_Timezone;  -- Timezone of the birthday
   Birthday_Ind : Boolean;       -- True when Birthday is NULL
begin
   ...
   Prepare(Q,"INSERT INTO BIRTHDAY (CUST_NO,BIRTHDAY)");
   Append(Q, "VALUES (");
   Append(Q,Cust_No,",");
   Encode(Q,Birthday,Birthday_TZ,Birthday_Ind,")" & New_Line);
   ...
\end{Example}

If the Birthday\_Ind indicator\index{indicator} is false (not null\index{null, not}),
then the resulting query would look something like this:

\begin{SQL}
INSERT INTO BIRTHDAY (CUST_NO,BIRTHDAY)
VALUES (12345,'1984-09-25 22:47:06+03')
\end{SQL}
The ``+03'' after the time represents the time zone \index{time zone}UTC+3
hours.


\section{Query Execution}

Once the SQL query has been constructed using all of the techniques
described in \Ref{SQL Initialization} and \Ref{SQL Query Building},
you are ready to send\index{send the query} the query to the database engine\index{engine, database} to have it
executed. This is done with the help of the Query\_Type's primitive
Execute\index{Execute}. The Execute call requires the following calling arguments:

\begin{Code}
procedure Execute(
   Query :      in out Root_Query_Type;
   Connection : in out Root_Connection_Type'Class
);
\end{Code}

The Execute primitive can raise the exceptions that are listed
in Table~\ref{t:exx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name &  Reason\\
         \hline 
         Not\_Connected &  There is no connection to use\\
         Abort\_State   &  Transaction in {}``abort state{}``\\
         SQL\_Error     &  The submitted SQL query failed\\
         Failed         &  Hidden APQ query failure\\
      \end{tabular}
   \end{center}
   \caption{Execute Exceptions}\label{t:exx}
\end{table}

The PostgreSQL\index{PostgreSQL} Abort\_State\index{Abort\_State}
exception is described in \Ref{Abort_State exception}. This exception indicates that
the current transaction has failed\index{failed transaction}. All other types of errors\index{errors} raise\index{raise}
the SQL\_Error\index{SQL\_Error} exception, unless the connection is bad. The Failed\index{Failed exception}
exception only occurs for some databases where a hidden\index{hidden SQL query} SQL query
must be performed and it unexpectedly failed.%
\footnote{For Sybase, APQ will do a SELECT @@identity after an INSERT query
is performed.%
}

The use of the Execute\index{Execute} primitive is illustrated by extending the example
from page \pageref{Birthday Timezone Example}:

\begin{Example}
declare
   type Cust_No_Type is new Integer range 1000..100_000;
   type Birthday_Type is new APQ_Timestamp;

   procedure Append is new Append_Integer(Cust_No_Type);

   procedure Encode is new
      Encode_Integer(Cust_No_Type,Boolean);
   procedure Encode is new
      Encode_Timezone(Birthday_Type,APQ_Timezone,Boolean);

   C :            Connection_Type;
   Q :            Query_Type;
   Cust_No :      Cust_No_Type;     -- NOT NULL
   Birthday :     Birthday_Type;
   Birthday_TZ :  APQ_Timezone;     -- Timezone
   Birthday_Ind : Boolean;          -- Indicator
begin
   ...
   Prepare(Q,"INSERT INTO BIRTHDAY (CUST_NO,BIRTHDAY)");
   Append(Q, "VALUES (");
   Append(Q,Cust_No,",");
   Encode(Q,Birthday,Birthday_TZ,Birthday_Ind,")" & New_Line);
   Execute(Q,C);
\end{Example}

The example shows the Execute primitive pairing the query object Q
with the database connection object C.

\subsection{Error Message Reporting\label{Error Message Reporting}}

It is useful to know that your SQL query failed, but more information
is usually necessary. The Error\_Message\index{Error\_Message} primitive can be invoked
on the Query\_Type object. This function has the following calling
signature:

\begin{Code}
function Error_Message(
   Query : Query_Type;
) return String;
\end{Code}

The following example shows how this function might be used:

\begin{Example}
begin
   ...
   Execute(Q,C);
exception
   when SQL_Error =>
      Put(Standard_Error,"SQL Error: ");
      Put_Line(Standard_Error,Error_Message(Q));
      raise;
   when others =>
      raise;
end
\end{Example}

\subsection{Is\_Duplicate\_Key Function}

Duplicate\index{duplicate key} key errors\index{errors} often occur while performing SQL INSERT\index{INSERT} operations
on a table. A duplicate key insertion\index{insertion error} error is a special case because
the insert operation may not be considered a failure for some applications.
For this reason, the Is\_Duplicate\_Key\index{Is\_Duplicate\_Key} predicate function is provided
for use after a SQL\_Error exception has been raised%
\footnote{At present, this test is implemented by calling Error\_Message and
looking at the message text. Future versions of the APQ binding may
use a more reliable indicator if the PostgreSQL libpq library provides
such a status indication.%
}. The specification is listed as follows:

\begin{Code}
function Is_Duplicate_Key(
   Query : Query_Type
) return Boolean;
\end{Code}

The following example reports an SQL error\index{SQL error} only if the error is not
a duplicate key insert problem:

\begin{Example}
...
begin
   Execute(Q,C);  -- Execute an INSERT SQL statement
exception
   when SQL_Error =>
      if not Is_Duplicate_Key(Q) then
         -- Report error if not a duplicate insert
         Put(Standard_Error,"SQL Error: ");
         Put_Line(Standard_Error,Error_Message(Q));
         raise;
      else
         null; -- Ignore duplicate insert
      end;
end;
\end{Example}

\subsection{Command\_Status Function (PostgreSQL)\label{Command_Status Function}}

The Command\_Status\index{Command\_Status} function provides a string of status information
after a PostgreSQL\index{PostgreSQL} query has been executed. The results returned depends
upon the type of execution that was last performed. Table~\ref{t:csrv}
summarizes the types of return status strings available:%
\marginpar{This is a PostgreSQL specific function, only. Avoid its use for portability.}

\begin{table}
   \begin{center}
      \begin{tabular}{|l|l|l|}
         \hline
         After Event    &  Result               &  Comments\\
         \hline
         CREATE ...     &  "CREATE"             &  \\
         BEGIN WORK     &  "BEGIN"              &  \\
         COMMIT WORK    &  "COMMIT"             &  \\
         ROLLBACK WORK  &  "ROLLBACK"           &  \\
         SELECT ...     &  "SELECT"             &  \\
         INSERT ...     &  "INSERT <OID> <\#>"  &  \# is normally 1\\
         \hline
      \end{tabular}
   \end{center}
   \caption{Command\_Status Return Values}\label{t:csrv}
\end{table}

Notice that after an INSERT\index{INSERT} is performed, the returned status string
includes the OID\index{OID} (row ID\index{row ID}) of the new row, and the number of rows inserted
(normally 1). If you need to extract the OID value, see the Command\_Oid
function in \Ref{Command_Oid Function}.

The calling signature of Command\_Status is:

\begin{Code}
function Command_Status(
   Query : Query_Type
) return String;
\end{Code}

The Command\_Status function can raise the exceptions listed in
Table~\ref{t:cstsx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There is no result status (no execution)\\
      \end{tabular}
   \end{center}
   \caption{Command\_Status Exceptions}\label{t:cstsx}
\end{table}


\subsection{Command\_Oid Function \label{Command_Oid Function}}

After an INSERT\index{INSERT} operation, it is often required to know the OID\index{OID} (row ID\index{row ID})
value for the newly created row. When using PostgreSQL, this can be
extracted from the Command\_Status\index{Command\_Status} return string (see
\Ref{Command_Status Function}), but this approach is not
portable to other vendor databases.

The APQ user is encouraged to call the Command\_Oid function when
it is necessary to know the identity\index{identity} of the newly inserted row. This
function primitive hides the differences\index{differences} between the different database
products and makes your code more portable.

The calling signature for Command\_Oid is as follows:

\begin{Code}
function Command_Oid(
   Query : Query_Type
) return Row_ID_Type;
\end{Code}

Table \ref{t:coidx} lists the exceptions that are possible for Command\_Oid.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There is no result status (no execution)\\
         SQL\_Error        &  An SQL error occurred obtaining the OID\\
      \end{tabular}
   \end{center}
   \caption{Command\_Oid Exceptions}\label{t:coidx}
\end{table}

Be aware that the exception No\_Result\index{No\_Result} can be raised for two different
reasons:

\begin{itemize}
   \item There was no prior ``execution'' (thus no result)
   \item The prior execution was not an INSERT operation (hence no OID value available)
\end{itemize}

APQ applications should \emph{not} be written to provoke these exceptions,
since different database products behave differently in this respect
(Sybase\index{Sybase} users will never see an exception from Command\_Oid for example).
The raising of either of these exceptions does however indicate that
there is a programming error\index{error, programming} that requires correction in the calling
application.


\subsubsection{Database OID (Row ID) Support}

Some databases do not support the concept of OID\index{OID} (row ID\index{row ID}) values.
This creates a huge portability\index{portability} problem for the application programmer.
However, all databases provide some technique for identifying\index{identifying rows} rows
uniquely in a table. Table~\ref{t:roids} summarizes the ways that
APQ adapts the database server to concept of OID values:%
\footnote{Applications should be written to avoid row ID concepts and use key values instead.}

\begin{table}
   \begin{center}
      \begin{tabular}{|l|l|l|l|}
         \hline 
         Database          &  OID      &  How               &  How APQ Supports OID\\
         \hline
         PostgreSQL        & Yes       &  OID = Row ID      &  PostgreSQL Object ID (OID)\\
         MySQL             & No        &  AUTO\_INCREMENT   &  Serial value from primary key\\
         Sybase            & No        &  Identity column   &  SELECT @@identity\\
         \hline
      \end{tabular}
   \end{center}
   \caption{Row ID Database Support}\label{t:roids}
\end{table}


\subsubsection{MySQL OID (Row ID) Support}

From the preceeding table, you can observe that MySQL\index{MySQL} does not support
any concept of a row ID\index{row ID} value. APQ can fake OID-like\index{OID} support, if the
table is defined using a primary key in the following form\index{AUTO\_INCREMENT}:

\begin{SQL}

   INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY

\end{SQL}

When a MySQL table has a primary key like the one shown, APQ is able
to return the created primary key value using Command\_OID\index{Command\_OID}. 

The following is an example table declaration:

\begin{SQL}
CREATE TABLE ITEM_DESC (
   ITEM_ID     INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
   DESCRIPTION VARCHAR(80)
);
\end{SQL}

\subsubsection{Sybase OID (Row ID) Support}

Sybase\index{Sybase} does not support the concept of row ID\index{row ID} values. APQ however,
can provide row ID-like support if you declare your table with a primary
key in the following form\index{IDENTITY}:

\begin{SQL}

   NUMERIC IDENTITY NOT NULL PRIMARY KEY

\end{SQL}

For Sybase, when the APQ procedure Execute is performed, APQ will
check to see if the SQL query peformed was an INSERT\index{INSERT} command. If it
was, a hidden SQL query is performed immediately afterwards on the
same connection to query the identity\index{identity of a row} of the row that was created\index{@@identity}:

\begin{SQL}

   SELECT @@identity

\end{SQL}

The value returned by this hidden query will be saved as the row ID\index{row ID}
in the Query\-\_Type object used to perform the INSERT\index{INSERT}. A later call
to Command\_OID on this same Query\_Type object, will then return
this row identity value as a Row\_ID\_Type\index{Row\_ID\_Type}.

The following is an example Sybase table declaration:

\begin{SQL}
CREATE TABLE ITEM_DESC (
   ITEM_ID     NUMERIC IDENTITY NOT NULL PRIMARY KEY,
   DESCRIPTION VARCHAR(80)
);
\end{SQL}

\subsubsection{Example of Command\_OID Use}

The following example will always work for PostgreSQL\index{PostgreSQL}. It will also
work for MySQL\index{MySQL} and Sybase\index{Sybase}, if the primary key\index{primary key} guidelines in the prior
subsections were followed. 

This example shows how the INSERTed\index{INSERT} row's OID value (or primary key\index{primary key})
is obtained:

\begin{Example}
declare
   C :      Connection_Type;
   Q :      Query_Type;
   Obj_Id : Row_ID_Type;
begin
   ...
   Prepare(Q,"INSERT INTO CUST_ORDER (CATALOG_NO,QUANTITY,...");
   ...
   Execute(Q,C);
   Obj_Id := Command_Oid(Q);  -- row id/identity of inserted row
\end{Example}

The variable named Obj\_ID will contain the PostgreSQL\index{PostgreSQL} OID\index{OID} value of
the inserted row, when PostgreSQL is used. For MySQL\index{MySQL} and Sybase\index{Sybase}, the
variable Obj\_ID will contain the primary key value of the newly created
row.


\subsubsection{Generic\_Command\_Oid Function}

To allow strong typing\index{strong typing} to be used in place of the supplied Row\_ID\_Type\index{Row\_ID\_Type}
type, the Generic\_Command\_Oid\index{Generic\_Command\_Oid} function can be instantiated for use
in the application. The instantiated function otherwise behaves identical
with the Command\_Oid function described on page \pageref{Command_Oid Function}.
The instantiation arguments for Generic\_Command\_Oid are as follows:

\begin{Code}
generic
   type Oid_Type is new Row_ID_Type;
function Generic_Command_Oid(
   Query : Query_Type'Class
) return Oid_Type;
\end{Code}

An instantiation example follows:

\begin{Example}
declare
   type My_Oid_Type is new Row_ID_@Type;

   function Command_Oid 
      is new Generic_Command_Oid(My_Oid_Type);
\end{Example}

\subsection{Error Status Reporting\label{Error Status Reporting}}

The Result\index{Result} function primitive is documented here for completeness.
Applications should avoid using this function, since the values that
it returns are very database technology specific.


\subsubsection{Result Codes}

The Result function primitive should be avoided in portable code. However,
there may be circumstances where a particular code is important to the
application developer.

\begin{Code}
function Result(
   Query : Query_Type
) return Natural;
  -- Returns Result_Type'Pos()
\end{Code}

The Result function returns a Natural\index{Natural} value. To obtain the Result\_Type\index{Result\_Type}
for the database being used, you should use;

\begin{Example}
declare
   Q : Query_Type;
   R : Result_Type;
begin
   R := Result_Type'Val(Result(Q));
\end{Example}

\subsubsection{Notes:}

\begin{itemize}
   \item The Execute\index{Execute} primitive will throw an exception if the execution failed
         (the PostgreSQL Nonfatal\_Error\index{Nonfatal\_Error} case).
   \item For SELECT\index{SELECT} queries, the fact that no rows are returned will be identifiable upon
         the first FETCH\index{FETCH} operation (the PostgreSQL Empty\_Query\index{Empty\_Query}
         case), or upon calling End\_of\_Query\index{End\_of\_Query}.
   \item When rows are returned (the PostgreSQL Tuples\_OK\index{Tuples\_OK} case), the application will
         successfully fetch at least one row.
   \item For other SQL commands, successful execution is determined by Execute
         not throwing an exception (the PostgreSQL Command\_OK\index{Command\_OK} case). 
\end{itemize}

\subsubsection{PostgreSQL Result Codes}

The PostgreSQL\index{PostgreSQL} result\index{result types} types are declared in the APQ\-.PostgreSQL package.
The Result\_Type values are highly PostgreSQL engine\index{engine} specific and are
enumerated in Table~\ref{t:pqresc}.

\begin{longtable}{|c|c|l|}
\hline 
Name              &  Value          &  Description\\
\hline
Empty\_Query      &  0              &  The query returned 0 rows of data\\
Command\_OK       &  1              &  The non-query statement executed successfully\\
Tuples\_OK        &  2              &  The SQL query returned at least 1 row of data\\
Copy\_Out         &  3              &  \\
Copy\_In          &  4              &  \\
Bad\_Response     &  5              &  Bad response from database server\\
Nonfatal\_Error   &  6              &  A non fatal error has occurred\\
Fata\_Error       &  7              &  A fatal error has occurred\\
\hline
\caption{PostgreSQL Result Codes}\label{t:pqresc}
\end{longtable}

\begin{quote}
Note that the numeric values in Table~\ref{t:pqresc} are subject to change if the
PostgreSQL\index{PostgreSQL} database server software designers choose to do so. Use
the enumerated names instead.
\end{quote}

\subsubsection{MySQL Result Codes}

Result types for MySQL\index{MySQL} are declared in package APQ\-.MySQL. These are
generated by the APQ install process from the MySQL database 
C macros provided. The following is the list from MySQL version 4.0.14 :

\begin{Code}
type Result_Type is (
   CR_NO_ERROR,
   ER_HASHCHK,
   ER_NISAMCHK,
   ER_NO,
   ER_YES,
   ER_CANT_CREATE_FILE,
   ER_CANT_CREATE_TABLE,
   ER_CANT_CREATE_DB,
   ER_DB_CREATE_EXISTS,
   ER_DB_DROP_EXISTS,
   ER_DB_DROP_DELETE,
   ER_DB_DROP_RMDIR,
   ER_CANT_DELETE_FILE,
   ER_CANT_FIND_SYSTEM_REC,
   ER_CANT_GET_STAT,
   ER_CANT_GET_WD,
   ER_CANT_LOCK,
   ER_CANT_OPEN_FILE,
   ER_FILE_NOT_FOUND,
   ER_CANT_READ_DIR,
   ER_CANT_SET_WD,
   ER_CHECKREAD,
   ER_DISK_FULL,
   ER_DUP_KEY,
   ER_ERROR_ON_CLOSE,
   ER_ERROR_ON_READ,
   ER_ERROR_ON_RENAME,
   ER_ERROR_ON_WRITE,
   ER_FILE_USED,
   ER_FILSORT_ABORT,
   ER_FORM_NOT_FOUND,
   ER_GET_ERRNO,
   ER_ILLEGAL_HA,
   ER_KEY_NOT_FOUND,
   ER_NOT_FORM_FILE,
   ER_NOT_KEYFILE,
   ER_OLD_KEYFILE,
   ER_OPEN_AS_READONLY,
   ER_OUTOFMEMORY,
   ER_OUT_OF_SORTMEMORY,
   ER_UNEXPECTED_EOF,
   ER_CON_COUNT_ERROR,
   ER_OUT_OF_RESOURCES,
   ER_BAD_HOST_ERROR,
   ER_HANDSHAKE_ERROR,
   ER_DBACCESS_DENIED_ERROR,
   ER_ACCESS_DENIED_ERROR,
   ER_NO_DB_ERROR,
   ER_UNKNOWN_COM_ERROR,
   ER_BAD_NULL_ERROR,
   ER_BAD_DB_ERROR,
   ER_TABLE_EXISTS_ERROR,
   ER_BAD_TABLE_ERROR,
   ER_NON_UNIQ_ERROR,
   ER_SERVER_SHUTDOWN,
   ER_BAD_FIELD_ERROR,
   ER_WRONG_FIELD_WITH_GROUP,
   ER_WRONG_GROUP_FIELD,
   ER_WRONG_SUM_SELECT,
   ER_WRONG_VALUE_COUNT,
   ER_TOO_LONG_IDENT,
   ER_DUP_FIELDNAME,
   ER_DUP_KEYNAME,
   ER_DUP_ENTRY,
   ER_WRONG_FIELD_SPEC,
   ER_PARSE_ERROR,
   ER_EMPTY_QUERY,
   ER_NONUNIQ_TABLE,
   ER_INVALID_DEFAULT,
   ER_MULTIPLE_PRI_KEY,
   ER_TOO_MANY_KEYS,
   ER_TOO_MANY_KEY_PARTS,
   ER_TOO_LONG_KEY,
   ER_KEY_COLUMN_DOES_NOT_EXITS,
   ER_BLOB_USED_AS_KEY,
   ER_TOO_BIG_FIELDLENGTH,
   ER_WRONG_AUTO_KEY,
   ER_READY,
   ER_NORMAL_SHUTDOWN,
   ER_GOT_SIGNAL,
   ER_SHUTDOWN_COMPLETE,
   ER_FORCING_CLOSE,
   ER_IPSOCK_ERROR,
   ER_NO_SUCH_INDEX,
   ER_WRONG_FIELD_TERMINATORS,
   ER_BLOBS_AND_NO_TERMINATED,
   ER_TEXTFILE_NOT_READABLE,
   ER_FILE_EXISTS_ERROR,
   ER_LOAD_INFO,
   ER_ALTER_INFO,
   ER_WRONG_SUB_KEY,
   ER_CANT_REMOVE_ALL_FIELDS,
   ER_CANT_DROP_FIELD_OR_KEY,
   ER_INSERT_INFO,
   ER_INSERT_TABLE_USED,
   ER_NO_SUCH_THREAD,
   ER_KILL_DENIED_ERROR,
   ER_NO_TABLES_USED,
   ER_TOO_BIG_SET,
   ER_NO_UNIQUE_LOGFILE,
   ER_TABLE_NOT_LOCKED_FOR_WRITE,
   ER_TABLE_NOT_LOCKED,
   ER_BLOB_CANT_HAVE_DEFAULT,
   ER_WRONG_DB_NAME,
   ER_WRONG_TABLE_NAME,
   ER_TOO_BIG_SELECT,
   ER_UNKNOWN_ERROR,
   ER_UNKNOWN_PROCEDURE,
   ER_WRONG_PARAMCOUNT_TO_PROCEDURE,
   ER_WRONG_PARAMETERS_TO_PROCEDURE,
   ER_UNKNOWN_TABLE,
   ER_FIELD_SPECIFIED_TWICE,
   ER_INVALID_GROUP_FUNC_USE,
   ER_UNSUPPORTED_EXTENSION,
   ER_TABLE_MUST_HAVE_COLUMNS,
   ER_RECORD_FILE_FULL,
   ER_UNKNOWN_CHARACTER_SET,
   ER_TOO_MANY_TABLES,
   ER_TOO_MANY_FIELDS,
   ER_TOO_BIG_ROWSIZE,
   ER_STACK_OVERRUN,
   ER_WRONG_OUTER_JOIN,
   ER_NULL_COLUMN_IN_INDEX,
   ER_CANT_FIND_UDF,
   ER_CANT_INITIALIZE_UDF,
   ER_UDF_NO_PATHS,
   ER_UDF_EXISTS,
   ER_CANT_OPEN_LIBRARY,
   ER_CANT_FIND_DL_ENTRY,
   ER_FUNCTION_NOT_DEFINED,
   ER_HOST_IS_BLOCKED,
   ER_HOST_NOT_PRIVILEGED,
   ER_PASSWORD_ANONYMOUS_USER,
   ER_PASSWORD_NOT_ALLOWED,
   ER_PASSWORD_NO_MATCH,
   ER_UPDATE_INFO,
   ER_CANT_CREATE_THREAD,
   ER_WRONG_VALUE_COUNT_ON_ROW,
   ER_CANT_REOPEN_TABLE,
   ER_INVALID_USE_OF_NULL,
   ER_REGEXP_ERROR,
   ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
   ER_NONEXISTING_GRANT,
   ER_TABLEACCESS_DENIED_ERROR,
   ER_COLUMNACCESS_DENIED_ERROR,
   ER_ILLEGAL_GRANT_FOR_TABLE,
   ER_GRANT_WRONG_HOST_OR_USER,
   ER_NO_SUCH_TABLE,
   ER_NONEXISTING_TABLE_GRANT,
   ER_NOT_ALLOWED_COMMAND,
   ER_SYNTAX_ERROR,
   ER_DELAYED_CANT_CHANGE_LOCK,
   ER_TOO_MANY_DELAYED_THREADS,
   ER_ABORTING_CONNECTION,
   ER_NET_PACKET_TOO_LARGE,
   ER_NET_READ_ERROR_FROM_PIPE,
   ER_NET_FCNTL_ERROR,
   ER_NET_PACKETS_OUT_OF_ORDER,
   ER_NET_UNCOMPRESS_ERROR,
   ER_NET_READ_ERROR,
   ER_NET_READ_INTERRUPTED,
   ER_NET_ERROR_ON_WRITE,
   ER_NET_WRITE_INTERRUPTED,
   ER_TOO_LONG_STRING,
   ER_TABLE_CANT_HANDLE_BLOB,
   ER_TABLE_CANT_HANDLE_AUTO_INCREMENT,
   ER_DELAYED_INSERT_TABLE_LOCKED,
   ER_WRONG_COLUMN_NAME,
   ER_WRONG_KEY_COLUMN,
   ER_WRONG_MRG_TABLE,
   ER_DUP_UNIQUE,
   ER_BLOB_KEY_WITHOUT_LENGTH,
   ER_PRIMARY_CANT_HAVE_NULL,
   ER_TOO_MANY_ROWS,
   ER_REQUIRES_PRIMARY_KEY,
   ER_NO_RAID_COMPILED,
   ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
   ER_KEY_DOES_NOT_EXITS,
   ER_CHECK_NO_SUCH_TABLE,
   ER_CHECK_NOT_IMPLEMENTED,
   ER_CANT_DO_THIS_DURING_AN_TRANSACTION,
   ER_ERROR_DURING_COMMIT,
   ER_ERROR_DURING_ROLLBACK,
   ER_ERROR_DURING_FLUSH_LOGS,
   ER_ERROR_DURING_CHECKPOINT,
   ER_NEW_ABORTING_CONNECTION,
   ER_DUMP_NOT_IMPLEMENTED,
   ER_FLUSH_MASTER_BINLOG_CLOSED,
   ER_INDEX_REBUILD,
   ER_MASTER,
   ER_MASTER_NET_READ,
   ER_MASTER_NET_WRITE,
   ER_FT_MATCHING_KEY_NOT_FOUND,
   ER_LOCK_OR_ACTIVE_TRANSACTION,
   ER_UNKNOWN_SYSTEM_VARIABLE,
   ER_CRASHED_ON_USAGE,
   ER_CRASHED_ON_REPAIR,
   ER_WARNING_NOT_COMPLETE_ROLLBACK,
   ER_TRANS_CACHE_FULL,
   ER_SLAVE_MUST_STOP,
   ER_SLAVE_NOT_RUNNING,
   ER_BAD_SLAVE,
   ER_MASTER_INFO,
   ER_SLAVE_THREAD,
   ER_TOO_MANY_USER_CONNECTIONS,
   ER_SET_CONSTANTS_ONLY,
   ER_LOCK_WAIT_TIMEOUT,
   ER_LOCK_TABLE_FULL,
   ER_READ_ONLY_TRANSACTION,
   ER_DROP_DB_WITH_READ_LOCK,
   ER_CREATE_DB_WITH_READ_LOCK,
   ER_WRONG_ARGUMENTS,
   ER_NO_PERMISSION_TO_CREATE_USER,
   ER_UNION_TABLES_IN_DIFFERENT_DIR,
   ER_LOCK_DEADLOCK,
   ER_TABLE_CANT_HANDLE_FULLTEXT,
   ER_CANNOT_ADD_FOREIGN,
   ER_NO_REFERENCED_ROW,
   ER_ROW_IS_REFERENCED,
   ER_CONNECT_TO_MASTER,
   ER_QUERY_ON_MASTER,
   ER_ERROR_WHEN_EXECUTING_COMMAND,
   ER_WRONG_USAGE,
   ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
   ER_CANT_UPDATE_WITH_READLOCK,
   ER_MIXING_NOT_ALLOWED,
   ER_DUP_ARGUMENT,
   ER_USER_LIMIT_REACHED,
   ER_SPECIFIC_ACCESS_DENIED_ERROR,
   ER_LOCAL_VARIABLE,
   ER_GLOBAL_VARIABLE,
   ER_NO_DEFAULT,
   ER_WRONG_VALUE_FOR_VAR,
   ER_WRONG_TYPE_FOR_VAR,
   ER_VAR_CANT_BE_READ,
   ER_CANT_USE_OPTION_HERE,
   ER_NOT_SUPPORTED_YET,
   ER_MASTER_FATAL_ERROR_READING_BINLOG,
   ER_SLAVE_IGNORED_TABLE,
   CR_UNKNOWN_ERROR,
   CR_SOCKET_CREATE_ERROR,
   CR_CONNECTION_ERROR,
   CR_CONN_HOST_ERROR,
   CR_IPSOCK_ERROR,
   CR_UNKNOWN_HOST,
   CR_SERVER_GONE_ERROR,
   CR_VERSION_ERROR,
   CR_OUT_OF_MEMORY,
   CR_WRONG_HOST_INFO,
   CR_LOCALHOST_CONNECTION,
   CR_TCP_CONNECTION,
   CR_SERVER_HANDSHAKE_ERR,
   CR_SERVER_LOST,
   CR_COMMANDS_OUT_OF_SYNC,
   CR_NAMEDPIPE_CONNECTION,
   CR_NAMEDPIPEWAIT_ERROR,
   CR_NAMEDPIPEOPEN_ERROR,
   CR_NAMEDPIPESETSTATE_ERROR,
   CR_CANT_READ_CHARSET,
   CR_NET_PACKET_TOO_LARGE,
   CR_EMBEDDED_CONNECTION,
   CR_PROBE_SLAVE_STATUS,
   CR_PROBE_SLAVE_HOSTS,
   CR_PROBE_SLAVE_CONNECT,
   CR_PROBE_MASTER_CONNECT,
   CR_SSL_CONNECTION_ERROR,
   CR_MALFORMED_PACKET
);
\end{Code}

\subsubsection{Sybase Result Codes}

The Result\_Type values available from package APQ.Sybase are as follows;

\begin{Code}
type Result_Type is (
   Execution_Failed, -- ct_results() call failed
   No_Results,       -- Cmd processed, but no results
   Row_Results,      -- Cmd processed, and row results
   Cursor_Results,   -- Cmd processed, and cursor row result
   Info_Results,     -- Cmd processed, no row data, but info
   Compute_Results,  -- Computed results
   Param_Results,    -- Parameter results
   Status_Results    -- Status results
);
\end{Code}

\subsection{Generic APQ.Result\label{Generic APQ.Result}}

To enable generic database processing, APQ version 2.0 adds a new
API function which is declared at the APQ\-.Root\_Query\_Type\index{APQ.Root\_Query\_Type} object
level. This function returns a Natural result:

\begin{Code}
function Result(
   Query : Root_Query_Type;
) return Natural;
\end{Code}

The value returned, represents the Result\_Type'Pos(arg)\index{Result\_Type'Pos}. In generic
database code, you could use this generic function to retrieve the
value. Later it can be turned into the appropriate Result\_Type when
required by doing a conversion. The following example illustrates:

\begin{Example}
with APQ.MySQL.Client, APQ.PostgreSQL.Client;
...
procedure App(Q : Root_Query_Type'Class) is
   R :      Natural;
   PQ_R :   APQ.PostgreSQL.Result_Type;
   My_R :   APQ.MySQL.Result_Type;
begin
   ...
   R := APQ.Result(Q);
   if APQ.Engine_Of(Q) = Engine_MySQL then
      My_R := APQ.MySQL.Result_Type'Val(R);
      ...
   elsif APQ.Engine_Of(Q) = Engine_PostgreSQL then
      PQ_R := APQ.PostgreSQL.Result_Type'Val(R);
      ...
   ...
\end{Example}

The code above demonstrates how generic database code is able to test
for specific database error codes, when required.


\subsection{Generic APQ.Engine\_Of\label{Generic APQ.Engine_Of}}

As seen in the example of \Ref{Generic APQ.Result}, it is
sometimes necessary to determine in portable code, what database
technology is being used. Once this fact is known, the correct, more
specific action can be taken.  For example, the ``LIMIT n''\index{LIMIT} clause can
be added to MySQL\index{MySQL} queries to limit the number of returned rows for
greater efficiency.

The function primitive Engine\_Of\index{Engine\_Of} can be used to determine
the database technology being used:

\begin{Code}
type Database_Type is (
   Engine_PostgreSQL,
   Engine_MySQL,
   Engine_Sybase
);

function Engine_Of(
   Query : Root_Query_Type;
) return Database_Type;
\end{Code}

\subsection{Checked Execution}

For many utility programs \index{utility programs}where error reporting
and recovery have simple requirements, a more compact and convenient
way to execute queries can be applied. With checked execution, the
query is not only executed, but any SQL errors are intercepted and
reported\index{reported} to Standard\_Error\index{Standard\_Error} automatically. This saves the programmer
effort when writing simple utility programs. Once the SQL\_Error\index{SQL\_Error} exception
is intercepted and reported, the exception is re-raised to leave control
in the caller's hands. The important thing here is that the error\index{error}
is caught and reported.

The Execute\_Checked\index{Execute\_Checked} primitive has the following calling signature:

\begin{Code}
procedure Execute_Checked(
   Query :      in out Root_Query_Type;
   Connection : in out Root_Connection_Type'Class;
   Msg :        in     String := ""
);
\end{Code}

When the argument Msg is a non-empty\index{non-empty string} string like ``Dropping table
temp\_tbl'', the error message reported will be of the following
format:

\begin{Example}
*** SQL ERROR: Dropping table temp_tbl
FATAL_ERROR: ERROR: Relation "temp_tbl" does not exist
\end{Example}

The first line just identifies the fact that an SQL error occurred,
and reports the Msg text. The second line first reports Result\_Type'Image
of the error, and then reports the error message text as returned
by Error\_Message\index{Error\_Message}. In this case, the example shows that Result\_Type
Fatal\_Error was returned, and the error message returned from the
database server was ``ERROR: Relation ``temp\_tbl'' does not
exist''.

When the null string\index{null string} (or the default value for
the parameter) is given to argument Msg, then the SQL query is dumped\index{dumped}
out to Standard\_Error\index{Standard\_Error} instead. This is often useful for debugging\index{debugging}
purposes.

Changing the example found on page \pageref{Birthday Timezone Example}
slightly, we can apply the Execute\_Checked primitive in the place
of the Execute\index{Execute} call.

\begin{Example}
declare
   type Cust_No_Type is new Integer range 1000..100_000;
   type Birthday_Type is new APQ_Timestamp;

   procedure Append is new Append_Integer(Cust_No_Type);

   procedure Encode is new
      Encode_Integer(Cust_No_Type,Boolean);
   procedure Encode is new
      Encode_Timezone(Birthday_Type,APQ_Timezone,Boolean);

   C :            Connection_Type;
   Q :            Query_Type;
   Cust_No :      Cust_No_Type;     -- NOT NULL
   Birthday :     Birthday_Type;
   Birthday_TZ :  APQ_Timezone;     -- Timezone
   Birthday_Ind : Boolean;          -- Indicator
begin
   ...
   Prepare(Q,"INSERT INTO BIRTHDAY (CUST_NO,BIRTHDAY)");
   Append(Q, "VALUES (");
   Append(Q,Cust_No,",");
   Encode(Q,Birthday,Birthday_TZ,Birthday_Ind,")" & New_Line);
   Execute_Checked(Q,C);
\end{Example}


\subsection{Suppressing Checked Exceptions}

For utility work, it is sometimes convenient to have Execute\_Checked
report errors, but not raise SQL\_Error\index{SQL\_Error}. This is useful when you don't
care about the outcome but want the error to be reported when detected.
The raising or not raising of SQL\_Error can be controlled for the
Execute\_Checked\index{Execute\_Checked} primitive by calling
Raise\_Exceptions\index{Raise\_Exceptions}. It has the following calling
requirements:

\begin{Code}
procedure Raise_Exceptions(
   Query :    in out Query_Type;
   Raise_On : in     Boolean := True
);
\end{Code}

The following example shows how exceptions can be suppressed:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   ...
   Raise_Exceptions(Q,False); -- Suppress SQL_Error exception
   Execute_Checked(Q,C);      -- Report errors only
   Raise_Exceptions(Q,True);  -- Re-enable SQL_Error exceptions
\end{Example}

\subsection{Suppressing Checked Reports}

Occaisionally, it is useful to control whether or not reporting is
performed in the event of an SQL\_Error\index{SQL\_Error}. The reporting of errors can
be controlled by the Report\_Errors\index{Report\_Errors} primitive procedure:

\begin{Code}
procedure Report_Errors(
   Query :     in out Query_Type;
   Report_On : in     Boolean := True
);
\end{Code}

The default behaviour of a Query\_Type is to report errors and raise
SQL\_Error when Execute\_Checked experiences an SQL\_Error exception.
The reporting behaviour can be disabled\index{disable reporting} as follows:

\begin{Example}
declare
   C :   Connection_Type;
   Q :   Query_Type;
begin
   ...
   Report_Errors(Q,False); -- Suppress error reporting
   Execute_Checked(Q,C);
\end{Example}

Normally application programmers would not use Execute\_Checked with
error reporting disabled. However, it may be useful as a temporary
measure to cause error reporting while debugging\index{debugging} a program. Once the
debugging has been completed, a global Boolean\index{Boolean} value could be set
to false to prevent these errors from being reported.


\section{Transaction Operations}

Database transaction\index{Transaction} operations consist of:

\begin{itemize}
   \item BEGIN WORK\index{BEGIN WORK}
   \item COMMIT WORK\index{COMMIT WORK}
   \item ROLLBACK WORK\index{ROLLBACK WORK}
\end{itemize}

It is possible to build your own queries to accomplish these operations
but the programmer is encourage to use the primitive operations below
instead. One reason for using the APQ provided functions is to make
your application portable to different databases. There are slight
variations on the SQL syntax\index{syntax, SQL} required for these operations. It may
also be possible in the future to query the state of the transaction.%
\footnote{It is likely that a function like an In\_Transaction function will
be added in the future.%
}

The three primitives are named according to function \label{Begin, Commit and Rollback Work functions}
and are listed in Table~\ref{t:txp}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Primitive Name    &  SQL Function\\
         \hline 
         Begin\_Work       &  BEGIN WORK\\
         Commit\_Work      &  COMMIT WORK\\
         Rollback\_Work    &  ROLLBACK WORK\\
      \end{tabular}
   \end{center}
   \caption{Transaction Primitives}\label{t:txp}
\end{table}

The specifications of these primitives are listed below:

\begin{Code}
procedure Begin_Work(
   Query :      in out Query_Type;
   Connection : in out Connection_Type'Class
);
\end{Code}

\begin{Code}
procedure Commit_Work(
   Query :      in out Query_Type;
   Connection : in out Connection_Type'Class
);
\end{Code}

\begin{Code}
procedure Rollback_Work(
   Query :      in out Query_Type;
   Connection : in out Connection_Type'Class
);
\end{Code}

These primitives will raise the exceptions listed in Table~\ref{t:tranpx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Not\_Connected    &  There is no connection\\
         Abort\_State      &  A ROLLBACK is required\\
         SQL\_Error        &  This should not normally occur\\
      \end{tabular}
   \end{center}
   \caption{Transaction Primitives Exceptions}\label{t:tranpx}
\end{table}

The following simple example demonstrates the use of these primitives:

\begin{Example}
declare
   C :   Connection_Type;
   Q :   Query_Type;
begin
   ...
   Begin_Work(Q,C);
   ...
   Commit_Work(Q,C);
\end{Example}

\begin{description}
   \item [Note:] There is an implicit\index{implicit Clear} Clear operation before and after the
      execution of these operations for the Query\_Type\index{Query\_Type} object. The original
      fetch mode of the object is preserved after the call. 
\end{description}

\subsection{The PostgreSQL Abort\_State}

The Abort\_State\index{Abort\_State} is unique to the PostgreSQL\index{PostgreSQL} database. Other databases
will tolerate failed steps within a transaction, but PostgreSQL will not.
The Abort\_State \label{Abort_State exception} exception indicates that the database
was in a transaction%
\footnote{A {}``BEGIN WORK'' statement was executed.%
} when a processing error occurred (like a duplicate key on insert
error). Once an error\index{error in transaction} is encountered within a PostgreSQL transaction,
the only course to recovery is by executing a ROLLBACK\index{ROLLBACK} WORK statement
(this is done by the Rollback\_Work\index{Rollback\_Work} call shown above). If duplicate\index{duplicate inserts}
inserts\index{inserts} may occur, you must test for them in advance of the INSERT\index{INSERT},
to avoid placing the transaction into the ``abort state''\index{abort state}. Note
that this PostgreSQL\index{PostgreSQL} behavior is different from other database vendor
offerings.

The ``abort state''\index{abort state} itself is maintained in the Connection\_Type\index{Connection\_Type}
object, causing the state\index{state} to influence all Query\_Type objects using
the same connection. To clear the status\index{status}, you must perform a Rollback\_Work\index{Rollback\_Work}
call on any Query\_Type object, using the affected Connection\_Type
object where the status is saved.

The Query\_Type object is used to form the SQL\index{SQL} statement and to hold
the result\index{result status} status. In application programming, you may want to dedicate
one Query\_Type object for each transaction in progress.%
\footnote{This will be important later, if you want to query whether or not
you are in a transaction.%
}

\section{Fetch Operations}

Some database operations, particularly SELECT\index{SELECT}, return
results. There are two fetch\index{fetch} related primitives: 

\begin{enumerate}
   \item Sequential\index{Sequential access} row fetch\index{fetch, sequential}
   \item Random\index{Random access} access row fetch\index{fetch, random}
\end{enumerate}

The sequential fetch permits serial\index{serial access} access of the resulting rows (tuples\index{tuples}).
Random access fetching permits rapid\index{rapid access} access to particular row results.

\subsection{Fetch Limitations\label{Fetch Limitations}}

Some databases like PostgreSQL\index{PostgreSQL} have \emph{no} limitations\index{limitations} on how row
data is fetched. The fetch\index{fetch} may be sequential or random, as the application
requires. Some other databases however, require some planning by the
application programmer in this area. This distinction, and the API
to control this problem is new to APQ 2.0 and later, for database
engines\index{engines} that require it.

For example, MySQL\index{MySQL} retrieves row data into the client program's address\index{address space}
space in one of two ways:

\begin{itemize}
   \item one row at a time, but all rows must be fetched
   \item all rows are loaded into client memory\index{client memory}, for random access by the application
\end{itemize}

For large result sets\index{large result sets}, fetching one row%
\footnote{This is done using the mysql\_use\_result() function.%
} at a time is very practical. However, MySQL\index{MySQL} requires that the program
fetch \emph{all} row data. If the result set\index{result set} is large, and only an
initial number of rows are required, this can be a serious performance
issue. This is a greater problem if the application would like to
cancel\index{cancel} the operation.

When random access%
\footnote{This is done using the mysql\_store\_result() function.%
} of rows is required, MySQL\index{MySQL} requires that all row data be retrieved
and stored into the client program (behind the scenes). Fetching all
of this data into client memory\index{client memory} can be impractical for size\index{size} reasons
for large numbers of rows (there is an SQL work-around\index{SQL work-around} for this).

The default APQ query mode varies according to database as listed in Table~\ref{t:fchmd}.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Database       &  Default Mode      &  Comments\\
         \hline 
         PostgreSQL     &  Random\_Fetch     &  Random or Sequential supported\\
         MySQL          &  Random\_Fetch     &  Watch \# of rows returned\\
         Sybase         &  Sequential\_Fetch &  Random\_Fetch not supported\\
      \end{tabular}
   \end{center}
   \caption{APQ Fetch Modes}\label{t:fchmd}
\end{table}

From the table, you can see that PostgreSQL\index{PostgreSQL} has no difficulty in either
mode. MySQL\index{MySQL} supports both modes, but the programmer must be careful
about the result set size returned if Random\_Fetch mode is in use.
Finally, Sybase\index{Sybase} support does not support Random\_Fetch\index{Random\_Fetch} mode (Sybase
\emph{can} fetch rows randomly with a cursor, but only sequential
cursors\index{cursors} are currently supported by APQ).

All database engines\index{engines} support sequential\index{sequential} access \- even in random\index{random}
access mode. Even if you are using the default or configured Random\_Fetch\index{Random\_Fetch}
mode, APQ will return rows sequentially unless a specific row is requested.
If the application programmer is using a database that is limited
in this way (MySQL), and has determined that fetching all results
into client memory is not suitable, then the mode of the Query\_Type\index{Query\_Type}
needs to be changed by the program to use sequential access instead.
See the next few sections on how to control the fetch query mode.

If you are only planning to use PostgreSQL\index{PostgreSQL}, you can effectively ignore
the sections about Fetch Query modes. However, if you plan to write
your application in a database generic sort of way, or support MySQL\index{MySQL}
and/or Sybase\index{Sybase} code, then you need to plan for the fetch query modes
in your code.


\subsection{Fetch Query Modes\label{Fetch Query Modes}}

Due to the performance limitations of different database engines,
APQ provides the application programmer a way to control the fetch\index{fetch}
mode used. Package APQ defines the Fetch\_Mode\_Type\index{Fetch\_Mode\_Type} for this purpose:

\begin{Code}
type Fetch_Mode_Type is (
   Sequential_Fetch,    -- All databases
   Random_Fetch,        -- PostgreSQL, MySQL, not Sybase yet
   Cursor_For_Update,   -- Sybase
   Cursor_For_Read_Only -- Sybase
);
\end{Code}

The last two modes related to cursors will be discussed separately.

The application programmer can query the fetch mode that is in effect.
The Fetch\-\_Mode\index{Fetch\_Mode} function primitive returns the current state
of the Query\-\_Type object:

\begin{Code}
function Fetch_Mode(
   Q : Query_Type
) return Fetch_Mode_Type;
\end{Code}

To change the current mode in effect, use the function primitive Set\_Fetch\_Mode\index{Set\_Fetch\_Mode}:

\begin{Code}
procedure Set_Fetch_Mode(
   Q :    in out Query_Type;
   Mode : in     Fetch_Mode_Type
);
\end{Code}

The application should only change the query mode \emph{prior} to
the \emph{execution} of the query. When Execute\index{Execute} or Execute\_Checked\index{Execute\_Checked}
are called, APQ must commit to the fetch method being used. For this
reason, set the query mode when the Query\_Type is initially declared,
after a call to Reset\index{Reset} or Prepare\index{Prepare}. The mode must
be established prior to executing the query.

Table \ref{t:sfmdx} lists the exceptions that may be raised by Set\_Fetch\_Mode.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Failed            &  Query results exist - cannot change mode\\
      \end{tabular}
   \end{center}
   \caption{Set\_Fetch\_Mode Exceptions}\label{t:sfmdx}
\end{table}


\subsection{Sequential Fetch}

The \emph{Query\_Type} object is always positioned at the first row\index{first row}
after the query has been executed. Sequential fetches\index{fetches} can then be
performed to retrieve the first row, through to the last resulting
row. The sequential \textbf{Fetch} primitive has the following calling
arguments:

\begin{Code}
procedure Fetch(
   Q : in out Query_Type
);
\end{Code}

A sequential fetch can always be made, whether the query object is
in sequential or random mode. However, be aware that some databases
(MySQL\index{MySQL}) require that all results be fetched when in Sequential\_Fetch\index{Sequential\_Fetch}
mode. The APQ default varies according to the database software being
used. See \Ref{Fetch Query Modes} to establish a mode explicitly.

Table \ref{t:fchx} lists the exceptions that can be raised by Fetch.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no command executed\\
         No\_Tuple         &  There were no result rows returned\\
         Not\_Supported    &  The fetch mode in effect is not supported\\
      \end{tabular}
   \end{center}
   \caption{Fetch Exceptions}\label{t:fchx}
\end{table}

The No\_Result\index{No\_Result} exception is raised when the Query\_Type
object is in the wrong\index{wrong state} state. For example, if the Query\_Type
object is cleared, and/or an SQL query is built but not Executed,
then a No\_Result exception will be raised.

The No\_Tuple\index{No\_Tuple} exception is raised to indicate that no rows
were available, or that there are no more rows remaining. In Sequential\_Fetch
mode, this indicates that there are no more rows to be returned. In
Random\_Fetch\index{Random\_Fetch} mode, this indicates that no rows were returned.%
\footnote{Note that requesting a non existant row in random fetch mode will
not raise an exception until a value is extracted.%
}

The Not\_Supported\index{Not\_Supported} exception is also possible with APQ 2.2
and later. This exception is raised to indicate that the database
software being used does not support the current Fetch\_Mode\index{Fetch\_Mode} that
is in effect.

The following code shows a normal sequential fetch loop:\label{Sequential Fetch Example}

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when APQ.No_Tuple =>
            exit;
      end;
      ...
   end loop;
   Clear(Q); -- Release any query results
\end{Example}

Clearing the query (or allowing it to fall out of scope) is recommended.
This releases\index{releases} resources\index{resources} that are
holding any prior query results.


\subsection{Random Fetch}

The random fetch\index{fetch} operation requires the use of the Tuple\_Index\_Type\index{Tuple\_Index\_Type}
defined in the package APQ:

\begin{Code}
type Tuple_Index_Type is mod 2 ** 64;
First_Tuple_Index : constant Tuple_Index_Type := 1;
\end{Code}

The random Fetch primitive has the following calling arguments:

\begin{Code}
procedure Fetch(
   Q :  in out Query_Type;
   TX : in     Tuple_Index_Type
);
\end{Code}

Table \ref{t:rfchx} lists the possible exceptions for
a random Fetch call.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no command executed\\
         No\_Tuple         &  There were no result rows returned\\
         Not\_Supported    &  Random access is not supported\\
      \end{tabular}
   \end{center}
   \caption{Random Fetch Exceptions}\label{t:rfchx}
\end{table}

A random fetch example is provided below:\label{Random Fetch Example}

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);

   for TX in 1..Tuple_Index_Type(Tuples(Q)) loop
      Fetch(Q,TX);
      ...
   end loop;
   Clear(Q);
\end{Example}

The function Tuples(Q)\index{Tuples} that was used in the \emph{for} loop, returns
the number of result rows for the query.%
\footnote{Which can be zero.%
} A slight modification of this loop could permit processing the rows
in reverse order.


\subsubsection{Notes:}

\begin{enumerate}
   \item If the tuple\index{tuple} index \emph{TX} provided to Fetch is out
         of range for the result set, no exception will be raised. An exception
         \emph{will} be raised however, when the application attempts to fetch
         any value from that out of range row.
   \item Any subsequent sequential fetch operation will fetch the row following
         the last randomly accessed row.
\end{enumerate}

\subsection{Function End\_of\_Query\label{End_of_Query}}

To facilitate sequential
fetch operations, the End\_of\_Query primitive function was provided in
early versions of APQ. This API remains, but is considered
\emph{obsolete} and should be avoided. MySQL\index{MySQL} users should not use it at
all, due to the bug\index{bug} present in the MySQL client library. See the note
that follows the tables.

\begin{quote}
Note: This function is depreciated. Catch the No\_Tuple exception
instead for greater database portability.
\end{quote}

The calling requirements are summarized in the following specification:

\begin{Code}
function End_of_Query(
   Q : Query_Type
) return Boolean;
\end{Code}

Table \ref{t:eoqx} lists the exceptions for this function.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no command executed\\
      \end{tabular}
   \end{center}
   \caption{End\_of\_Query Exceptions}\label{t:eoqx}
\end{table}

The End\_of\_Query\index{End\_of\_Query} function returns a Boolean\index{Boolean} result:

\begin{description}
   \item [False] there is at least one more result row available (not at end)
   \item [True] there are no more rows\index{rows} available (at end)
\end{description}

\begin{quote}
MySQL Note: 
The MySQL\index{MySQL} implementation of End\_Of\_Query is not a good
one. End\_Of\_Query\index{End\_of\_Query} should \emph{not} be used. The problem is located
in the MySQL C client library that comes with MySQL. The C mysql\_eof()\index{mysql\_eof()}
function returns false after reading the last row. It is only by fetching
one more row and discovering that there are no more rows, that mysql\_eof()
then starts to return true. In other words, it returns true, when
the end has already been reached. Since there is no way to work around
this problem in MySQL, a developer should avoid using End\_Of\_Query
completely.
\end{quote}

Catch the exception No\_Tuple\index{No\_Tuple} instead, when fetching rows.


\subsection{Function Tuple}

The Tuple\index{Tuple} function primitive is an information function that
returns the current tuple number\index{tuple number} that was last
fetched. If there has been no fetch yet, the No\_Tuple\index{No\_Tuple} exception
is raised. The calling signature is as follows:

\begin{Code}
function Tuple(
   Q : Query_Type
) return Tuple_Index_Type;
\end{Code}

Tuple can raise the exceptions listed in Table~\ref{t:tupx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Tuple         &  There was no fetch performed yet\\
      \end{tabular}
   \end{center}
   \caption{Tuple Exceptions}\label{t:tupx}
\end{table}

The following example shows the function being used:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
   X : Tuple_Index_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when APQ.No_Tuple =>
            exit;
      end;
      TX := Tuple(Q); -- Get Row #
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{Rewind Procedure}

Sometimes it is desireable to reprocess results sequentially. This
is easily accomplished with the Rewind\index{Rewind} primitive. This
primitive merely alters the state of the Query\_Type object such that
the next fetch\index{fetch} operation will start with the first row. This only
works when the fetch mode is Random\_Fetch\index{Random\_Fetch}.

The calling requirements are listed as follows:

\begin{Code}
procedure Rewind(
   Q : in out Query_Type
);
\end{Code}

Table \ref{t:rwx} lists the possible exceptions for Rewind.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         SQL\_Error        &  The Query\_Type is not in Random\_Fetch mode\\
      \end{tabular}
   \end{center}
   \caption{Rewind Exceptions}\label{t:rwx}
\end{table}

The following example shows the Rewind procedure being used:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when APQ.No_Tuple =>
            exit;
      end;
      ...
   end loop;

   -- REPROCESS THE QUERY RESULTS :

   Rewind(Q);

   loop
      begin
         Fetch(Q);
      exception
         when APQ.No_Tuple =>
            exit;
      end;
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{Tuples Function}

You have already seen this function used in the example on page
\pageref{Random Fetch Example}. This information function returns the
number of result rows that are available. It should only be called after
the \emph{Query\_Type} has been executed however. Otherwise the
No\_Result exception will be raised by Tuples\index{Tuples}.

The calling requirement for this function is summarized as follows:

\begin{Code}
function Tuples(
   Q : Query_Type
) return Tuple_Count_Type;
\end{Code}

Tuples can raise the exceptions listed in Table~\ref{t:tupsx}. For an
example of use, see \Ref{Random Fetch Example}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed yet\\
      \end{tabular}
   \end{center}
   \caption{Tuples Exceptions}\label{t:tupsx}
\end{table}

\subsection{Using Cursors}

For databases supporting cursor\index{cursor} operations in their client\index{client libraries} libraries
(Sybase), APQ will automatically generate cursor names for each Query\_Type
object. The function Cursor\_Name\index{Cursor\_Name} will retrieve this for you (see
\Ref{Cursor_Name}).

To perform cursor operations, there are the following general steps
to follow:

\begin{enumerate}
   \item Set the cursor mode of the Query\_Type object.
   \item Prepare the SQL query to fetch rows.
   \item Execute the SQL query.
   \item Fetch a row.
   \item Prepare the inner SQL query using ``WHERE CURRENT OF''\index{WHERE CURRENT OF}
   \item Execute the inner query
   \item Repeat steps 4-6 as required
\end{enumerate}

Describing cursor operation in APQ is probably best done with a concrete
example. Assume a simple SALARIES table like the one below:

\begin{SQL}
CREATE TABLE SALARIES (
   EMPNO    INT NOT NULL PRIMARY KEY,
   SALARY   REAL NOT NULL
);
\end{SQL}

Our example, will assume the following values in the table:

\begin{SQL}
select * from salaries
go
empno       salary
----------- --------------------
          2         56000.000000
          3         82800.000000
          4         82500.000000
          5         43600.000000

4 rows affected
1>
\end{SQL}

Our application is tasked with the job of rewarding all employees
with salaries greater than or equal to \$50,000 with an increase of
5\% (life is often unfair). It is possible to construct an SQL\index{SQL} statement
to do this without using cursors but we're going to build the shell
of a program that will be required to get approval from the user (using
a GUI\index{GUI} etc.) Getting user approval is not possible in SQL, so we need
to code a fetch loop and an inner query to do the update if the approval
is granted. This is one example of how a cursor can be useful.

The following is a Sybase\index{Sybase} APQ program listing for the
update:\label{Cursor Example Program}

\begin{Example}
with Ada.Text _IO;
with APQ.Sybase.Client;
use APQ, APQ.Sybase.Client, Ada.Text_IO;

procedure Salaries is
   function Value is new Integer_Value(Integer);
   function Value is new Float_Value(APQ_Double);
   procedure Append is new Append_Float(APQ_Double);

   C :      Connection_Type;
   Q :      Query_Type;
   Q2 :     Query_Type;
   Empno :  Integer;
   Salary : APQ_Double;
begin
   Set_Instance(C,"SYBIL");
   Set_DB_Name(C,"wwg");
   Set_User_Password(C,"wwg","somepw");
   Connect(C);

   Begin_Work(Q,C);
   Set_Fetch_Mode(Q,Cursor_For_Update);

   Prepare(Q,    "SELECT EMPNO,SALARY");
   Append_Line(Q,"FROM SALARIES");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;

      Empno  := Value(Q,1);
      Salary := Value(Q,2);
      Put_Line("Empno=" & Empno'Img & " Salary=" 
         & Salary'Img);
      if Salary >= 50_000.0 then
         Salary := Salary * 1.05; -- 5% raise

         Prepare(Q2,    "UPDATE SALARIES");
         Append(Q2,     "SET SALARY = ");
         Append(Q2,Salary,Line_Feed);
         Append_Line(Q2,"WHERE CURRENT OF " & Cursor_Name(Q));
         Execute(Q2,C);
         Clear(Q2);
      end if;
   end loop;
   Clear(Q);

   Commit_Work(Q,C);
   Disconnect(C);
end Salaries;
\end{Example}

The fetch mode of query object Q is set to Cursor\_For\_Update\index{Cursor\_For\_Update}. This is
critical for the cursor\index{cursor} operation to work (you can also use
Cursor\_For\_Read\_Only for non-update operations). The outer query\index{outer query} is
formed, which is then executed. When the program decides it wants to
update a particular row (here we pretend the user has approved it from
the terminal), we prepare and execute the inner query\index{inner query} Q2. The special
WHERE clause ``WHERE CURRENT OF''\index{WHERE CURRENT OF} is used, naming the cursor being
used from the outer query object Q. The function Cursor\_Name(Q)\index{Cursor\_Name}
supplies the cursor name for it. Once the inner query is processed, more
outer query rows can be fetched\index{fetched} and processed in like manner.

Note that the inner query can also include DELETE\index{DELETE} ... WHERE CURRENT
OF\index{WHERE CURRENT OF} operations. Using a cursor\index{cursor} guarantees that when you go to delete
the row, that some other external process hasn't deleted it before
you have (this avoids experiencing an error). Similarly for updates\index{updates},
if the correct isolation\index{isolation level} level is used, you can be sure that the values
in the row have not changed by the time you perform the inner query.

\section{Column Information Functions}

After a query has been executed, which returns a set of rows, it is
sometimes necessary to obtain information\index{information, column} about the columns. Many
of the functions make use of the following data type: 

\begin{Code}

	type Column_Index_Type is new Postive;

\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Function Name           &  Purpose\\
         \hline   
         Columns                 &  Return the \# of columns in each row\\
         Column\_Name            &  Return the column name for an index value\\
         Column\_Index           &  Return the index for a column name\\
         Column\_Type            &  Return type information for the column\\
         Is\_Null                &  Test if a column is null\\
      \end{tabular}
   \end{center}
   \caption{Column Information Functions}\label{t:cif}
\end{table}

Table \ref{t:cif}
lists four column information functions that are available to the
application programmer.
All of these functions will raise the exception No\_Result\index{No\_Result}
if an execute has not been performed successfully on the Query\_Type
object.

Note that the case of the column name returned will match the SQL
case policy for the connection. If the policy is Upper\_Case\index{Upper\_Case}, then
column names are returned in uppercase. Other possibilities follow
the established case policy\index{case policy}.


\subsection{Function Columns}

The Columns primitive function returns the number of columns\index{columns}
available in each row of the result set. The calling arguments are
summarized as follows:

\begin{Code}
function Columns(
   Q : Query_Type
) return Natural;
\end{Code}

The Columns\index{Columns} function may raise the exceptions found in
Table~\ref{t:cex}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
      \end{tabular}
   \end{center}
   \caption{Columns Exceptions}\label{t:cex}
\end{table}

The following example shows the function at work:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when APQ.No_Tuple =>
            exit;
      end;

      for CX in 1..Column_Index_Type(Columns(Q)) loop
         ...process each column...
      end loop;
   end loop;
   Clear(Q);
\end{Example}

\subsection{Function Column\_Name}

The primitive Column\_Name\index{Column\_Name} returns the name of the column for a particular
column index\index{column index} value. The calling requirements
are summarized in the following table:

\begin{Code}
function Column_Name(
   Query : in Query_Type;
   Index : in Column_Index_Type
) return String;
\end{Code}

The Column\_Name function may raise the exceptions listed in Table~\ref{t:cnx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  Bad Column\_Index\_Type value\\
      \end{tabular}
   \end{center}
   \caption{Column\_Name Exceptions}\label{t:cnx}
\end{table}

Note that the case of the column name returned will match the SQL
case policy for the connection. If the policy is Upper\_Case\index{Upper\_Case}, then
column names are returned in uppercase. Other possibilities follow
the established case policy\index{case policy}.

The following example shows the function in use:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q, "SELECT CUST_NO,CUST_NAME");
   Append(Q,  "FROM CUSTOMER");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;

      for CX in 1..Column_Index_Type(Columns(Q)) loop
         Put_Line("Column Name: " & Column_Name(Q,CX));
      end loop;
   end loop;
   Clear(Q);
\end{Example}

\subsection{Function Column\_Index}

If you have a column name, but want to know the column index value,
then the Column\_Index\index{Column\_Index} primitive function can be used. It's calling
requirements are as follows:

\begin{Code}
function Column_Index(
   Query : in Query_Type;
   Name :  in String
) return Column_Index_Type;
\end{Code}

The function may raise any of the exceptions listed in Table~\ref{t:cidxx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  Unknown column name\\
      \end{tabular}
   \end{center}
   \caption{Column\_Index Exceptions}\label{t:cidxx}
\end{table}

The following rather contrived example shows the Column\_Index function
used in the pragma\index{pragma assert} assert statement:

\begin{NumberedExample}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM~CUSTOMER");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;

      for CX in 1..Column_Index_Type(Columns(Q)) loop
         declare
            Col_Name : String := Column_Name(Q,CX);
         begin
            Put_Line("Column Name: " & Col_Name);
            pragma assert(CX = Column_Index(Col_Name));\label{Ex:pragma}
         end;
      end loop;
   end loop;
   Clear(Q);
\end{NumberedExample}

The pragma statement in line~\ref{Ex:pragma} is not necessary, but 
was included in this example to show how the Column\_Index and the
Column\_Name are related.

\subsection{Function Column\_Type}

\index{Column\_Type}The column type information varies according to the database product
being used. The following subsections are specific to the APQ supported
database products.

\subsubsection{PostgreSQL Type Information}

The Column\_Type\index{Column\_Type} primitive is the beginning of type information for
the column. This function returns the Row\_ID\_Type\index{Row\_ID\_Type}
value that describes the type in the pg\_type\index{pg\_type} PostgreSQL\index{PostgreSQL} table\index{table}. See
the PostgreSQL database documentation for more details.

The Column\_Type calling signature is as follows:

\begin{Code}
function Column_Type(
   Q :  in Query_Type;
   CX : in Column_Index_Type
) return Row_ID_Type;
\end{Code}

Table \ref{t:ctypx} lists the exceptions that
may be raised by Column\_Type.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  Unknown column name\\
      \end{tabular}
   \end{center}
   \caption{Column\_Type Exceptions}\label{t:ctypx}
\end{table}

\subsubsection{MySQL Type Information}

The field\index{field types} types supported by MySQL\index{MySQL} are defined by APQ\-.MySQL\-.Field\_Type.
The programmer may use the Query\_Type primitive APQ\-.MySQL\-.Client\-.Column\_Type
to determine the column's type:

\begin{Code}
function Column_Type(
   Q :  in Query_Type;
   CX : in Column_Index_Type
) return Field_Type;
\end{Code}

At the writing of this manual, the values in Table~\ref{t:mysqlftyp}
are supported MySQL field (column) type names.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Field\_Type                &  MySQL Datatype\\
         \hline 
         FIELD\_TYPE\_DECIMAL       &  DECIMAL\\
         FIELD\_TYPE\_TINY          &  TINYINT | BOOLEAN\\
         FIELD\_TYPE\_SHORT         &  SMALLINT\\
         FIELD\_TYPE\_LONG          &  INTEGER\\
         FIELD\_TYPE\_FLOAT         &  FLOAT\\
         FIELD\_TYPE\_DOUBLE        &  DOUBLE\\
         FIELD\_TYPE\_NULL          &  BOOLEAN\\
         FIELD\_TYPE\_TIMESTAMP     &  TIMESTAMP\\
         FIELD\_TYPE\_LONGLONG      &  BIGINT\\
         FIELD\_TYPE\_INT24         &  MEDIUMINT\\
         FIELD\_TYPE\_DATE          &  DATE\\
         FIELD\_TYPE\_TIME          &  TIME\\
         FIELD\_TYPE\_DATETIME      &  DATETIME\\
         FIELD\_TYPE\_YEAR          &  YEAR\\
         FIELD\_TYPE\_NEWDATE       &  ?\\
         FIELD\_TYPE\_ENUM          &  ENUM\\
         FIELD\_TYPE\_SET           &  SET\\
         FIELD\_TYPE\_TINY\_BLOB    &  TINYTEXT | TINYBLOB\\
         FIELD\_TYPE\_MEDIUM\_BLOB  &  MEDIUMTEXT | MEDIUMBLOB\\
         FIELD\_TYPE\_LONG\_BLOB    &  LONGTEXT | LONGBLOB\\
         FIELD\_TYPE\_BLOB          &  TEXT | BLOB\\
         FIELD\_TYPE\_VAR\_STRING   &  VARCHAR(N)\\
         FIELD\_TYPE\_STRING        &  CHAR(N)\\
      \end{tabular}
   \end{center}
   \caption{MySQL Field Types}\label{t:mysqlftyp}
\end{table}

APQ does not yet fully support all of MySQL data types.


\subsection*{Sybase Type Information}

Sybase\index{Sybase} also provides type information:

\begin{Code}
function Column_Type(
   Q :  in Query_Type;
   CX : in Column_Index_Type
) return Field_Type;
\end{Code}

Sybase is capable of returning types listed in the Column\_Type column
of Table~\ref{t:sycoltyp}.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Column\_Type               &  Sybase Database Type &  APQ Support\\
         \hline 
         Type\_CHAR                 &  CHAR/VARCHAR         &  Yes\\
         Type\_BINARY               &  BINARY/VARBINARY     &  No\\
         Type\_LONGCHAR             &  \emph{None}          &  No\\
         Type\_LONGBINARY           &  \emph{None}          &  No\\
         Type\_TEXT                 &  TEXT                 &  Yes\\
         Type\_IMAGE                &  IMAGE                &  No\\
         Type\_TINYINT              &  TINYINT              &  Yes\\
         Type\_SMALLINT             &  SMALLINT             &  Yes\\
         Type\_INT                  &  INT/INTEGER          &  Yes\\
         Type\_REAL                 &  REAL                 &  Yes\\
         Type\_FLOAT                &  FLOAT                &  Yes\\
         Type\_BIT                  &  BIT                  &  Yes\\
         Type\_DATETIME             &  DATETIME             &  Yes\\
         Type\_DATETIME4            &  SMALLDATETIME        &  Yes\\
         Type\_MONEY                &  MONEY                &  Yes\\
         Type\_MONEY4               &  SMALLMONEY           &  Yes\\
         Type\_NUMERIC              &  NUMERIC              &  Yes\\
         Type\_DECIMAL              &  DECIMAL              &  Yes\\
         Type\_VARCHAR              &  VARCHAR              &  Yes\\
         Type\_VARBINARY            &  VARBINARY            &  No\\
         Type\_LONG                 &  LONG                 &  Yes\\
         Type\_SENSITIVITY          &  \emph{None}          &  No\\
         Type\_BOUNDARY             &  BOUNDARY             &  No\\
         Type\_VOID                 &  \emph{None}          &  No\\
         Type\_USHORT               &  USHORT               &  Yes\\
         Type\_UNICHAR              &  UNICHAR/UNIVARCHAR   &  No\\
         Type\_BLOB                 &  BLOB                 &  No\\
         Type\_DATE                 &  DATE                 &  Yes\\
      \end{tabular}
   \end{center}
   \caption{Sybase Column Types}\label{t:sycoltyp}
\end{table}


\subsection{Is\_Null Function}

If a column is capable of returning a NULL\index{NULL} value, it
becomes necessary to test for this. The Is\_Null\index{Is\_Null} function calling
specification is as follows:

\begin{Code}
function Is_Null(
   Q :  in Query_Type;
   CX : in Column_Index_Type
) return Boolean;
\end{Code}

The Is\_Null function may raise the exceptions listed in Table~\ref{t:isnullx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  Unknown column name\\
      \end{tabular}
   \end{center}
   \caption{Is\_Null Exceptions}\label{t:isnullx}
\end{table}

The following example shows how to test if the CUST\_NAME column is
null\index{null} or not:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,BIRTH_DATE");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);

   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...

      if Is_Null(Q,2) then
         -- CUST_NAME value is null
      end if;
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{Column\_Is\_Null Generic Function}

If you need to test for null\index{null} using strongly typed
indicators\index{indicators}, you may want to instantiate the
Column\_Is\_Null\index{Column\_Is\_Null} generic function. The generic parameters are:

\begin{Code}
generic
   type Ind_Type is new Boolean;
function Column_Is_Null(
   Q :  in Query_Type'Class;
   CX : in Column_Index_Type
) return Ind_Type;
\end{Code}

Table~\ref{t:isnullx} lists exceptions that also apply to the Column\_Is\_Null function.

%\begin{tabular}{ll}
%Exception Name    &  Reason\\
%\hline 
%No\_Result        &  There was no execute performed\\
%No\_Column        &  No column at index\\
%\end{tabular}

The following example illustrates its use:

\begin{Example}
declare
   type Cust_Name_Ind_Type is new Boolean;
   function Is_Null
       is new Column_Is_Null(Cust_Name_Ind_Type);

   C :             Connection_Type;
   Q :             Query_Type;
   Cust_Name_Ind : Cust_Name_Ind_Type;
 begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      Cust_Name_Ind := Is_Null(Q,2);
      if not Cust_Name_Ind then
         -- Get Cust_Name since it is not null
      end if;
   end loop;
   Clear(Q);
\end{Example}

\section{Value Fetching Functions\label{Value Fetching Functions}}

Once a fetch\index{fetch} operation has been performed, the application needs to
retrieve the values for each column from the row. The function primitive
Value\index{Value} assumes that the column's value is \emph{not} going
to be NULL\index{NULL}. If it should be null however, the exception
Null\_Value\index{Null\_Value} is raised. A better set of primitives should be used for
columns that may return NULL. See \Ref{Value and Indicator Fetch Procedures}.

The following subsections will cover the function primitives for extracting
the values for builtin types\index{builtin types}.


\subsection{Function Value\label{Standard Value Functions}}

The value for a Row\_ID\_Type\index{OID}, string, bit string or
Unbounded\_String\index{Unbounded\_String} can be extracted for a column
using the Value function primitive. This function should only used
for columns that cannot return a NULL \index{NULL}value.%
\footnote{If the value is NULL, the exception Null\_Value will be raised.%
} The calling requirements for these primitives are the same with 
different return types:

\begin{Code}
function Value(
   Query : in Query_Type;
   CX :    in Column_Index_Type
) return Row_ID_Type;
\end{Code}

\begin{Code}
function Value(
   Query : in Query_Type;
   CX :    in Column_Index_Type
) return String;
\end{Code}

\begin{Code}
function Value(
   Query : in Query_Type;
   CX :    in Column_Index_Type
) return Ada.Strings.Unbounded.Unbounded_String;
\end{Code}

\begin{Code}
function Value(
   Query : in Query_Type;
   CX :    in Column_Index_Type
) return APQ_Bitstring;
\end{Code}

Table \ref{t:valx} lists the possible exceptions for these functions.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
         Null\_Value       &  The column's value is NULL\\
      \end{tabular}
   \end{center}
   \caption{Value Exceptions}\label{t:valx}
\end{table}

The following example shows how all the column values are fetched:

\begin{Example}
   declare
     C : Connection_Type;
     Q : Query_Type;
   begin
     Prepare(Q,"SELECT CUST_NO,CUST_NAME");
     Append(Q, "FROM CUSTOMER");
     Execute(Q,C);
     loop
        begin
           Fetch(Q);
        exception
           when No_Tuple =>
              exit;
        end;
        for CX in 1..Column_Index_Type(Columns(Q)) loop
           declare
               Col_Value : String := Value(Q,CX);
           begin
               Put("Column");
               Put(Column_Index_Type'Image(CX));
               Put(" = '");
               Put(Value(Q,CX));
               Put_Line("'");
           end;
        end loop;
     end loop;
     Clear(Q);
\end{Example}

\subsection{Null\_Oid Function\label{Null_Oid Function}}

Since different database engines have different approaches to row
ID values%
\footnote{MySQL for example, does not return row ID values.%
}, it is necessary to know how to represent a null row ID\index{row ID} value in
the current database context. Use the Null\_Oid\index{Null\_Oid} primitive
to obtain that value:

\begin{Code}
function Null_Oid(
   Query : Query_Type
) return Row_ID_Type;
\end{Code}

\begin{floatingtable}{
   \begin{tabular}{lc}
      Database       &  Value\\
      \hline 
      PostgreSQL     &  0\\
      MySQL          &  0\\
      Sybase         &  0\\
   \end{tabular}}
   \caption{Null Oid Values by Product}\label{t:nulloid}
\end{floatingtable}

Using the Null\_Oid function in generic database code allows helps
to eliminate the need to identify the database engine being used. 
Table~\ref{t:nulloid} lists the numeric values that represent a 
null OID (row ID) value. The application programmer should rely
of the function Null\_Oid to avoid hardcoding a numeric value
that might change in the future.

\subsection{Generic Value Functions}

The Value functions documented in \Ref{Standard Value Functions}
were suitable for the specific data types that they supported. However,
Ada programmers often derive distinct new types to prevent accidental
mixing of values in expressions. To accomodate all of these custom
data types, you need to use generic functions for the purpose:

\begin{Code}
generic
   type Val_Type is new Boolean;
function Boolean_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is range <>;
function Integer_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is mod <>;
function Modular_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is digits <>;
function Float_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <>;
function Fixed_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <> digits <>;
function Decimal_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Date;
function Date_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Time;
function Time_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
function Timestamp_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return Val_Type;
\end{Code}

Table \ref{t:gvalx} lists the exceptions possible for these
instantiated routines.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
         Null\_Value       &  The column's value is NULL\\
      \end{tabular}
   \end{center}
   \caption{Generic Value Exceptions}\label{t:gvalx}
\end{table}

The following example illustrates the use of the Integer\_Value and
Date\_Value generic functions:

\begin{Example}
declare
   type Cust_No_Type is new APQ_Integer;
   type Cust_Birthday_Type is new APQ_Date;
   function Value is new Integer_Value(Cust_No_Type);
   function Value is new Date_Value(Cust_Birthday_Type);
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,BIRTH_DATE");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      declare
         Cust_Name : String := Value(Q,2);
         Cust_No :   Cust_No_Type;
         Birthday :  Cust_Birthday_Type;
      begin
         Cust_No  := Value(Q,1);  -- CUST_NO is col 1
         Birthday := Value(Q,3);  -- BIRTH_DATE is col 3
         ...
      end;
   end loop;
   Clear(Q);
\end{Example}

In the example shown, \emph{Cust\_Name} is returned by the builtin
function Value for String types. The variables \emph{Cust\_No} and
\emph{Birthday} are assigned through the generic instantiations of
the functions Integer\_Value\index{Integer\_Value} and Date\_Value\index{Date\_Value} respectively.


\subsection{Fixed Length String Value Procedure}

Sometimes in an application it is desireable to work with fixed\index{fixed length} length
string\index{string} values. The following Value\index{Value} procedure does just this:

\begin{Code}
procedure Value(
   Query: in     Query_Type;
   CX :   in     Column_Index_Type;
   V :       out String
);
\end{Code}

This function raises the exceptions listed in Table~\ref{t:fxflsx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
         Null\_Value       &  The column's value is null\\
      \end{tabular}
   \end{center}
   \caption{Fixed Length String Value Exceptions}\label{t:fxflsx}
\end{table}

The following example extracts the CUST\_NAME column result into variable
\emph{Cust\_Name} as a 30 byte string value:

\begin{Example}
declare
   C :         Connection_Type;
   Q :         Query_Type;
   Cust_Name : String(1..30);
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q,"FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...
      Value(Q,2,Cust_Name);
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{APQ\_Timezone Value Procedure}

A TIMESTAMP\index{TIMESTAMP} value that carries with it a time zone\index{time zone}
value, requires a special procedure since two values must be extracted
for the same column:

\begin{itemize}
   \item The Ada.Calendar.Time%
      \footnote{From which APQ\_Timestamp is derived.} value holding the TIMESTAMP value
   \item The APQ\_Timezone\index{APQ\_Timezone} value holding the time zone
      offset.
\end{itemize}

The generic procedure requires the following type arguments:

\begin{Code}
generic
   type Date_Type is new Ada.Calendar.Time;
   type Zone_Type is new APQ_Timezone;
procedure Timezone_Value(
   Query : in     Query_Type'Class;
   CX :    in     Column_Index_Type;
   TS :       out Date_Type;
   TZ :       out Zone_Type
);
\end{Code}

Table \ref{t:tzvx} lists the exceptions for Timezone\_Value.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
         Null\_Value       &  The column's value is null\\
      \end{tabular}
   \end{center}
   \caption{Timezone\_Value Exceptions}\label{t:tzvx}
\end{table}

The following example shows how the procedure can be used:

\begin{Example}
declare
   procedure Value is new Timezone_Value(APQ_Timestamp,APQ_Timezone);
   C : Connection_Type;
   Q : Query_Type;
   Birth_Date : APQ_Timestamp;
   Birth_Zone : APQ_Timezone;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,BIRTH_DATE");
   Append(Q,"FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...
      Value(Q,3,Birth_Date,Birth_Zone); -- Column BIRTH_DATE
      ...
      end loop;
   end loop;
   Clear(Q);
\end{Example}

In this example code fragment, the Value procedure call expects the
column's value to be column 3 (argument CX). This works as long as
column BIRTH\_DATE can never be null. If a NULL value is encountered
in this program, the exception Null\_Value\index{Null\_Value} will be raised and not
caught by the code in this example.%
\footnote{Either an exception handler must be added or a different way of extracting
the value must be used. Fetch\_Timezone is recommended if NULL is
possible.}

\subsection{Bounded\_Value Function}

Bounded\index{bounded strings} strings require a separate instantiation of
Ada\-.Strings\-.Bounded\index{Ada.Strings.Bounded} for each string length.
For this reason, a function supporting bounded strings must be provided
in generic form. The Bounded\_Value\index{Bounded\_Value} generic function accepts
the following generic arguments:

\begin{Code}
generic
   with package P is new
      Ada.Strings.Bounded.Generic_Bounded_Length(<>);
function Bounded_Value(
   Query : in Query_Type'Class;
   CX :    in Column_Index_Type
) return P.Bounded_String;
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
         Null\_Value       &  The column's value is null\\
      \end{tabular}
   \end{center}
   \caption{Bounded\_Value Exceptions}\label{t:bvx}
\end{table}

Table \ref{t:bvx} lists the exceptions possible for Bounded\_Value.
The example below illustrates the use of Bounded\_Value:

\begin{Example}
with Ada.Strings.Bounded;
declare
   package B30 is new 
      Ada.Strings.Bounded.Generic_Bounded_Length(30);
   function Value is new Bounded_Value(B30); 
   C :         Connection_Type;
   Q :         Query_Type;
   Cust_Name : B30;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,BIRTH_DATE");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
      end;
      ...
      Cust_Name := Value(Q,2);
      ...
      end loop;
   end loop;
   Clear(Q);
\end{Example}

\section{Value and Indicator Fetch Procedures\label{Value and Indicator Fetch Procedures}}

The Value\index{Value} functions\index{value functions} presented in
\Ref{Value Fetching Functions} were useful when the returned value was
always going to be present. However, their use becomes clumsy and less
efficient if exception handlers must be used to handle the
NULL\index{NULL} value case. This section documents Fetch procedures to
return both a value and a null indicator together. With this convenience
comes the added responsibility of checking the null
indicator\index{indicator} values, that are returned.


\subsection{Char and Unbounded Fetch}

The Char\_Fetch and Unbounded\_Fetch generic procedures
fetch both a string value and an indicator value. In the Char\_Fetch
case, the returned value is blank filled to the full size of the receiving
String buffer. Each of these has the following instantiation parameters:

\begin{Code}
generic
   type Ind_Type is new Boolean;
procedure Char_Fetch(
   Query :     in     Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out String;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Ind_Type is new Boolean;
procedure Unbounded_Fetch(
   Query :     in     Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Ada.Strings.Unbounded.Unbounded_String;
   Indicator :    out Ind_Type
);
\end{Code}

The Unbounded\_Fetch routine may raise any of the exceptions listed in Table~\ref{t:ufx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
      \end{tabular}
   \end{center}
   \caption{Unbounded\_Fetch Exceptions}\label{t:ufx}
\end{table}

The following example illustrates two different column fetch applications:

\begin{Example}
with Ada.Strings.Unbounded;
declare
   type Cust_Name_Ind_Type is new Boolean;
   type Cust_City_Ind_Type is new Boolean;
   subtype Cust_Name_Type is String(1..30);
   subtype Cust_City_Type is
       Ada.Strings.Unbounded.Unbounded_String;

   procedure Value is new 
       Char_Fetch(Cust_Name_Ind_Type);
   procedure Value is new 
       Unbounded_Fetch(Cust_City_Ind_Type);

   C :             Connection_Type;
   Q :             Query_Type;
   Cust_Name :     Cust_Name_Type;
   Cust_Name_Ind : Cust_Name_Ind_Type;
   Cust_City :     Cust_City_Type;
   Cust_City_Ind : Cust_City_Ind_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,CITY");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
      end;
      ...
      Value(Q,2,Cust_Name,Cust_Name_Ind);
      Value(Q,3,Cust_City,Cust_City_Ind);
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{Varchar\_Fetch and Bitstring\_Fetch Procedures}

To return a varying length string\index{varying length string} requires
the use of a function. However, to return two values, we must resort
to a procedure call for the purpose. In order to return both a varying
length string and a null indicator, an additional return value is
returned that indicates the length of the string. To accomodate strongly
typed indicators\index{indicators}, these two procedures are provided in generic form.
The instantiation parameters are:

\begin{Code}
generic
   type Ind_Type is new Boolean;
procedure Varchar_Fetch(
   Query :     in     Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out String;
   Last :         out Natural;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Ind_Type is new Boolean;
procedure Bitstring_Fetch(
   Query :     in     Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out APQ_Bitstring;
   Last :         out Natural;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
      \end{tabular}
   \end{center}
   \caption{Bitstring\_Fetch Exceptions}\label{t:bfx}
\end{table}

Table \ref{t:bfx} lists the exceptions for Bitstring\_Fetch.
The next example illustrates two different column fetch applications:

\begin{Example}
declare
   type Cust_Name_Ind_Type is new Boolean;
   type Cust_City_Ind_Type is new Boolean;

   procedure Value is new 
      Varchar_Fetch(Cust_Name_Ind_Type);
   procedure Value is new 
      Varchar_Fetch(Cust_City_Ind_Type);

   C :              Connection_Type;
   Q :              Query_Type;
   Cust_Name :      String(1..30);
   Cust_Name_Last : Natural;
   Cust_Name_Ind :  Cust_Name_Ind_Type;
   Cust_City :      String(1..40);
   Cust_City_Last : Natural;
   Cust_City_Ind :  Cust_City_Ind_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,CITY");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...
      Value(Q,2,Cust_Name,Cust_Name_Last,Cust_Name_Ind);
      Value(Q,3,Cust_City,Cust_City_Last,Cust_City_Ind);
      ...
   end loop;
   Clear(Q);
\end{Example}

After the first Value call in the example, the customer name would
be represented by the expression:

\begin{Code}

   Cust_Name(1..Cust_Name_Last)

\end{Code}

provided that the value Cust\_Name\_Ind was false.


\subsection{Bounded\_Fetch Procedure}

To fetch both a Bounded\_String value and its associated null\index{null indicator} indicator,
you instantiate and call the Bounded\_Fetch\index{Bounded\_Fetch}. The instantiation
parameters are as follows:

\begin{Code}
generic
   type Ind is new Boolean;
   with package P is new 
      Ada.Strings.Bounded.Generic_Bounded_Length(<>);
procedure Bounded_Fetch(
   Query :     in     Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out P.Bounded_String;
   Indicator :    out Ind);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
      \end{tabular}
   \end{center}
   \caption{Bounded\_Fetch Exceptions}\label{t:bfx2}
\end{table}

The Bounded\_Fetch routine may raise any of the exceptions listed in Table~\ref{t:bfx2}.
The example below illustrates a fetch instantiation and call:

\begin{Example}
with Ada.Strings.Bounded;
declare
   package B32 is new 
      Ada.Strings.Bounded.Generic_Bounded_Length(32);
   type Cust_Name_Ind_Type is new Boolean;

   procedure Value is new 
      Bounded_Fetch(Cust_Name_Ind_Type,B32);

   C :              Connection_Type;
   Q :              Query_Type;
   Cust_Name :      B32;
   Cust_Name_Ind :  Cust_Name_Ind_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...
      Value(Q,2,Cust_Name,Cust_Name_Ind); 
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{Discrete Type Fetch Procedures}

Several of the discrete\index{discrete types} types can be grouped and documented in this
section. The following table indicates the generic procedure names
and their associated class of data type for which they are designed:

\begin{Code}
generic
   type Val_Type is new Boolean;
   type Ind_Type is new Boolean;
procedure Boolean_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is range <>;
   type Ind_Type is new Boolean;
procedure Integer_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is mod <>;
   type Ind_Type is new Boolean;
procedure Modular_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is digits <>;
   type Ind_Type is new Boolean;
procedure Float_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <>;
   type Ind_Type is new Boolean;
procedure Fixed_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <> digits <>;
   type Ind_Type is new Boolean;
procedure Decimal_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
   type Ind_Type is new Boolean;
procedure Date_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Day_Duration;
   type Ind_Type is new Boolean;
procedure Time_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
   type Ind_Type is new Boolean;
procedure Timestamp_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Val_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline      
         No\_Result        &  There was no execute performed\\
         No\_Column        &  No column at index\\
      \end{tabular}
   \end{center}
   \caption{Timestamp\_Fetch Exceptions}\label{t:tfx2}
\end{table}

The Timestamp\_Fetch exceptions are listed in Table~\ref{t:tfx2}.
The following example illustrates how to instantiate and call a
Integer\_Fetch procedure.

\begin{Example}
declare
   type Cust_No_Type is new Integer;
   type Cust_No_Ind_Type is new Boolean;
   procedure Value is new Integer_Fetch
      (Cust_No_Type,Cust_No_Ind_Type);
   C :              Connection_Type;
   Q :              Query_Type;
   Cust_No :        Cust_No_Type;
   Cust_No_Ind :    Cust_No_Ind_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...
      Value(Q,1,Cust_No,Cust_No_Ind);
      ...
   end loop;
   Clear(Q);
\end{Example}

\subsection{Timezone\_Fetch Procedure}

The Timezone\_Fetch\index{Timezone\_Fetch} generic procedure is unique because it returns
an additional parameter: the timezone\index{timezone}. The procedure's
instantiation parameters are listed below:

\begin{Code}
generic
   type Date_Type is new Ada.Calendar.Time;
   type Zone_Type is new APQ_Timezone;
   type Ind_Type is new Boolean;
procedure Timezone_Fetch(
   Query :     in     Root_Query_Type'Class;
   CX :        in     Column_Index_Type;
   V :            out Date_Type;
   Z :            out Zone_Type;
   Indicator :    out Ind_Type
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name       &  Reason\\
         \hline 
         No\_Result           &  There was no execute performed\\
         No\_Column           &  No column at index\\
      \end{tabular}
   \end{center}
   \caption{Timezone\_Fetch Exceptions}\label{t:tzfx}
\end{table}

Table \ref{t:tzfx} lists the possible exceptions for Timezone\_Fetch.
The following example illustrates how to instantiate and call a Timezone\_Fetch
procedure.

\begin{Example}
declare
   type Bday_Type is new Integer;
   type Bday_Zone_Type is new APQ_Timezone;
   type Bday_Ind_Type is new Boolean;
   procedure Value is new Timezone_Fetch
      (Bday_Type,Bday_Zone_Type,Bday_Ind_Type);
   C :              Connection_Type;
   Q :              Query_Type;
   Bday :           Bday_Type;
   Bday_Zone :      Bday_Zone_Type;
   Bday_Ind :       Bday_Ind_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,BIRTH_DATE");
   Append(Q, "FROM CUSTOMER");
   Execute(Q,C);
   loop
      begin
         Fetch(Q);
      exception
         when No_Tuple =>
            exit;
      end;
      ...
      Value(Q,3,Bday,Bday_Zone,Bday_Ind);
      ...
   end loop;
   Clear(Q);
\end{Example}

\section{Information Functions}

You have already seen two information functions Result\index{Result} and Error\_Message\index{Error\_Message}
in \Ref{Error Message Reporting} and \Ref{Error Status Reporting}.
Another useful Query\_Type primitive is the To\_String\index{To\_String} function. It
is described in the next subsection.


\subsection{The To\_String Function}

The To\_String\index{To\_String} primitive allows the caller to retrieve the collected
SQL text from the Query\_Type object. The function's calling signature
is as follows:

\begin{Code}
function To_String(
   Query : Query_Type
) return String;
\end{Code}

The To\_String function returns the full text of the SQL query, including
newline characters.%
\footnote{One is included at the end of the string if it is missing.%
} If there has not been any SQL text\index{SQL text} collected, the
function returns an empty string.%
\footnote{In this case, no newline is provided.%
}

The following example shows how a programmer can dump out the SQL\index{SQL}
query, but only when it fails:

\begin{Example}
declare
   C :   Connection_Type;
   Q :   Query_Type;
begin
   Prepare(Q,"SELECT CUST_NO,CUST_NAME,BIRTH_DATE");
   Append(Q, "FROM CUSTOMER");
   begin
      Execute(Q,C);
   exception
      when SQL_Error =>
         Put_Line("The failed SQL Query was:"); 
         Put_Line(To_String(Q));
         raise;
      when others =>
         raise;
   end;
\end{Example}

\subsection{Cursor Names\label{Cursor_Name}}

While PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL} do not yet support cursors\index{cursors} in their client
libraries \footnote{PostgreSQL supports server cursors, but cursor support is absent in libpq.},
other database products like Sybase\index{Sybase} do. Cursors allow the programmer
to work with the concept of a ``current row''\index{current row}. For those databases
that do support the use of cursors, you can retrieve the cursor name\index{cursor name}
with the use of the Cursor\_Name\index{Cursor\_Name} function primitive:

\begin{Code}
function Cursor_Name(
   Query : Query_Type
) return String;
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         No\_Result        &  No cursor results pending\\
      \end{tabular}
   \end{center}
   \caption{Cursor\_Name Exceptions}\label{t:cnamx}
\end{table}

The Cursor\_Name exceptions are documented in Table~\ref{t:cnamx}.
To use cursors within APQ, you must set the fetch mode of the Query\_Type
to one of the following:

\begin{itemize}
   \item Cursor\_For\_Update\index{Cursor\_For\_Update}
   \item Cursor\_For\_Read\_Only\index{Cursor\_For\_Read\_Only}
\end{itemize}

Once you have set the fetch mode to one of the cursor fetch modes
listed above, and you have executed the query to produce cursor results,
\emph{then} the call to Cursor\_Name is valid. For a description of
fetch query modes in \Ref{Fetch Query Modes}.


\chapter{Blob Support}

The MySQL\index{MySQL} database provides a very different type of blob support\index{blob support}.
For the moment, blobs are unsupported in MySQL. Blob support is also
absent for Sybase\index{Sybase}. These are two areas ripe for further work in APQ.

Blobs are supported for PostgreSQL\index{PostgreSQL} in APQ however. This provides the
application programmer with the ability to store large amounts of
information in a ``blob''\index{blob}. In many ways this resembles
a file\index{file}, with the exception that the contents are stored
in the database and is accessed by number (OID\index{OID}). The APQ
binding provides full PostgreSQL blob support for the Ada programmer.
In addition, the Ada\index{Ada} stream\index{stream} concept is employed to
provide reliable and Ada95\index{Ada95} convenient access to the blob.


\subsubsection{Endian Note:}

The application programmer must keep in mind that any binary data
written to a blob, by means of the Ada stream, is not endian\index{endian} neutral.
This becomes a concern when a client application accesses or writes
to blobs stored on a database over the network, on another host. If
the endianess of the server and client differ, endian problems will
emerge.


\section{Introduction}

Blob functions are managed primarily through the Blob\_Type\index{Blob\_Type} access
type.%
\footnote{The object itself is of type Blob\_Object. Blob\_Type is an access
to Blob\_Object type.%
} Stream I/O to and from the blob is performed using an Ada streams
access value.%
\footnote{Internally named Root\_Stream\_Access type, which is the type ''access
all Ada.Streams.Root\_Stream\_Type'Class''.%
} 

The blob support can generally be grouped into the following categories:

\begin{itemize}
   \item Create, Open and Close operations
   \item Index setting and querying operations
   \item Information operations for Size and OID
   \item Stream accessor\index{stream accessor} function
   \item Blob destruction\index{blob destruction}
   \item File and Blob operations
\end{itemize}

The following sections will document the blob support using these
groupings.


\section{Blob Memory Leak Prevention}

\index{memory leak prevention}It is extremely important that the
programmer realize that the Blob\_Type data type is an access type.%
\footnote{This design choice was necessary to accomodate Ada stream oriented
I/O.%
} Additionally this access\index{access value} value is a pointer\index{pointer} to a dynamically\index{dynamic} allocated
tagged\index{tagged} record (type Blob\_Object). For this reason, the programmer
must take great care to ``close'' the Blob\_Type before discarding
the Blob\_Type value, when it goes out of scope. Failure to close
a Blob\_Type value, will result in a memory leak\index{memory leak} and cause subsequent
database performance issues. Use the Blob\_Type value as if it were
an open file that needs closing.

The following example represents a ``Blob\_Type leak'':

\begin{Example}
declare
   C :   aliased Connection_Type;
   B :   Blob_Type;
begin
   ...
   B := Blob_Create(C'Access);
   ...
end;
\end{Example}

The example above is bad because a ``blob leak''\index{blob leak}
occurs when the ``end'' statement is reached.%
\footnote{It should also be noted that after creating a blob in the database,
the application must save the OID value for the blob somewhere. Otherwise,
you will have a blob in the database that will never be accessed!%
} The variable \emph{C} finalizes itself OK because it is a controled
object.%
\footnote{Both Connection\_Type and Query\_Type objects are controlled records
with finalization.%
} However, B is an access type, pointing to a Blob\_Object record.
When variable B falls out of scope, only the pointer value
in B is lost. The object it pointed to has not been released!

The following example code is better:

\begin{Example}
declare
   C :   aliased Connection_Type;
   B :   Blob_Type;
begin
   ...
   B := Blob_Create(C'Access);
   ...
   Blob_Close(B);
end;
\end{Example}

The call to Blob\_Close\index{Blob\_Close} insures that the memory associated with the
opened blob is released, before the value \emph{B} falls out of scope.%
\footnote{Note that Close does not destroy the blob in the database.%
} However, if there is a chance that an exception may be raised, you
may still be vulnerable to leaks. The following example covers all
of the bases:

\begin{Example}
declare
   C :   aliased Connection_Type;
   B :   Blob_Type;
begin
   ...
   B := Blob_Create(C'Access);
   ...
   Blob_Close(B);
exception
   when others =>
      if B /= null then
         Blob_Close(B);
      end if;
      ...recovery steps...
end;
\end{Example}

While the recovery steps have been left to the reader's imagination
in the example above, the exception is caught and the value for variable
\emph{B} is tested. Only if \emph{B} is not null, should the Blob\_Close
procedure call made. Only you can prevent blob memory leaks!


\section{Create, Open and Close of Blobs}

The most basic operations possible in an Ada program using blobs are:

\begin{itemize}
   \item Creating a new blob in the database (Blob\_Create)
   \item Opening an existing blob in the database (Blob\_Open)
   \item Flushing buffered writes to the database (Blob\_Flush)
   \item Closing a blob (Blob\_Close)
\end{itemize}

The following subsections will explain how to perform these operations
in detail.


\subsection{Blob\_Create Procedure}

Before the application can open an existing blob\index{opening a blob},
there must be some way to create a blob\index{creating a blob}. The
Blob\_Create\index{Blob\_Create} function does just this with the following calling signature:%
\marginpar{Note: Blob operations must be performed within the context of a transaction.%
}

\begin{Code}
function Blob_Create(
   DB :       access Connection_Type;
   Buf_Size : in     Natural := Buf_Size_Default
) return Blob_Type;
\end{Code}

The returned value is a Blob\_Type that is capable of being used to
read and/or write a blob. The blob is positioned at index position
1 (the beginning). See \Ref{Blob OID Function} for information
about how to determine the created blob's OID\index{OID}. 

Starting with APQ version 1.2, all blob I/O is buffered if the Buf\_Size
argument is supplied with a value greater than zero, or is not supplied
such that the default value applies. Table~\ref{t:bcbsgx} summarizes
the Buf\_Size\index{Buf\_Size} argument behaviour. The exceptions
are listed in Table~\ref{t:blbcx}.

\begin{table}
   \begin{center}
      \begin{tabular}{lll}
         Buf\_Size Value                        &  Description          &  Performance\\
         \hline 
         0                                      &  Unbuffered blob I/O  &  Very poor\\
         0 < Buf\_Size < 1024                   &  Buffered             &  Poor\\
         1024 <= Buf\_Size < Buf\_Size\_Default & Buffered blob I/O     &  Better\\
         Buf\_Size\_Default                     &  Buffered: 5120 bytes &  Very good\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Create Buf\_Size Guidelines}\label{t:bcbsgx}
\end{table}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  There was no blob created\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Create Exceptions}\label{t:blbcx}
\end{table}

Possible reasons for a Blob\_Error\index{Blob\_Error} exception to be raised would include:

\begin{itemize}
   \item bad database connection object%
      \footnote{Or the database connection object went out of scope.}
   \item a database error occurred (no more blob space?)
\end{itemize}

The following example shows how a new blob can be created:

\begin{Example}
declare
   C :   aliased Connection_Type;
   B :   Blob_Type;
begin
   ...
   B := Blob_Create(C'Access);
   ...
   Blob_Close(B);
end;
\end{Example}

\subsubsection{Note:}

The argument DB in the call to the Blob\_Create\index{Blob\_Create}, is an access
to Connection\_Type argument. You must guarantee that the Connection\_Type
object does not finalize before the created blob has been closed.


\subsection{Blob\_Open Function\label{Blob_Open Function}}

To open an existing blob\index{existing blob}, you must know the OID\index{OID} of the blob in the
database. This is normally a value that is stored in a database column
somewhere. See \Ref{Blob OID Function} for information on
how to determine the OID of a created blob.%
\marginpar{Note: Blob operations must be performed within the context of a transaction.%
}

Blobs can be opened for various types of access:

\begin{description}
   \item [Read\index{Read}] for readonly access to the blob contents
   \item [Write\index{Write}] for writing to the blob
   \item [Read\_Write\index{Write}] for both reading and writing of the blob
\end{description}

The Blob\_Open\index{Blob\_Open} function has the following specification:

\begin{Code}
type Mode_Type is (
   Write,
   Read,
   Read_Write
);

function Blob_Open(
   DB :       access Connection_Type;
   Oid :      in     Row_ID_Type;
   Mode :     in     Mode_Type;
   Buf_Size : in     Natural := Buf_Size_Default
) return Blob_Type;
\end{Code}

The returned value is a Blob\_Type that is accessable according to
the Mode selected. The blob is positioned\index{blob position} at index value 1
(the beginning).

Starting with APQ version 1.2, all blob I/O is buffered\index{buffered blob I/O} if the Buf\_Size
argument is supplied with a value greater than zero, or is not supplied
such that the default value applies. Refer to Table~\ref{t:bcbsgx} for guidance on
the value to use for Buf\_Size. The exceptions are documented
in Table~\ref{t:bopnx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  There was no blob opened\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Open Exceptions}\label{t:bopnx}
\end{table}

Possible reasons for a Blob\_Error exception to be raised would include:

\begin{itemize}
   \item bad database connection object
   \item the Oid value supplied is not known by the database
   \item a database error occurred
\end{itemize}

The following example shows how blob 73763 can be opened for reading:

\label{Example-code-with-OID-73763}
\begin{Example}
declare
   C :   aliased Connection_Type;
   B :   Blob_Type;
   OID : Row_ID_Type := 73763;
begin
   ...
   B := Blob_Open(C'Access,OID,Read);
   ...
   Blob_Close(B);
exception
   when others =>
      if B /= null then
         Blob_Close(B);
      end if;
      raise;
end;
\end{Example}

\subsubsection{Note:}

The argument DB in the call to the Blob\_Open, is an access
to Connection\_Type argument. You must guarantee that the Connection\_Type
object does not finalize\index{finalize} before the opened blob has been closed.


\subsubsection{Generic\_Blob\_Open Function}

To allow the application programmer to use strong types in place of
the supplied Row\_ID\_Type\index{Row\_ID\_Type} type, a generic procedure for opening blobs
is also provided. The instantiated function behaves exactly as described
for Blob\_Open\index{Open\_Blob} on page \pageref{Blob_Open Function}. The instantiation
arguments for Generic\_Blob\_Open\index{Generic\_Blob\_Open} are:

\begin{Code}
type Mode_Type is (
   Write,
   Read,
   Read_Write
);

generic
   type Oid_Type is new Row_ID_Type;
function Generic_Blob_Open(
   DB :       access Connection_Type;
   Oid :      in     Oid_Type;
   Mode :     in     Mode_Type;
   Buf_Size : in     Natural := Buf_Size_Default
) return Blob_Type;
\end{Code}

The following example shows how to instantiate the function:

\begin{Example}
declare
type My_Oid_Type is new Row_ID_Type;
function Blob_Open is new
   Generic_Blob_Open(My_Oid_Type);
\end{Example}

\subsection{Blob\_Flush Procedure}

\index{Blob\_Flush}When you are using buffered\index{buffered blob I/O} blob I/O%
\footnote{Buffered blob I/O is the default for performance reasons.%
} and your application has performed one or more writes to the blob,
you may need to be certain that all of the buffered data is physically
written out to the database. For example, you may have a timing\index{timing} opportunity
to perform this expensive operation while the user is waiting for
something else to occur. Buffer flushes\index{flush} are automatically performed
when the blob is closed or due to changes made by the Blob\_Set\_Index\index{Blob\_Set\_Index}
operation. To give the application programmer control over the timing
of the physical write to the database, the Blob\_Flush\index{Blob\_Flush} procedure can
be used.%
\marginpar{Blob\_Flush calls are ignored when unbuffered blob I/O is being used.
This makes it easy for the application to choose buffered or unbuffered
operation without source code changes.}

The Blob\_Flush procedure has the specification below. Table~\ref{tblbflx} lists the exceptions.

\begin{Code}
procedure Blob_Flush(Blob : Blob_Type);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name       &  Reason\\
         \hline 
         Blob\_Error          &  The blob is not open\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Flush Exceptions}\label{t:blbflx}
\end{table}


\subsection{Blob\_Close Procedure}

When the programmer no longer requires access to a open/created blob,
the procedure Blob\_Close\index{Blob\_Close} should be called. Since an open blob depends
upon a hidden access value that points back to the Connection\_Type
object, the programmer should call Blob\_Close as soon as is practical.
This reduces the possibility of error that will occur if the Connection\_Type
object is finalized too soon.

The Blob\_Close procedure has the following specification. Exceptions are
listed in Table~\ref{t:bclsx}.

\begin{Code}
procedure Blob_Close(Blob : in out Blob_Type);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  The blob is not open\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Close Exceptions}\label{t:bclsx}
\end{table}

Normally the Blob\_Error\index{Blob\_Error} exception will indicate an attempt to close
a blob that is not open. However, it is possible that the database
engine may experience a problem that will raise the same exception.

The procedure Blob\_Close will also null out the the Blob\_Type value
that was passed in. This is done to eliminate any accidental access
to a Blob\_Object that no longer exists.


\section{Index Setting Operations}

Like a file, a blob's ``position''\index{position of a blob} can be changed and queried.
The index\index{index} operations require the use of two types defined for the
purpose. They are:

\begin{Code}

   type Blob_Count is new 
      Ada.Streams.Stream_Element_Offset
      range 0..Ada.Streams.Stream_Element_Offset'Last;

\end{Code}

\begin{Code}

   subtype Blob_Offset is 
      Blob_Count range 1..Blob_Count'Last;

\end{Code}

The type Blob\_Count\index{Blob\_Count} is used where there is a count involved
(which may require the value zero). The type Blob\_Offset\index{Blob\_Offset} is
used whenever a blob offset is used, since it starts at the value
1.

The next subsections describe facilities for performing blob indexing
operations.


\subsection{Blob\_Set\_Index Procedure}

The Blob\_Set\_Index\index{Blob\_Set\_Index} procedure is used when the caller needs to seek
to a new position within the opened blob. See \Ref{Blob Size Function}
if you need to know the size of the blob.

The calling requirements for Blob\_Set\_Index are summarized below
(exceptions in Table~\ref{t:blbsxx}).

\begin{Code}
procedure Blob_Set_Index (
   Blob : in Blob_Type;
   To :   in Blob_Offset
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  Not open or seek failed\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Set\_Index Exceptions}\label{t:blbsxx}
\end{table}

The following example shows how to seek to the end of the blob:

\begin{Example}
declare
   C :        aliased Connection_Type;
   B :        Blob_Type;
   B_Size :   Blob_Count;
   End_Blob : Blob_Index;
begin
   ...
   B_Size := Blob_Size(B);
   if B_Size > 0 then
      End_Blob := B_Size;
      Blob_Set_Index(B,End_Blob);
   ...
\end{Example}

\section{Blob\_Index Function}

Applications sometimes need to query where they are positioned in
the blob. The Blob\_Index\index{Blob\_Index} function returns the current Blob\_Offset\index{Blob\_Offset}
position\index{position} information. The specification is shown below,
while the exceptions are listed in Table~\ref{t:blbxx}.

\begin{Code}
function Blob_Index(
   Blob : in Blob_Type
) return Blob_Offset;
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  Not open\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Index Exceptions}\label{t:blbxx}
\end{table}

The following example code determines where in the presently opened
blob the blob position index is:

\begin{Example}
declare
   C :        aliased Connection_Type;
   B :        Blob_Type;
   Pos_Blob : Blob_Index;
begin
   ...
   Pos_Blob := Blob_Index(B);
\end{Example}

\section{Information Functions}

The following subsections describe information gathering functions.
They provide the programmer a way to obtain size\index{size} and identification\index{identification}
information.

\subsection{Blob Size Function\label{Blob Size Function}}

To determine the present size\index{blob size} of a blob, the Blob\_Size\index{Blob\_Size}
function can be used. Table~\ref{t:blbszx} documents the exceptions while the specification
is listed as follows:

\begin{Code}
function Blob_Size(
   Blob : in Blob_Type
) return Blob_Count;
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  Not open\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Size Exceptions}\label{t:blbszx}
\end{table}

Notice that the return type Blob\_Count\index{Blob\_Count} does permit the value zero
to be returned (blob is empty).

The following example code determines the size of the presently opened
blob:

\begin{Example}
declare
   C :	       aliased Connection_Type;
   B :	       Blob_Type;
   Blob_Size : Blob_Count;
begin
   ...
   Blob_Size := Blob_Size(B);
\end{Example}

\subsection{Blob\_OID Function\label{Blob OID Function}}

After a blob is created, it is very necessary to determine the OID\index{OID}
for the blob. The Blob\_Oid function may be called after Blob\_Create\index{Blob\_Create}
or Blob\_Open\index{Blob\_Open} to obtain OID information.
Table~\ref{t:blboidx} lists the exceptions and the specification is
shown below:

\begin{Code}
function Blob_Oid(
   Blob : in Blob_Type
) return Row_ID_Type;
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  Not open\\
      \end{tabular}
   \end{center}
   \caption{Blob\_OID Exceptions}\label{t:blboidx}
\end{table}

The following example code determines the OID\index{OID} value for the newly
created blob\index{blob}:

\begin{Example}
declare
   C :         aliased Connection_Type;
   B :         Blob_Type;
   Blob_OID :  Row_ID_Type;
begin
   ...
   B        := Blob_Create(C'Access);
   Blob_OID := Blob_Oid(B);
\end{Example}

\subsubsection{Generic\_Blob\_Oid Function}

To use a strongly typed version of the Blob\_Oid\index{Blob\_Oid} function, the application
programmer can instantiate from Generic\_Blob\_Oid. The instantiated
function otherwise behaves exactly as the Blob\_Oid function on page
\pageref{Blob OID Function}. The instantiation parameters for Generic\_Blob\_Oid\index{Generic\_Blob\_Oid}
are:

\begin{Code}
generic
   type Oid_Type is new Row_ID_Type;
function Generic_Blob_Oid(
   Blob : in Blob_Type
) return Oid_Type;
\end{Code}

The following example shows how to instantiate the function:

\begin{Example}
declare
   type My_Oid_Type is new Row_ID_Type;
   function Blob_Oid is new Generic_Blob_Oid(My_Oid_Type);
\end{Example}

\subsection{End\_Of\_Blob Function}

The End\_Of\_Blob\index{End\_Of\_Blob} function can be used by programs that sequentially
read through a blob. The calling signature for this function is given
below:%
\marginpar{Note that this function results in poor performance if the buffer
size is set to zero (unbuffered) in the opening Blob\_Open/Blob\_Create
calls.%
}

\begin{Code}
function End_of_Blob(
   Blob : in Blob_Type
) return Boolean;
\end{Code}

The return value is True if the current position in the blob is at
the end of the blob. Otherwise the value False is returned. Table~\ref{teoblbx}
lists the possible exceptions.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  Not open\\
      \end{tabular}
   \end{center}
   \caption{End\_of\_Blob Exceptions}\label{t:eoblbx}
\end{table}

The following example code reads a series of strings from the blob,
using the End\_Of\_Blob function:

\begin{Example}
declare
   C : aliased Connection_Type;
   B : Blob_Type;
begin
   ...
   B := Blob_Open(...);
   declare
      S : Root_Stream_Access := Blob_Stream(B);
   begin
      while not End_Of_Blob(B) loop
         declare
            Line : String := String'Input(S);
         begin
            Put_Line(Line);
         end;
      end loop;
   end;
   Blob_Close(B);
\end{Example}

\section{Stream Access}

In order for an Ada program to perform stream I/O\index{stream I/O}
on a blob, you must obtain a useable stream pointer\index{stream pointer}.
The APQ binding defines a type named Root\_Stream\_Access\index{Root\_Stream\_Access} for
this purpose. It is defined as follows:

\begin{Code}

   type Root_Stream_Access is access all
      Ada.Streams.Root_Stream_Type'Class;

\end{Code}

The function Blob\_Stream\index{Blob\_Stream} returns this stream pointer to the caller.
Use of this returned pointer makes it possible to use the native Ada\index{Ada}
stream\index{stream I/O} I/O facilities. The function Blob\_Stream is 
specified below while Table~\ref{t:blbstrx} documents the exceptions
possible.

\begin{Code}
function Blob_Stream(
   Blob : in Blob_Type
) return Root_Stream_Access;
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  Not open\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Stream Exceptions}\label{t:blbstrx}
\end{table}

The following example shows how a blob is created, a stream access
value is obtained, and a APQ\_Timestamp\index{APQ\_Timestamp} value is written to the new
blob:

\begin{Example}
declare
   C :         aliased Connection_Type;
   B :         Blob_Type;
   Str :       Root_Stream_Access;
   Some_Date : APQ_Timestamp;
begin
   ...
   B   := Blob_Create(C'Access);
   declare
      Str : Root_Stream_Access := Blob_Stream(B);
   begin
      APQ_Timestamp'Write(Str,Some_Date);
      ...
   end;
   Blob_Close(B);
end;
\end{Example}

Notice in this example, that the declaration and the existance of
the stream pointer Str was restricted as much as possible.
While not strictly necessary, there are good reasons for following
this practice. See the special following note for the details.


\subsubsection{Note:}

The programmer does not have to worry about ``closing'' or freeing\index{freeing}
the returned stream pointer (Str in the example). It can be
nulled or left to fall out of scope. Only the type Blob\_Type
must be ``closed'' by calling Blob\_Close\index{Blob\_Close}.

The programmer must however be careful to never use the stream\index{stream pointer} pointer
after the blob has been closed, or after the connection object has
been closed or finalized\index{finalized}. The stream pointer should be nulled\index{nulled} when
it has outlived its usefulness, or allowed to fall out of scope.


\section{Blob Destruction}

To release a blob\index{releasing a blob}, you must use the Blob\_Unlink\index{Blob\_Unlink}
procedure call. Table~\ref{t:blbunlkx} lists the exceptions while the specification
is shown below:

\begin{Code}
procedure Blob_Unlink(
   DB :  in Connection_Type;
   Oid : in Row_ID_Type
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Blob\_Error       &  No such Oid\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Unlink Exceptions}\label{t:blbunlkx}
\end{table}

The following code releases the blob referenced in the example on
page \pageref{Example-code-with-OID-73763}.

\begin{Example}
declare
   C :   aliased Connection_Type;
   Oid : Row_ID_Type := 73763;
begin
   ...
   Blob_Unlink(C,Oid);
\end{Example}

\subsubsection{Generic\_Blob\_Unlink Procedure}

To use a strongly typed version of the Blob\_Unlink procedure, the
application programmer can instantiate from Generic\_Blob\_Unlink\index{Generic\_Blob\_Unlink}.
The instantiated function otherwise behaves exactly as the Blob\_Unlink
function. The instantiation parameters for Generic\_Blob\_Unlink are:

\begin{Code}
generic
   type Oid_Type is new Row_ID_Type;
procedure Generic_Blob_Unlink(
   DB :  in Connection_Type;
   Oid : in Oid_Type
);
\end{Code}

The following example shows how to instantiate the function:

\begin{Example}
declare
   type My_Oid_Type is new Row_ID_Type;
   procedure Blob_Unlink is new 
      Generic_Blob_Unlink(My_Oid_Type);
\end{Example}

\section{File and Blob Operations}

Blobs are very similar to files\index{files}. It should be no surprise
then that sometimes a file is imported\index{imported} into a blob,
or exported\index{exported} from a blob.

A file is imported into a blob with the Blob\_Import\index{Blob\_Import} call:

\begin{Code}
procedure Blob_Import(
   DB :       in     Connection_Type;
   Pathname : in     String;
   Oid :         out Row_ID_Type
);
\end{Code}

Blob\_Import returns the Oid of the newly created blob, that now contains
a copy of the file specified by the Pathname argument.

A blob's contents can be written out (exported) to a file with a call
to Blob\_Export\index{Blob\_Export}:

\begin{Code}
procedure Blob_Export(
   DB :       in Connection_Type;
   Oid :      in Row_ID_Type;
   Pathname : in String
);
\end{Code}

After a successful return from Blob\_Export, the file named by the
Pathname argument, contains a copy of the specified blob.
If any error in these import/export operations occur, the
exceptions listed in Table~\ref{t:blbxpx} occur.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name       &  Reason\\
         \hline 
         Blob\_Error          &  Import/export failed\\
      \end{tabular}
   \end{center}
   \caption{Blob\_Export Exceptions}\label{t:blbxpx}
\end{table}

Note that Blob\_Import creates a new blob if necessary. Blob\_Export
creates a new file if necessary.


\subsubsection{Generic\_Blob\_Import and Generic\_Blob\_Export Procedures}

To use strongly typed versions of the Blob\_Import and Blob\_Export,
the application programmer can instantiate from Generic\_Blob\_Import\index{Generic\_Blob\_Import}
and Generic\_Blob\_Export\index{Generic\_Blob\_Export} respectively. The instantiated procedure
otherwise behaves exactly as the Blob\_Import or Blob\_Export function.
The instantiation parameters for Generic\_Blob\_Import or Generic\_Blob\_Export
are:

\begin{Code}
generic
   type Oid_Type is new Row_ID_Type;
procedure Generic_Blob_Import(
   DB :       in     Connection_Type;
   Pathname : in     String;
   Oid :         out Oid_Type
);
\end{Code}

\begin{Code}
generic
   type Oid_Type is new Row_ID_Type;
procedure Generic_Blob_Export(
   DB :       in     Connection_Type;
   Oid :      in     Oid_Type;
   Pathname : in     String
);
\end{Code}

The following example shows how to instantiate the function:

\begin{Example}
declare
   type My_Oid_Type is new Row_ID_Type;
   procedure Blob_Import is new
      Generic_Blob_Import(My_Oid_Type);
\end{Example}


\chapter{Utility Functions} % Chapter 5

\section{To\_String Support}

To ease the job for programming, a number of builtin To\_String\index{To\_String} functions
are provided to allow conversion from the data type to its string
representation. The following To\_String functions are available with
the following builtin types (only one function requires a second argument):

\begin{Code}
function To_String(
   V : APQ_Boolean
) return String;
\end{Code}

\begin{Code}
function To_String(
   V : APQ_Date
) return String;
\end{Code}

\begin{Code}
function To_String(
   V : APQ_Time
) return String;
\end{Code}

\begin{Code}
function To_String(
   V : APQ_Timestamp
) return String;
\end{Code}

\begin{Code}
function To_String(
   V :  APQ_Timestamp;
   TZ : APQ_Timezone
) return String;
\end{Code}

\begin{Code}
function To_String(
   V : APQ_Timezone
) return String;
\end{Code}

\begin{Code}
function To_String(
   V : APQ_Bitstring
) return String;
\end{Code}

The following illustrates one example:

\begin{Example}
declare
   Ship_Date : APQ_Date;
begin
   Put({
   Put_Line(To_String(Ship_Date));
\end{Example}

\section{Generic To\_String Support}

Programs that make use of distinct types will require the use of generic
functions to perform To\_String\index{generic To\_String} conversions. The following generic
functions are available for instantiation:

\begin{Code}
generic
   type Val_Type is new Boolean;
function Boolean_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is range <>;
function Integer_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is mod <>;
function Modular_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <>;
function Fixed_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is digits <>;
function Float_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is delta <> digits <>;
function Decimal_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
function Date_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Day_Duration;
function Time_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
function Timestamp_String(
   V : Val_Type
) return String;
\end{Code}

\begin{Code}
generic
   type Val_Type is new APQ_Timezone;
function Timezone_String(
   V : Val_Type
) return String;
\end{Code}

The following example illustrates their use:

\begin{Example}
declare
   type My_Date_Type is new APQ_Timestamp;

   function To_String is new 
      Timestamp_String(My_Date_Type);

   Execution_Date : My_Date_Type;
begin
   ...
   Put("Program Execution Date: ");
   Put_Line(To_String(Execution_Date));
\end{Example}

\section{Conversion Generic Functions}

Sometimes a programmer must convert from a text format string into
another data type for manipulation. Several generic conversion \index{conversion functions} functions are
provided for the purpose (exceptions listed in Table~\ref{t:cvtx}):

\begin{Code}
generic
   type Val_Type is new Boolean;
function Convert_To_Boolean(
   S : String
) return Val_Type;
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
function Convert_To_Date(
   S : String
) return Val_Type; -- YYYY-MM-DD format
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Day_Duration;
function Convert_To_Time(
   S : String
) return Val_Type; -- HH:MM:SS format
\end{Code}

\begin{Code}
generic
   type Val_Type is new Ada.Calendar.Time;
function Convert_To_Timestamp(
   S : String  
) return Val_Type;  -- YYYY-MM-DD HH:MM:SS
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Invalid\_Format   &  The input value was not a proper value for the type\\
      \end{tabular}
   \end{center}
   \caption{Conversion Exceptions}\label{t:cvtx}
\end{table}

The following example illustrates some converions:

\begin{Example}
declare
   type Bool is new APQ_Boolean;
   type Birth_Date_Type is new APQ_Date;
   function To_Boolean is new Convert_To_Boolean(Bool);
   function To_Date is new Convert_To_Date(Birth_Date_Type);
   My_Bool : Bool;
   Elvis :   Birth_Date_Type;
begin
   ...
   My_Bool := To_Boolean("F");
   Elvis   := To_Timestamp("1957-01-08");
\end{Example}

\section{The Convert\_Date\_and\_Time Generic Function}

Sometimes the programmer needs the convenience of putting separate
date and time values together into a returned timestamp\index{timestamp}
value. For example the date of birth may be stored in one database
column\index{column}, while the time of birth is stored in another.
It may be necessary to work with a timestamp value instead, that contains
both of these components. To permit the use of strongly typed values\index{strongly typed values},
a generic function is provided for this purpose.

The generic specification for Convert\_Date\_and\_Time\index{Convert\_Date\_and\_Time} is:

\begin{Code}
generic
   type Date_Type is new Ada.Calendar.Time;
   type Time_Type is new Ada.Calendar.Day_Duration;
   type Result_Type is new Ada.Calendar.Time;
function Convert_Date_and_Time(
   DT : Date_Type;
   TM : Time_Type
) return Result_Type;
\end{Code}

The following example shows how to apply this function:

\begin{Example}
declare
   type My_Date_Type is new APQ_Date;
   type My_Time_Type is new APQ_Time; 
   type My_Timestamp_Type is new APQ_Timestamp;
   function To_Timestamp is new 
      Convert_Date_and_Time(
         Date_Type => My_Date_Type,
         Time_Time => My_Time_Type,
         Result_Type => My_Timestamp_Type);
   Some_Date :      My_Date_Type;
   Some_Time :      My_Time_Type;
   Some_Timestamp : My_Timestamp_Type;
begin
   ...
   Some_Timestamp := To_Timestamp(Some_Date,Some_Time);
\end{Example}

\section{The Extract\_Timezone Generic Procedure}

When a database table or result column provides a timestamp and timezone
together, it is sometimes necessary to extract\index{extract} these
components so that they can be manipulated separately. To permit the
use of application defined types, a generic procedure is provided.
The Extract\_Timezone\index{Extract\_Timezone} generic procedure is defined below,
while Table~\ref{t:xtzx} documents the exceptions:

\begin{Code}
generic
   type Date_Type is new Ada.Calendar.Time;
   type Zone_Type is new APQ_Timezone;
procedure Extract_Timezone(
   S :  in     String;
   DT :    out Date_Type;
   TZ :    out Zone_Type
);
\end{Code}

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Invalid\_Format   &  The input value was not a proper value for the type\\
      \end{tabular}
   \end{center}
   \caption{Extract\_Timezone Exceptions}\label{t:xtzx}
\end{table}

The following example shows how to apply this procedure:

\begin{Example}
declare
   type My_Date_Type is new APQ_Timestamp;
   type My_Zone_type is new APQ_Timezone;
   procedure Extract is new 
      Extract_Timezone(My_Date_Type,My_Zone_Type);
   Ex_Date :      My_Date_Type;  -{
   Ex_Zone :      My_Zone_Type;  -{
begin
   ...
   Extract("1957-01-08 01:13:45+04",Ex_Date,Ex_Zone);
\end{Example}

\chapter{Calendar Functions}

There is frequently the need in applications to separate out the hour\index{hour},
minute\index{minute} and second\index{second} from a time\index{time}
value. To make this easier, and to permit the continued use of strong
typing, the following generic functions are available:%
\footnote{It could be argued that these generic functions do not go the full
generic distance, because the return value types are standard types
only (types Hour\_Number, Minute\_Number and Second\_Number).%
}

\begin{Code}
generic
   type Time_Type is new Ada.Calendar.Day_Duration;
function Generic_Hour(
   TM : Time_Type
) return Hour_Number;
\end{Code}

\begin{Code}
generic
   type Time_Type is new Ada.Calendar.Day_Duration;
function Generic_Minute(
   TM : Time_Type
) return Minute_Number;
\end{Code}

\begin{Code}
generic
   type Time_Type is new Ada.Calendar.Day_Duration;
function Generic_Second(
   TM : Time_Type
) return Second_Number;
\end{Code}

The following example shows how to apply this procedure:

\begin{Example}
declare
   type Evt_Time_Type is new Ada.Calendar.Day_Duration;
   function Hour is new Generic_Hour(Evt_Time_Type); 
   function Minute is new Generic_Minute(Evt_Time_Type);
   Evt_Time : Evt_Time_Type;
   HH :       Hour_Number;
   MM :       Minute_Number;
begin
   ...
   HH := Hour(Evt_Time);
   MM := Minute(Evt_Time);
\end{Example}

\chapter{Decimal Support}

In order to support accurate number calculations, particularly for
financial work, the package APQ\-.PostgreSQL\-.Decimal\index{APQ.PostgreSQL.Decimal}
is available for the programmer to use. This package is based upon
the C source\index{C source} code extracted out of the PostgreSQL server.%
\footnote{Portions copyright (c) 1996-2001, The PostgreSQL Global Development
Group, and portions copyright (c) 1994, The Regents of the University
of California.%
} The decimal support\index{decimal support} is \emph{not} a floating
point\index{floating point} package, but does support approximately
1,000 digits worth of accuracy\index{accuracy}. Note that this is currently PostgreSQL\index{PostgreSQL}
specific code, and as such, it has not been reworked for general use
in databases like MySQL\index{MySQL}.


\section{Introduction}

The APQ\-.PostgreSQL\-.Decimal package is a binding to the extracted server
decimal code. This gives the Ada programmer access to the same numeric
support\index{numeric support} as used by the database engine to
sum columns etc. Because it is decimal\index{decimal} based, you will not have to
worry about representation issues for values like 0.3,%
\footnote{In binary floating point, the value 0.3 must be represented as 0.29999
repeat.} allowing for accurate sums and hash total calculations.


\begin{quote}
Special Note: The APQ\-.PostgreSQL\-.Decimal package is still under development,
and is subject to change. One of the most serious limitations at present
is the fact that assignment clobbers any prior concept of precision\index{precision}
and scale\index{scale} for the variable being assigned to. To overcome this, it
is possible that a future implementation of this package may provide
task safe storage to preserve the variable's precision and scale.
This can be done by saving the variable's precision and scale in task
safe storage at finalization time. When the Adjust primitive is later
called, the saved precision and scale can be restored and followed
by a call to the Constrain()\index{Constrain} function. This will implicitly keep the
variable within its configured precision and scale parameters.
\end{quote}


\section{Decimal Exceptions}

The APQ\-.PostgreSQL\-.Decimal binding can raise any of the exceptions
listed in Table~\ref{t:decx}.

\begin{table}
   \begin{center}
      \begin{tabular}{ll}
         Exception Name    &  Reason\\
         \hline 
         Decimal\_NaN      &  The value is ``Not a Number{}`` (or NULL)\\
         Decimal\_Format   &  Input does not represent a decimal number\\
         Decimal\_Overflow &  Value over/under-flowed\\
         Undefined\_Result &  Computation does not have a defined result\\
         Divide\_By\_Zero  &  An attempt to divide by zero occurred\\
      \end{tabular}
   \end{center}
   \caption{Decimal Exceptions}\label{t:decx}
\end{table}

\section{``Not a Number'' Operations}

A new Decimal\_Type\index{Decimal\_Type} value is initialized to NaN\index{NaN} (Not a
Number). This is a special status for the value, which can be assigned
to other Decimal\_Type values. When this status is detected in an
expression where a computation is being performed, the exception
Decimal\_NaN\index{Decimal\_NaN exception} is raised to indicate that no
valid result can be determined.


\section{The Decimal\_Type Type}

Decimal values are manipulated in a type, which is defined in terms
of a tagged\index{tagged} controlled\index{controlled} record:

\begin{Code}

   type Decimal_Type is new 
      Ada.Finalization.Controlled with private;

\end{Code}

These values are further defined by the following additional two attributes:

\begin{description}
   \item [Precision] specifies the precision of the decimal variable
   \item [Scale] specifies the scale of the decimal variable
\end{description}

\section{Is\_NaN Function}

To test if a value is ``Not a Number'', the Is\_NaN\index{Is\_NaN} function can
be used:

\begin{Code}
function Is_Nan(
   DT : Decimal_Type
) return Boolean;
\end{Code}

The following example shows how to apply the function:

\begin{Example}
declare
   D : Decimal_Type;
begin
   if Is_NaN(D) then
   Put_Line("D is NaN!");
   ...
\end{Example}

\section{Convert Procedure}

To import\index{import} a large decimal value from a String, the programmer may
invoke the Convert\index{Convert} procedure:

\begin{Code}
procedure Convert(
   DT :        in out Decimal_Type;
   S :         in     String;
   Precision : in     Precision_Type := 0;
   Scale :     in     Scale_Type := 2
);
\end{Code}

The arguments \emph{Precision} and \emph{Scale} arguments can be omitted
if you can accept the default values of 0 and 2 for the precision
and scale respectively. When \emph{Precision} is given as zero, the
value has no defined precision, and may grow to whatever size is necessary
to carry the result.%
\footnote{The source code indicates that the maximum precision is approximately
1,000 decimal digits.}

The following example shows how to initialize a Decimal\_Type from
a string:

\begin{Example}
declare
   D : Decimal_Type;
begin
   Convert(D,"12345.6789",0,4);
\end{Example}

\section{To\_String Function}

To make a Decimal\_Type value printable, you can call upon the To\_String\index{To\_String}
function:

\begin{Code}
function To_String(
   DT : Decimal_Type
) return String;
\end{Code}

The To\_String will return the string ``NULL''\index{NULL} if the value is
in the ``Not a Number'' state.

The following example shows how to use it in a Put\_Line call:

\begin{Example}
declare
   D : Decimal_Type;
begin
   ...
   Put_Line("D := " & To_String(D));
\end{Example}

\section{Constrain Function}

Sometimes it is desireable to constrain\index{constraining values}
a result to a particular precision and scale, while watching for overflows.
The Constrain function takes an input value, and returns a new value
with the values constrained to the given precision and scale\index{Constrain}:

\begin{Code}
function Constrain(
   DT :        in Decimal_Type;
   Precision : in Precision_Type;
   Scale :     in Scale_Type
) return Decimal_Type;
\end{Code}

The returned value is rounded (if necessary) to accomodate the \emph{Scale}\index{scale}
argument. The result must fit within the precision\index{precision} given by the \emph{Precision}
argument. The following example illustrates how the function is used:

\begin{Example}
declare
   A : Decimal_Type;
   B : Decimal_Type;
begin
   A := ...some calculation...;
   B := Constrain(A,10,2);  -- Precision 10, Scale 2
\end{Example}

\section{Expression Operations}

The Decimal\_Type values can be both assigned and computed with the
normal set of operators\index{operators} as shown in Table~\ref{t:decopr}.

\begin{table}
   \begin{center}
      \begin{tabular}{|c|c|}
         \hline 
         Operator             &  Description\\
         \hline
         +                    &  Add\\
         -                    &  Subtract\\
         {*}                  &  Multiply\\
         /                    &  Divide\\
         unary -              &  Negate\\
         =                    &  Equal\\
         <                    &  Less than\\
         <=                   &  Less than or equal\\
         >                    &  Greater than\\
         >=                   &  Greater than or equal\\
         \hline
      \end{tabular}
   \end{center}
   \caption{Decimal Operators}\label{t:decopr}
\end{table}

The following code fragment shows some Decimal\_Type expressions\index{expressions}
at work:

\begin{Example}
declare
   Watts_per_Hp : Decimal_Type; 
   Watts :        Decimal_Type;
   Volts :        Decimal_Type;
   Amperes :      Decimal_Type;
   Hp :           Decimal_Type;
begin
   Convert(Watts_per_Hp,"745.577",0,3); -- Watts/HP
   Convert(Volts,"120.0",0,1);
   Convert(Amperes,"7.0",0,1);
   Watts := Volts * Amperes;       -- # of Watts
   Hp := Watts / Watts_per_Hp;     -- # of Horsepower
\end{Example}

\section{Minimum and Maximum Values}

The Min\_Value\index{Min\_Value} and Max\_Value\index{Max\_Value} functions are available to the programmer
to conveniently return the minimum\index{minimum} or maximum\index{maximum}
value of a pair, respectively. These functions share the following
common calling signature:

\begin{Code}
function Min_Value(
   Left, Right : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Max_Value(
   Left, Right : Decimal_Type
) return Decimal_Type;
\end{Code}

The following example illustrates its use:

\begin{Example}
declare
   A, B :     Decimal_Type;
   Smallest : Decimal_Type;
begin
   Smallest := Min_Value(A,B);
\end{Example}

\section{Abs\_Value, Sign, Ceil and Floor Functions}

The functions in the following table are documented in this section\index{Abs\_Value}\index{Sign}\index{Ceil}
\index{Floor}:

\begin{Code}
function Abs_Value(
   DT : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Sign(
   DT : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Ceil(
   DT : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Floor(
   DT : Decimal_Type
) return Decimal_Type;
\end{Code}

The following example illustrates its use:

\begin{Example}
declare
   A, B :    Decimal_Type;
   Pos_Val : Decimal_Type;
begin
   Pos_Val := Abs_Value(A,B);
\end{Example}

\section{Sqrt, Exp, Ln and Log10 Functions}

The functions in the following table are documented in this section%
\index{Sqrt}\index{Exp}\index{Ln}\index{Log10}:

\begin{Code}
function Sqrt(
   X : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Exp(
   X : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Ln(
   X : Decimal_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Log10(
   X : Decimal_Type
) return Decimal_Type;
\end{Code}

The following example illustrates its use:

\begin{Example}
declare
   X :   Decimal_Type;
   L10 : Decimal_Type;
begin
   L10 := Log10(X);
\end{Example}

\section{The Log Function}

The Log\index{Log} function permits the caller to evaluate a logrithm $\log$
$_{\textrm{base}}$ x . It has the following calling requirements:

\begin{Code}
function Log(
   X, Base : Decimal_Type
) return Decimal_Type;
\end{Code}

The following example illustrates its use:

\begin{Example}
declare
   X :    Decimal_Type;
   Base : Decimal_Type;
   L :    Decimal_Type;
begin
   L := Log(X,Base);
\end{Example}

\section{The Power Function}

The Power\index{Power} function permits the caller to evaluate the expression x$^{\textrm{y}}$.
The function accepts the following calling arguments:

\begin{Code}
function Power(
   X, Y : Decimal_Type
) return Decimal_Type;
\end{Code}

The following example assigns to \emph{P}, the value x$^{\textrm{y}}$.

\begin{Example}
declare
   X : Decimal_Type;
   Y : Decimal_Type;
   P : Decimal_Type;
begin
   P := Power(X,Y);
\end{Example}

\section{The Round and Trunc Functions}

To round\index{round} or truncate\index{truncate} a Decimal\_Type
value, the application designer may call the Round\index{Round} and Trunc\index{Trunc} functions
respectively. They both accept the following calling arguments:

\begin{Code}
function Round(
   DT :    in Decimal_Type;
   Scale : in Scale_Type
) return Decimal_Type;
\end{Code}

\begin{Code}
function Trunc(
   DT :    in Decimal_Type;
   Scale : in Scale_Type
) return Decimal_Type;
\end{Code}

The following example assigns to \emph{R}, the rounded value of \emph{X},
to 2 decimal places:

\begin{Example}
declare
   X : Decimal_Type;
   R : Decimal_Type;
begin
   R := Round(X,2);
\end{Example}

\section{Builtin Decimal\_Type Constants}

The builtin decimal constants\index{decimal constants} are defined
as the following functions%
\index{Zero}\index{One}\index{Two}\index{Ten}\index{NaN}:

\begin{Code}

   function Zero return Decimal_Type;
   function One return Decimal_Type;
   function Two return Decimal_Type;
   function Ten return Decimal_Type;
   function NaN return Decimal_Type;

\end{Code}

The NaN function can be used to put a value into a ``Not a Number''
state. This doubles as setting the value to NULL\index{NULL}, for SQL query use.


\section{Using Decimal\_Types with Query\_Type}

Creating SQL\index{SQL} queries using the Decimal\_Type\index{Decimal\_Type} and retrieving values
from SQL queries has been made easy for the application programmer.
The NaN\index{NaN} state is used to represent a NULL\index{NULL} value. This eliminates the
need for the application programmer to define indicator values.

The Append procedure allows the programmer to build SQL queries with
Decimal\_Type values. The Value\index{Value} function, permits the programmer to
retrieve a column value into a Decimal\_Type variable (with or without
a NULL\index{NULL} value).


\subsection{Using Decimal\_Type with Append}

The Append procedure has the following specification:

\begin{Code}
procedure Append(
   Query : in out PostgreSQL.Client.Query_Type;
   DT :    in     Decimal_Type'Class;
   After : in     String := ""
);
\end{Code}

\subsection{Fetching Decimal\_Type Values}

A decimal value may be retrieved from a SQL query, using the Value
function:

\begin{Code}
function Value(
   Query : in PostgreSQL.Client.Query_Type;
   CX :    in Column_Index_Type
) return Decimal_Type;
\end{Code}

If the returned value for the column is NULL\index{NULL}, the value
returned will be in the NaN state. The following example illustrates
how to apply the Value\index{Value} function:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
   D : Decimal_Type := NaN;
begin
   ...
   Prepare(Q,  "SELECT QTY, ...");
   Append_Line("FROM ORDERS");
   Execute(Q,C);
   while not End_of_Query loop
      Fetch(Q);
      D := Value(Q,1);  -- Fetch Decimal_Type
   end loop;
   Clear(Q);
\end{Example}

\chapter{Generic Database Programming}

With APQ 2.0, the support of the MySQL database becomes available.
The future may allow APQ to support even more database technologies.
With this in mind, it becomes very desireable in some circumstances
to write applications in a database neutral way. Within this documentation,
we will use the term ``Generic Database Programming'' to describe
portable\index{portable} database code.

This chapter is about programming for databases generically. Given
that APQ is built using object oriented techniques (tagged\index{tagged} Ada95\index{Ada95} records),
it should be possible to leverage this in a way to write application
procedures once, and enjoy the flexibility of choosing or changing
the database technology used later. \Ref{Generic APQ.Result}
identified one aspect of generic database processing.


\section{Generic Connections}

For most routine database work, the only object that needs to be defined
up front, is the database connection. In APQ version 2.2 and later,
there are three concrete choices:

\begin{enumerate}
   \item APQ.PostgreSQL.Client.Connection\_Type
   \item APQ.MySQL.Client.Connection\_Type
   \item APQ.Sybase.Client.Connection\_Type
\end{enumerate}

Once the high level layer of the application chooses one of these
connection objects, and establishes a connection with the database,
the connection object may be passed around as parameters to procedures.
The recommended generic way to do this, is to pass the connection
as a APQ\-.Root\_Connection\_Type\-'Class\index{Root\_Connection\_Type'Class} parameter. See the following
example:

\begin{Example}
procedure MyApp(C : in out APQ.Root_Connection_Type'Class) is
begin
   ...
\end{Example}

The classwide parameter then permits any database connection object
to be passed as a parameter. The classwide attribute causes all operations
performed upon that object to be dispatching calls. By dispatching
on the object's primitives, you ensure that database specific operations
are carried out according to the type of database being used.


\section{Database Specific Code}

Due to the wide differences that sometimes exist between database
engines\index{engines}, it is sometimes necessary to take different course of action,
depending upon the database being used. For example, PostgreSQL\index{PostgreSQL} allows
a varchar(256)\index{varchar} column to be defined, where MySQL\index{MySQL} is limited to varchar(255)
instead.%
\footnote{MySQL requires you declare the type as TEXT if you need more than
255 characters.%
} 

To determine the database being used, use the Engine\_Of\index{Engine\_Of}
predicate\index{predicate} function. This primitive exists on both the Root\_Connection\_Type\index{Root\_Connection\_Type}
and Root\_Query\_Type objects. \Ref{Generic Database Engine_Of}
and \Ref{Generic APQ.Engine_Of} describe functions and examples for
this purpose.

Obviously, if you are only given a Root\_Connection\_Type'Class connection
argument to use, you cannot know in advance which Query\_Type\index{Query\_Type} object
to use. Make use of the New\_Query\index{New\_Query} factory\index{factory} function to create
one (See \Ref{Query_Type Factories}) or use cloning\index{cloning} 
(\Ref{Query_Type Cloning}) if you have an existing Query\_Type object
available.


\subsection{Row ID Values}\label{Portability Note for Row ID Values}

When designing a new system, it is important to plan for the use of
row ID\index{row ID} values. MySQL\index{MySQL} does not support them at all, while PostgreSQL\index{PostgreSQL}
encourages their use.%
\footnote{For example, a blob is identified by a Oid value, which is basically
a row ID.%
} MySQL encourages the use of serial values instead, which is a good
practice. For generic database programming you must plan for these
differences to reduce the amount of specialized code. For more information
about obtaining row ID values, see the \Ref{Command_Oid Function},
and \Ref{Portability Note for Row ID Values} for portability\index{portability}
notes.

Additionally, the assumptions about what constitutes a null row ID\index{null row ID}
must be scrutinized. Since different databases use different values
to represent ``no row'', you should make careful use of the APQ
Null\_Oid\index{Null\_Oid} function, rather than depend upon a particular
constant. See \Ref{Null_Oid Function} for information about
that.


\section{Data Types}

When writing generic database code it is important to choose your
datatypes\index{datatypes} very carefully. One example where this is important is when
using a PostgreSQL\index{PostgreSQL} timezone\index{timezone} type (APQ\_Timezone\index{APQ\_Timezone}).
While a timezone
variable can be used in MySQL\index{MySQL} specific code, it should be emphasized
that MySQL does not support timezone values within a TIMESTAMP\index{TIMESTAMP} database
column type. Sybase\index{Sybase} does not support timezones at all.

A similar problem exists with PostgreSQL bit string types (APQ\_Bitstring\index{APQ\_Bitstring}).
MySQL and Sybase do not support them. So if you want to write portable
code, stick to simple data types in your application. 

When you must make use of special database types, be prepared to specialize
the code somewhat, depending upon the database being used.


\subsection{Column Types}

Another area that is important to consider is the database column
\index{column types} types that are chosen for tables. Comparing the table in
\Ref{PostgreSQL SQL Data Types} and \Ref{MySQL Data Types}, the
reader can see that most columns can be declared in SQL using the
same column type declarations. However, there are some important differences.
For example, a SERIAL\index{SERIAL} column in PostgreSQL must be declared as an
INTEGER\index{INTEGER} type when using MySQL. For most applications, this is not
too much of an issue, because applications usually don't create and
drop tables. However, this can be an issue with temporary tables.

As noted in the prior section, MySQL also does not directly support
some data types such as the time zone value within a DATETIME\index{DATETIME} type.
If time zones must be supported, the writer may simply add a time
zone column declared in SQL as a SMALLINT\index{SMALLINT} value, and work with the
timezone separately.


\section{Pulling it All Together}

This section will examine a fairly trivial example of a generic database
procedure. It will make one exception for MySQL\index{MySQL}, so that the reader
will know how to work with database engine\index{engine} differences. Ideally, you
would want to avoid differences, where possible.

The example is a real world example. A procedure is required to fetch
the most recent stock price available on file, for a given security
(by ticker symbol). While there may be a price for the security on
the given day, if there is not one listed, the procedure is expected
to fall back to the most recent price available. The table being consulted,
is defined as follows:\label{PRICE_HIST Table Definition}

\begin{SQL}
CREATE TABLE PRICE_HIST (
    SECURITY   CHAR(10) NOT NULL,
    PRICE_DATE DATE NOT NULL,
    PRICE      REAL NOT NULL,
    PRIMARY KEY(SECURITY,PRICE_DATE)
);
\end{SQL}

Here is the package spec for the Prices module, which makes the procedure
Last\_Price available for use:

\begin{Example}
with APQ;
use APQ;
  
package Prices is
  
   procedure Last_Price(
      C :       in out Root_Connection_Type'Class;
      Security : in     String;
      Price :       out APQ_Double
   );
 
end Prices;
\end{Example}

Given any database connection, and a ticker symbol provided in argument
Security, the procedure Last\_Price is expected to lookup the most
recent stock price in the PRICE\_HIST table and return that price
in the Price argument. Here is the body of the package, written to
work with any database:

\begin{NumberedExample}
package body Prices is
   procedure Last_Price(
      C :        in out Root_Connection_Type'Class;\label{Ex:RootConn}
      Security : in     String;
      Price :       out APQ_Double
   ) is
      function Value is new Float_Value(APQ_Double);
  
      Q : Root_Query_Type'Class := New_Query(C);\label{Ex:QFact}
   begin
  
      Prepare(Q,     "SELECT SECURITY,PRICE_DATE,PRICE");
      Append_Line(Q, "FROM PRICE_HIST");
      Append(Q,      "WHERE SECURITY = ");
      Append_Quoted(Q,C,Security,Line_Feed);
      Append_Line(Q, "ORDER BY SECURITY,PRICE_DATE DESC");\label{Ex:OrBy}
 
      if Engine_Of(C) = Engine_MySQL then\label{Ex:EngOf}
         Append_Line(Q,"LIMIT 1");\label{Ex:Limit1_Again}
      end if;
 
      Execute(Q,C);
 
      begin
         Fetch(Q);
      exception
          when No_Tuple =>
             raise;    -- Indicates no price
      end;
 
      Price := Value(Q,3);
 
   end Last_Price;
 
end Prices;
\end{NumberedExample}

A few notes are in order here: The spec already with's and uses the
package APQ. So it is not repeated in the body of the package. The
Last\_Price procedure takes a Root\_Connection\_Type'Class
(line~\ref{Ex:RootConn} connection object type, so it can be supplied
with a MySQL or PostgreSQL database connection\index{connection} (Connection\_Type).

The New\_Query factory\index{factory} function (line~\ref{Ex:QFact}) is used to create
the correct Query\_Type object necessary to match the connection. It is
used to form and execute the query. The Prepare, Append\_line,
Append\_Quoted calls build up an SQL query, and then the type of the
database is queried by calling Engine\_Of (line \ref{Ex:EngOf}). If the
database being used is a MySQL database, the query is optimized
\footnote{One could also argue that it is {}``fixed'' here, since MySQL
insists that all row results of a query be fetched.} so that only one
row is returned by use of the extended SQL ``LIMIT 1''\index{LIMIT} clause
(line~\ref{Ex:Limit1_Again}).

Note that the ``ORDER BY''\index{ORDER BY} clause in line~\ref{Ex:OrBy} requires that
the sort order be descending (most recent dates first). Given that the
``ORDER BY'' clause specifies indexed columns, this retrieval should
be quick since a reverse index retrieval is possible (if the database
cannot do this, you should create a new index or fix the primary key to
be descending).

Since we are only interested in the most recent price (ie. one price),
only one Fetch call is made. This is not a problem for PostgreSQL,
but it is for MySQL if there there are more than one row (see 
\Ref{Fetch Limitations} to find out why). If the database is MySQL
the problem is addressed by adding to the query a MySQL extended clause
``LIMIT 1''\index{LIMIT}, to limit the results to one row (line~\ref{Ex:Limit1_Again}).

The price is then fetched from column 3 (PRICE) and the procedure
returns. If no rows are returned, we simply raise the APQ.No\_Tuple
exception here to keep the example simple. A finished application
would handle this in a more elegant way perhaps.

The important thing to recognize here is that there is nothing specific
to the type of database being used in this Prices package, except
for the MySQL work-around. The only APQ package being used is the
top level package APQ, and the root types for connection and query
types.

Here is a PostgreSQL main program:

\begin{Example}
with Ada.Text_IO;
with APQ.
with Prices;
  
use APQ, Prices, APQ.
  
procedure Price_PG is
   C : Connection_Type;
   P : APQ_Double;
begin
 
   Set_DB_Name(C,"investments");
   Connect(C);
 
   Last_Price(C,"RHAT",P);
   Put_Line("RHAT $" & APQ_Double'Image(P));
 
   Disconnect(C);
 
end Price_PG;
\end{Example}

Please notice the following points about the main program:

\begin{enumerate}
   \item The database specific package is with'ed as APQ.PostgreSQL.Client
         here to choose the database connection being used.
   \item The Connection\_Type object is declared in APQ.PostgreSQL.Client and
         derives from APQ.Root\_Connection\_Type.
   \item The database is chosen and a connection is established.
         \item The Last\_Price procedure is called, providing only the connection
         and the security's ticker symbol that the price is being sought for.
   \item The returned price P is then printed (albeit crudely)
   \item The application disconnects from the server and exits.
\end{enumerate}

The same main program using MySQL looks like this:

\begin{Example}
with Ada.Text_IO;
with APQ.
with Prices;
 
use APQ, Prices, APQ.
 
procedure Price_My is
   C : Connection_Type;
   P : APQ_Double;
begin
 
   Set_DB_Name(C,"investments");
   Connect(C);
 
   Last_Price(C,"RHAT",P);
   Put_Line("RHAT $" & APQ_Double'Image(P));
 
   Disconnect(C);
 
end Price_My;
\end{Example}

The only difference between this MySQL\index{MySQL} main program and the prior
PostgreSQL\index{PostgreSQL} main program, is the name of the package used (APQ\-.MySQL\-.Client).
APQ truly is the closest thing to database independance!


\section{Miscellaneous Portability Issues}

There are a number of other database portability issues that should
be born in mind. An incomplete list has begun in this document below:

\begin{itemize}
   \item temporary tables creation
   \item SELECT ... INTO TABLE ...
\end{itemize}

This list will grow with submissions and experience.
\footnote{Contributions are welcome.}


\subsection{Temporary Tables\label{Creating Temp Tables}}

Many databases allow the SQL programmer to create a temporary\index{temporary tables} table
prior to its use in the application. This temporary table is only
visible to the user of the established database connection. When the
database connection is closed or disconnected, the temporary table
is automatically discarded and its space recycled by the database
engine.

The difficulty that a generic database programmer needs to be aware
of is that some databases work differently. Normally, an application
would perform something like the following to create a temporary table
in the database session that required it:

\begin{SQL}
CREATE TEMP TABLE INTERMED_RESULTS (
   SECURITY  CHAR(10) NOT NULL,
   HOLDINGS  BIGINT NOT NULL
);
\end{SQL}

Subsequent to the successful creation\index{create temp table} of this temporary table, the
application would populate it and use it as necessary. The application
may even create indexes on the table after the table is populated,
to help performance in later stages of the table's use.

While this works for PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL}, the generic programmer
should be aware that this will not work on an Oracle\index{Oracle} database (when
APQ gets there some day). Oracle permits the same syntax, but operates
differently: Oracle only permits one CREATE TEMP TABLE\index{CREATE TEMP TABLE} operation to
be performed, in the same way that a permanent table is created. Once
created, the user implicitly gets access to the table upon demand.
Upon the first reference to the temporary table in a particular session,
you get a temporary table created, which is empty. You then populate
and use that temporary table without ever having to create it within
that particular session. When the session is over, the table's contents
are discarded.

So how do you plan for this? If the Engine\_Of\index{Engine\_Of} function
indicates Engine\_Oracle\index{Engine\_Oracle}, you must \emph{not} create the
temporary table during your database session. This will be done when
the permanent tables are created.%
\footnote{In many respects, this is perhaps the best time to declare and plan
for a temporary table.%
} For other database engines, you should create the temporary table
when you are about to use them in your application.

Perhaps the most sensible thing for temporary tables is to isolate
much of that work to stored\index{stored procedures} procedures. Your program can then just
invoke the stored procedure in a portable fashion.


\subsubsection{Indexes on Temporary Tables}

There is an additional piece of advice to consider when creating indexes
for temporary tables. For performance reasons, it is often best to
populate the temp table with no indexes\index{indexes} created. After the table has
been populated, indexes can then be efficiently added and dropped
as the needs arise.

In the Oracle case, these indexes are likely to be predefined as is
the declaration of the temporary table itself. So when creating indexes
for temporary tables, you should also probably test for Oracle in
the generic code. When using Oracle, you probably do \emph{not} want
to create or drop the index\index{index, create/drop}, as it will probably affect all users
of that temporary table definition.%
\footnote{The author has not verified this point, but the reader is encouraged
to do so.%
}

\subsection{SELECT ... INTO TABLE}

A number of database engines support a SQL syntax along the lines
of:

\label{SelectIntoTempTable}
\begin{SQL}
SELECT *
FROM MY_TABLE
WHERE ...
INTO TEMP TABLE TEMP123
\end{SQL}

The above SQL code performs the usual SELECT\index{SELECT INTO TEMP}, but places its results
into a temporary table named TEMP123. \footnote{One application
framework that the author is familiar with used a suffix of ``123'' to
denote the name of a temporary table.} Alternatively, databases will
also often permit:

\begin{SQL}
SELECT *
FROM MY_TABLE
WHERE ...
INTO TABLE RESULTS
\end{SQL}

This query places the results into a permanent table named RESULTS
(note that the keyword TEMP was dropped).

Both of these operations are very convenient for processing intermediate
results. However, database engines vary in their support. Neither
of these formats are supported by PostgreSQL or MySQL, but they are
supported by INFORMIX.

The SQL-99\index{SQL-99} way to perform this operation is specified as follows:

\begin{SQL}
INSERT INTO RESULTS
SELECT *
FROM MY_TABLE
WHERE ...
\end{SQL}

This syntax is supported by both PostgreSQL\index{PostgreSQL} and MySQL\index{MySQL} for permanent
tables.

There is no provision currently to create a temporary table on the
fly with syntax shown on page \pageref{SelectIntoTempTable}
using PostgreSQL or MySQL. So even SQL-99 syntax won't help you there.
You can only create a temporary table, and then use the INSERT INTO\index{INSERT INTO}
... SELECT syntax after the temporary table is created. But don't
forget the limitation in \Ref{Creating Temp Tables}.


\chapter{Troubleshooting}

There are several problems\index{problems} that can crop up in applications using
the APQ Binding. These problems usually fall into one of the following
categories:

\begin{itemize}
   \item PostgreSQL database server ``personality''
   \item The PostgreSQL libpq C library interface
   \item The MySQL client library
   \item Sybase libraries and/or interfaces file
   \item The APQ binding itself
\end{itemize}

The APQ Binding attempts to insulate the user as much as is practical
from the client library issues and the database server. However, some
issues still manage to poke through. This chapter is an attempt to
provide some useful advice for those people that are encountering
unexpected behaviour, using the APQ Binding.


\section{General Problems}

The following subsections provide general troubleshooting help with
APQ binding issues.


\subsection{Missing Rows After Inserts (PostgreSQL)}

The first step in identifying whether this section applies or not,
is to ask:

\begin{itemize}
   \item is a transaction\index{transaction} processing being used?
   \item or, is a transaction pending when it shouldn't be?
\end{itemize}

If the second bullet applies to you, then you need to correct the
logic in your program (but read on to find out why).

On the other hand, if you are purposely using transactions (first
case) and you are losing\index{losing rows} inserted row information, then it is likely
that you are suffering from an aborted transaction in PostgreSQL\index{PostgreSQL} (this
is PostgreSQL specific). It might also represent an APQ binding bug\index{bug},
but check first to make sure that you have not put PostgreSQL into
an ``abort state''\index{abort state} (ie. in a snit). This is unusal database behavior,
but the PostgreSQL group seems to be proud of it.

The APQ Binding should prevent aborted\index{aborted transactions} transactions from being left
unnoticed.%
\footnote{If however, the Abort\_State\index{Abort\_State} exception is never being raised, then
it is possible you have a PostgreSQL porting issue. If the PostgreSQL
notice message format changes, the APQ binding code will fail to recognize
the notification of an ``abort state'' from the database server.%
} When the database server notificaties the APQ binding that an {}``abort
state'' has been entered%
\footnote{After a duplicate key on insert error, for example.%
}, any further attempts to execute SQL queries or COMMIT WORK\index{COMMIT WORK} on that
connection, will raise the Abort\_State exception for PostgreSQL (see
also \Ref{In_Abort_State Function} and \Ref{Abort_State exception}).

One common reason this happens is when an application inserts\index{insert of rows} rows
into a table, and intercepts the SQL\_Error\index{SQL\_Error} exception. This exception
is caught because the application writer wants to ignore the insert
on a duplicate\index{duplicate key insert} key error. The difficulty here is that the PostgreSQL
database engine will enter an ``abort state'' after the failed
INSERT\index{INSERT} operation, regardless of how the application handles the exception.
The only recourse to recovery at this point is to rollback the transaction
with a call to Rollback\_Work (\Ref{Begin, Commit and Rollback Work functions}).

This brings up a question about the APQ Binding. Why doesn't the APQ
binding raise Abort\_State immediately after the failed INSERT\index{INSERT} operation
within a transaction? There are two reasons:

\begin{enumerate}
   \item The ``Abort State'' notice is provided to the APQ binding in the
         form of a callback.
   \item Processing SQL\_Error exception within a transaction implies an aborted
         transaction (for PostgreSQL only).
\end{enumerate}

Notices are received by the APQ binding by registering a callback
with the database server. As a result, it is not always possible to
know about the ``abort state''\index{abort state} when it might be critical to the
application. Even if the information is available, this may not always
be so in future versions of PostgreSQL\index{PostgreSQL} (timing may change).

The very fact that you've started a transaction with Begin\_Work and
you have encountered an SQL\_Error exception should tell you that
you must Rollback\_Work and recover (remember this is only for PostgreSQL).
So as the developer, you should be thinking:

$Abort\, State=Begin\, Work+SQL\, Error$

The APQ binding has been designed to avoid several SQL statements
from being executed and being ignored because the database server
is in this ``Abort State''. This is why the Execute and Commit\_Work
calls check for this and raise the Abort\_State\index{Abort\_State} exception. However,
the best advice is to not rely on this mechanism when programming
the logic of your application.


\subsection{Missing Time Data (Or Time is 00:00:00)}

You build a query to insert or update a row with date and time\index{time} information,
but only the date\index{date} is getting stored in the database. The time component
always reads midnight\index{midnight} (00:00:00). Or perhaps you provide a date and
timestamp as part of a WHERE\index{WHERE clause} clause, but it fails because only the
date value is being put into the query (the time component always
shows as midnight). You print out the variables using To\_String and
they show the correct values, as follows:

\begin{Example}
declare
   type My_Date_Type is new APQ_Timestamp;
   My_Date : My_Date_Type;
begin
   ...
   Put_Line(
      "My_Date='"
      & To_String(APQ_Timestamp(My_Date))
      & "'"
   );
\end{Example}

The above symptoms are the result of a common problem. This human
error is easy to make and is due to choosing the incorrect generic
procedure. Look for a generic instantiation statement like the following:

\begin{Code}

   procedure Append
      is new Append_Date(My_Date_Type);

\end{Code}

If your data type My\_Date\_Type holds time information, then
it is likely that you meant to code the following instead:

\begin{Code}

   procedure~Append
      is new Append_Timestamp(My_Date_Type);

\end{Code}

The error was choosing generic procedure Append\_Date\index{Append\_Date} over the correct
Append\_Timestamp\index{Append\_Timestamp} routine.

A similar mistake can be made choosing between Encode\_Date\index{Encode\_Date} and Encode\_Timestamp\index{Encode\_Timestamp}
generic procedures. So watch for these subtle differences!


\subsection{Exception No\_Tuple}

If you are having the exception No\_Tuple\index{No\_Tuple} being raised when you don't
think it should be, then check to see if the following apply:

\begin{itemize}
   \item Are you using MySQL\index{MySQL}?
   \item Do you use the End\_of\_Query\index{End\_of\_Query} function calls?
\end{itemize}

If you do, then you need to look for any code calling End\_of\_Query,
particularly loops:

\begin{Example}
   while not End_of_Query(Q) loop
      Fetch(Q);
      ...
   end loop;
\end{Example}

This type of code works well for PostgreSQL\index{PostgreSQL}, but may be problematic
with some other databases (MySQL has a problem with this). Restructure
your code to eliminate the calls to End\_of\_Query (this call is now
considered \emph{obsolete} within APQ). \Ref{End_of_Query}
describes the problem in greater detail. Restructure the loop to something
like the following:

\begin{Example}
loop
   begin
      Fetch(Q);
   exception
      when No_Tuple =>
         exit;
   end;
   ...
end loop;
\end{Example}

\subsection{Null Values}

If you are using Sybase\index{Sybase} and experiencing a problem where you are receiving
a Null\_Value\index{Null\_Value} exception when there should be a value, then check to
make sure that you have called Fetch\index{Fetch}. MySQL and PostgreSQL will raise
No\_Result\index{No\_Result} when this happens. Sybase however, will appear to APQ as
holding row results (which it might be), but APQ will not realize
that Fetch has not yet been called. The Sybase library will then return
a NULL\index{NULL} value if an attempt to get a column value is made, without
a prior call to Fetch.

Forgetting to call Fetch is easy to do when you code a SELECT\index{SELECT} to return
one row with the help of a primary key reference in a WHERE\index{WHERE clause} clause.
Since you are expecting one row to be returned, you will not code
it as part of a traditional loop. So it is human nature to forget
to code the call to Fetch after the Execute call. The following example
might be typical of this:

\begin{Example}
   Prepare(Sy_Q,     "SELECT PUB_ID,PUB_NAME,CITY,STATE");
   Append_Line(Sy_Q, "FROM PUBLISHERS");
   Append(Sy_Q,      "WHERE PUB_ID = ");
   Append_Quoted(Sy_Q,Sy_C,Pub_Id);
   Execute(Sy_Q,Sy_C);
   Fetch(Sy_Q);      -- Easy to forget
\end{Example}

\subsection{Database Client Problems}

If problems with the database engine begin to occur after a particular
query, look for the following:

\begin{itemize}
   \item Are you using MySQL\index{MySQL}?
   \item Are your doing a SELECT\index{SELECT}, or otherwise returning row results?
   \item Is your Query\_Type object in Sequential\_Fetch mode?
   \item Is your code fetching all row data?
\end{itemize}

This problem may occur with MySQL\index{MySQL}, since the client library for MySQL
requires that all row result data be fetched. Failure to fetch all
rows may cause a backlog in communication with the database server
and cause strange behaviour or errors. Check the Query\_Type fetch
mode.


\subsection{Client Performance or Memory Problems}

Check to see if the following apply:

\begin{itemize}
   \item Are you using MySQL\index{MySQL}?
   \item Are you doing a SELECT\index{SELECT} or otherwise returning large row sets?
   \item Is your Query\_Type object in Random\_Fetch\index{Random\_Fetch} mode? 
\end{itemize}

If the above are true, then it is possible you have formed a query
that has generated a large row set. Since the default for the MySQL
Query\_Type object is for Random\_Fetch mode, the APQ library calls
upon mysql\_store\_result() to fetch all of the result set into the
client's memory for random access. For reasonable sized sets of rows,
this works well, but for larger results, this can be very expensive
and may run your application out of memory.

Consider the PRICE\_HIST table like the one discussed on page \pageref{PRICE_HIST Table Definition}.
For MySQL, if you fail to include the LIMIT 1 clause, and your Query\_Type
object uses the default Random\_Fetch mode, you could easily find
your application selecting the entire history of one security into
your application client memory! If you have several years of price
history for that security, your application may be destined to run
out of memory the first time that query is run.

When using the MySQL database, you must consider the following:

\begin{itemize}
   \item MySQL fetches in Random\_Fetch mode must guarantee a \emph{reasonably
         small result set} (use the LIMIT clause if necessary).
   \item MySQL fetches in Sequential\_Fetch mode must fetch \emph{all} row
         data
\end{itemize}

Unless otherwise noted, you probably do not need to be concerned about
this. PostgreSQL\index{PostgreSQL} for example, does not require all row data to be
fetched. However, if there are ways to restrict the row set, this
may improve database server performance.


\subsection{Can't Find Existing Table Names}

Some databases use caseless\index{caseless} references to database objects, while
others are case\index{case sensitive} sensitive (MySQL can be either). If you are using
MySQL and experiencing problems, one solution is to configure the MySQL parameter:

\begin{Code}

   [mysqld]
   set-variable = lower_case_table_names=1

\end{Code}

By default, MySQL distinguishes
between table names PRICE\_HIST, Price\_Hist, and price\_hist for
example. Setting the parameter true (1), causes all table names
to be lowercased (effectively caseless)\index{caseless table names}.

The another approach is to check the SQL case policy\index{case policy} being used. APQ
can work with MySQL in Lower\_Case, Upper\_Case or Preserve\_Case
mode. The last choice only makes sense of course, if the SQL text
in the program is correct.

The suggested approach is to configure lower\_case\_table\_names=1
(as shown above) and to Set\_Case(C,Upper\_Case). Uppercase\index{uppercase} is easier
to read in the trace logs, since the SQL stands out from the other trace
information.

If you are using Sybase\index{Sybase}, you cannot change the server. This means
that either a Upper\_Case or Lower\_Case policy has to work for you,
or you have to use exact case\index{exact case} for SQL code in the Ada code. It is
possible to use a Lower\_Case policy most of the time, and make exceptions
where they are required. The following shows how to make exceptions
for a table name only:

\begin{Example}
declare
   C : Connection_Type;
   Q : Query_Type;
begin
   Prepare(Q,"SELECT DESCRIPTION");
   Append(Q,"FROM ");
   Set_Case(Q,Preserve_Case);
   Append(Q,"Part_Info",Line_Feed);
   Set_Case(Q,Lower_Case);
   Append_Line(Q,"WHERE ...");
   ...
   Execute(Q,C);
\end{Example}

In the example presented, the case policy\index{case policy} was changed temporarily
while building the query. Here the table name Part\_Info will have
its case preserved, even though it is not a quoted string\index{quoted string}. The example
assumes here that the normal policy is Lower\_Case. 

Note however, that any case policy change in the Query\_Type object
is lost once Execute is called. An example will clarify this. Assume
from our example above, two things:

\begin{enumerate}
   \item The case policy in effect in the connection object C, is Lower\_Case
         (all SQL text is lowercased except where case must be preserved).
   \item Assume that the second Set\_Case(Q,Lower\_Case) call in the example
         code was commented out (the policy for Q is left at Preserve\_Case)
\end{enumerate}

If the above two assumptions are true, then upon return from the Execute(Q,C)
call, the Query\_Type object would now hold the case policy of Lower\_Case
(this came from Connection\_Type). Even after you call Clear, or Prepare
and start a new query, this is the SQL case policy that is now in
effect for Q.


\section{Blob Related Problems}

Blob operations on a database can be tricky to get right. The following
subsections provide some assistance with blob related issues.


\section{Blob\_Create and Blob\_Open Fails}

You have written what seems like a simple piece of code that creates
a blob, and then writes some data to it. It couldn't possibly fail
on paper, but it does when you run it. Or you are wondering why that
Blob\_Open\index{Blob\_Open failures} call keeps failing, because you are certain that the OID
of that blob surely does exist. These are both symptoms of the same
problem!

\begin{quote}
   \emph{``All blob operations in PostgreSQL must be performed within
      a transaction''}
\end{quote}

Repeat it to yourself again. It is too easy to forget this fact!

Unless you have started a transaction on the connection that you are
using, \emph{all blob operations will fail}. They will only succeed within
a transaction\index{transaction}. Furthermore, make certain your application commits\index{commit}
the changes to your blob, after they have been performed successfully.
Otherwise your application may fall prey to the default actions of
PostgreSQL, which may be to rollback\index{rollback} your changes.%
\footnote{Check your PostgreSQL documentation to determine what the default
transaction action is for your version of PostgreSQL database.}


\section{Blob I/O Buffering Bugs Suspected}

If you have good reason to believe that the APQ binding software%
\footnote{Only APQ versions 1.2 and later have buffered blob I/O.%
} has a bug\index{bug} in its buffered\index{buffered blob I/O} blob I/O, you can disable blob I/O buffering.
This is done by specifying a value of zero for the Buf\_Size argument
in the Blob\_Open and/or Blob\_Create calls that you are troubleshooting.
Be prepared to accept a large degradation in performance when specifying
unbuffered I/O this way. The performance\index{performance} is especially poor when array
I/O is performed.

Another possibility might be that you need to call upon Blob\_Flush\index{Blob\_Flush}
at strategic points in your application. While the buffering algorithms
used are such that you should not need to worry about this, it is
worth investigating when problems exist. 

Note also that multiple write access to the same blob is definitely
\emph{not} supported by APQ.


\section{Transaction Problems}

The following subsections deal with transaction problems that may
occur with application termination.


\subsection{Abnormal Termination of Transactions}

The APQ binding is designed to commit or rollback a transaction when the
Connection\_Type object finalizes. The default behavior of the
Connection\_Type is to ROLLBACK WORK\index{ROLLBACK WORK}, when the object finalizes\index{finalizes}%
\footnote{Provided that the Connection\_Type object is connected to the
database at the time of finalization.}. Consequently, if your program
raises an uncaught exception (perhaps Program\_Error or
Constraint\_Error), the Connection\_Type object will finalize\index{finalize} and
rollback\index{rollback} the transaction on you. \footnote{Unless you have changed the
default setting for the object. } If this is undesired behaviour, then
check out the Set\_Rollback\_On\_Finalize primitive in section
\Ref{Set_Rollback_On_Finalize Procedure}.


\subsection{Aborted Applications}

The APQ binding can only perform the default COMMIT/ROLLBACK action
(see \Ref{Set_Rollback_On_Finalize Procedure}) if the Connection\_Type
object is permitted to have its Finalize\index{finalize} primitive called. If the
process under UNIX for example, is terminated with a signal (by the
kill(1)\index{kill(1) command} command), the objects within your application may not experience
a Finalize call, because normal Ada shutdown procedures were not invoked.%
\footnote{There are Ada95 ways to deal with UNIX signals, which permit an orderly
Ada shutdown of your application. However, a kill -9 prevents any
action at all from being performed by the application!%
} If this is the reason for your problem, then you have two courses
of action:

\begin{itemize}
   \item Commit/Rollback explicitly in the program (prior to receiving a signal)
   \item Avoid signalling the application
   \item Add signal\index{signal handling} handling capability to your Ada application, to permit
         an orderly application shutdown
   \item Not use kill -9, which prevents any application recovery or notification
\end{itemize}

The choice is generally up to the application designer. Whenever possible
however, where it is important, the application should perform its
own explicit commit or rollback operation.

Note however, that if the Connection\_Type object is not permitted
to finalize\index{finalize} successfully on its own, the database software itself
has default procedures for dealing with disconnected sessions. Some
databases will rollback transactions if the socket/pipe connection
to the server is disconnected. Others will commit. You'll need to
check your server documentation and configuration to sort that one
out.


\section{SQL Problems\label{SQL Problems}}

If you are experiencing SQL problems that you don't understand, the
quickest way to inspect what is really going on is to use the APQ
trace\index{trace facility} facility. The documentation for the SQL trace facility is given
in \Ref{Trace Facilities}. So RTFM.


\subsection{Tracing SQL}

Where your Connection\_Type connects to the database, add a call to
Open\_DB\_Trace as follows:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   Connect(C);
   Open_DB_Trace(C,"trace_file.txt",Trace_APQ);
\end{Example}

Without adding another line of code, every SQL interaction will be
captured to trace\_file.txt, which you can inspect when the application
completes.%
\footnote{Note however that the tracing facilities are not task (thread) safe.
If your application uses tasking, then disable tracing in the tasks
or avoid using APQ in more than one task.%
}


\subsection{Too Much Trace Output}

If your application performs so many SQL operations that the trace
file becomes too large, then disable\index{disable tracing} the tracing until you get to
a strategic point in the program:

\begin{Example}
declare
   C : Connection_Type;
begin
   ...
   Connect(C);
   Open_DB_Trace(C,"trace_file.txt",Trace_APQ);
   Set_Trace(C,False);  -- Disable trace for now..
   ...
   Set_Trace(C,True);   -- Start tracing now
\end{Example}

The overhead of the Set\_Trace primitive is light, unless you have
selected Trace\_libpq or Trace\_Full (these add the overhead of invoking
libpq functions PQtrace() and PQuntrace()). Light overhead permits
you to use Set\_Trace within a loop without severe penalty, to gather
only the information you need.


\subsection{Captured SQL Looks OK}

If the SQL code captured in \Ref{SQL Problems} looks OK,
but the database engine is still reporting a problem, then try the
following:

\begin{enumerate}
   \item Create a capture file using Trace\_APQ (or use the current one you
         have).
   \item Edit (cut) out the portion of the SQL queries in the capture file
         that you are having difficulty with.
   \item Use the database interactive SQL command (psql for PostgreSQL) and
         replay the extracted problem SQL queries.
   \item Edit SQL query and repeat step \#3 as necessary until you discover
         your error.
\end{enumerate}

This allows you to experiment with the SQL text as your applicaton
created it. Once you achieve success with psql, you can then go back
and correct your application to form the query correctly.


\subsection{You Want to Report a Problem to PostgreSQL}

If you want to report a trace file in terms that the PostgreSQL people
understand, simply choose the Trace\_libpq trace mode when creating
a trace file. Then send them the trace file with a description of
the problem.


\subsection{Missing Trace Information}

The trace information is collected at the Connection\_Type object
level. Check to see if you have more than one Connection\_Type object
involved. If so, make sure you set the appropriate trace settings\index{trace settings}
on the connections that you want to collect trace information for.
Different instances of a Connection\_Type object should write its
traces to different files.

Note also, that when a Connection\_Type object finalizes\index{finalizes}, its trace
file is closed.


\section{Cursor Related Problems}

To use a cursor\index{cursor} you generally need an SQL phrase of the form\index{WHERE CURRENT OF}:

\begin{SQL}

   WHERE CURRENT OF <Cursor_Name>

\end{SQL}

Obviously, the APQ function primitive Cursor\_Name\index{Cursor\_Name} is expected to
provide this name. But does this function primitive seem to raise
the exception \emph{No\_Results}\index{No\_Results} for you? If so, you've probably supplied
the wrong Query\_Type object to the function Cursor\_Name.

Review the test program on page \pageref{Cursor Example Program},
where you see the statement:

\begin{Example}

   Append_Line(Q2,"WHERE CURRENT OF " & Cursor_Name(Q));

\end{Example}

There are two Query\_Type objects being used:

\begin{enumerate}
   \item Q for the cursor fetch (outer query)
   \item Q2 for the inner SQL query (the UPDATE)
\end{enumerate}

When coding this statement, it is very easy to type Q2 for Cursor\_Name
argument, instead of Q.%
\footnote{The author made this very mistake the first time the example program
was written.%
} However, the cursor name is only available for the outer query\index{outer query} (the
one with the cursor and cursor results). So be certain to carefully
distinguish between the inner and outer query objects.


\section{Connection Related Problems}

If you are experiencing trouble establishing a connection to the database
itself, then there are a number of environment\index{environment} related issues.


\subsection{PostgreSQL Connections}

A number of environment variables affect a PostgreSQL database connection:%
\footnote{Check your PostgreSQL documentation for the final word on this subject.%
}

\begin{description}
   \item [PGHOST]Host name of the database server
   \item [PGPORT]IP port number or UNIX socket pathname of the database server
   \item [PGDATABASE]Database name within the database server
   \item [PGUSER]Database user name
   \item [PGPASSWORD]Database password
   \item [PGREALM]Kerberos realm for the database server
   \item [PGOPTIONS]Database server options
\end{description}

Any of these connection mode parameters that are not configured in
the application are defaulted to the ones defined by the above environment
variables. If you are experiencing trouble, make certain that your
variables are \emph{exported}\index{exported variables}. In many shells, like the Bourne\index{Bourne shell} and
Korn\index{Korn shell} shells,%
\footnote{I won't encourage anyone here to use the csh.%
} this is done as follows (for the PGHOST\index{PGHOST} variable):

\begin{Example}

   export PGHOST

\end{Example}

Some shells, like the Korn shell and the GNU bash\index{bash shell, GNU} shell, allow multiple
variable names to be listed at once:

\begin{Example}

   export PGHOST PGPORT PGDATABASE PGUSER

\end{Example}

Once you have the environment configured correctly, you should be
able to access the database with the PostgreSQL psql\index{psql} command. If the
psql%
\footnote{Do a ``man psql'' for details about the psql client command.%
} command still fails, then you may need to revisit your environment
variable settings or possibly even the database server configuration.%
\footnote{Check the security aspects of your connection first.%
}


\subsubsection{PostgreSQL UNIX (Local) Connections}

The way that the local socket\index{local socket} is specified for PostgreSQL seems to
have changed with its different releases. Make sure you choose the
correct Set\_Port\index{Set\_Port} procedure to specify the local UNIX socket. Use
the Set\_Port that accepts a string argument. The string indicates
that a local UNIX connection is required. PostgreSQL 7.3.5 and later
(unless it has changed again), requires only the ``number'' to
specify the local socket. For example, if you ``netstat -na'' command
shows the following:\footnote{The output lines have had the RefCnt
and Flags columns removed to allow the lines to fit the space
available.}

\begin{NumberedExample}
$ netstat -na --unix
Active UNIX domain sockets (servers and established)
Proto  Type    State         I-Node Path
unix   DGRAM                 2086   /dev/log
unix   STREAM  LISTENING     2937   /var/run/mysqld/mysqld.sock
unix   STREAM  LISTENING     2942   /tmp/.s.PGSQL.5432\label{Ex:5432}
unix   STREAM  CONNECTED     3363
unix   STREAM  CONNECTED     3362
unix   DGRAM                 3138
...
\end{NumberedExample}

From this display, you can see that a database connection is available
with UNIX\index{UNIX socket} socket /tmp/.s.PGSQL.5432 (line~\ref{Ex:5432}). For Set\_Port, you only need
to supply the last numerical part, namely ``5432'' (which happens
to match the default IP port number). So to specify a UNIX socket
connection for this, you would code:

\begin{Example}

   Set_Port(C,"5432");

\end{Example}

Note especially, that the number must be in a \emph{string} to cause
a UNIX\index{UNIX socket} local\index{local socket} socket to be used. If you specify an integer costant,
a TCP/IP\index{TCP/IP socket} socket will be used, which uses the IP port number you specified.


\subsection{MySQL Connections}

APQ does not currently look for environment variables for MySQL.\footnote{although changes to MySQL are possible}
If you suspect environmental influences, check the MySQL C client library
documentation for conditions where the environment may be consulted.

A successful MySQL connection must have:

\begin{enumerate}
   \item A designated host name or address for the database server\index{host name}
   \item A port number\index{port number}
   \item Userid\index{userid} and password\index{password} (or ``'')
   \item Options (only if necessary)\index{options}
\end{enumerate}

Any supplied instance information is ignored.


\subsection{Sybase Connections}

APQ itself does not currently look for environment variables for Sybase\index{Sybase}.
The Sybase client libraries \emph{probably} do, if the variables exist.
Check the Sybase documentation (\emph{todo: check documentation for
influencing environment variables that are believed to exist}).

A successful Sybase connection must have:

\begin{enumerate}
   \item A designated instance name (Set\_Instance)\index{Set\_Instance}
   \item A userid\index{userid} and password\index{password} (or {}``'')
   \item Options (only if necessary)\index{options}
\end{enumerate}

Sybase ignores the host name/address and port information. The database
name is only important once the connection has been established. See
the Sybase specific notes about Set\_DB\_Name in \Ref{Context_Setting_Operations}.

The instance\index{instance name} name must exist in the local hosts \emph{interfaces}
file. In most cases this file can be found in /opt/sybase/interfaces
(\$SYBASE/interfaces) on UNIX platforms or possibly C:\textbackslash{}opt\textbackslash{}sybase\textbackslash{}ini\textbackslash{}sql.ini
(\%SYBASE\%\textbackslash{}ini\textbackslash{}sql.ini) on windows
(depending upon where it was installed). There may be exceptions to
this rule in more advanced Sybase configurations.


\subsection{Sybase Disconnect Problems}

If you experience a APQ.Not\_Connected\index{Not\_Connected} exception
in one of the following scenarios:

\begin{itemize}
   \item When the Connection\_Type object is finalized\index{finalized}
   \item When Disconnect is called on the Connection\_Type object
\end{itemize}

then look for Query\_Type objects that are still hanging onto query
results. This most often happens in a program where the Connection\_Type
object and Query\_Type objects are declared together and the Connection\_Type
object finalizes\index{finalizes} first. The solution is to either arrange it so that
all Query\_Type objects finalize first, or clear the query results
explicitly by calling Clear, prior to disconnecting or finalizing
the connection. For example if Q is the Query\_Type object and C the
connection, then the following sequence will ensure that the disconnect
(or finalize) will always succeed\index{Clear}:

\begin{Example}

   Clear(Q);      -- Release query results

   Disconnect(C); -- Disconnect (or finalize)

\end{Example}

\subsection{Sybase Options}

APQ permits the application developer to set various Sybase\index{Options} server
options. Some of these are known to create problems for APQ. Rather
than dictate policy for the developer, APQ gives you full access to
the Sybase options. Clearly some options should be avoided when using
APQ.

One such option is the following:

\begin{Example}

   Set_Options(C,"SHOWPLAN=TRUE"); -- CS_OPT_SHOWPLAN

\end{Example}

This option setting seems to do something strange to the underlying
Sybase connection after it is set. APQ has been observed raising Program\_Error\index{Program\_Error}
when other exceptions were supposed to have been raised. Unless you
know what you are doing, you seem to be well advised to stay clear
of this option when using APQ for Sybase.

The developer should also avoid using any Sybase options that change
the way the date is formatted. APQ functions look for dates to be
in a specific format so that they can be converted into APQ data types.


\subsection{Connection Cloning Problems}

If the original Connection\_Type object connects OK, but the Connect
clone\index{clone} call fails, then it could be that the network has gone bad since
the original connection was made. If exceptions other than Not\_Connected
are being raised, then check that:

\begin{itemize}
   \item Make sure the parameters are in the correct order in the Connect call.
   \item Make certain that the connected object, is indeed connected.
   \item Make certain that the new object is not already connected.
   \item Make sure you haven't exceeded the number of allowed database server
         connections
\end{itemize}

\subsection{Connection Tracing}

Problem: Your first Connection\_Type object is tracing to a file successfully,
but the cloned\index{cloned} Connection\_Type object is not.

Reason: Cloned connections do not have the trace\index{cloned trace} file parameters cloned.
This was a compromise to make APQ more portable to other platforms
that may not share files well.

Solution: Configure the cloned connection to trace to a file separate
from the original connection, after the clone operation is complete.


\appendix
\chapter{PostgreSQL Credits}

\section*{PostgreSQL Decimal C Sources}

PostgreSQL Database Management System (formerly known as Postgres,
then as Postgres95)

\begin{itemize}
\item Portions Copyright (c) 1996-2001, The PostgreSQL Global Development
Group
\item Portions Copyright (c) 1994, The Regents of the University of California
\end{itemize}
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose, without fee, and without a written
agreement is hereby granted, provided that the above copyright notice
and this paragraph and the following two paragraphs appear in all
copies.

IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.

THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER
IS ON AN ``AS IS'' BASIS, AND THE UNIVERSITY OF CALIFORNIA
HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
OR MODIFICATIONS.


\section*{Modification Notice}

The numeric C routines required extensive interface modifications
for use in this APQ Binding. These modified C sources were extracted
from the PostgreSQL server project. No guarantee is made with regard
to the quality of these modifications.


\section*{Contributor Notice}

In no event shall the author or contributors to the APQ Binding be
liable to any party for any cause that the modified PostgreSQL software
may cause or contribute to.


\chapter{APQ License}


\section*{Scope of the APQ Binding License}

The {}``APQ Binding'' license covers those software modules not
provided by or extracted from the PostgreSQL database software (such
as the Decimal C source modules). The APQ license does not cover database
products themselves that APQ binds to.


\section*{APQ Binding License}

The APQ Binding used to be covered under a dual-license arrangement. This
was reflected in the file name COPYING. The following two licenses
were available:

\begin{enumerate}
   \item The Ada Community License (ACL).
   \item The GNU Public License 2 (GPL2)
\end{enumerate}

This dual-license arrangement was to allow use of the package both with GPL programs
and non GPL programs. This can be achieved by using a single license now, and thus APQ
has changed it's license to GMGPL.

Please see pages \pageref{gmgpl} and \pageref{gpl} for more information.


\section*{Patents}

The author is not aware of any patent infringements made by
the APQ software. However the author makes \emph{absolutely no warrante}
about any possible patent infringements.

You are encouraged to lobby against any kind of software patents, since
software patents today do not serve the public's best interest.
Companies and individuals are using software patents to
legally extort from other companies and individuals. This is not in
the spirit of the original patent legislation and works against
all reasonable public interests.

\chapter{GNAT Modified GPL}
\label{gmgpl}


\begin{quote}
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.

As a special exception, if other files instantiate generics from
this unit, or you link this unit with other files to produce an
executable, this unit does not by itself cause the resulting
executable to be covered by the GNU General Public License. This
exception does not however invalidate any other reasons why the
executable file might be covered by the GNU Public License.
\end{quote}

\chapter{GNU Public License}
\label{gpl}

\section*{GNU GENERAL PUBLIC LICENSE Version 2, June 1991}

\begin{quote}
Copyright (C) 1989, 1991 Free Software Foundation,

Inc. 59 Temple Place, Suite 330, Boston, 

MA 02111-1307 USA

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
\end{quote}

\subsection*{Preamble}

The licenses for most software are designed to take away your freedom
to share and change it. By contrast, the GNU General Public License
is intended to guarantee your freedom to share and change free software--to
make sure the software is free for all its users. This General Public
License applies to most of the Free Software Foundation's software
and to any other program whose authors commit to using it. (Some other
Free Software Foundation software is covered by the GNU Library General
Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price.
Our General Public Licenses are designed to make sure that you have
the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get
it if you want it, that you can change the software or use pieces
of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone
to deny you these rights or to ask you to surrender the rights. These
restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis
or for a fee, you must give the recipients all the rights that you
have. You must make sure that they, too, receive or can get the source
code. And you must show them these terms so they know their rights.

We protect your rights with two steps:

\begin{enumerate}
   \item copyright the software, and
   \item offer you this license which gives you legal permission to copy, distribute
      and/or modify the software.
\end{enumerate}

Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on,
we want its recipients to know that what they have is not the original,
so that any problems introduced by others will not reflect on the
original authors' reputations.

Finally, any free program is threatened constantly by software patents.
We wish to avoid the danger that redistributors of a free program
will individually obtain patent licenses, in effect making the program
proprietary. To prevent this, we have made it clear that any patent
must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification
follow.


\section*{GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION
AND MODIFICATION}


\paragraph{0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The ``Program'',
below, refers to any such program or work, and a ``work based
on the Program'' means either the Program or any derivative
work under copyright law: that is to say, a work containing the Program
or a portion of it, either verbatim or with modifications and/or translated
into another language. (Hereinafter, translation is included without
limitation in the term ``modification''.) Each licensee
is addressed as ``you''.}


\paragraph{Activities other than copying, distribution and modification are
not covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the Program
(independent of having been made by running the Program). Whether
that is true depends on what the Program does.}


\paragraph{1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy an appropriate copyright notice
and disclaimer of warranty; keep intact all the notices that refer
to this License and to the absence of any warranty; and give any other
recipients of the Program a copy of this License along with the Program.}


\paragraph{You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for
a fee.}


\paragraph{2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and distribute
such modifications or work under the terms of Section 1 above, provided
that you also meet all of these conditions:}


\subparagraph*{a) You must cause the modified files to carry prominent notices stating
that you changed the files and the date of any change.}


\subparagraph*{b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any part
thereof, to be licensed as a whole at no charge to all third parties
under the terms of this License.}


\subparagraph{c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such interactive
use in the most ordinary way, to print or display an announcement
including an appropriate copyright notice and a notice that there
is no warranty (or else, saying that you provide a warranty) and that
users may redistribute the program under these conditions, and telling
the user how to view a copy of this License. (Exception: if the Program
itself is interactive but does not normally print such an announcement,
your work based on the Program is not required to print an announcement.) }


\paragraph{These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, and can be
reasonably considered independent and separate works in themselves,
then this License, and its terms, do not apply to those sections when
you distribute them as separate works. But when you distribute the
same sections as part of a whole which is a work based on the Program,
the distribution of the whole must be on the terms of this License,
whose permissions for other licensees extend to the entire whole,
and thus to each and every part regardless of who wrote it.}


\paragraph{Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is
to exercise the right to control the distribution of derivative or
collective works based on the Program.}


\paragraph{In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume
of a storage or distribution medium does not bring the other work
under the scope of this License.}


\paragraph*{3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms
of Sections 1 and 2 above provided that you also do one of the following:}


\subparagraph*{a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange;
or,}


\subparagraph{b) Accompany it with a written offer, valid for at least three years,
to give any third party, for a charge no more than your cost of physically
performing source distribution, a complete machine-readable copy of
the corresponding source code, to be distributed under the terms of
Sections 1 and 2 above on a medium customarily used for software interchange;
or,}


\subparagraph{c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is allowed
only for noncommercial distribution and only if you received the program
in object code or executable form with such an offer, in accord with
Subsection b above.)}


\paragraph{The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to control
compilation and installation of the executable. However, as a special
exception, the source code distributed need not include anything that
is normally distributed (in either source or binary form) with the
major components (compiler, kernel, and so on) of the operating system
on which the executable runs, unless that component itself accompanies
the executable.}


\paragraph{If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent access
to copy the source code from the same place counts as distribution
of the source code, even though third parties are not compelled to
copy the source along with the object code. ~4. You may not copy,
modify, sublicense, or distribute the Program except as expressly
provided under this License. Any attempt otherwise to copy, modify,
sublicense or distribute the Program is void, and will automatically
terminate your rights under this License. However, parties who have
received copies, or rights, from you under this License will not have
their licenses terminated so long as such parties remain in full compliance.}


\paragraph*{5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the Program),
you indicate your acceptance of this License to do so, and all its
terms and conditions for copying, distributing or modifying the Program
or works based on it.}


\paragraph{6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject
to these terms and conditions. You may not impose any further restrictions
on the recipients' exercise of the rights granted herein. You are
not responsible for enforcing compliance by third parties to this
License.}


\paragraph{7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do
not excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a consequence
you may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program
by all those who receive copies directly or indirectly through you,
then the only way you could satisfy both it and this License would
be to refrain entirely from distribution of the Program.}


\paragraph{If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended
to apply and the section as a whole is intended to apply in other
circumstances.}


\paragraph{It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the integrity
of the free software distribution system, which is implemented by
public license practices. Many people have made generous contributions
to the wide range of software distributed through that system in reliance
on consistent application of that system; it is up to the author/donor
to decide if he or she is willing to distribute software through any
other system and a licensee cannot impose that choice.}


\paragraph{This section is intended to make thoroughly clear what is believed
to be a consequence of the rest of this License. ~8. If the distribution
and/or use of the Program is restricted in certain countries either
by patents or by copyrighted interfaces, the original copyright holder
who places the Program under this License may add an explicit geographical
distribution limitation excluding those countries, so that distribution
is permitted only in or among countries not thus excluded. In such
case, this License incorporates the limitation as if written in the
body of this License.}


\paragraph{9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.}


\paragraph{Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and
``any later version'', you have the option of following
the terms and conditions either of that version or of any later version
published by the Free Software Foundation. If the Program does not
specify a version number of this License, you may choose any version
ever published by the Free Software Foundation.}


\paragraph{10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the
author to ask for permission. For software which is copyrighted by
the Free Software Foundation, write to the Free Software Foundation;
we sometimes make exceptions for this. Our decision will be guided
by the two goals of preserving the free status of all derivatives
of our free software and of promoting the sharing and reuse of software
generally.}


\subsection*{NO WARRANTY}


\paragraph{11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.}


\paragraph{12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING
BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.}


\paragraph{END OF TERMS AND CONDITIONS}



\chapter{Credits}

This appendix documents the contributors to the ``APQ Binding''
that are separate from the PostgreSQL project.


\section*{Authors}

\begin{itemize}
\item Warren W. Gay VE3WWG
	\begin{itemize}
		\item 29 Glen Park Road, St. Catharines, Ontario
		\item Canada L2N 3E3
		\item ve3wwg@cogeco.ca
	\end{itemize}
	\item Marcelo Cora\c ca de Freitas <marcelo@kow.com.br>
\end{itemize}


\section*{Contributions}

\subsection*{Source Code Modifications}

Some people has contributed to the 3.0 release:
\begin{itemize}
	\item Alex Abate Biral <abiral@ydeasolutions.com.br>
		\begin{itemize}
			\item Most notably implemented the ODBC support which is not include in this release yeat
		\end{itemize}
\end{itemize}

\subsection*{Bug Reports}

\begin{itemize}
\item There appears to be a problem with win32 releases using PostgreSQL
7.2.1, where specifying the database server by IP \# creates a problem.
The problem is believed to be in libpq.dll. (September 22, 2004: this
problem is believed to be fixed in more current releases of PostgreSQL).
\end{itemize}


\subsection*{Bug Report/Fix Contributions}

\begin{itemize}
\item Charles Darcy <charlie@mullum.com.au>, November 23, 2002
\item Jesse Lang <jesse@solidrockdata.com>, March 2008
\end{itemize}

\chapter{History}


\section*{APQ 1.0}

First released August 3, 2002, under the Ada Community License (ACL).


\section*{APQ 1.1}

Second release August 4, 2002, but under the dual ACL and GPL2%
\footnote{GNU Public License 2%
} license. This license change was suggested by Florian Weimer.


\section*{APQ 1.2}

\begin{itemize}
   \item Added function End\_Of\_Blob to streamline sequential processing.
   \item Added buffered blob I/O for higher performance.
   \item Added procedure Blob\_Flush to force unwritten blob data to the database
         server.
   \item Blob\_Create has new optional Buf\_Size argument.
   \item Blob\_Open has new optional Buf\_Size argument.
   \item Fixed Blob\_Create to release the created blob, if the blob cannot
         be opened. This most often happens when the caller is attempting to
         create a blob, outside of a transaction.
\end{itemize}

\section*{APQ 1.3}

\begin{itemize}
   \item Removed some debug Put\_Line statements that should have been removed
         in 1.2.
   \item Added a few pragma Inline statements to the spec PostgreSQL.Client
\end{itemize}

\section*{APQ 1.4}

\begin{itemize}
   \item Added Generic\_Command\_Oid for strong PG\_Oid type use
   \item Added Generic\_Blob\_Open for strong PG\_Oid type use
   \item Added Generic\_Blob\_Oid function for strong PG\_Oid type use
   \item Added Generic\_Blob\_Unlink for strong PG\_Oid type use
   \item Added Generic\_Blob\_Import and Generic\_Blob\_Export for strong PG\_Oid
         type use
\end{itemize}

\section*{APQ 1.5}

\begin{itemize}
   \item Bug fix: Append\_Time, Append\_Date and Append\_Timestamp now emit
         the surrounding single quote characters around the value to satisfy
         the SQL syntax required by the database server.
   \item Troubleshooting help added to this manual for {}``Missing Time Data
         (Or Time is 00:00:00)''.
\end{itemize}

\section*{APQ 1.6}

\begin{itemize}
   \item Added Set\_Rollback\_On\_Finalize controlling primitive for Connection\_Type.
   \item Added Will\_Rollback\_On\_Finalize function for Connection\_Type for
         inquiry.
   \item Expanded manual and added transaction problem help to the Troubleshooting
         chapter.
\end{itemize}

\section*{APQ 1.7}

\begin{itemize}
   \item Open\_DB\_Trace and Close\_DB\_Trace procedures added.
   \item Set\_Trace procedure added to enable and disable tracing.
   \item Is\_Trace function added to query the tracing state.
\end{itemize}

\section*{APQ 1.8}

\begin{itemize}
   \item Connection information functions like Host\_Name and Port were added.
   \item A connection cloning primitive was added.
\end{itemize}

\section*{APQ 1.9}

\begin{itemize}
   \item A compiler work-around was provided. Some versions of GNAT would not
         compile the APQ source code, because certain instantiations of Ada.Text\_IO.Integer\_IO
         were producing duplicate symbol errors in the assembler phase of the
         compile. This problem was absent in gnat 3.13p compiles, but have
         shown up in gcc-3.1.1 and probably in gnat 3.14p and later releases.
         The instantiation names INTIO were made unique within the source code
         to avoid this problem.
\end{itemize}

\section*{APQ 1.91}

\begin{itemize}
   \item The PostgreSQL Connect call now performs an automatic {}``SET DATESTYLE
         TO ISO'' command prior to returning from a successful connect. This
         is necessary to guarantee that ISO date format is returned from the
         database engine and recognized from the engine. This guarantees that
         APQ correctly handles dates, even when the user has specified a PGDATESTYLE
         environment variable value that is different than ISO.
         \item Fixed bug in Host\_Name function. It was returning a null string when
         a host name was set in the Connection\_Type object.
   \item Win32 apq-1.91 source release (subdirectory win32) and apq-1.91-win32-2.7.1
         binary release created.
\end{itemize}

\section*{APQ 1.92}

\begin{itemize}
   \item Fixed bug for floating point and fixed point types (was rounding the
         value to the nearest integer, due to the fact that the Ada.Text\_IO.Float\_IO.Put
         call was receiving the argument Aft => 0). Omitting the Aft parameter
         causes the value to be formatted as required for the SQL floating/fixed
         point type. The bug was reported by Charles Darcy <charlie@mullum.com.au>.
\end{itemize}

\section*{APQ 1.93}

\begin{itemize}
   \item Modified the Ada95 package hierarchy to insert a top level package
         named APQ. Hence package PostgreSQL now becomes APQ.PostgreSQL. This
         is an interim release, which will pave the way to future support of
         other database products such as MySQL.
\end{itemize}

\section*{APQ 2.0}

\begin{itemize}
   \item MySQL support added. This was made possible by the package restructuring
         done in the interim release APQ 1.93.
   \item Generic database programming support added. Special generic services
         like Engine\_Of, New\_Query etc. were added to make this possible.
         A heavy reliance is made upon object inheritance and polymorphism
         to make this work.
   \item A new example subdirectory eg2 was added. The programs in this subdirectory
         show the original example program, but done in a database generic
         way. The test program can be compiled and run for both PostgreSQL
         and MySQL databases.
   \item PG\_Oid is now named APQ\_Row\_ID and is 64 bits unsigned integer.
   \item Null\_Oid() function added for generic database support (and much
         more).
   \item Engine\_Of() function added for generic database support.
   \item Exception {}``Failed'' was added to handle some general failures.
   \item Fetch\_Mode() and Set\_Fetch\_Mode() were added to accommodate MySQL
         limitations.
   \item Documentation went through some restructuring to accomodate two databases,
         and their differences.
\end{itemize}

\section*{APQ 2.1}

\begin{itemize}
   \item This was the win32 port.
   \item See win32.pdf for instructions for building APQ on a win32 platform.
   \item win32\_test.adb program was added to the distribution to allow testing
         of APQ in the windows environment.
\end{itemize}

\section*{APQ 2.2}

\begin{itemize}
   \item PostgreSQL now defaults to Set\_Port(C,5432), which is an TCP/IP connection
         for port 5432.
   \item APQ now uses Ada.Exceptions.Raise\_Exception in many places to provide
         more information. For example if a Value() function raises a Constraint\_Error,
         it now indicates in the message which column \# the error occurred
         for (where Value takes a Column\_Index\_Type argument). The informative
         message makes it easier to debug a new APQ application.
   \item Documentation added for Set\_Port for UNIX socket connections.
   \item The primitives Begin\_Work, Commit\_Work and Rollback\_Work now include
         an implicit call to Clear before and after the Query\_Type's object's
         use. This is necessary in some cases to clean up results and to put
         the object into the right state (Sybase made this necessary). The
         fetch mode of the Query\_Type object is preserved, even though it
         may be changed to something else while being used.
   \item The Set\_DB\_Name now works differently for PostgreSQL, if the connection
         has already been established. In the past, APQ (for PostgreSQL) simply
         took note of the new database name, but did nothing with it. This
         was inconsitent behavior compared to the fact that APQ\-.MySQL\-.Client\-.Set\_DB\_Name()
         would make a database switch on the connected connection. Now this
         behaviour is harmonized, by having the PostgreSQL version perform
         a hidden {}``USE <database>'' SQL query to make it happen.
   \item When a APQ\-.MySQL\-.Set\_DB\_Name(C) fails on a connected C, the exception
         raised is now APQ.Use\_Error instead of APQ.Failed. This helps to
         distinguish the difference between a successful connection and failed
         database change.
   \item Sybase always connects to the server's configured default database
         for the user. To make APQ.Sybase consistent with other supported databases,
         any Set\_DB\_Name(C) on connection C prior to the connection, now
         queues up a ``USE <database>'' query to be performed, once the
         connection is successful (effectively making it appear the same in
         APQ). Any call to Set\_DB\_Name(C) while C is connected, will result
         in another ``USE <database>'' SQL query being performed behind
         the scenes.
   \item Fixed bug in APQ\-.MySQL\-.Client\-.Reset so that the Connection\_Type object
         was properly reset for re-use.
   \item APQ.Sybase.Client support was added
   \item Set\_Instance and Instance functions were added to permit specification
         of Sybase instances.
   \item Fetch modes Cursor\_For\_Update and Cursor\_For\_Read\_Only were added
         for Sybase cursor support.
   \item Function Cursor\_Name was added for Sybase cursor support.
   \item Functions Set\_Case and Case were added to deal with Sybase's case
         sensitivity for database agnostic code.
   \item Fixed MySQL encoding of APQ\_Boolean types. Now sends 1 or 0, for
         True or False respectively (MySQL uses bit or tinyint to represent
         boolean values).
   \item Fixed MySQL decoding of date/time types (MySQL provides YYYYMMDDHHMMSS
         instead of YYYY-MM-DD HH:MM:SS, which APQ expected).
   \item APQ.PostgreSQL.Client.Value now trims trailing blanks returned for
         string values. This helps the returned values to be consistent across
         all database vendor products (MySQL always trims the trailing blanks).
\end{itemize}

\section*{APQ 3.0}
\begin{itemize}
	\item New build system.
	\item GPR file support
	\item APQ was divided into sub projects:
		\begin{itemize}
			\item \textbf{apq} the core APQ classes
			\item \textbf{apq-ct\_lib} ct\_lib backend support (MySQL Server and Sybase)
			\item \textbf{apq-mysql} MySQL backend support
			\item \textbf{apq-postgresql} PostgreSQL backend support
			\item \textbf{apq-sybase} Sybase backend support
		\end{itemize}
	\item Microsoft SQL Server Support
	\item Can be built with FreeTDS and Sybase's ct\_lib
	\item New single license in favour of the old dual-license
	\item some bug fixes
\end{itemize}


\printindex
\end{document}