File: sparql_io.sql

package info (click to toggle)
virtuoso-opensource 6.1.6+dfsg2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 260,992 kB
  • ctags: 125,220
  • sloc: ansic: 652,748; sql: 458,419; xml: 282,834; java: 61,031; sh: 40,031; cpp: 36,890; cs: 25,240; php: 12,692; yacc: 9,523; lex: 7,018; makefile: 6,157; jsp: 4,484; awk: 1,643; perl: 1,013; ruby: 1,003; python: 326
file content (4286 lines) | stat: -rw-r--r-- 169,781 bytes parent folder | download | duplicates (2)
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
--
--  $Id$
--
--  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
--  project.
--
--  Copyright (C) 1998-2012 OpenLink Software
--
--  This project 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; only version 2 of the License, dated June 1991.
--
--  This program is distributed in the hope that it will be useful, but
--  WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
--  General Public License for more details.
--
--  You should have received a copy of the GNU General Public License along
--  with this program; if not, write to the Free Software Foundation, Inc.,
--  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--
--

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_XML_WRITE_NS (inout ses any)
{
  --http ('<?xml version="1.0" encoding="UTF-8"?>\n', ses);
  http ('<sparql xmlns="http://www.w3.org/2005/sparql-results#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/sw/DataAccess/rf1/result2.xsd">', ses);
}
;


--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_XML_WRITE_HEAD (inout ses any, in colnames any)
{
  declare i, col_count integer;
  http ('\n <head>', ses);
  i := 0; col_count := length (colnames);
  while (i < col_count)
    {
      http (sprintf ('\n  <variable name="%s"/>', colnames[i]), ses);
      i := i + 1;
    }
  http ('\n </head>', ses);
}
;

--!AWK PUBLIC
create function DB.DBA.SPARQL_RSET_XML_HTTP_PRE (in colnames any, in accept varchar)
{
  declare ses integer;
  ses := 0;
  -- dbg_obj_princ ('DB.DBA.SPARQL_RSET_XML_HTTP_PRE (', colnames, accept, ')');
  if (strchr (accept, ' ') is not null)
    accept := subseq (accept, strchr (accept, ' ')+1);
  http_header ('Content-Type: ' || accept || '; charset=UTF-8\r\n');
  http_flush (1);
  DB.DBA.SPARQL_RSET_XML_WRITE_NS (ses);
  DB.DBA.SPARQL_RSET_XML_WRITE_HEAD (ses, colnames);
  http ('\n <results>');
  return colnames;
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_XML_HTTP_INIT (inout env any)
{
  env := 0;
}
;

--!AWK PUBLIC
create function DB.DBA.SPARQL_RSET_XML_HTTP_FINAL (inout env any)
{
  http ('\n </results>');
  http ('\n</sparql>');
}
;

--!AWK PUBLIC
create aggregate DB.DBA.SPARQL_RSET_XML_HTTP (inout colnames any, inout row any) from
  DB.DBA.SPARQL_RSET_XML_HTTP_INIT,
  sparql_rset_xml_write_row,
  DB.DBA.SPARQL_RSET_XML_HTTP_FINAL
order
;


--!AWK PUBLIC
create function DB.DBA.SPARQL_DICT_XML_HTTP_PRE (in colnames any, in accept varchar)
{
  declare ses integer;
  -- dbg_obj_princ ('DB.DBA.SPARQL_DICT_XML_HTTP_PRE (', colnames, accept, ')');
  http_header ('Content-Type: ' || accept || '; charset=UTF-8\r\n');
  http_flush (1);
  ses := 0;
  DB.DBA.SPARQL_RSET_XML_WRITE_NS (ses);
  http ('\n <head><variable name="S"/><variable name="P"/><variable name="O"/></head>');
  http ('\n <results distinct="false" ordered="true">');
  return colnames;
}
;

--!AWK PUBLIC
create aggregate DB.DBA.SPARQL_DICT_XML_HTTP (inout colnames any, inout row any) from
  DB.DBA.SPARQL_RSET_XML_HTTP_INIT,
  sparql_dict_xml_write_row,
  DB.DBA.SPARQL_RSET_XML_HTTP_FINAL
;


--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_TTL_WRITE_NS (inout ses any)
{
  http ('@prefix res: <http://www.w3.org/2005/sparql-results#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
_:_ a res:ResultSet .\n', ses);
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_TTL_WRITE_HEAD (inout ses any, in colnames any)
{
  declare i, col_count integer;
  col_count := length (colnames);
  if (0 = col_count)
    return;
  http ('_:_ res:resultVariable "', ses);
  for (i := 0; i < col_count; i := i + 1)
    {
      if (i > 0)
        http ('" , "', ses);
      http_escape (colnames[i], 11, ses, 0, 1);
    }
  http ('" .\n', ses);
}
;

--!AWK PUBLIC
create function DB.DBA.SPARQL_RSET_TTL_HTTP_PRE (in colnames any, in accept varchar)
{
  declare ses, colctr, colcount integer;
  declare res any;
  -- dbg_obj_princ ('DB.DBA.SPARQL_RSET_TTL_HTTP_PRE (', colnames, accept, ')');
  http_header ('Content-Type: ' || accept || '; charset=UTF-8\r\n');
  http_flush (1);
  ses := 0;
  DB.DBA.SPARQL_RSET_TTL_WRITE_NS (ses);
  DB.DBA.SPARQL_RSET_TTL_WRITE_HEAD (ses, colnames);
  colcount := length (colnames);
  res := make_array (colcount * 7, 'any');
  for (colctr := 0; colctr < colcount; colctr := colctr + 1)
    {
      res [colctr * 7] := colnames [colctr];
    }
  return vector (dict_new (16000), 0, '', '', '', 0, 0, res, 0);
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_TTL_HTTP_INIT (inout env any)
{
  env := 0;
}
;

--!AWK PUBLIC
create function DB.DBA.SPARQL_RSET_TTL_HTTP_FINAL (inout env any)
{
  ;
}
;

--!AWK PUBLIC
create aggregate DB.DBA.SPARQL_RSET_TTL_HTTP (inout colnames any, inout row any) from
  DB.DBA.SPARQL_RSET_TTL_HTTP_INIT,
  sparql_rset_ttl_write_row,
  DB.DBA.SPARQL_RSET_TTL_HTTP_FINAL
order
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_NT_WRITE_NS (inout ses any)
{
  http ('_:ResultSet2053 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#ResultSet> .\n', ses);
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_RSET_NT_WRITE_HEAD (inout ses any, in colnames any)
{
  declare i, col_count integer;
  col_count := length (colnames);
  for (i := 0; i < col_count; i := i + 1)
    {
      http ('_:ResultSet2053 <http://www.w3.org/2005/sparql-results#resultVariable> "', ses);
      http_escape (colnames[i], 11, ses, 0, 1);
      http ('" .\n', ses);
    }
}
;

--!AWK PUBLIC
create function DB.DBA.SPARQL_RSET_NT_HTTP_PRE (in colnames any, in accept varchar)
{
  declare ses, colctr, colcount integer;
  declare res any;
  -- dbg_obj_princ ('DB.DBA.SPARQL_RSET_NT_HTTP_PRE (', colnames, accept, ')');
  http_header ('Content-Type: ' || accept || '; charset=UTF-8\r\n');
  http_flush (1);
  ses := 0;
  DB.DBA.SPARQL_RSET_NT_WRITE_NS (ses);
  DB.DBA.SPARQL_RSET_NT_WRITE_HEAD (ses, colnames);
  colcount := length (colnames);
  res := make_array (colcount * 7, 'any');
  for (colctr := 0; colctr < colcount; colctr := colctr + 1)
    {
      res [colctr * 7] := colnames [colctr];
    }
  return vector (0, res, 0);
}
;

--!AWK PUBLIC
create aggregate DB.DBA.SPARQL_RSET_NT_HTTP (inout colnames any, inout row any) from
  DB.DBA.SPARQL_RSET_TTL_HTTP_INIT,
  sparql_rset_nt_write_row,
  DB.DBA.SPARQL_RSET_TTL_HTTP_FINAL
order
;

-----
-- SPARQL protocol client, i.e., procedures to execute remote SPARQL statements.

create procedure DB.DBA.SPARQL_REXEC_INT (
  in res_mode integer,
  in res_make_obj integer,
  in service varchar,
  in query varchar,
  in dflt_graph varchar,
  inout named_graphs any,
  inout req_hdr any,
  in maxrows integer,
  inout metas any,
  inout bnode_dict any,
  in expected_var_list any := null,
  in options any := null
  )
{
  declare quest_pos integer;
  declare req_uri, req_method, req_body, local_req_hdr, ret_body, ret_hdr any;
  declare ret_content_type, ret_known_content_type, ret_format varchar;
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT (', res_mode, res_make_obj, service, query, dflt_graph, named_graphs, req_hdr, maxrows, metas, bnode_dict, options, ')');
  quest_pos := strchr (service, '?');
  req_body := string_output();
  if (quest_pos is not null)
    {
      http (subseq (service, quest_pos+1), req_body);
      http ('&', req_body);
      service := subseq (service, 0, quest_pos);
    }
  http ('query=', req_body);
  http_url (query, 0, req_body);
  if (dflt_graph is not null and dflt_graph <> '')
    {
      http ('&default-graph-uri=', req_body);
      http_url (dflt_graph, 0, req_body);
    }
  foreach (varchar uri in named_graphs) do
    {
      http ('&named-graph-uri=', req_body);
      http_url (uri, 0, req_body);
    }
  if (maxrows is not null)
    http (sprintf ('&maxrows=%d', maxrows), req_body);
  req_body := string_output_string (req_body);
  local_req_hdr := 'Accept: application/sparql-results+xml, text/rdf+n3, text/rdf+ttl, text/rdf+turtle, text/turtle, application/turtle, application/x-turtle, application/rdf+xml, application/xml';
  req_method := coalesce (
    get_keyword ('req_method', options, null),
    (sparql define input:storage "" select ?mtd from virtrdf: where { `iri(?:service)` virtrdf:bestRequestMethod ?mtd }),
    case when (length (req_body) + length (service) >= 1900) then 'POST' else 'GET' end );
  if ('POST' = req_method)
    {
      req_uri := service;
      local_req_hdr := local_req_hdr || '\r\nContent-Type: application/x-www-form-urlencoded';
    }
  else
    {
      req_method := 'GET';
      req_uri := service || '?' || req_body;
      req_body := '';
    }
  if (length (req_hdr) > 0)
    req_hdr := concat (req_hdr, '\r\n', local_req_hdr );
  else
    req_hdr := local_req_hdr;
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT Request: ', req_method, req_uri);
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT Request: ', req_hdr);
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT Request: ', req_body);
  ret_body := http_get (req_uri, ret_hdr, req_method, req_hdr, req_body);
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT Returned header: ', ret_hdr);
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT Returned body: ', ret_body);
  ret_content_type := http_request_header (ret_hdr, 'Content-Type', null, null);
  ret_known_content_type := http_sys_find_best_sparql_accept (ret_content_type, 0, ret_format);
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT ret_content_type=', ret_content_type, ' ret_known_content_type=', ret_known_content_type, ' ret_format=', ret_format);
  if (ret_format is null or not (ret_format in ('XML', 'RDFXML', 'TTL')))
    {
      declare ret_begin, ret_html any;
      ret_begin := "LEFT" (ret_body, 1024);
      ret_html := xtree_doc (ret_begin, 2);
      -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_INT ret_html=', ret_html);
      if (xpath_eval ('/html|/xhtml', ret_html) is not null)
        ret_format := 'HTML';
      else if (xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] /rset:sparql', ret_html) is not null
            or xpath_eval ('[xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"] /rset2:sparql', ret_html) is not null)
        ret_format := 'XML';
      else if (xpath_eval ('[xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"] /rdf:rdf', ret_html) is not null)
        ret_format := 'RDFXML';
      else if (strstr (ret_begin, '<html>') is not null or
        strstr (ret_begin, '<xhtml>') is not null )
        ret_format := 'HTML';
    }
  if (ret_format = 'XML')
    {
      declare ret_xml, var_list, var_metas, ret_row, out_nulls any;
      declare var_ctr, var_count integer;
      declare vect_acc any;
      declare row_inx integer;
      -- dbg_obj_princ ('application/sparql-results+xml ret_body=', ret_body); string_to_file ('DB.DBA.SPARQL_REXEC_INT.reply.xml', ret_body, -2);
      ret_xml := xtree_doc (ret_body, 0);
      var_list := xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] [xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"]
                               /rset:sparql/rset:head/rset:variable/@name | /rset2:sparql/rset2:head/rset2:variable/@name', ret_xml, 0);
      if (0 = length (var_list))
        {
	  declare bool_ret any;
          bool_ret := xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] [xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"]
                                   /rset:sparql/rset:boolean | /rset2:sparql/rset2:boolean', ret_xml);
	  if (bool_ret is not null)
	    {
	      bool_ret := cast (bool_ret as varchar);
	      if ('true' = bool_ret)
	        bool_ret := 1;
	      else if ('false' = bool_ret)
	        bool_ret := 0;
	      else
                signal ('RDFZZ', sprintf (
                    'DB.DBA.SPARQL_REXEC(''%.300s'', ...) has received invalid boolean value ''%.300s''',
                    service, bool_ret ) );
              metas :=
	        vector (
		  vector (
	            vector ('__ask_retval', 242, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0) ),
		  1 );
              if (0 = res_mode)
	        {
		  declare __ask_retval integer;
		  result_names (__ask_retval);
		  result (bool_ret);
		}
              else if (1 = res_mode)
	        return vector (vector (bool_ret));
	      return;
	    }
          signal ('RDFZZ', sprintf (
            'DB.DBA.SPARQL_REXEC(''%.300s'', ...) has received result with no variables',
	    service ) );
	}
      var_count := length (var_list);
      if (expected_var_list is not null)
        {
          for (var_ctr := var_count - 1; var_ctr >= 0; var_ctr := var_ctr - 1)
            {
              declare var_name varchar;
              var_name := cast (var_list[var_ctr] as varchar);
              if (0 >= position (var_name, expected_var_list))
                signal ('RDFZZ', sprintf (
                  'DB.DBA.SPARQL_REXEC(''%.300s'', ...) has received result with unexpected variable name ''%.300s''',
                  service, var_name ) );
            }
          var_list := expected_var_list;
          var_count := length (var_list);
        }
      var_metas := make_array (var_count, 'any');
      out_nulls := make_array (var_count, 'any');
      for (var_ctr := var_count - 1; var_ctr >= 0; var_ctr := var_ctr - 1)
        {
          declare var_name varchar;
          var_name := cast (var_list[var_ctr] as varchar);
          var_list [var_ctr] := var_name;
          var_metas [var_ctr] := vector (var_name, 242, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0);
          out_nulls [var_ctr] := null;
        }
      -- dbg_obj_princ ('var_metas=', var_metas);
      if (0 = res_mode)
        exec_result_names (var_metas);
      else if (1 = res_mode)
        vectorbld_init (vect_acc);
      row_inx := 0;
      for (ret_row := xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] [xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"]
                                   /rset:sparql/rset:results/rset:result | /rset2:sparql/rset2:results/rset2:result', ret_xml);
        ret_row is not null;
        ret_row := xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] [xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"]
                                following-sibling::rset:result | following-sibling::rset2:result', ret_row) )
        {
          declare out_fields, ret_cols any;
          declare col_ctr, col_count integer;
          out_fields := out_nulls;
          ret_cols := xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] [xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"]
                                   rset:binding | rset2:binding', ret_row, 0);
          col_count := length (ret_cols);
          for (col_ctr := col_count - 1; col_ctr >= 0; col_ctr := col_ctr - 1)
            {
              declare ret_col any;
              declare var_name, var_type, var_strval varchar;
              declare var_pos integer;
              ret_col := ret_cols[col_ctr];
              var_name := cast (xpath_eval ('string(@name)', ret_col) as varchar);
              -- dbg_obj_princ ('var_name=', var_name);
              var_pos := position (var_name, var_list) - 1;
              if (var_pos >= 0)
                {
                  var_type := cast (xpath_eval ('local-name(*)', ret_col) as varchar);
                  var_strval := charset_recode (xpath_eval ('string(*)', ret_col), '_WIDE_', 'UTF-8');
                  -- dbg_obj_princ ('var_type=', var_type);
                  if ('uri' = var_type)
                    out_fields [var_pos] := iri_to_id (var_strval);
                  else if ('bnode' = var_type)
                    {
                      declare local_iid IRI_ID;
                      if (bnode_dict is null)
                        {
                          bnode_dict := dict_new ();
                          local_iid := iri_id_from_num (sequence_next ('RDF_URL_IID_BLANK'));
                          dict_put (bnode_dict, var_strval, local_iid);
                        }
                      else
                        {
                          local_iid := dict_get (bnode_dict, var_strval, null);
                          if (local_iid is null)
                            {
                              local_iid := iri_id_from_num (sequence_next ('RDF_URL_IID_BLANK'));
                              dict_put (bnode_dict, var_strval, local_iid);
                            }
                        }
                      out_fields [var_pos] := local_iid;
                    }
                  else if ('literal' = var_type)
                    {
                      declare lang, dt varchar;
                      lang := charset_recode (xpath_eval ('*/@xml:lang', ret_col), '_WIDE_', 'UTF-8');
                      dt := charset_recode (xpath_eval ('*/@datatype', ret_col), '_WIDE_', 'UTF-8');
                      if (res_make_obj)
                        out_fields [var_pos] := DB.DBA.RDF_MAKE_OBJ_OF_TYPEDSQLVAL_STRINGS (
                          var_strval, dt, lang );
                      else
                        out_fields [var_pos] := DB.DBA.RDF_MAKE_LONG_OF_TYPEDSQLVAL_STRINGS (
                          var_strval, dt, lang );
                    }
                  else
                    signal ('RDFZZ', sprintf (
                        'DB.DBA.SPARQL_REXEC(''%.300s'', ...) contains unsupported type of bound value ''%.300s''',
                        service, var_type ) );
                }
            }
          if (0 = res_mode)
            exec_result (out_fields);
          else if (1 = res_mode)
            vectorbld_acc (vect_acc, out_fields);
          row_inx := row_inx + 1;
          if (maxrows is not null and maxrows > 0 and row_inx >= maxrows)
            ret_row := xpath_eval ('[xmlns:rset="http://www.w3.org/2005/sparql-results#"] [xmlns:rset2="http://www.w3.org/2001/sw/DataAccess/rf1/result2"]
                                    ../rset:result[position() = last()] | ../rset2:result[position() = last()]', ret_row);
        }
      metas := vector (var_metas, 1);
      if (0 = res_mode)
        {
          return;
        }
      else if (1 = res_mode)
        {
          vectorbld_final (vect_acc);
          return vect_acc;
        }
    }
  if (ret_format = 'RDFXML')
    {
      declare res_dict any;
      res_dict := DB.DBA.RDF_RDFXML_TO_DICT (ret_body,'http://local.virt/tmp','http://local.virt/tmp');
      metas := vector (vector (vector ('res_dict', 242, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0)), 1);
      if (0 = res_mode)
        {
          result_names (res_dict);
          result (res_dict);
          return;
        }
      else if (1 = res_mode)
        return vector (vector (res_dict));
    }
  if (ret_format = 'TTL')
    {
      declare res_dict any;
      res_dict := DB.DBA.RDF_TTL2HASH (ret_body, '');
      metas := vector (vector (vector ('res_dict', 242, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0)), 1);
      if (0 = res_mode)
        {
          result_names (res_dict);
          result (res_dict);
          return;
        }
      else if (1 = res_mode)
        return vector (vector (res_dict));
    }
  if (strstr (ret_content_type, 'text/plain') is not null)
    {
      signal ('RDFZZ', sprintf (
          'DB.DBA.SPARQL_REXEC(''%.300s'', ...) returned Content-Type ''%.300s'' status ''%.300s''\n%.1000s',
          service, ret_content_type, ret_hdr[0], "LEFT" (ret_body, 1024) ) );
    }
  if (strstr (ret_content_type, 'text/html') is not null)
    {
      signal ('RDFZZ', sprintf (
          'DB.DBA.SPARQL_REXEC(''%.300s'', ...) returned Content-Type ''%.300s'' status ''%.300s''\n%.1000s',
          service, ret_content_type, ret_hdr[0],
	  "LEFT" (cast (xtree_doc (ret_body, 2) as varchar), 1024) ) );
    }
  signal ('RDFZZ', sprintf (
      'DB.DBA.SPARQL_REXEC(''%.300s'', ...) returned unsupported Content-Type ''%.300s''',
      service, ret_content_type ) );
}
;

create procedure DB.DBA.SPARQL_REXEC (
  in service varchar,
  in query varchar,
  in dflt_graph varchar,
  in named_graphs any,
  in req_hdr any,
  in maxrows integer,
  in bnode_dict any,
  in options any := null
  )
{
  declare metas any;
  DB.DBA.SPARQL_REXEC_INT (0, 0, service, query, dflt_graph, named_graphs, req_hdr, maxrows, metas, bnode_dict, options);
}
;

create function DB.DBA.SPARQL_REXEC_TO_ARRAY (
  in service varchar,
  in query varchar,
  in dflt_graph varchar,
  in named_graphs any,
  in req_hdr any,
  in maxrows integer,
  in bnode_dict any,
  in expected_var_list any := null,
  in options any := null
  ) returns any
{
  declare metas any;
  return DB.DBA.SPARQL_REXEC_INT (1, 0, service, query, dflt_graph, named_graphs, req_hdr, maxrows, metas, bnode_dict, expected_var_list, options);
}
;

create function DB.DBA.SPARQL_REXEC_TO_ARRAY_OF_OBJ (
  in service varchar,
  in query varchar,
  in dflt_graph varchar,
  in named_graphs any,
  in req_hdr any,
  in maxrows integer,
  in bnode_dict any,
  in expected_var_list any := null,
  in options any := null
  ) returns any
{
  declare metas any;
  return DB.DBA.SPARQL_REXEC_INT (1, 1, service, query, dflt_graph, named_graphs, req_hdr, maxrows, metas, bnode_dict, expected_var_list, options);
}
;

create procedure DB.DBA.SPARQL_REXEC_WITH_META (
  in service varchar,
  in query varchar,
  in dflt_graph varchar,
  in named_graphs any,
  in req_hdr any,
  in maxrows integer,
  in bnode_dict any,
  out metadata any,
  out resultset any,
  in options any := null
  )
{
  resultset := DB.DBA.SPARQL_REXEC_INT (1, 0, service, query, dflt_graph, named_graphs, req_hdr, maxrows, metadata, bnode_dict, options);
  -- dbg_obj_princ ('DB.DBA.SPARQL_REXEC_WITH_META (): metadata = ', metadata, ' resultset = ', resultset);
}
;

create procedure DB.DBA.SPARQL_SD_PROBE (in service_iri varchar, in proxy_iri varchar := null, in verbose integer := 0, in inside_resultset integer := 0)
{
  declare STAT, MSG varchar;
  declare g_iri, lang_bits_hex varchar;
  declare guess_bits, lang_bits, get_is_ok, post_is_ok integer;
  if (not inside_resultset)
    result_names (STAT, MSG);
  lang_bits := 0;
  g_iri := null;
  get_is_ok := null;
  post_is_ok := null;
  if (isstring (registry_get ('URIQADefaultHost')) and strstr (service_iri, registry_get ('URIQADefaultHost')) is not null)
    signal ('22023', 'Can not load own service description');
  if (exists (sparql define input:storage ""
      prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
      prefix sd: <http://www.w3.org/ns/sparql-service-description#>
      ask { graph `iri (?:service_iri)` { { ?s a sd:Service } union { ?s sd:endpoint ?ep } } } ) )
    {
      result ('00000', 'The graph <' || service_iri || '> contains old service description data, the graph will be erased first');
      sparql define input:storage "" clear graph iri (?:service_iri);
      commit work;
    }
  if (proxy_iri is not null)
  {
    sparql load iri (?:proxy_iri);
    if (not exists (sparql define input:storage "" ask where { graph `iri(?:proxy_iri)` { ?s ?p ?o }}))
      signal ('22023', 'The resource <' || proxy_iri || '> exists but does not contain any RDF data');
    if (not exists (sparql define input:storage ""
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        ask where { graph `iri(?:proxy_iri)` { ?s sd:endpoint ?o }}))
      signal ('22023', 'The resource <' || proxy_iri || '> exists but does not contain service description data');
    if (not exists (sparql define input:storage ""
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        ask where { graph `iri(?:proxy_iri)` { ?s sd:endpoint ?o }}))
      {
        result ('0000', 'The resource <' || proxy_iri || '> exists and describes some services but not the desired service <' || service_iri || '>');
        goto g_done;
      }
    g_iri := proxy_iri;
    goto g_done;
  }
  if (not (ends_with (service_iri, '-sd')))
    {
      declare sd_iri varchar;
      sd_iri := service_iri || '-sd';
      if (exists (sparql define input:storage ""
          prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
          prefix sd: <http://www.w3.org/ns/sparql-service-description#>
          ask { graph `iri (?:sd_iri)` { { ?s a sd:Service } union { ?s sd:endpoint ?ep } } }))
        {
          result ('00000', 'The graph <' || sd_iri || '> contains old service description data, the graph will be erased first');
          sparql define input:storage "" clear graph iri (?:sd_iri);
          commit work;
        }
      whenever sqlstate '*' goto no_sd;
      result ('00000', 'Trying to load <' || sd_iri || '> as a standalone service description...');
      sparql load iri (?:sd_iri);
      if (not exists (sparql define input:storage "" ask where { graph `iri(?:sd_iri)` { ?s ?p ?o }}))
        {
          result ('00000', 'The resource <' || sd_iri || '> does not contain any RDF data, ignored');
          goto no_sd;
        }
      if (not exists (sparql define input:storage ""
          prefix sd: <http://www.w3.org/ns/sparql-service-description#>
          ask where { graph `iri(?:sd_iri)` { ?s sd:endpoint ?o }}))
        {
          result ('00000', 'The resource <' || sd_iri || '> exists but does not contain service description data, ignored');
          goto no_sd;
        }
      g_iri := sd_iri;
      result ('00000', 'The resource <' || sd_iri || '> contains service description data and is used as an authoritative source');
      goto g_done;
    }
no_sd:
  if (verbose)
    result (__SQL_STATE, __SQL_MESSAGE);
  {
    whenever sqlstate '*' goto g_done;
    result ('00000', 'Trying to load <' || service_iri || '> as self-description of the service...');
    sparql load iri (?:service_iri);
    if (not exists (sparql define input:storage "" ask where { graph `iri(?:service_iri)` { ?s ?p ?o }}))
      {
        result ('00000', 'The resource <' || service_iri || '> exists but does not contain any RDF data, ignored');
        goto g_done;
      }
    if (not exists (sparql define input:storage ""
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        ask where { graph `iri(?:service_iri)` { ?s sd:endpoint ?o }}))
      {
        result ('00000', 'The resource <' || service_iri || '> exists but does not contain service description data, ignored');
        goto g_done;
      }
    g_iri := service_iri;
    goto g_done;
  }
  if (verbose)
    result (__SQL_STATE, __SQL_MESSAGE);
g_done:
  if (g_iri is not null)
    {
      declare srv_iri varchar;
      srv_iri := (sparql define input:storage ""
        prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        select ?srv where { graph `iri(?:g_iri)` { ?srv sd:endpoint `iri (?:service_iri)` } }
        order by desc (str (?srv)) limit 1 );
      if (srv_iri is null)
        signal ('22023', 'The resource <' || g_iri || '> is loaded but it does not contain metadata related to <' || service_iri || '> as a SPARQL web service endpoint');
      for (sparql define input:storage ""
        prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        select ?endpoint
        where { graph `iri(?:g_iri)` { `iri(?:srv_iri)` sd:endpoint ?endpoint } } ) do
        {
          sparql
          prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
          prefix sd: <http://www.w3.org/ns/sparql-service-description#>
          insert in virtrdf: { `iri(?:endpoint)` virtrdf:isEndpointOfService `iri(?:srv_iri)` };
          DB.DBA.SECURITY_CL_EXEC_AND_LOG ('jso_triple_add (?,?,?)', vector ("endpoint", UNAME'http://www.openlinksw.com/schemas/virtrdf#isEndpointOfService', srv_iri));
          result ('00000', 'The IRI <' || endpoint || '> is registered as an web service endpoint of SPARQL service <' || service_iri || '>');
        }
      declare feats any;
      feats := vector (
        'QUAD_MAP'		, 0hex0001,
        'OPTION'		, 0hex0002,
        'BREAKUP'		, 0hex0004,
        'PKSELFJOIN'		, 0hex0008,
        'RVR'			, 0hex0010,
        'IN'			, 0hex0020,
        'LIKE'			, 0hex0040,
        'GLOBALS'		, 0hex0080,
        'BI'			, 0hex0100,
        'VIRTSPECIFIC'		, 0hex0200,
        'VOS_509'		, 0hex03FF,
        'SERVICE'		, 0hex0400,
        'VOS_5_LATEST'		, 0hex0FFF,
        'TRANSIT'		, 0hex1000,
        'VOS_6'			, 0hex1FFF,
        'SPARQL11_DRAFT'	, 0hex2000,
        'SPARQL11_FULL'		, 0hex4000,
        'SPARQL11'		, 0hex6000 );
      for (sparql define input:storage ""
        prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        select (bif:subseq (str(?le), bif:length (str(virtrdf:SSG_SD_)))) as ?feat
        where { graph `iri (?:g_iri)` { { `iri(?:srv_iri)` sd:languageExtension ?le } union { `iri(?:service_iri)` sd:languageExtension ?le } } } ) do
        {
          declare bits integer;
          bits := get_keyword ("feat", feats, 0);
          lang_bits := bit_or (lang_bits, bits);
        }
      if (lang_bits = 0)
        result ('00000', 'The service metadata does not contain enough data about language capabilities, they will be probed by sample requests');
      else
        result ('00000', sprintf ('The service metadata contains data about language capabilities: equivalent of define lang:dialect %d (hex %8x)', lang_bits, lang_bits));
      for (sparql define input:storage ""
        prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
        prefix sd: <http://www.w3.org/ns/sparql-service-description#>
        select ?mtd
        where { graph `iri (?:g_iri)` { `iri(?:srv_iri)` virtrdf:requestMethod ?mtd } } ) do
        {
          if ('POST' = mtd) post_is_ok := 1;
          else if ('GET' = mtd) get_is_ok := 1;
        }
    }
  if (get_is_ok is null and post_is_ok is null)
    {
      {
        whenever sqlstate '*' goto bad_get_endpoint;
        result ('00000', 'Trying to query <' || service_iri || '> as SPARQL web service endpoint, GET mode...');
        DB.DBA.SPARQL_REXEC_TO_ARRAY (service_iri, 'select ?s where { ?s ?p ?o } limit 1', null, null, null, 1, null, null, vector ('req_method', 'GET'));
      }
      get_is_ok := 1;
      goto get_done;
bad_get_endpoint:
      if (verbose)
        result (__SQL_STATE, __SQL_MESSAGE);
      get_is_ok := 0;
get_done: ;
      {
        whenever sqlstate '*' goto bad_post_endpoint;
        result ('00000', 'Trying to query <' || service_iri || '> as SPARQL web service endpoint, POST mode...');
        DB.DBA.SPARQL_REXEC_TO_ARRAY (service_iri, 'select ?s where { ?s ?p ?o } limit 1', null, null, null, 1, null, null, vector ('req_method', 'POST'));
      }
      post_is_ok := 1;
      goto post_done;
bad_post_endpoint:
      if (verbose)
        result (__SQL_STATE, __SQL_MESSAGE);
      post_is_ok := 0;
post_done: ;
    }
  if (get_is_ok or post_is_ok)
    {
      declare req_method varchar;
      req_method := case when (get_is_ok and post_is_ok) then null when (get_is_ok) then 'GET' when (post_is_ok) then 'POST' else null end;
      sparql
      prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
      delete from virtrdf: { `iri(?:service_iri)` virtrdf:bestRequestMethod ?o }
      from virtrdf: where { `iri(?:service_iri)` virtrdf:bestRequestMethod ?o };
      sparql
      prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
      insert in virtrdf: { `iri(?:service_iri)` virtrdf:bestRequestMethod `(?:req_method)` };
      commit work;
      DB.DBA.SECURITY_CL_EXEC_AND_LOG ('jso_triples_del (?,?,null)', vector (service_iri, UNAME'http://www.openlinksw.com/schemas/virtrdf#bestRequestMethod'));
      if (req_method is not null)
        DB.DBA.SECURITY_CL_EXEC_AND_LOG ('jso_triple_add (?,?,?)', vector (service_iri, UNAME'http://www.openlinksw.com/schemas/virtrdf#bestRequestMethod', req_method));
    }
  else
    signal ('22023', 'The service <' || service_iri || '> has no description and the site is not responding as a SPARQL endpoint');
  if (lang_bits = 0)
    {
      declare feats any;
      declare ctr, len integer;
      feats := vector (
        'prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#> select ?s where { quad map virtrdf:DefaultQuadMap { ?s ?p ?o } } limit 1'	, 0hex0001,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o OPTION (TABLE_OPTION "ORDER") } } limit 1'		, 0hex0002,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o OPTION (BREAKUP) } } limit 1'		, 0hex0004,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o OPTION (PKSELFJOIN) } } limit 1'		, 0hex0008,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o OPTION (RVR) } } limit 1'			, 0hex0010,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o . filter (?o in ( 1, 2, 3)) } } limit 1'	, 0hex0020,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o . filter (?o like "%qaz%") } } limit 1'	, 0hex0040,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?:oglobal } } limit 1'				, 0hex0080,
        'select (str(?s) as ?str) where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o } } group by ?s limit 1'	, 0hex0100,
        'define input:storage "" select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o } } limit 1'	, 0hex0200,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> ?o } . service <http://dbpedia.org/sparql> { ?s <no-such-p-qazxswedc> ?t } } limit 1'		, 0hex0400,
        'select ?s where { graph <no-such-g-qazxswedc> { ?s <no-such-p-qazxswedc> <no-such-o-qazxswedc> OPTION (TRANSITIVE) } } limit 1'		, 0hex1000,
        'select (strdt (group_concat (?o), datatype (max(?o)) as ?gc) where { graph <no-such-g-qazxswedc> { { ?s <no-such-p-qazxswedc> ?o } MINUS { ?s <no-such-p-qazxswedc> <no-such-o-qazxswedc> } } group by ?s having ?o > 1 } limit 1'		, 0hex2000 );
      len := length (feats);
      for (ctr := 0; ctr < len; ctr := ctr + 2)
        {
          whenever sqlstate '*' goto no_such_feat;
          result ('00000', sprintf ('Test query %d/%d: define lang:dialect %d (hex %08x)...', ctr/2, len/2, feats[ctr+1], feats[ctr+1]));
          DB.DBA.SPARQL_REXEC_TO_ARRAY (service_iri, feats[ctr], null, null, null, 1, null);
          lang_bits := bit_or (lang_bits, feats[ctr+1]);
          result ('00000', sprintf ('Test query %d/%d has found support for define lang:dialect %d (hex %08x)', ctr/2, len/2, feats[ctr+1], feats[ctr+1]));
          goto probe_done;
no_such_feat:
          if (verbose)
            result (__SQL_STATE, __SQL_MESSAGE);
probe_done:;
        }
      result ('00000', sprintf ('The endpoint <' || service_iri || '> has support for define lang:dialect %d (hex %08x)', lang_bits, lang_bits));
    }
  sparql define input:storage ""
  prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
  prefix sd: <http://www.w3.org/ns/sparql-service-description#>
  delete from virtrdf: { `iri(?:service_iri)` virtrdf:dialect ?lb } from virtrdf: { `iri(?:service_iri)` virtrdf:dialect ?lb };
  lang_bits_hex := sprintf ('%08x', lang_bits);
  sparql define input:storage ""
  prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#>
  prefix sd: <http://www.w3.org/ns/sparql-service-description#>
  insert in virtrdf: { `iri(?:service_iri)` virtrdf:dialect ?:lang_bits_hex };
  DB.DBA.SECURITY_CL_EXEC_AND_LOG ('jso_triples_del (?,?,null)', vector (service_iri, UNAME'http://www.openlinksw.com/schemas/virtrdf#dialect'));
  DB.DBA.SECURITY_CL_EXEC_AND_LOG ('jso_triple_add (?,?,?)', vector (service_iri, UNAME'http://www.openlinksw.com/schemas/virtrdf#dialect', lang_bits_hex));
}
;

create procedure DB.DBA.SPARQL_SINV_IMP (in ws_endpoint varchar, in ws_params any, in qtext_template varchar, in qtext_posmap nvarchar, in param_row any, in expected_vars any)
{
  declare RSET, retarray any;
  result_names (RSET);
  -- dbg_obj_princ ('DB.DBA.SPARQL_SINV_IMP (', ws_endpoint, ws_params, qtext_template, qtext_posmap, param_row, expected_var_list, ')');
  if (N'' <> qtext_posmap)
    {
      declare qtext_ses any;
      declare prev_pos, qctr, qcount integer;
      qtext_ses := string_output ();
      prev_pos := 0;
      qcount := length (qtext_posmap)-1;
      for (qctr := 0; qctr < qcount; qctr := qctr+2)
        {
          declare qpos integer;
          qpos := qtext_posmap[qctr];
          http (subseq (qtext_template, prev_pos, qpos), qtext_ses);
          http_nt_object (param_row[qtext_posmap[qctr+1]-1], qtext_ses);
          prev_pos := qpos+8;
        }
      http (subseq (qtext_template, prev_pos), qtext_ses);
      qtext_template := string_output_string (qtext_ses);
    }
  retarray := DB.DBA.SPARQL_REXEC_TO_ARRAY_OF_OBJ (
    ws_endpoint,
    qtext_template,
    NULL, --in dflt_graph varchar,
    NULL, --in named_graphs any,
    NULL, -- in req_hdr any,
    10000000,
    NULL, --  in bnode_dict any
    expected_vars );
  foreach (any retrow in retarray) do
    {
      -- dbg_obj_princ ('DB.DBA.SPARQL_SINV_IMP returns ', retrow);
      result (retrow);
    }
}
;

create procedure view DB.DBA.SPARQL_SINV_2 as DB.DBA.SPARQL_SINV_IMP (ws_endpoint, ws_params, qtext_template, qtext_posmap, param_row, expected_vars)(RSET any)
;

-----
-- SPARQL SOAP web service (incomplete, do not try to use in applications!)

create procedure "querySoap"  (in  "Command" varchar
	    , in  "Properties" any
	    , out "Error" any __soap_fault '__XML__'
	    , out "ws_sparql_xsd" any
	   )
	__soap_options ( __soap_type:='__ANY__',
                 "soapAction":='urn:FIXME:querySoap',
                 "RequestNamespace":='urn:http://www.w3.org/2005/08/sparql-protocol-query/#',
                 "ResponseNamespace":='urn:http://www.w3.org/2005/08/sparql-protocol-query/#',
                 "PartName":='return'
	       )
{
   declare stmt, state, msg, mdta, dta, res, ses any;
   stmt := get_keyword ('Statement', "Command");
   ses := string_output ();

   -- dbg_obj_princ ('Statement to be executed by querySoap: ', stmt);
   res := exec (stmt, state, msg, vector (), 0, mdta, dta);

   SPARQL_RSET_XML_WRITE_NS (ses);
   SPARQL_RESULTS_XML_WRITE_HEAD (ses, mdta);
   SPARQL_RESULTS_XML_WRITE_RES (ses, mdta, dta);

   -- dbg_obj_princ (mdta);
   http ('</sparql>', ses);

   ses := string_output_string (ses);
   string_to_file ('out.xml', ses, -2);
   res := xml_tree_doc (ses);
   return res;
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_WRITE_EXEC_STATUS (inout ses any, in line_format varchar, inout status any)
{
  declare lctr, lcount integer;
  declare lines any;
  if (status is null)
    return;
  http (sprintf (line_format, 'SQL State', status[0]), ses);
  lines := split_and_decode (status[1], 0, '\0\0\n');
  lcount := length (lines);
  for (lctr := 0; lctr < lcount; lctr := lctr + 1)
    {
      http (sprintf (line_format, case (lctr) when 0 then 'SQL Message' else '' end, lines[lctr]), ses);
    }
  http (sprintf (line_format, 'Exec Time', cast (status[2] as varchar) || ' ms'), ses);
  http (sprintf (line_format, 'DB Activity', cast (status[3] as varchar)), ses);
}
;


create procedure DB.DBA.SPARQL_RESULTS_XML_WRITE_HEAD (inout ses any, in mdta any)
{
  declare i, col_count integer;

  http ('\n <head>', ses);

  mdta := mdta[0];
  i := 0; col_count := length (mdta);
  while (i < col_count)
    {
      declare _name varchar;
      declare _type, _type_name, nill int;
      _name := mdta[i][0];
      _type := mdta[i][1];
      if (length (mdta[i]) > 4)
        nill := mdta[i][4];
      else
        nill := 0;
      http (sprintf ('\n  <variable name="%s"/>', _name), ses);
      i := i + 1;
    }
--  http (sprintf ('<link href="%s" />', 'FIX_ME'), ses);
  http ('\n </head>', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_XML_WRITE_RES (inout ses any, in mdta any, inout dta any)
{
  http ('\n <results distinct="false" ordered="true">', ses);

  for (declare ctr integer, ctr := 0; ctr < length (dta); ctr := ctr + 1)
      SPARQL_RESULTS_XML_WRITE_ROW (ses, mdta, dta[ctr]);

  http ('\n </results>', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_XML_WRITE_ROW (inout ses any, in mdta any, inout dta any)
{
  -- dbg_obj_princ ('DB.DBA.SPARQL_RESULTS_XML_WRITE_ROW (..., ',mdta, dta, ')');
  http ('\n  <result>', ses);
  mdta := mdta[0];
  for (declare x any, x := 0; x < length (mdta); x := x + 1)
    {
      declare _name varchar;
      declare _val any;
      _name := mdta[x][0];
      _val := dta[x];
      if (_val is null)
        goto end_of_binding;
      -- dbg_obj_princ ('_name=', _name, ',val=', _val, __tag(_val), __box_flags (_val));
      if (isiri_id (_val))
        {
          if (_val >= min_bnode_iri_id ())
            http (sprintf ('\n   <binding name="%s"><bnode>%s</bnode></binding>', _name, id_to_iri (_val)), ses);
	  else
	    {
              declare res varchar;
              res := id_to_iri (_val);
--              res := coalesce ((select RU_QNAME from DB.DBA.RDF_URL where RU_IID = _val));
              if (res is null)
                res := sprintf ('bad://%d', iri_id_num (_val));
              http (sprintf ('\n   <binding name="%s"><uri>', _name), ses);
	      res := charset_recode (res, 'UTF-8', '_WIDE_');
              http_value (res, 0, ses);
              http ('</uri></binding>', ses);
	    }
	}
      else if (isstring (_val) and (bit_and (1, __box_flags (_val))))
        {
          if (_val like 'nodeID://%')
            http (sprintf ('\n   <binding name="%s"><bnode>%s</bnode></binding>', _name, _val), ses);
          else
            http (sprintf ('\n   <binding name="%s"><uri>%V</uri></binding>', _name, charset_recode (_val, 'UTF-8', '_WIDE_')), ses);
        }
      else
        {
	  declare lang, dt varchar;
	  declare is_xml_lit int;
	  declare sql_val any;
	  if (__tag (_val) = 185) -- string output
	    {
              http (sprintf ('\n   <binding name="%s"><literal>', _name), ses);
	      http_value (_val, 0, ses);
              http ('</literal></binding>', ses);
              goto end_of_binding;
	    }
	  if (__tag (_val) = 230) -- XML entity
	    {
              http (sprintf ('\n   <binding name="%s"><literal datatype="http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral">', _name), ses);
	      http_value (_val, 0, ses);
              http ('</literal></binding>', ses);
              goto end_of_binding;
	    }
	  lang := DB.DBA.RDF_LANGUAGE_OF_LONG (_val, null);
	  dt := DB.DBA.RDF_DATATYPE_IRI_OF_LONG (_val, null);
	  if (dt = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral')
	    is_xml_lit := 1;
	  else
            is_xml_lit := 0;
	  if (lang is not null)
	    {
	      if (dt is not null)
                http (sprintf ('\n   <binding name="%s"><literal xml:lang="%V" datatype="%V">',
		    _name, cast (lang as varchar), cast (dt as varchar)), ses);
	      else
                http (sprintf ('\n   <binding name="%s"><literal xml:lang="%V">',
		    _name, cast (lang as varchar)), ses);
	    }
	  else
	    {
	      if (dt is not null)
                http (sprintf ('\n   <binding name="%s"><literal datatype="%V">',
		    _name, cast (dt as varchar)), ses);
	      else
                http (sprintf ('\n   <binding name="%s"><literal>',
		    _name), ses);
	    }
	  sql_val := __rdf_sqlval_of_obj (_val, 1);
	  if (isentity (sql_val))
	    is_xml_lit := 1;
	  if (__tag (sql_val) = __tag of varchar) -- UTF-8 value kept in a DV_STRING box
	    sql_val := charset_recode (sql_val, 'UTF-8', '_WIDE_');
	  if (is_xml_lit) http ('<![CDATA[', ses);
	  http_value (__rdf_strsqlval (sql_val), 0, ses);
	  if (is_xml_lit) http (']]>', ses);
          http ('</literal></binding>', ses);
        }
end_of_binding: ;
    }

  http ('\n  </result>', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_RDFXML_WRITE_NS (inout ses any)
{
  http ('<rdf:RDF xmlns:res="http://www.w3.org/2005/sparql-results#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <rdf:Description rdf:nodeID="rset">
    <rdf:type rdf:resource="http://www.w3.org/2005/sparql-results#ResultSet" />', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_RDFXML_WRITE_HEAD (inout ses any, in mdta any)
{
  declare i, col_count integer;
  mdta := mdta[0];
  i := 0; col_count := length (mdta);
  while (i < col_count)
    {
      declare _name varchar;
      declare _type, _type_name, nill int;
      _name := mdta[i][0];
      _type := mdta[i][1];
      if (length (mdta[i]) > 4)
        nill := mdta[i][4];
      else
        nill := 0;
      http (sprintf ('\n    <res:resultVariable>%V</res:resultVariable>', _name), ses);
      i := i + 1;
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_RDFXML_WRITE_RES (inout ses any, in mdta any, inout dta any)
{
  for (declare ctr integer, ctr := 0; ctr < length (dta); ctr := ctr + 1)
    {
      http ( sprintf ('\n    <res:solution rdf:nodeID="r%d">', ctr), ses);
      SPARQL_RESULTS_RDFXML_WRITE_ROW (ses, mdta, dta, ctr);
      http ('\n    </res:solution>', ses);
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_RDFXML_WRITE_ROW (inout ses any, in mdta any, inout dta any, in rowno integer)
{
  mdta := mdta[0];
  for (declare x any, x := 0; x < length (mdta); x := x + 1)
    {
      declare _name varchar;
      declare _val any;
      _name := mdta[x][0];
      _val := dta[rowno][x];
      if (_val is null)
        goto end_of_binding;
      http (sprintf ('\n      <res:binding rdf:nodeID="r%dc%d"><res:variable>%V</res:variable><res:value', rowno, x, _name), ses);
      if (isiri_id (_val))
        {
          if (_val >= min_bnode_iri_id ())
	    {
	      http (sprintf (' rdf:nodeID="b%s"/></res:binding>', id_to_iri (_val)), ses);
	    }
	  else
	    {
              declare res varchar;
              res := id_to_iri (_val);
--              res := coalesce ((select RU_QNAME from DB.DBA.RDF_URL where RU_IID = _val));
              if (res is null)
                res := sprintf ('bad://%d', iri_id_num (_val));
              http (sprintf (' rdf:resource="%V"/></res:binding>', charset_recode (res, 'UTF-8', '_WIDE_')), ses);
	    }
	}
      else if (isstring (_val) and (1 = __box_flags (_val)))
        {
          if (_val like 'nodeID://%')
            http (sprintf (' rdf:nodeID="b%s"/></res:binding>', subseq(_val, 9)), ses);
          else
            http (sprintf (' rdf:resource="%V"/></res:binding>', charset_recode (_val, 'UTF-8', '_WIDE_')), ses);
        }
      else
        {
	  declare lang, dt varchar;
          declare val_tag integer;
          val_tag := __tag (_val);
	  if (val_tag = 185) -- string output
	    {
              http ('>', ses);
	      http_value (_val, 0, ses);
              http ('</res:value></res:binding>', ses);
              goto end_of_binding;
	    }
	  if (val_tag = 230) -- XML entity
	    {
              http (' rdf:parseType="Literal">', ses);
	      http_value (_val, 0, ses);
              http ('</res:value></res:binding>', ses);
              goto end_of_binding;
	    }
	  lang := DB.DBA.RDF_LANGUAGE_OF_LONG (_val, null);
	  dt := DB.DBA.RDF_DATATYPE_IRI_OF_LONG (_val, null);
	  if (lang is not null)
	    {
	      if (dt is not null)
                http (sprintf (' xml:lang="%V" datatype="%V">', cast (lang as varchar), cast (dt as varchar)), ses);
	      else
                http (sprintf (' xml:lang="%V">', cast (lang as varchar)), ses);
	    }
	  else
	    {
	      if (dt is not null)
                http (sprintf (' datatype="%V">', cast (dt as varchar)), ses);
	      else
                http ('>', ses);
	    }
          if (__tag of datetime = rdf_box_data_tag (_val))
            __rdf_long_to_ttl (_val, ses);
          else
	    {
	      _val := __rdf_sqlval_of_obj (_val, 1);
	      if (__tag (_val) = __tag of varchar) -- UTF-8 value kept in a DV_STRING box
		_val := charset_recode (_val, 'UTF-8', '_WIDE_');
	      http_value (__rdf_strsqlval (_val), 0, ses);
	    }
          http ('</res:value></res:binding>', ses);
        }
end_of_binding: ;
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_TTL_WRITE_NS (inout ses any)
{
  http ('@prefix res: <http://www.w3.org/2005/sparql-results#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
_:_ a res:ResultSet .\n', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_TTL_WRITE_HEAD (inout ses any, in mdta any)
{
  declare i, col_count integer;
  mdta := mdta[0];
  i := 0; col_count := length (mdta);
  if (0 = col_count)
    return;
  http ('_:_ res:resultVariable "', ses);
  while (i < col_count)
    {
      declare _name varchar;
      declare _type, _type_name, nill int;
      _name := mdta[i][0];
      _type := mdta[i][1];
      if (length (mdta[i]) > 4)
        nill := mdta[i][4];
      else
        nill := 0;
      http_escape (_name, 11, ses, 0, 1);
      i := i + 1;
      if (i < col_count)
        http ('" , "', ses);
    }
  http ('" .\n', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_TTL_WRITE_RES (inout ses any, in mdta any, inout dta any)
{
  declare colctr, colcount, rowctr, len, fake_agg_ctx integer;
  declare cols, colbuf, env any;
  cols := mdta[0];
  colcount := length (cols);
  colbuf := make_array (colcount * 7, 'any');
  len := length (dta);
  for (colctr := 0; colctr < colcount; colctr := colctr + 1)
    {
      colbuf [colctr * 7] := cols[colctr][0];
    }
  env := vector (dict_new (__min (len * 3, 16000)), 0, '', '', '', 0, 0, colbuf, ses);
  rowctr := 0;
  while (rowctr < len)
    {
      declare r any;
      r := aref_set_0 (dta, rowctr);
      sparql_rset_ttl_write_row (fake_agg_ctx, env, r);
      aset_zap_arg (dta, rowctr, r);
      rowctr := rowctr + 1;
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_NT_WRITE_NS (inout ses any)
{
  http ('_:ResultSet2053 rdf:type <http://www.w3.org/1999/02/22-rdf-syntax-ns#res:ResultSet> .\n', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_NT_WRITE_HEAD (inout ses any, in mdta any)
{
  declare i, col_count integer;
  mdta := mdta[0];
  i := 0; col_count := length (mdta);
  while (i < col_count)
    {
      declare _name varchar;
      declare _type, _type_name, nill int;
      _name := mdta[i][0];
      _type := mdta[i][1];
      if (length (mdta[i]) > 4)
        nill := mdta[i][4];
      else
        nill := 0;
      http ('_:ResultSet2053 <http://www.w3.org/2005/sparql-results#resultVariable> "', ses);
      http_escape (_name, 11, ses, 0, 1);
      http ('" .\n', ses);
      i := i + 1;
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_NT_WRITE_RES (inout ses any, in mdta any, inout dta any)
{
  declare colctr, colcount, rowctr, len, fake_agg_ctx integer;
  declare cols, colbuf, env any;
  cols := mdta[0];
  colcount := length (cols);
  colbuf := make_array (colcount * 7, 'any');
  len := length (dta);
  for (colctr := 0; colctr < colcount; colctr := colctr + 1)
    {
      colbuf [colctr * 7] := cols[colctr][0];
    }
  env := vector (0, colbuf, ses);
  rowctr := 0;
  while (rowctr < len)
    {
      declare r any;
      r := aref_set_0 (dta, rowctr);
      sparql_rset_nt_write_row (fake_agg_ctx, env, r);
      aset_zap_arg (dta, rowctr, r);
      rowctr := rowctr + 1;
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_JAVASCRIPT_HTML_WRITE (inout ses any, inout metas any, inout rset any, in is_js integer := 0, in esc_mode integer := 1, in pure_html integer := 0)
{
  declare varctr, varcount, resctr, rescount integer;
  declare trnewline, newline varchar;
  varcount := length (metas[0]);
  rescount := length (rset);
  if (esc_mode = 13)
    {
      newline := '';
      trnewline := ''');\ndocument.writeln(''';
    }
  else
    newline := trnewline := '\n';
  if (is_js)
    {
      http ('document.writeln(''', ses);
      SPARQL_RESULTS_JAVASCRIPT_HTML_WRITE(ses,metas,rset,0,13);
      http (''');', ses);
      return;
   }
  http ('<table class="sparql" border="1">', ses);
  http (trnewline || '  <tr>', ses);
  --http ('\n    <th>Row</th>', ses);
  for (varctr := 0; varctr < varcount; varctr := varctr + 1)
    {
      http(newline || '    <th>', ses);
      http_escape (metas[0][varctr][0], esc_mode, ses, 0, 1);
      http('</th>', ses);
    }
  http (newline || '  </tr>', ses);
  for (resctr := 0; resctr < rescount; resctr := resctr + 1)
    {
      http(trnewline || '  <tr>', ses);
      --http('\n    <td>', ses);
      --http(cast((resctr + 1) as varchar), ses);
      --http('</td>', ses);
      for (varctr := 0; varctr < varcount; varctr := varctr + 1)
        {
          declare val any;
          val := rset[resctr][varctr];
          if (val is null)
            {
              http(newline || '    <td></td>', ses);
              goto end_of_val_print; -- see below
            }
          http(newline || '    <td>', ses);
          if (isiri_id (val))
            http_escape (id_to_iri (val), esc_mode, ses, 1, 1);
          else if (isstring (val) and (1 = __box_flags (val)))
            http_escape (val, esc_mode, ses, 1, 1);
          else if (__tag of varchar = __tag (val))
            {
              http_escape (val, esc_mode, ses, 1, 1);
            }
	  else if (185 = __tag (val)) -- string output
	    {
              http_escape (cast (val as varchar), esc_mode, ses, 1, 1);
	    }
	  else if (__tag of XML = rdf_box_data_tag (val)) -- string output
	    {
              --if (is_js)
                --{
                  declare tmpses any;
                  tmpses := string_output();
                  http_value (val, 0, tmpses);
                  http_escape (cast (tmpses as varchar), esc_mode, ses, 1, 1);
                --}
              --else
                --http_value (val, 0, ses);
	    }
	  else if (pure_html and __tag of rdf_box = __tag (val))
	      http_rdf_object (val, ses, 1);
          else
            {
              http_escape (__rdf_strsqlval (val), esc_mode, ses, 1, 1);
            }
          http ('</td>', ses);
end_of_val_print: ;
        }
      http(newline || '  </tr>', ses);
    }
  http (trnewline || '</table>', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_JSON_WRITE_BINDING (inout ses any, in colname varchar, inout val any)
{
  http(' "', ses);
  http_escape (colname, 11, ses, 0, 1);
  http('": { ', ses);
  if (isiri_id (val))
    {
      if (val > min_bnode_iri_id ())
        http (sprintf ('"type": "bnode", "value": "%s', id_to_iri (val)), ses);
      else
        {
          http ('"type": "uri", "value": "', ses);
          http_escape (id_to_iri (val), 11, ses, 1, 1);
        }
    }
  else if (__tag of rdf_box = __tag (val))
    {
      declare res varchar;
      declare dat, typ any;
      dat := __rdf_sqlval_of_obj (val, 1);
      typ := rdf_box_type (val);
      if (not isstring (dat))
        {
          http ('"type": "typed-literal", "datatype": "', ses);
          if (257 <> typ)
            res := coalesce ((select RDT_QNAME from DB.DBA.RDF_DATATYPE where RDT_TWOBYTE = typ));
          else
            res := cast (__xsd_type (dat) as varchar);
          http_escape (res, 11, ses, 1, 1);
          http ('", "value": "', ses);
          dat := __rdf_strsqlval (dat);
        }
      else if (257 <> typ)
        {
          http ('"type": "typed-literal", "datatype": "', ses);
          res := coalesce ((select RDT_QNAME from DB.DBA.RDF_DATATYPE where RDT_TWOBYTE = typ));
          http_escape (res, 11, ses, 1, 1);
          http ('", "value": "', ses);
        }
      else if (257 <> rdf_box_lang (val))
        {
          http ('"type": "literal", "xml:lang": "', ses);
          res := coalesce ((select lower (RL_ID) from DB.DBA.RDF_LANGUAGE where RL_TWOBYTE = rdf_box_lang (val)));
          http_escape (res, 11, ses, 1, 1);
          http ('", "value": "', ses);
        }
      else
        http ('"type": "literal", "value": "', ses);
      http_escape (dat, 11, ses, 1, 1);
    }
  else if (__tag of varchar = __tag (val))
    {
      if (1 = __box_flags (val))
        {
          if (val like 'nodeID://%')
            http (sprintf ('"type": "bnode", "value": "%s', val), ses);
          else
            {
              http ('"type": "uri", "value": "', ses);
              http_escape (val, 11, ses, 1, 1);
            }
        }
      else
        {
          http ('"type": "literal", "value": "', ses);
          http_escape (val, 11, ses, 1, 1);
        }
    }
  else if (__tag of varbinary = __tag (val))
    {
      http ('"type": "literal", "value": "', ses);
      http_escape (val, 11, ses, 0, 0);
    }
  else if (185 = __tag (val))
    {
      http ('"type": "literal", "value": "', ses);
      http_escape (cast (val as varchar), 11, ses, 1, 1);
    }
  else if (230 = __tag (val))
    {
      http ('"type": "literal", "value": "', ses);
      http_escape (serialize_to_UTF8_xml (val), 11, ses, 1, 1);
    }
  else
    {
      http ('"type": "typed-literal", "datatype": "', ses);
      http_escape (cast (__xsd_type (val) as varchar), 11, ses, 1, 1);
      http ('", "value": "', ses);
      http_escape (__rdf_strsqlval (val), 11, ses, 1, 1);
    }
  http ('" }', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_JSON_WRITE (inout ses any, inout metas any, inout rset any)
{
  declare varctr, varcount, resctr, rescount integer;
  varcount := length (metas[0]);
  rescount := length (rset);
  http ('\n{ "head": { "link": [], "vars": [', ses);
  for (varctr := 0; varctr < varcount; varctr := varctr + 1)
    {
      if (varctr > 0)
        http(', "', ses);
      else
        http('"', ses);
      http_escape (metas[0][varctr][0], 11, ses, 0, 1);
      http('"', ses);
    }
  http ('] },\n  "results": { "distinct": false, "ordered": true, "bindings": [', ses);
  for (resctr := 0; resctr < rescount; resctr := resctr + 1)
    {
      declare need_comma integer;
      if (resctr > 0)
        http(',\n    {', ses);
      else
        http('\n    {', ses);
      need_comma := 0;
      for (varctr := 0; varctr < varcount; varctr := varctr + 1)
        {
          declare val any;
          val := rset[resctr][varctr];
          if (val is null)
            goto end_of_val_print; -- see below
          if (need_comma)
            http('\t,', ses);
          else
            need_comma := 1;
          SPARQL_RESULTS_JSON_WRITE_BINDING (ses, metas[0][varctr][0], val);
end_of_val_print: ;
        }
      http('}', ses);
    }
  http (' ] } }', ses);
}
;

create procedure DB.DBA.SPARQL_RESULTS_CSV_WRITE (inout ses any, inout metas any, inout rset any)
{
  declare varctr, varcount, resctr, rescount integer;
  varcount := length (metas[0]);
  rescount := length (rset);
  for (varctr := 0; varctr < varcount; varctr := varctr + 1)
    {
      if (varctr > 0)
        http(',', ses);
      DB.DBA.SPARQL_RESULTS_CSV_WRITE_VALUE (ses, metas[0][varctr][0]);
    }
  http ('\n', ses);
  for (resctr := 0; resctr < rescount; resctr := resctr + 1)
    {
      for (varctr := 0; varctr < varcount; varctr := varctr + 1)
        {
          declare val any;
          val := rset[resctr][varctr];
          if (varctr > 0)
            http(',', ses);
          if (val is not null)
            DB.DBA.SPARQL_RESULTS_CSV_WRITE_VALUE (ses, val);
        }
      http('\n', ses);
    }
}
;

create procedure DB.DBA.SPARQL_RESULTS_TSV_WRITE (inout ses any, inout metas any, inout rset any)
{
  declare varctr, varcount, resctr, rescount integer;
  varcount := length (metas[0]);
  rescount := length (rset);
  for (varctr := 0; varctr < varcount; varctr := varctr + 1)
    {
      if (varctr > 0)
        http('\t', ses);
      DB.DBA.SPARQL_RESULTS_CSV_WRITE_VALUE (ses, metas[0][varctr][0]);
    }
  http ('\n', ses);
  for (resctr := 0; resctr < rescount; resctr := resctr + 1)
    {
      for (varctr := 0; varctr < varcount; varctr := varctr + 1)
        {
          declare val any;
          val := rset[resctr][varctr];
          if (varctr > 0)
            http('\t', ses);
          if (val is not null)
            DB.DBA.SPARQL_RESULTS_CSV_WRITE_VALUE (ses, val);
        }
      http('\n', ses);
    }
}
;


create function DB.DBA.SPARQL_RESULTS_WRITE (inout ses any, inout metas any, inout rset any, in accept varchar, in add_http_headers integer, in status any := null) returns varchar
{
  declare singlefield varchar;
  declare ret_mime, ret_format varchar;
  if (status is not null)
    {
      http_header (concat (coalesce (http_header_get (), ''),
          'X-SQL-State: ', status[0], '\r\nX-SQL-Message: ', status[1],
          '\r\nX-Exec-Milliseconds: ', cast (status[2] as varchar), '\r\nX-Exec-DB-Activity: ', cast (status[3] as varchar),
          '\r\n' ) );
    }
  if ((1 >= length (rset)) and (1 = length (metas[0])))
    singlefield := metas[0][0][0];
  else
    singlefield := NULL;
  -- dbg_obj_princ ('DB.DBA.SPARQL_RESULTS_WRITE: length(rset) = ', length(rset), ' metas=', metas, ' singlefield=', singlefield, ' accept=', accept, ' add_http_headers=', add_http_headers);
  if ('__ask_retval' = singlefield)
    {
      ret_mime := http_sys_find_best_sparql_accept (accept, 0, ret_format);
      if (ret_format in ('JSON', 'JSON;RES'))
        {
          http (
            concat (
              '{  "head": { "link": [] }, "boolean": ',
              case (length (rset)) when 0 then 'false' else 'true' end,
              '}'),
            ses );
        }
      else if (ret_format = 'XML')
        {
          SPARQL_RSET_XML_WRITE_NS (ses);
          http (
            concat (
              '\n <head></head>\n <boolean>',
              case (length (rset)) when 0 then 'false' else 'true' end,
              '</boolean>\n</sparql>'),
            ses );
        }
      else if (ret_format = 'TTL')
        {
          http ('@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n@prefix rs: <http://www.w3.org/2005/sparql-results#> .\n', ses);
          http (sprintf ('[] rdf:type rs:results ; rs:boolean %s .', case (length (rset)) when 0 then 'false' else 'true' end), ses);
        }
      else if (ret_format = 'CSV' or ret_format = 'TSV')
        {
          http (sprintf ('"bool"\n%d\n', case (length (rset)) when 0 then 0 else 1 end), ses);
        }
      else
        {
          ret_mime := 'text/html';
          http (case (length (rset)) when 0 then 'false' else 'true' end, ses); --- stub
        }
      goto body_complete;
    }
  if ((1 = length (rset)) and
    (1 = length (rset[0])) and
    (214 = __tag (rset[0][0])) )
    {
      declare triples any;
      triples := dict_list_keys (rset[0][0], 1);
      ret_mime := http_sys_find_best_sparql_accept (accept, 1, ret_format);
      if ((ret_format is null) or (ret_format = 'TTL'))
        {
          if (ret_format is null)
            ret_mime := 'text/rdf+n3';
          DB.DBA.RDF_TRIPLES_TO_TTL (triples, ses);
          if (status is not null)
            SPARQL_WRITE_EXEC_STATUS (ses, '#%015s: %s\n', status);
	}
      else if (ret_format = 'TRIG')
        DB.DBA.RDF_TRIPLES_TO_TRIG (triples, ses);
      else if (ret_format = 'NT')
        DB.DBA.RDF_TRIPLES_TO_NT (triples, ses);
      else if (ret_format in ('JSON', 'JSON;TALIS'))
        DB.DBA.RDF_TRIPLES_TO_TALIS_JSON (triples, ses);
      else if (ret_format = 'JSON;LD')
        DB.DBA.RDF_TRIPLES_TO_JSON_LD (triples, ses);
      else if (ret_format = 'JSON;RES')
        DB.DBA.RDF_TRIPLES_TO_JSON (triples, ses);
      else if (ret_format = 'RDFA;XHTML')
        DB.DBA.RDF_TRIPLES_TO_RDFA_XHTML (triples, ses);
      else if (ret_format = 'HTML;UL')
	{
          DB.DBA.RDF_TRIPLES_TO_HTML_UL (triples, ses);
	  ret_mime := 'text/html';
	}
      else if (ret_format = 'HTML;TR')
	{
          DB.DBA.RDF_TRIPLES_TO_HTML_TR (triples, ses);
	  ret_mime := 'text/html';
	}
      else if (ret_format = 'HTML;MICRODATA')
	{
          DB.DBA.RDF_TRIPLES_TO_HTML_MICRODATA (triples, ses);
	  ret_mime := 'text/html';
	}
      else if (ret_format = 'JSON;MICRODATA')
        DB.DBA.RDF_TRIPLES_TO_JSON_MICRODATA (triples, ses);
      else if (ret_format = 'ATOM;XML')
        DB.DBA.RDF_TRIPLES_TO_ATOM_XML_TEXT (triples, 1, ses);
      else if (ret_format = 'JSON;ODATA')
        DB.DBA.RDF_TRIPLES_TO_ODATA_JSON (triples, ses);
      else if (ret_format = 'CXML')
        DB.DBA.RDF_TRIPLES_TO_CXML (triples, ses, accept, add_http_headers, 0, status);
      else if (ret_format = 'CXML;QRCODE')
        DB.DBA.RDF_TRIPLES_TO_CXML (triples, ses, accept, add_http_headers, 1, status);
      else if (ret_format = 'CSV')
        DB.DBA.RDF_TRIPLES_TO_CSV (triples, ses);
      else if (ret_format = 'TSV')
        DB.DBA.RDF_TRIPLES_TO_TSV (triples, ses);
      else if (ret_format = 'SOAP')
	{
	  declare soap_ns, spt_ns varchar;
	  declare soap_ver int;

	  if (strstr (accept, 'application/soap+xml;11') is not null)
	    soap_ver := 11;
	  else
	    soap_ver := 12;
	  soap_ns := DB.DBA.SPARQL_SOAP_NS (soap_ver);
	  spt_ns := DB.DBA.SPARQL_PT_NS ();
	  if (soap_ver = 12)
	    ret_mime := 'application/soap+xml';
	  else
	    ret_mime := 'text/xml';
	  http ('<soapenv:Envelope xmlns:soapenv="'||soap_ns||'"><soapenv:Body><query-result xmlns="'||spt_ns||'">', ses);
          http ('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" '||
      			'xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">', ses);
          DB.DBA.RDF_TRIPLES_TO_RDF_XML_TEXT (triples, 0, ses);
	  http ('</rdf:RDF>', ses);
	  http ('</query-result></soapenv:Body></soapenv:Envelope>', ses);
	}
      else
        {
          ret_mime := 'application/rdf+xml';
          DB.DBA.RDF_TRIPLES_TO_RDF_XML_TEXT (triples, 1, ses);
        }
      goto body_complete;
    }
  ret_mime := http_sys_find_best_sparql_accept (accept, 0, ret_format);
  if (ret_format in ('JSON', 'JSON;RES'))
    {
      if ((singlefield like 'fmtaggret-HTTP+RDF/XML%') or (singlefield like 'fmtaggret-HTTP+TURTLE-0%') or (singlefield like 'fmtaggret-HTTP+TTL-0%'))
        {
          http('"', ses);
          http_escape (cast (rset[0][0] as varchar), 11, ses, 1, 1);
          http('"', ses);
        }
      else
        SPARQL_RESULTS_JSON_WRITE (ses, metas, rset);
      goto body_complete;
    }
  if ((singlefield like 'fmtaggret-HTTP+RDF/XML%') and ('auto' = accept))
    {
      ret_mime := 'application/rdf+xml';
      http (rset[0][0], ses);
      goto body_complete;
    }
  if ((singlefield like 'fmtaggret-HTTP+TURTLE%') or (singlefield like 'fmtaggret-HTTP+TTL%'))
    {
      if ((ret_format = 'TTL') or (ret_format is null))
        {
          if (ret_format is null)
            ret_mime := 'text/rdf+n3';
        }
      http (rset[0][0], ses);
      if (status is not null)
        SPARQL_WRITE_EXEC_STATUS (ses, '#%015s: %s\n', status);
      goto body_complete;
    }
  if (singlefield like 'fmtaggret-%')
    {
      declare ws_pos integer;
      ws_pos := strchr (singlefield, ' ');
      if (ws_pos is not null)
        ret_mime := subseq (singlefield, ws_pos + 1);
      -- dbg_obj_princ ('fmtaggret selected ', ret_mime, ret_format, ' for ', rset[0][0]);
--      if (not (singlefield like 'fmtaggret-HTTP+%'))
        http (rset[0][0], ses);
      goto body_complete;
    }
  if (ret_format = 'HTML')
    {
      SPARQL_RESULTS_JAVASCRIPT_HTML_WRITE(ses, metas, rset, 0, 1, case when ret_mime = 'text/html' then 1 else 0 end);
      goto body_complete;
    }
  if (ret_format = 'JS')
    {
      SPARQL_RESULTS_JAVASCRIPT_HTML_WRITE(ses, metas, rset, 1);
      goto body_complete;
    }
  if (ret_format = 'SOAP')
    {
      declare soap_ns, spt_ns varchar;
      declare soap_ver int;

      if (strstr (accept, 'application/soap+xml;11') is not null)
        soap_ver := 11;
      else
        soap_ver := 12;
      soap_ns := DB.DBA.SPARQL_SOAP_NS (soap_ver);
      spt_ns := DB.DBA.SPARQL_PT_NS ();
      if (soap_ver = 12)
        ret_mime := 'application/soap+xml';
      else
        ret_mime := 'text/xml';
      http ('<soapenv:Envelope xmlns:soapenv="'||soap_ns||'"><soapenv:Body><query-result xmlns="'||spt_ns||'">', ses);
      SPARQL_RSET_XML_WRITE_NS (ses);
      SPARQL_RESULTS_XML_WRITE_HEAD (ses, metas);
      SPARQL_RESULTS_XML_WRITE_RES (ses, metas, rset);
      http ('\n</sparql>', ses);
      http ('</query-result></soapenv:Body></soapenv:Envelope>', ses);
      goto body_complete;
    }
  if (ret_format = 'TTL')
    {
      if (ret_format is null)
        ret_mime := 'text/rdf+n3';
      SPARQL_RESULTS_TTL_WRITE_NS (ses);
      SPARQL_RESULTS_TTL_WRITE_HEAD (ses, metas);
      SPARQL_RESULTS_TTL_WRITE_RES (ses, metas, rset);
      goto body_complete;
    }
  if (ret_format = 'NT')
    {
      SPARQL_RESULTS_NT_WRITE_NS (ses);
      SPARQL_RESULTS_NT_WRITE_HEAD (ses, metas);
      SPARQL_RESULTS_NT_WRITE_RES (ses, metas, rset);
      goto body_complete;
    }
  if (ret_format = 'RDFXML')
    {
      ret_mime := 'application/rdf+xml';
      SPARQL_RESULTS_RDFXML_WRITE_NS (ses);
      SPARQL_RESULTS_RDFXML_WRITE_HEAD (ses, metas);
      SPARQL_RESULTS_RDFXML_WRITE_RES (ses, metas, rset);
      http ('\n  </rdf:Description>', ses);
      http ('\n</rdf:RDF>', ses);
      goto body_complete;
    }
  if ((ret_format = 'CXML') or (ret_format = 'CXML;QRCODE'))
    {
      DB.DBA.SPARQL_RESULTS_CXML_WRITE(ses, metas, rset, accept, add_http_headers, status);
      goto body_complete;
    }
  if (ret_format = 'CSV')
    {
      ret_mime := 'text/csv';
      DB.DBA.SPARQL_RESULTS_CSV_WRITE (ses, metas, rset);
      goto body_complete;
    }
  if (ret_format = 'TSV')
    {
      ret_mime := 'text/tab-separated-values';
      DB.DBA.SPARQL_RESULTS_TSV_WRITE (ses, metas, rset);
      goto body_complete;
    }
  ret_mime := 'application/sparql-results+xml';
  SPARQL_RSET_XML_WRITE_NS (ses);
  SPARQL_RESULTS_XML_WRITE_HEAD (ses, metas);
  SPARQL_RESULTS_XML_WRITE_RES (ses, metas, rset);
  http ('\n</sparql>', ses);

body_complete:
  if (add_http_headers and strcasestr (http_header_get (), 'Content-Type:') is null)
    http_header (coalesce (http_header_get (), '') || 'Content-Type: ' || ret_mime || '; charset=UTF-8\r\n');
  return ret_mime;
}
;

-- CLIENT --
--select -- dbg_obj_princ (soap_client (url=>'http://neo:6666/SPARQL', operation=>'querySoap', target_namespace=>'urn:FIXME', soap_action =>'urn:FIXME:querySoap', parameters=> vector ('Command', soap_box_structure ('Statement' , 'select TEST from DB.DBA.SPARQL_TABLE3'), 'Properties', soap_box_structure ('PropertyList', 'None' )), style=>2));

create procedure WS.WS.SPARQL_ENDPOINT_SVC_DESC ()
{
  declare ses any;
  ses := string_output ();
  http ('    <div xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"\n', ses);
  http ('         xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"\n', ses);
  http ('         xmlns="http://www.w3.org/1999/xhtml"\n', ses);
  http ('         xmlns:sd="http://www.w3.org/ns/sparql-service-description#"\n', ses);
  http ('         xmlns:xsd="http://www.w3.org/2001/XMLSchema#"\n', ses);
  http ('         style="display:none">\n', ses);
  http ('       <div class="description" about="" typeof="sd:Service">\n', ses);
  http (sprintf ('          <div rel="sd:endpoint" resource="http://%{WSHost}s/sparql"/>\n', ses), ses);
  http ('          <div rel="sd:feature"\n', ses);
  http ('               resource="http://www.w3.org/ns/sparql-service-description#UnionDefaultGraph"/>\n', ses);
  http ('          <div rel="sd:feature"\n', ses);
  http ('               resource="http://www.w3.org/ns/sparql-service-description#DereferencesURIs"/>\n', ses);
  http ('          <div rel="sd:resultFormat" resource="http://www.w3.org/ns/formats/RDF_XML"/>\n', ses);
  http ('          <div rel="sd:resultFormat" resource="http://www.w3.org/ns/formats/Turtle"/>\n', ses);
  http ('          <div rel="sd:resultFormat"\n', ses);
  http ('               resource="http://www.w3.org/ns/formats/SPARQL_Results_CSV"/>\n', ses);
  http ('          <div rel="sd:resultFormat" resource="http://www.w3.org/ns/formats/N-Triples"/>\n', ses);
  http ('          <div rel="sd:resultFormat" resource="http://www.w3.org/ns/formats/N3"/>\n', ses);
  http ('          <div rel="sd:resultFormat"\n', ses);
  http ('               resource="http://www.w3.org/ns/formats/SPARQL_Results_JSON"/>\n', ses);
  http ('          <div rel="sd:resultFormat" resource="http://www.w3.org/ns/formats/RDFa"/>\n', ses);
  http ('          <div rel="sd:resultFormat"\n', ses);
  http ('               resource="http://www.w3.org/ns/formats/SPARQL_Results_XML"/>\n', ses);
  http ('          <div rel="sd:supportedLanguage"\n', ses);
  http ('               resource="http://www.w3.org/ns/sparql-service-description#SPARQL10Query"/>\n', ses);
  http (sprintf ('          <div rel="sd:url" resource="http://%{WSHost}s/sparql"/>\n', ses), ses);
  http ('       </div>\n', ses);
  http ('    </div>\n', ses);
  return ses;
}
;


create procedure WS.WS.SPARQL_VHOST_RESET ()
{
  declare gr varchar;
  declare oopts any;
  oopts := null;
  if (not exists (select 1 from "DB"."DBA"."SYS_USERS" where U_NAME = 'SPARQL'))
    {
      DB.DBA.USER_CREATE ('SPARQL', uuid(), vector ('DISABLED', 1, 'LOGIN_QUALIFIER', 'SPARQL'));
      DB.DBA.EXEC_STMT ('grant SPARQL_SELECT to "SPARQL"', 0);
    }
  if (registry_get ('__SPARQL_VHOST_RESET') >= '20120519')
    return;
  DB.DBA.VHOST_REMOVE (lpath=>'/SPARQL');
  DB.DBA.VHOST_REMOVE (lpath=>'/services/sparql-query');
  oopts := (select deserialize (HP_OPTIONS) from HTTP_PATH 
  	where HP_PPATH = '/!sparql/' and HP_LPATH = '/sparql' and HP_HOST = '*ini*' and HP_LISTEN_HOST = '*ini*');
  if (oopts is null) oopts := vector ('noinherit', 1);
  DB.DBA.VHOST_REMOVE (lpath=>'/sparql');
  DB.DBA.VHOST_DEFINE (lpath=>'/sparql/', ppath => '/!sparql/', is_dav => 1, vsp_user => 'dba', opts => oopts);
  oopts := (select deserialize (HP_OPTIONS) from HTTP_PATH 
  	where HP_PPATH = '/!sparql-graph-crud/' and HP_LPATH = '/sparql-graph-crud' and HP_HOST = '*ini*' and HP_LISTEN_HOST = '*ini*');
  if (oopts is null) oopts := vector ('noinherit', 1, 'exec_as_get', 1);
  DB.DBA.VHOST_REMOVE (lpath=>'/sparql-graph-crud');
  DB.DBA.VHOST_DEFINE (lpath=>'/sparql-graph-crud/', ppath => '/!sparql-graph-crud/', is_dav => 1, vsp_user => 'dba', opts => oopts);
  oopts := (select deserialize (HP_OPTIONS) from HTTP_PATH 
  	where HP_PPATH = '/!sparql/' and HP_LPATH = '/sparql-auth' and HP_HOST = '*ini*' and HP_LISTEN_HOST = '*ini*');
  if (oopts is null) oopts := vector ('noinherit', 1);
  DB.DBA.VHOST_REMOVE (lpath=>'/sparql-auth');
  DB.DBA.VHOST_DEFINE (lpath=>'/sparql-auth',
    ppath => '/!sparql/',
    is_dav => 1,
    vsp_user => 'dba',
    opts => oopts,
    auth_fn=>'DB.DBA.HP_AUTH_SPARQL_USER',
    realm=>'SPARQL',
    sec=>'digest');
  oopts := (select deserialize (HP_OPTIONS) from HTTP_PATH 
  	where HP_PPATH = '/!sparql-graph-crud/' and HP_LPATH = '/sparql-graph-crud-auth' and HP_HOST = '*ini*' and HP_LISTEN_HOST = '*ini*');
  if (oopts is null) oopts := vector ('noinherit', 1, 'exec_as_get', 1);
  DB.DBA.VHOST_REMOVE (lpath=>'/sparql-graph-crud-auth');
  DB.DBA.VHOST_DEFINE (lpath=>'/sparql-graph-crud-auth',
    ppath => '/!sparql-graph-crud/',
    is_dav => 1,
    vsp_user => 'dba',
    opts => oopts,
    auth_fn=>'DB.DBA.HP_AUTH_SPARQL_USER',
    realm=>'SPARQL',
    sec=>'digest');
--DB.DBA.EXEC_STMT ('grant execute on DB.."querySoap" to "SPARQL", 0);
--VHOST_DEFINE (lpath=>'/services/sparql-query', ppath=>'/SOAP/', soap_user=>'SPARQL',
--              soap_opts => vector ('ServiceName', 'XMLAnalysis', 'elementFormDefault', 'qualified'));
  DB.DBA.VHOST_REMOVE (lpath=>'/sparql-sd');
  DB.DBA.VHOST_DEFINE (lpath=>'/sparql-sd/', ppath => '/!sparql-sd/', is_dav => 1, vsp_user => 'dba', opts => vector('noinherit', 1));
  gr := concat ('http://', registry_get ('URIQADefaultHost'), '/sparql');
  DB.DBA.RDF_LOAD_RDFA (WS.WS.SPARQL_ENDPOINT_SVC_DESC (), gr, gr);
  registry_set ('__SPARQL_VHOST_RESET', '20120519');
}
;


-----
-- SPARQL HTTP request handler
create procedure DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (
  inout path varchar, inout params any, inout lines any,
  in httpcode varchar, in httpstatus varchar,
  in query varchar, in state varchar, in msg varchar, in accept varchar := null)
{
  -- dbg_obj_princ ('DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (...', httpcode, httpstatus, '...', state, msg, accept);
--  declare exit handler for sqlstate '*' { signal (state, msg); };
  if (httpstatus is null)
    {
      declare errtitle varchar;
      declare delim varchar;
      delim := strchr (msg, '\n');
      if (delim is null)
        errtitle := msg;
      else
        errtitle := subseq (msg, 0, delim);
      httpstatus := sprintf ('Error %s %s', state, errtitle);
    }
  if (accept is not null and strstr (accept, 'application/soap+xml') is not null)
    {
      declare err_str any;
      declare soap_ver int;
      if (strstr (accept, 'application/soap+xml;11') is not null)
	{
	  soap_ver := 11;
	  http_header ('Content-Type: text/xml; charset=UTF-8\r\n');
	}
      else
	{
          soap_ver := 12;
	  http_header ('Content-Type: application/soap+xml; charset=UTF-8\r\n');
	}
      http_request_status (sprintf ('HTTP/1.1 500 %s', httpstatus));
      err_str := soap_make_error ('320', state, msg, soap_ver);
      http (err_str);
      return;
    }
  http_request_status (sprintf ('HTTP/1.1 %s %s', httpcode, httpstatus));
  http_header ('Content-Type: text/plain\r\n');
  http (concat ('Virtuoso ', state, ' Error ', msg));
  if (query is not null)
    {
      http ('\n\nSPARQL query:\n');
      http (query);
    }
}
;

create procedure DB.DBA.SPARQL_WSDL11 (in lines any)
{
  declare host any;
  host := http_request_header (lines, 'Host', null, null);
    http (sprintf ('<?xml version="1.0" encoding="utf-8"?>
    <definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
		 xmlns:tns="http://www.w3.org/2005/08/sparql-protocol-query/#"
		 targetNamespace="http://www.w3.org/2005/08/sparql-protocol-query/#">
    <import namespace="http://www.w3.org/2005/08/sparql-protocol-query/#"
    location="http://www.w3.org/TR/sprot11/sparql-protocol-query-11.wsdl"/>
      <service name="SparqlService">
        <port name="SparqlServicePort" binding="tns:QuerySoapBinding">
	  <address location="http://%s/sparql"/>
	</port>
      </service>
    </definitions>', host));
}
;

create procedure DB.DBA.SPARQL_WSDL (in lines any)
{
  declare host any;
  host := http_request_header (lines, 'Host', null, null);
    http (sprintf ('<?xml version="1.0" encoding="utf-8"?>
    <description xmlns="http://www.w3.org/2006/01/wsdl"
		 xmlns:tns="http://www.w3.org/2005/08/sparql-protocol-query/#"
		 targetNamespace="http://www.w3.org/2005/08/sparql-protocol-query/#">
      <include location="http://www.w3.org/TR/rdf-sparql-protocol/sparql-protocol-query.wsdl" />
      <service name="SparqlService" interface="tns:SparqlQuery">
	<endpoint name="SparqlEndpoint" binding="tns:querySoap" address="http://%s/sparql"/>
      </service>
    </description>', host));
}
;

create procedure DB.DBA.SPARQL_SOAP_NS (in ver int)
{
  if (ver = 11)
    return 'http://schemas.xmlsoap.org/soap/envelope/';
  else if (ver = 12)
    return 'http://www.w3.org/2003/05/soap-envelope';
  else
    signal ('42000', 'Un-supported SOAP version');
}
;

create procedure DB.DBA.SPARQL_PT_NS ()
{
  return 'http://www.w3.org/2005/09/sparql-protocol-types/#';
}
;

--!AWK PUBLIC
create function DB.DBA.PARSE_SPARQL_WS_PARAMS (in lst any) returns any
{
  declare pval, parse, res any;
  declare lst_len, ctr integer;
  declare pname, ttl_txt varchar;
  lst_len := length (lst);
  ttl_txt := '';
  vectorbld_init (res);
  for (ctr := 0; ctr < lst_len; ctr := ctr+2)
    {
      pname := lst[ctr];
      pval := lst[ctr+1];
      if (regexp_like (pval, '^(("[^"\\\\]")|(\'[^\'\\\\]\'))\044'))
        parse := subseq (pval, 1, length (pval)-1);
      else if (regexp_like (pval, '^(("""[^"\\\\]""")|(\'\'\'[^\'\\\\]\'\'\'))\044'))
        parse := subseq (pval, 3, length (pval)-3);
      else if (regexp_like ('^<.+>\044', pval))
        {
          parse := (subseq (pval, 1, length (pval)-1));
          __box_flags_set (parse, 1);
        }
      else if (regexp_like (pval, '^([+-]?[0-9]+)\044'))
        parse := cast (pval as integer);
      else if (regexp_like (pval, '^([+-]?[0-9]+\.[0-9]+([eE][+-]?[0-9]+)?)\044'))
        parse := cast (pval as double precision);
      else
        {
          parse := null;
          ttl_txt := concat (ttl_txt, '<', pname, '> <p> ', pval, ' .\n');
        }
      if (parse is not null)

        vectorbld_acc (res, ':' || pname, parse);
    }
  if (ttl_txt <> '')
    {
      declare triples any;
      triples := DB.DBA.RDF_TTL2SQLHASH (ttl_txt, '', '!sparql', 0);
      triples := dict_list_keys (triples, 1);
      foreach (any t in triples) do
        {
          vectorbld_acc (res, ':' || t[0], t[2]);
        }
    }
  vectorbld_final (res);
  return res;
}
;

create procedure DB.DBA.rdf_find_str (in x any)
{
  return cast (x as varchar);
}
;

grant execute on DB.DBA.rdf_find_str to public
;


create procedure WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE()
{
    http('<?xml version="1.0" encoding="UTF-8" ?>\n');
    http('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n');
    http('<html version="-//W3C//DTD XHTML 1.1//EN"\n');
    http('    xmlns="http://www.w3.org/1999/xhtml"\n');
    http('    xml:lang="en"\n');
    http('>\n');
}
;


create procedure WS.WS.SPARQL_ENDPOINT_HTML_HEAD(in title varchar)
{
    http('    <title>' || title || '</title>\n');
    http(sprintf('    <meta name="Copyright" content="Copyright &copy; %d OpenLink Software" />\n', year(now())));
    http('    <meta name="Keywords" content="OpenLink Virtuoso Sparql" />\n');
    http('    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />\n');
}
;


create procedure WS.WS.SPARQL_ENDPOINT_STYLE ()
{
    http('\n');
    http('
    <style type="text/css">
    /*<![CDATA[*/
	html { padding: 0; }
	body {
	    padding: 0;
	    margin: 0;
    	    font-family:Gill Sans, Arial, Helvetica, sans-serif;
	    font-size: 9pt;
	    color: #333;
	    background-color: #FDFDFD;
	}
	#header {
	    padding: 0;
	    margin: 0;
	    background-color: #86B9D9;
	    color: #FFFFFF;
	    border-bottom: 1px solid #AAA;
	}
	#header h1 {
	    font-size: 16pt;
	    font-weight: normal;
	    text-align: left;
	    vertical-align: middle;
	    padding: 4px 8px 4px 8px;
	    margin: 0px 0px 0px 0px;
	}
	#menu {
	    margin-left: 8px;
	    margin-right: 8px;
 	    margin-top: 0px;
	    clear: right;
	    float: right;
	}
	#intro,#main {
	    margin-left: 8px;
	    margin-right: 8px;
	}
	#help {
	    margin-left: 8px;
	    margin-right: 8px;
	    width: 80%
	}
	#footer {
	    width: 100%;
	    float: left;
	    clear: left;
	    margin: 2em 0 0;
	    padding-top: 0.7ex;
	    border-top: 1px solid #AAA;
	    font-size: 8pt;
	    text-align: center;
	}
	fieldset {
	    border: 0;
	    padding: 0;
	    margin: 0;
	}
	fieldset label {
	    font-weight: normal;
	    white-space: nowrap;
	    font-size: 11pt;
	    color: #000;
	}
	fieldset label.n {
	    display: block;
	    vertical-align: bottom;
	    margin-top:5px;
	    width: 160px;
	    float:left;
	    white-space: nowrap;
	}
	fieldset label.n:after { content: ":"; }
	fieldset label.n1 {
	    display: block;
	    vertical-align: bottom;
	    margin-top:5px;
	    width: 160px;
	    float:left;
	    white-space: nowrap;
	}
	fieldset label.ckb {
	    width: 160px;
	    font-weight: normal;
	    font-size: 10pt;
	}
	fieldset label.ckb:after { content: ""; }
	fieldset textarea {
	    width: 99%;
	    font-family: monospace;
	    font-size: 10pt;
	}
	#cxml {
	    clear: both;
	    display: block;
	}
	#savefs {
	    clear: both;
	    display: block;
	}
	span.info {
	    font-size: 9pt;
	    white-space: nowrap;
	    height: 2em;
	}
	br { clear: both; }
    /*]]>*/
    </style>
    ');
}
;


create procedure WS.WS.SPARQL_ENDPOINT_JAVASCRIPT (in can_cxml integer, in can_qrcode integer)
{
    http('\n');
    http('    <script type="text/javascript">\n');
    http('    /*<![CDATA[*/\n');
    http('	var last_format = 1;\n');
    http('	function format_select(query_obg)\n');
    http('	{\n');
    http('		var query = query_obg.value; \n');
    http('		var format = query_obg.form.format;\n');
    http('\n');
    http('		if ((query.match(/\\bconstruct\\b/i) || query.match(/\\bdescribe\\b/i)) && last_format == 1) {\n');
    http('			for(var i = format.options.length; i > 0; i--)\n');
    http('				format.options[i] = null;\n');
    http('			format.options[1] = new Option(\'N3/Turtle\',\'text/rdf+n3\');\n');
    http('			format.options[2] = new Option(\'RDF/JSON\',\'application/rdf+json\');\n');
    http('			format.options[3] = new Option(\'RDF/XML\',\'application/rdf+xml\');\n');
    http('			format.options[4] = new Option(\'N-Triples\',\'text/plain\');\n');
    http('			format.options[5] = new Option(\'XHTML+RDFa\',\'application/xhtml+xml\');\n');
    http('			format.options[6] = new Option(\'ATOM+XML\',\'application/atom+xml\');\n');
    http('			format.options[7] = new Option(\'ODATA/JSON\',\'application/odata+json\');\n');
    http('			format.options[8] = new Option(\'JSON-LD\',\'application/x-json+ld\');\n');
    http('			format.options[9] = new Option(\'HTML (list)\',\'text/x-html+ul\');\n');
    http('			format.options[10] = new Option(\'HTML (table)\',\'text/x-html+tr\');\n');
    http('			format.options[11] = new Option(\'HTML+Microdata\',\'text/html\');\n');
    http('			format.options[12] = new Option(\'Microdata/JSON\',\'application/microdata+json\');\n');
    http('			format.options[13] = new Option(\'CSV\',\'text/csv\');\n');
    http('			format.options[14] = new Option(\'TSV\',\'text/tab-separated-values\');\n');
    http('			format.options[15] = new Option(\'TriG\',\'application/x-trig\');\n');
    if (can_cxml)
      {
	http('			format.options[15] = new Option(\'CXML (Pivot Collection)\',\'text/cxml\');\n');
	if (can_qrcode)
	  http('		format.options[16] = new Option(\'CXML (Pivot Collection with QRcodes)\',\'text/cxml+qrcode\');\n');
      }
    http('			format.selectedIndex = 1;\n');
    http('			last_format = 2;\n');
    http('		}\n');
    http('\n');
    http('		if (!(query.match(/\\bconstruct\\b/i) || query.match(/\\bdescribe\\b/i)) && last_format == 2) {\n');
    http('			for(var i = format.options.length; i > 0; i--)\n');
    http('				format.options[i] = null;\n');
    http('			format.options[1] = new Option(\'HTML\',\'text/html\');\n');
    http('			format.options[2] = new Option(\'Spreadsheet\',\'application/vnd.ms-excel\');\n');
    http('			format.options[3] = new Option(\'XML\',\'application/sparql-results+xml\');\n');
    http('			format.options[4] = new Option(\'JSON\',\'application/sparql-results+json\');\n');
    http('			format.options[5] = new Option(\'Javascript\',\'application/javascript\');\n');
    http('			format.options[6] = new Option(\'N3/Turtle\',\'text/rdf+n3\');\n');
    http('			format.options[7] = new Option(\'RDF/XML\',\'application/rdf+xml\');\n');
    http('			format.options[8] = new Option(\'N-Triples\',\'text/plain\');\n');
    http('			format.options[9] = new Option(\'CSV\',\'text/csv\');\n');
    http('			format.options[10] = new Option(\'TSV\',\'text/tab-separated-values\');\n');
    if (can_cxml)
      http('			format.options[11] = new Option(\'CXML (Pivot Collection)\',\'text/cxml\');\n');
    http('			format.selectedIndex = 1;\n');
    http('			last_format = 1;\n');
    http('		}\n');
    http('	}\n');
    http('
	function format_change(e)
	{
		var format = e.value;
		var cxml = document.getElementById("cxml");
		if (!cxml) return;
		if ((format.match (/\\bCXML\\b/i)))
		{
			cxml.style.display="block";
		} else {
			cxml.style.display="none";
		}
	}
	function savedav_change(e)
	{
		var savefs = document.getElementById("savefs");
		if (!savefs) return;
		if (e.checked)
		{
			savefs.style.display = "block";
		}
		else
		{
			savefs.style.display = "none";
		}
	}
	function sparql_endpoint_init()
	{
		var cxml = document.getElementById("cxml");
		if (cxml) cxml.style.display="none";
		var savefs = document.getElementById("savefs");
		if (savefs) savefs.style.display="none";
	}
    ');
    http('    /*]]>*/\n');
    http('    </script>\n');
}
;


create procedure WS.WS.SPARQL_ENDPOINT_FOOTER()
{
    http('    <div id="footer">\n');
    http(sprintf('	Copyright &copy; %d <a href="http://www.openlinksw.com/virtuoso">OpenLink Software</a>', year(now())));
    http(sprintf('<br />Virtuoso version %s on %s (%s), ', sys_stat('st_dbms_ver'), sys_stat('st_build_opsys_id'), host_id()));
    if (1 = sys_stat('cl_run_local_only'))
	http('Single Server Edition\n');
    else
	http(sprintf('Cluster Edition (%d server processes)\n', sys_stat('cl_n_hosts')));
    http('    </div>\n');
}
;


create procedure WS.WS.SPARQL_ENDPOINT_FORMAT_OPTS (in can_cxml integer, in can_qrcode integer, in params varchar, in qr varchar)
{
  declare opts any;
  declare format varchar;
  format := get_keyword ('format', params, get_keyword ('output', params, ''));
  qr := lower (qr);
  if (format <> '')
  {
    format := (
      case lower(format)
        when 'json'		then 'application/sparql-results+json'
        when 'js'		then 'application/javascript'
        when 'html'		then 'text/html'
        when 'sparql'		then 'application/sparql-results+xml'
        when 'xml'		then 'application/sparql-results+xml'
        when 'rdf'		then 'application/rdf+xml'
        when 'n3'		then 'text/rdf+n3'
        when 'cxml'		then 'text/cxml'
        when 'cxml+qrcode'	then 'text/cxml+qrcode'
        when 'csv'		then 'text/csv'
	when 'json-ld'		then 'application/ld+json'
        else format
      end);
  }
  if (
      regexp_match ('\\bconstruct\\b', qr) is not null
      or
      regexp_match ('\\bdescribe\\b', qr) is not null
      )
    {
      opts := vector (
	  vector ('text/rdf+n3'				, 'N3/Turtle'		),
	  vector ('application/rdf+json'		, 'RDF/JSON'		),
	  vector ('application/rdf+xml'			, 'RDF/XML'		),
	  vector ('text/plain'				, 'N-Triples'		),
	  vector ('application/xhtml+xml'		, 'XHTML+RDFa'		),
	  vector ('application/atom+xml'		, 'ATOM+XML'		),
	  vector ('application/odata+json'		, 'ODATA/JSON'		),
	  vector ('application/x-json+ld'		, 'JSON-LD'		),
	  vector ('text/x-html+ul'			, 'HTML (list)'		),
	  vector ('text/x-html+tr'			, 'HTML (table)'	),
	  vector ('text/html'				, 'HTML+Microdata'	),
	  vector ('application/microdata+json'		, 'Microdata/JSON'	),
	  vector ('text/csv'				, 'CSV'			),
        vector ('text/tab-separated-values'			, 'TSV'			),
	  vector ('application/x-trig'			, 'TriG'		) );
    }
  else
    {
      if (not length (format)) format := 'text/html';
      opts := vector (
	  vector ('auto'				, 'Auto'		),
	  vector ('text/html'				, 'HTML'		),
	  vector ('application/vnd.ms-excel'		, 'Spreadsheet'		),
	  vector ('application/sparql-results+xml'	, 'XML'			),
	  vector ('application/sparql-results+json'	, 'JSON'		),
	  vector ('application/javascript'		, 'Javascript'		),
	  vector ('text/plain'				, 'NTriples'		),
	  vector ('application/rdf+xml'			, 'RDF/XML'		) );
    }
  foreach (any x in opts) do
    {
      http(sprintf ('			<option value="%V" %s>%V</option>\n',
	  x[0], case when format = x[0] then 'selected="selected"' else '' end , x[1]));
    }
  http('			<option value="text/csv">CSV</option>\n');
  http('			<option value="text/tab-separated-values">TSV</option>\n');
  if (can_cxml)
    {
      http('			<option value="text/cxml">CXML (Pivot Collection)</option>\n');
      if (can_qrcode)
	http('			<option value="text/cxml+qrcode">CXML (Pivot Collection with QRcode)</option>\n');
    }
}
;

create procedure WS.WS.SPARQL_ENDPOINT_SPONGE_OPTS (in params varchar)
{
  declare s_param varchar;
  declare opts any;

  s_param := get_keyword ('should-sponge', params, '');
  opts := vector (
      vector ('', 		  'Use only local data (including data retrieved before), but do not retrieve more'),
      vector ('soft', 		  'Retrieve remote RDF data for all missing source graphs'),
      vector ('grab-all',	  'Retrieve all missing remote RDF data that might be useful'),
      vector ('grab-all-seealso', 'Retrieve all missing remote RDF data that might be useful, including seeAlso references'),
      vector ('grab-everything',  'Try to download all referenced resources (this may be very slow and inefficient)')
      );

  foreach (any x in opts) do
    {
      http(sprintf ('			<option value="%V" %s>%V</option>\n',
	  x[0], case when s_param = x[0] then 'selected="selected"' else '' end , x[1]));
    }
}
;


create procedure WS.WS.SPARQL_ENDPOINT_CXML_OPTION (in can_pivot integer, in params varchar, in lbl varchar)
{
  declare val varchar;
  declare opts varchar;

  if ('CXML_redir_for_subjs' = lbl)
    {
      val := get_keyword (lbl, params, '121');
      http ('		<label for="CXML_redir_for_subjs" class="n">External resource link</label>\n');
      http ('		<select name="CXML_redir_for_subjs" id="CXML_redir_for_subjs">\n');
      opts := vector (
	  vector ('',			'No link out'),
	  vector ('121',		'External resource link'),
	  vector ('LOCAL_TTL', 		'External description resource (TTL)'),
	  vector ('LOCAL_NTRIPLES', 	'External description resource (NTRIPLES)'),
	  vector ('LOCAL_JSON', 	'External description resource (JSON)'),
	  vector ('LOCAL_XML', 		'External description resource (RDF/XML)')
      );
    } else {
      val := get_keyword (lbl, params, '');
      http ('		<label for="CXML_redir_for_hrefs" class="n">Facet link behavior</label>\n');
      http ('		<select name="CXML_redir_for_hrefs" id="CXML_redir_for_hrefs">\n');
      opts := vector (
	  vector ('',			'Local faceted navigation link'),
	  vector ('121',		'External resource link'),
	  vector ('LOCAL_PIVOT',	'External faceted navigation link'),
	  vector ('LOCAL_TTL', 		'External description resource (TTL)'),
	  vector ('LOCAL_CXML',		'External description resource (CXML)'),
	  vector ('LOCAL_NTRIPLES', 	'External description resource (NTRIPLES)'),
	  vector ('LOCAL_JSON', 	'External description resource (JSON)'),
	  vector ('LOCAL_XML', 		'External description resource (RDFXML)')
      );
    }

  foreach (any x in opts) do
    {
      if ('LOCAL_PIVOT' <> x[0] or can_pivot)
	  http(sprintf ('			<option value="%V" %s>%V</option>\n',
	       x[0], case when val = x[0] then 'selected="selected"' else '' end , x[1]));
    }

  http ('		</select><br />\n');
}
;


create procedure WS.WS.sparql_predefined_nsdecl ()
{
  declare label varchar;
  label := 'Predefined Namespace Prefixes';

  WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE();

  http('<head>\n');
  WS.WS.SPARQL_ENDPOINT_HTML_HEAD(label);
  WS.WS.SPARQL_ENDPOINT_STYLE();
  http('</head>\n');

  http ('<body>\n');
  http ('    <div id="header">\n');
  http ('	<h1 id="title">'); http (sprintf ('%s', label)); http ('</h1>\n');
  http ('    </div>\n\n');
  http ('    <div id="main">\n');
  http ('    <br />\n');
  http ('    <table class="tableresult" border="1">\n');
  http (sprintf ('	<tr><th>Prefix</th><th>URI</th></tr>\n'));
  for select NS_PREFIX, NS_URL from SYS_XML_PERSISTENT_NS_DECL order by 1 do
    {
       http (sprintf ('	<tr><td>%V</td><td>%V</td></tr>\n', NS_PREFIX, NS_URL));
    }
  http ('    </table>\n');
  http ('    </div>\n\n');

  http('<p>');
  http ('<button type="button" name="back" value="Back" onclick="javascript:history.go(-1);">Back</button>\n');
  http('</p>\n');

  WS.WS.SPARQL_ENDPOINT_FOOTER();
  http('</body>\n');
  http('</html>\n');
}
;


create procedure WS.WS.sparql_predefined_rdfinf ()
{
  declare label varchar;
  label := 'Predefined Inference Rules';

  WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE();

  http('<head>\n');
  WS.WS.SPARQL_ENDPOINT_HTML_HEAD(label);
  WS.WS.SPARQL_ENDPOINT_STYLE();
  http('</head>\n');

  http ('<body>\n');
  http ('    <div id="header">\n');
  http ('	<h1 id="title">'); http (sprintf ('%s', label)); http ('</h1>\n');
  http ('    </div>\n\n');
  http ('    <div id="main">\n');
  http ('    <br />\n');
  http ('    <table class="tableresult" border="1">\n');
  http (sprintf ('	<tr><th>Name</th><th>URI</th></tr>\n'));
  for select * from SYS_RDF_SCHEMA order by 1 do
    {
      http (sprintf ('	<tr><td>%V</td><td>%V</td></tr>\n', RS_NAME, RS_URI));
    }
  http ('    </table>\n');
  http ('    </div>\n\n');

  http('<p>');
  http ('<button type="button" name="back" value="Back" onclick="javascript:history.go(-1);">Back</button>\n');
  http('</p>\n');

  WS.WS.SPARQL_ENDPOINT_FOOTER();
  http('</body>\n');
  http('</html>\n');
}
;

create procedure WS.WS.SPARQL_ENDPOINT_GENERATE_FORM(
    in params any,
    in ini_dflt_graph varchar,
    in def_qry varchar,
    in timeout integer,
    in debug integer,
    in save_mode integer,
    in dav_refresh varchar)
{
    declare can_cxml, can_pivot, can_qrcode, can_sponge integer;
    can_cxml := case (isnull (DB.DBA.VAD_CHECK_VERSION ('sparql_cxml'))) when 0 then 1 else 0 end;
    can_pivot := case (isnull (DB.DBA.VAD_CHECK_VERSION ('PivotViewer'))) when 0 then 1 else 0 end;
    can_qrcode := isstring (__proc_exists ('QRcode encodeString8bit', 2));
    can_sponge := coalesce ((select top 1 1
      from DB.DBA.SYS_USERS as sup
        join DB.DBA.SYS_ROLE_GRANTS as g on (sup.U_ID = g.GI_SUPER)
        join DB.DBA.SYS_USERS as sub on (g.GI_SUB = sub.U_ID)
      where sup.U_NAME = 'SPARQL' and sub.U_NAME = 'SPARQL_SPONGE' ), 0);

    declare endpoint_xsl any;
    endpoint_xsl := registry_get ('sparql_endpoint_xsl');
    if (0 = endpoint_xsl) endpoint_xsl := '';
    if ('' <> endpoint_xsl) http_xslt(endpoint_xsl);

    declare user_id varchar;
    user_id := connection_get ('SPARQLUserId', 'SPARQL');

    declare save_dir varchar;
    declare save_dir_id any;
    save_dir := coalesce ((select U_HOME from DB.DBA.SYS_USERS where U_NAME = user_id and U_DAV_ENABLE));
    if (DAV_HIDE_ERROR (DAV_SEARCH_ID (save_dir, 'C')) is null)
	save_dir := null;
    else
    {
	save_dir := save_dir || 'saved-sparql-results/';
	save_dir_id := DAV_SEARCH_ID (save_dir, 'C');
	if (DAV_HIDE_ERROR (save_dir_id) is null)
	    save_dir := null;
    }

    http_header ('Content-Type: text/html; charset=UTF-8\r\n');
    if (http_request_get ('REQUEST_METHOD') = 'OPTIONS')
	http_header (http_header_get () || 'MS-Author-Via: SPARQL\r\n');

    WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE();

    http('<head>\n');
    WS.WS.SPARQL_ENDPOINT_HTML_HEAD('Virtuoso SPARQL Query Editor');
    WS.WS.SPARQL_ENDPOINT_STYLE ();
    WS.WS.SPARQL_ENDPOINT_JAVASCRIPT(can_cxml, can_qrcode);
    http('</head>\n');

    http('<body onload="sparql_endpoint_init()">\n');

    http('    <div id="header">\n');
    http('	<h1>Virtuoso SPARQL Query Editor</h1>\n');
    http('    </div>\n\n');

    http('    <div id="menu">\n');
    http('	  <a href="/sparql?help=intro">About</a>\n');
    http('	| <a href="/sparql?nsdecl">Namespace Prefixes</a>\n');
    http('	| <a href="/sparql?rdfinf">Inference rules</a>\n');
    if (DB.DBA.VAD_CHECK_VERSION('iSPARQL') is not null)
	http('	| <a href="/isparql">iSPARQL</a>\n');
    http('    </div>\n\n');

    http('    <div id="main">\n');
    http('    <br />\n');
    http('	<form action="" method="get">\n');
    http('	<fieldset>\n');
    http('		<label for="default-graph-uri">Default Data Set Name (Graph IRI)</label><br />\n');
    http('		<input type="text" name="default-graph-uri" id="default-graph-uri"');
    http(sprintf (' value="%s" size="80"/>\n', coalesce (ini_dflt_graph, '') ));
    http('		<br /><br />\n');

    http('		<label for="query">Query Text</label><br />\n');
    http('		<textarea rows="18" cols="80" name="query" id="query" onchange="format_select(this)" onkeyup="format_select(this)">'|| def_qry ||'</textarea>\n');

    http('		<br /><br />\n');
    if (can_sponge)
    {
	http('		<label for="should-sponge" class="n">Sponging</label>\n');
	http('		<select name="should-sponge" id="should-sponge">\n');
	WS.WS.SPARQL_ENDPOINT_SPONGE_OPTS (params);
	http('		</select>\n');
    }
    else
    {
	http('		<span class="info"><i>(Security restrictions of this server do not allow you to retrieve remote RDF data, see <a href="/sparql?help=enable_sponge">details</a>.)</i></span>\n');
    }

    http('		<br />\n');
    http('		<label for="format" class="n">Results Format</label>\n');
    http('		<select name="format" id="format" onchange="format_change(this)">\n');
    WS.WS.SPARQL_ENDPOINT_FORMAT_OPTS (can_cxml, can_qrcode, params, def_qry);
    http('		</select>\n');
    if (sys_stat('st_has_vdb'))
    {
	if (not can_cxml)
	    http('		<span class="info"><i>(The CXML output is disabled, see <a href="/sparql?help=enable_cxml">details</a>)</i></span>\n');
	else if (not can_qrcode)
	    http('		<span class="info"><i>(The QRCODE output is disabled, see <a href="/sparql?help=enable_cxml">details</a>)</i></span>\n');
    }
    http('		<br />\n');

    if (can_cxml)
    {
	http ('		<fieldset id="cxml">\n');
	WS.WS.SPARQL_ENDPOINT_CXML_OPTION (can_pivot, params, 'CXML_redir_for_subjs');

	WS.WS.SPARQL_ENDPOINT_CXML_OPTION (can_pivot, params, 'CXML_redir_for_hrefs');
	http ('		</fieldset>\n');
    }

    http('		<label for="timeout" class="n">Execution timeout</label>\n');
    http('		<input name="timeout" id="timeout" type="text" value="' || coalesce (cast (timeout as varchar), '') || '" /> milliseconds\n');
    http('		<span class="info"><i>(values less than 1000 are ignored)</i></span>');
    http('		<br />\n');

    --http('		<li>\n');
    --http('		<label for="maxrows">Max Rows</label>\n');
    --http('		<input type="text" name="maxrows" id="maxrows"\n');
    --http( sprintf('		value="%d"/>\n',maxrows));
    --http('		<br />\n');

    http('		<label class="n" for="options">Options</label>\n');
    http('		<fieldset id="options">\n');
    http('		<input name="debug" id="debug" type="checkbox"' || case (debug) when '' then '' else ' checked="checked"' end || '/>\n');
    http('		<label for="debug" class="ckb">Strict checking of void variables</label>\n');


    if (save_dir is not null)
    {
	http('		<br />\n');
	http('		<input name="save" id="save" onclick="savedav_change(this)" type="checkbox"' || case when (save_mode is null) then '' else ' checked="checked"' end || ' />\n');
	http('		<label for="save" class="ckb">Save resultset to WebDAV folder on the server</label>\n');
	http('		<fieldset id="savefs">\n');
	http('		    <label for="fname">File name:</label>\n');
	http('		    <input type="text" id="fname" name="fname" />\n');
	http('		    <input type="checkbox" name="dav_refresh" id="dav_refresh"' || case when (dav_refresh is null) then '' else ' checked="checked"' end || ' />\n');
	http('		    <label class="ckb" for="dav_refresh">Refresh periodically</label>\n');
	http('		</fieldset>\n');
    }

    http('		</fieldset>\n');
    http('		<br />\n');

    if (save_dir is null)
    {
	http('		<span class="info"><i>(The result can only be sent back to browser, not saved on the server, see <a href="/sparql?help=enable_det">details</a>)</i></span>\n');
        http('		<br />\n');
    }

    http('		<br />\n');
    http('		<input type="submit" value="Run Query"/>\n');
    http('		<input type="reset" value="Reset"/>\n');
    http('	</fieldset>\n');
    http('	</form>\n');
    http('    </div>\n\n');
    WS.WS.SPARQL_ENDPOINT_FOOTER();
    http (WS.WS.SPARQL_ENDPOINT_SVC_DESC ());
    http('</body>\n');
    http('</html>\n');

    return;
}
;


-- Web service endpoint.

create procedure WS.WS."/!sparql/" (inout path varchar, inout params any, inout lines any)
{
  declare query, full_query, format, should_sponge, debug, def_qry varchar;
  declare dflt_graphs, named_graphs any;
  declare paramctr, paramcount, qry_params, maxrows, can_sponge,  start_time integer;
  declare ses, content any;
  declare def_max, add_http_headers, hard_timeout, timeout, client_supports_partial_res, sp_ini, soap_ver int;
  declare http_meth, content_type, ini_dflt_graph, get_user, jsonp_callback varchar;
  declare state, msg varchar;
  declare metas, rset any;
  declare accept, soap_action, user_id varchar;
  declare exec_time, exec_db_activity any;
  declare __debug_mode integer;
  declare qtxt, deadl integer;
  declare save_mode, save_dir, dav_refresh, fname varchar;
  declare save_dir_id any;
  declare help_topic varchar;
  -- dbg_obj_princ ('===============');
  -- dbg_obj_princ ('===============');
  -- dbg_obj_princ ('===============');
  -- dbg_obj_princ ('WS.WS."/!sparql/" (', path, params, lines, ')');
  for (declare i int, i := 0; i < length (params); i := i + 2)
    {
      declare vn, vv varchar;
      vn := params[i];
      vv := params[i+1];
      if (not (isstring (vv)) or (vv <> ''))
        connection_set ('SPARQL_' || vn, vv);
    }
  if (registry_get ('__sparql_endpoint_debug') = '1')
    {
      __debug_mode := 1;
      for (declare i int, i := 0; i < length (params); i := i + 2)
        {
	  if (isstring (params[i+1]))
	    dbg_printf ('%s=%s',params[i],params[i+1]);
	  else if (__tag (params[i+1]) = 185)
	    dbg_printf ('%s=%s',params[i],'<strses>');
	  else
	    dbg_printf ('%s=%s',params[i],'<box>');
	}
    }

  set http_charset='utf-8';
  http_methods_set ('OPTIONS', 'GET', 'HEAD', 'POST', 'TRACE');
  ses := 0;
  query := null;
  format := '';
  should_sponge := '';
  debug := get_keyword ('debug', params, case (get_keyword ('query', params, '')) when '' then '1' else '' end);
  add_http_headers := 1;
  sp_ini := 0;
  dflt_graphs := vector ();
  named_graphs := vector ();
  maxrows := 1024*1024; -- More than enough for web-interface.
  deadl := 0;
  http_meth := http_request_get ('REQUEST_METHOD');
  ini_dflt_graph := virtuoso_ini_item_value ('SPARQL', 'DefaultGraph');
  hard_timeout := atoi (coalesce (virtuoso_ini_item_value ('SPARQL', 'MaxQueryExecutionTime'), '0')) * 1000;
  timeout := atoi (coalesce (virtuoso_ini_item_value ('SPARQL', 'ExecutionTimeout'), '0')) * 1000;
  client_supports_partial_res := 0;

  user_id := connection_get ('SPARQLUserId', 'SPARQL');
  help_topic := get_keyword ('help', params, null);
  if (help_topic is not null)
    goto brief_help;

  def_qry := get_keyword('qtxt', params, '');
  ini_dflt_graph := get_keyword ('default-graph-uri', params, ini_dflt_graph);
  timeout := atoi (get_keyword ('timeout', params, cast (timeout as varchar)));

  if ('' <> def_qry)
    qtxt := 1;
  def_max := atoi (coalesce (virtuoso_ini_item_value ('SPARQL', 'ResultSetMaxRows'), '-1'));
  -- if timeout specified and it's over 1 second


  fname := trim (get_keyword ('fname', params, ''));
  if (fname = '')
    fname := null;

  dav_refresh := get_keyword ('dav_refresh', params, '');
  if (dav_refresh = '')
    dav_refresh := null;

  save_mode := get_keyword ('save', params, '');

  if (save_mode = '' OR save_mode = 'display') {
    save_mode := null;
    dav_refresh := null;
    fname := null;
  } else if (save_mode = 'dynamic' OR dav_refresh is not null) {
    save_mode := 'dynamic';
    dav_refresh := '1';
  } else {
    save_mode := 'tmpstatic';
    dav_refresh := null;
  }

  get_user := '';
  soap_ver := 0;
  soap_action := http_request_header (lines, 'SOAPAction', null, null);
  content_type := http_request_header (lines, 'Content-Type', null, '');

  if (content_type = 'application/soap+xml')
    soap_ver := 12;
  else if (soap_action is not null)
    soap_ver := 11;

  content := null;
  declare exit handler for sqlstate '*' {
    DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
      '500', 'SPARQL Request Failed',
      query, __SQL_STATE, __SQL_MESSAGE, format);
     return;
   };

  -- the WSDL
  if (http_path () = '/sparql/services.wsdl')
    {
      http_header ('Content-Type: application/wsdl+xml\r\n');
--      http_header ('Content-Type: text/xml\r\n');
      DB.DBA.SPARQL_WSDL (lines);
      return;
    }
  else if (http_path () = '/sparql/services11.wsdl')
    {
      http_header ('Content-Type: text/xml\r\n');
      DB.DBA.SPARQL_WSDL11 (lines);
      return;
    }

  if (__debug_mode) dbg_printf ('%d', soap_ver);

  if (get_keyword ('nsdecl', params) is not null)
    {
      WS.WS.sparql_predefined_nsdecl ();
      return;
    }
  if (get_keyword ('rdfinf', params) is not null)
    {
      WS.WS.sparql_predefined_rdfinf ();
      return;
    }

  can_sponge := coalesce ((select top 1 1
      from DB.DBA.SYS_USERS as sup
        join DB.DBA.SYS_ROLE_GRANTS as g on (sup.U_ID = g.GI_SUPER)
        join DB.DBA.SYS_USERS as sub on (g.GI_SUB = sub.U_ID)
      where sup.U_NAME = 'SPARQL' and sub.U_NAME = 'SPARQL_SPONGE' ), 0);

  paramcount := length (params);

  if ((0 = paramcount) or
      (((2 = paramcount) and ('Content' = params[0])) and soap_ver = 0) or
      qtxt = 1)
    {
       declare redir, acc varchar;
       redir := registry_get ('WS.WS.SPARQL_DEFAULT_REDIRECT');
       if (isstring (redir))
         {
            http_request_status ('HTTP/1.1 301 Moved Permanently');
            http_header (sprintf ('Location: %s\r\n', redir));
            return;
         }
      if (not qtxt)
        {
          def_qry := virtuoso_ini_item_value ('SPARQL', 'DefaultQuery');
          if (def_qry is null)
            def_qry := 'SELECT * WHERE {?s ?p ?o}';
        }

      if (qtxt <> 1)
	{
	  acc := DB.DBA.HTTP_RDF_GET_ACCEPT_BY_Q (http_request_header_full (lines, 'Accept', '*/*'));
	  if (strstr (acc, '/rdf+xml') is not null or strstr (acc, 'text/n3') is not null or strstr (acc, 'text/turtle') is not null)
	    {
	       query := sprintf ('construct { ?s ?p ?o } from <http://%s/sparql> { ?s ?p ?o }', registry_get ('URIQADefaultHost'));
	       accept := acc;
	       goto execute_query;
	    }
	}

      WS.WS.SPARQL_ENDPOINT_GENERATE_FORM(params, ini_dflt_graph, def_qry, timeout, debug, save_mode, dav_refresh);

      return;
    }
  execute_query:
  qry_params := dict_new (7);
  for (paramctr := 0; paramctr < paramcount; paramctr := paramctr + 2)
    {
      declare pname, pvalue varchar;
      pname := params [paramctr];
      pvalue := params [paramctr+1];
      if ('query' = pname)
        query := pvalue;
      else if ('find' = pname)
	{
	  declare cls, words, ft, vec, cond varchar;
	  cls := get_keyword ('class', params);
	  maxrows := atoi (get_keyword ('maxrows', params, cast (maxrows as varchar)));
	  if (def_max > 0 and def_max < maxrows)
	    maxrows := def_max;
	  if (cls is not null)
	    cond := sprintf (' ?s a %s . ', cls);
          else
	    cond := '';
	  ft := trim (DB.DBA.FTI_MAKE_SEARCH_STRING_INNER (pvalue, words), '()');
          if (ft is null or length (words) = 0)
            {
              DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
                '400', 'Bad Request',
                query, '22023', 'The value of "find" parameter of web service endpoint is not a valid search string' );
              return;
            }
	  vec := DB.DBA.SYS_SQL_VECTOR_PRINT (words);
	  if (get_keyword ('format', params, '') like '%/rdf+%' or http_request_header (lines, 'Accept', null, '') like '%/rdf+%')
	    query := sprintf ('construct { ?s ?p `bif:search_excerpt (bif:vector (%s), sql:rdf_find_str(?o))` } ' ||
	    'where { ?s ?p ?o . %s filter (bif:contains (?o, ''%s'')) } limit %d', vec, cond, ft, maxrows);
	  else
	    query := sprintf ('select ?s ?p (bif:search_excerpt (bif:vector (%s), sql:rdf_find_str(?o))) ' ||
	    'where { ?s ?p ?o . %s filter (bif:contains (?o, ''%s'')) } limit %d', vec, cond, ft, maxrows);
	}
      else if ('default-graph-uri' = pname and length (pvalue))
        {
	  if (position (pvalue, dflt_graphs) <= 0)
	    dflt_graphs := vector_concat (dflt_graphs, vector (pvalue));
	}
      else if ('named-graph-uri' = pname and length (pvalue))
        {
	  if (position (pvalue, named_graphs) <= 0)
	    named_graphs := vector_concat (named_graphs, vector (pvalue));
	}
      else if ('maxrows' = pname)
        {
	  maxrows := cast (pvalue as integer);
	}
      else if ('should-sponge' = pname)
        {
          if (can_sponge)
            should_sponge := trim(pvalue);
	}
      else if ('format' = pname or 'output' = pname)
        {
	  format := pvalue;
	}
      else if ('timeout' = pname and length (pvalue))
        {
          declare t integer;
          t := cast (pvalue as integer);
          if (t is not null and t >= 1000)
            {
              if (hard_timeout >= 1000)
                timeout := __min (t, hard_timeout);
              else
                timeout := t;
            }
          client_supports_partial_res := 1;
	}
      else if ('ini' = pname)
        {
	  sp_ini := 1;
	}
      else if (query is null and 'query-uri' = pname and length (pvalue))
	{
	  if (virtuoso_ini_item_value ('SPARQL', 'ExternalQuerySource') = '1')
	    {
	      declare uri varchar;
	      declare hf, hdr, charset any;
	      uri := pvalue;
	      if (uri like 'http://%' and uri not like 'http://localdav.virt/%' and uri not like 'http://local.virt/dav/%')
		{
		  query := http_get (uri, hdr);
		  if (hdr[0] not like '% 200%')
		    signal ('22023', concat ('HTTP request failed: ', hdr[0], 'for URI ', uri));
		  charset := http_request_header (hdr, 'Content-Type', 'charset', '');
		  if (charset <> '')
		    {
		      query := charset_recode (query, charset, 'UTF-8');
		    }
		}
	      else
		{
		  query := DB.DBA.XML_URI_GET ('', pvalue);
	        }
	    }
	  else
	    {
	       DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
		    '403', 'Prohibited', query, '22023', 'The external query sources are prohibited.');
	       return;
	    }
	}
      else if ('xslt-uri' = pname and length (pvalue))
	{
	  if (virtuoso_ini_item_value ('SPARQL', 'ExternalXsltSource') = '1')
	    {
	      add_http_headers := 0;
	      http_xslt (pvalue);
	    }
	  else
	    {
	       DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
		    '403', 'Prohibited', query, '22023', 'The XSL-T transformation is prohibited');
	       return;
	    }
	}
      else if ('get-login' = pname)
	{
	  get_user := pvalue;
	}
      else if ('callback' = pname)
        {
          jsonp_callback := pvalue;
        }
      else if (pname[0] = '?'[0])
        {
          dict_put (qry_params, subseq (pname, 1), pvalue);
        }
    }
  if (format <> '')
  {
    format := (
      case lower(format)
        when 'json' then 'application/sparql-results+json'
        when 'js' then 'application/javascript'
        when 'html' then 'text/html'
        when 'sparql' then 'application/sparql-results+xml'
        when 'xml' then 'application/sparql-results+xml'
        when 'rdf' then 'application/rdf+xml'
        when 'n3' then 'text/rdf+n3'
        when 'cxml' then 'text/cxml'
        when 'cxml+qrcode' then 'text/cxml+qrcode'
        when 'csv' then 'text/csv'
        else format
      end);
  }

  if (def_max > 0 and def_max < maxrows)
    maxrows := def_max;

  --if (0 = length (dflt_graphs) and length (ini_dflt_graph))
  --  dflt_graphs := vector (ini_dflt_graph);


  -- SOAP 1.2 operation begins
  if (http_meth = 'POST' and soap_ver > 0)
    {
       declare xt, dgs, ngs any;
       declare soap_ns, spt_ns, ns_decl varchar;
       soap_ns := DB.DBA.SPARQL_SOAP_NS (soap_ver);
       spt_ns := DB.DBA.SPARQL_PT_NS ();
       ns_decl := '[ xmlns:soap="'||soap_ns||'" xmlns:sp="'||spt_ns||'" ] ';
       content := http_body_read ();
       if (__debug_mode)
         dbg_printf ('content=[%s]', string_output_string (content));
       xt := xtree_doc (content);
       query := charset_recode (xpath_eval (ns_decl||'string (/soap:Envelope/soap:Body/sp:query-request/query)', xt), '_WIDE_', 'UTF-8');
       dgs := xpath_eval (ns_decl||'/soap:Envelope/soap:Body/sp:query-request/default-graph-uri', xt, 0);
       ngs := xpath_eval (ns_decl||'/soap:Envelope/soap:Body/sp:query-request/named-graph-uri', xt, 0);
       foreach (any frag in dgs) do
	 {
	   declare pvalue varchar;
	   pvalue := charset_recode (xpath_eval ('string(.)', frag), '_WIDE_', 'UTF-8');
	   if (position (pvalue, dflt_graphs) <= 0)
	     dflt_graphs := vector_concat (dflt_graphs, vector (pvalue));
	 }
       foreach (any frag in ngs) do
	 {
	   declare pvalue varchar;
	   pvalue := charset_recode (xpath_eval ('string(.)', frag), '_WIDE_', 'UTF-8');
	   if (position (pvalue, named_graphs) <= 0)
	     named_graphs := vector_concat (named_graphs, vector (pvalue));
	 }
       format := sprintf('application/soap+xml;%d', soap_ver);
    }
  if (format <> '')
    accept := format;
  else
    accept := http_request_header (lines, 'Accept', null, '');
  if (sp_ini)
    {
      SPARQL_INI_PARAMS (metas, rset);
      goto write_results;
    }

  if (query is null)
    {
      if (strstr (content_type, 'application/xml') is not null)
        {
          DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
            '400', 'Bad Request',
	    query, '22023', 'XML notation of SPARQL queries is not supported' );
	  return;
	}
      DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
        '400', 'Bad Request',
        query, '22023', 'The request does not contain text of SPARQL query', format);
      return;
    }

  full_query := query;
  -- dbg_obj_princ ('dflt_graphs = ', dflt_graphs, ', named_graphs = ', named_graphs);
  declare req_hosts varchar;
  declare req_hosts_split any;
  declare hctr integer;
  req_hosts := http_request_header (lines, 'Host', null, null);
  req_hosts := replace (req_hosts, ', ', ',');
  req_hosts_split := split_and_decode (req_hosts, 0, '\0\0,');
  for (hctr := length (req_hosts_split) - 1; hctr >= 0; hctr := hctr - 1)
    {
      for (select top 1 SH_GRAPH_URI, SH_DEFINES from DB.DBA.SYS_SPARQL_HOST
      where req_hosts_split [hctr] like SH_HOST) do
        {
          if (length (dflt_graphs) = 0 and length (SH_GRAPH_URI))
            dflt_graphs := vector (SH_GRAPH_URI);
          if (SH_DEFINES is not null)
            full_query := concat (SH_DEFINES, ' ', full_query);
          goto host_found;
        }
    }
host_found:

  foreach (varchar dg in dflt_graphs) do
    {
      full_query := concat ('define input:default-graph-uri <', dg, '> ', full_query);
      http_header (http_header_get () || sprintf ('X-SPARQL-default-graph: %s\r\n', dg));
    }
  foreach (varchar ng in named_graphs) do
    {
      full_query := concat ('define input:named-graph-uri <', ng, '> ', full_query);
      http_header (http_header_get () || sprintf ('X-SPARQL-named-graph: %s\r\n', ng));
    }
  if ((should_sponge = 'soft') or (should_sponge = 'replacing'))
    full_query := concat (sprintf('define get:soft "%s" ',should_sponge), full_query);
  else if (should_sponge = 'grab-all')
    full_query := concat ('define input:grab-all "yes" define input:grab-depth 5 define input:grab-limit 100 ', full_query);
  else if (should_sponge = 'grab-all-seealso')
    full_query := concat ('define input:grab-all "yes" define input:grab-depth 5 define input:grab-limit 200 define input:grab-seealso <http://www.w3.org/2000/01/rdf-schema#seeAlso> define input:grab-seealso <http://xmlns.com/foaf/0.1/seeAlso> ', full_query);
  else if (should_sponge = 'grab-everything')
    full_query := concat ('define input:grab-all "yes" define input:grab-intermediate "yes" define input:grab-depth 5 define input:grab-limit 500 define input:grab-seealso <http://www.w3.org/2000/01/rdf-schema#seeAlso> define input:grab-seealso <http://xmlns.com/foaf/0.1/seeAlso> ', full_query);
--  full_query := concat ('define output:valmode "LONG" ', full_query);
  if (debug <> '')
    full_query := concat ('define sql:signal-void-variables 1 ', full_query);
  if (get_user <> '')
    full_query := concat ('define get:login "', get_user, '" ', full_query);
  if (dict_size (qry_params) > 0)
    {
      declare pnames any;
      pnames := dict_list_keys (qry_params, 0);
      foreach (varchar pname in pnames) do
        {
          full_query := concat ('define sql:param "', pname, '" ', full_query);
        }
      qry_params := DB.DBA.PARSE_SPARQL_WS_PARAMS (dict_to_vector (qry_params, 1));
    }
  else
    qry_params := vector ();
  if (save_mode is not null and save_mode <> 'display')
    client_supports_partial_res := 0; -- because result is not sent at all in this case

  if (format <> '')
    {
      full_query := '\n#output-format:' || format || '\n' || full_query;
    }
  if (not client_supports_partial_res) -- partial results do not work with chunked encoding
    {
    -- No need to choose accurately if there are no variants.
    -- Disabled due to empty results:
    --  if (strchr (accept, ' ') is null)
    --    {
    --      if (accept='application/sparql-results+xml')
    --        full_query := 'define output:format "HTTP+XML application/sparql-results+xml" ' || full_query;
    ----      else if (accept='application/rdf+xml')
    ----        full_query := 'define output:format "HTTP+RDF/XML application/rdf+xml" ' || full_query;
    --    }
    --  else
    -- No need to choose accurately if there is the best variant.
    -- Disabled due to empty results:
    --    {
          declare fmtxml, fmtttl varchar;
          if (strstr (accept, 'application/sparql-results+xml') is not null)
            fmtxml := '"HTTP+XML application/sparql-results+xml" ';
          if (strstr (accept, 'text/rdf+n3') is not null)
            fmtttl := '"HTTP+TTL text/rdf+n3" ';
          else if (strstr (accept, 'text/rdf+ttl') is not null)
            fmtttl := '"HTTP+TTL text/rdf+ttl" ';
          else if (strstr (accept, 'text/rdf+turtle') is not null)
            fmtttl := '"HTTP+TTL text/rdf+turtle" ';
          else if (strstr (accept, 'text/turtle') is not null)
            fmtttl := '"HTTP+TTL text/turtle" ';
          else if (strstr (accept, 'application/turtle') is not null)
            fmtttl := '"HTTP+TTL application/turtle" ';
          else if (strstr (accept, 'application/x-turtle') is not null)
            fmtttl := '"HTTP+TTL application/x-turtle" ';
          if (isstring (fmtttl))
            {
              if (isstring (fmtxml))
                full_query := 'define output:format ' || fmtxml || 'define output:dict-format ' || fmtttl || full_query;
              else
                full_query := 'define output:format ' || fmtttl || full_query;
            }
    --    }
    ;
    }
  -- if odata asked we imply CBD
  if (accept = 'application/atom+xml' or accept = 'application/odata+json')
    {
      full_query := 'define sql:describe-mode "CBD" ' || full_query;
    }

  state := '00000';
  metas := null;
  rset := null;
  if (__debug_mode)
    dbg_printf ('query=[%s]', full_query);

  declare sc_max int;
  declare sc decimal;
  sc_max := atoi (coalesce (virtuoso_ini_item_value ('SPARQL', 'MaxQueryCostEstimationTime'), '-1'));
  if (sc_max < 0)
    sc_max := atoi (coalesce (virtuoso_ini_item_value ('SPARQL', 'MaxExecutionTime'), '-1'));
  if (sc_max > 0)
    {
      state := '00000';
      full_query := concat ('define sql:big-data-const 0 ', full_query);
      sc := exec_score (concat ('sparql ', full_query), state, msg);
      if ((sc/1000) > sc_max)
	{
	  signal ('42000', sprintf ('The estimated execution time %d (sec) exceeds the limit of %d (sec).', sc/1000, sc_max));
	}
    }

  state := '00000';
  metas := null;
  rset := null;

  save_dir := coalesce ((select U_HOME from DB.DBA.SYS_USERS where U_NAME = user_id and U_DAV_ENABLE));
  if (DAV_HIDE_ERROR (DAV_SEARCH_ID (save_dir, 'C')) is null)
    save_dir := null;
  else
    {
      save_dir := save_dir || 'saved-sparql-results/';
      save_dir_id := DAV_SEARCH_ID (save_dir, 'C');
      if (DAV_HIDE_ERROR (save_dir_id) is null)
	save_dir := null;
    }

  -- dbg_obj_princ ('accept = ', accept);
  -- dbg_obj_princ ('format = ', format);
  -- dbg_obj_princ ('full_query = ', full_query);
  -- dbg_obj_princ ('qry_params = ', qry_params);
  -- dbg_obj_princ ('save_mode = ', save_mode, ' save_dir = ', save_dir);
  commit work;
  if (client_supports_partial_res and (timeout > 0))
    {
      set RESULT_TIMEOUT = timeout;
      -- dbg_obj_princ ('anytime timeout is set to', timeout);
      set TRANSACTION_TIMEOUT=timeout + 10000;
    }
  else if (hard_timeout >= 1000)
    {
      set TRANSACTION_TIMEOUT=hard_timeout;
    }
  set_user_id (user_id, 1);
  again:
  state := '00000';
  start_time := msec_time();
  exec ( concat ('sparql ', full_query), state, msg, qry_params, vector ('max_rows', maxrows, 'use_cache', 1), metas, rset);
  commit work;
  -- dbg_obj_princ ('exec metas=', metas, ', state=', state, ', msg=', msg);
  if (state = '00000')
    goto write_results;
  if (state = 'S1TAT')
    {
      exec_time := msec_time () - start_time;
      exec_db_activity := db_activity ();
      --reply := xmlelement ("facets", xmlelement ("sparql", qr), xmlelement ("time", msec_time () - start_time),
      --                 xmlelement ("complete", cplete),
      --                 xmlelement ("db-activity", db_activity ()), res[0][0]);
    }
  else if ((not http_is_flushed ()) and state = '40001' and deadl < 6)
    {
      declare dt int;
      rollback work;
      deadl := deadl + 1;
      dt := ((rnd (5) + 1) / 10.0) * (2 * deadl);
      delay (dt);
      goto again;
    }
  else
    {
      declare state2, msg2 varchar;
      state2 := '00000';
      exec ('isnull (sparql_to_sql_text (''define sql:big-data-const 0 '' || ?))', state2, msg2, vector (full_query));
      if (state2 <> '00000')
        {
          DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
            '400', 'Bad Request',
            full_query, state2, msg2, format);
          return;
        }
      DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
        '500', 'SPARQL Request Failed',
        full_query, state, msg, format);
      return;
    }

write_results:
  if (save_mode is not null)
    {
      declare status any;
      if ((1 = length (metas[0])) and ('aggret-0' = metas[0][0][0]))
        {
          DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
            '500', 'SPARQL Request Failed',
            full_query, '00000', 'The result of the query can not be saved to a DAV resource', format);
          return;
        }
    }
  if ((1 <> length (metas[0])) or ('aggret-0' <> metas[0][0][0]))
    {
      declare status any;
      if (isinteger (msg))
        status := NULL;
      else
        status := vector (state, msg, exec_time, exec_db_activity);
      if (save_mode is not null)
        {
          if ((not isinteger (save_dir_id)) or not exists (select top 1 1 from WS.WS.SYS_DAV_COL where COL_ID = save_dir_id and COL_DET='DynaRes'))
            {
              DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
                '500', 'SPARQL Request Failed',
                full_query, '00000', sprintf ('To keep saved SPARQL results, the DAV directory "%.200s" should be of DAV extension type "DynaRes"', save_dir), format);
              return;
            }
          if (fname is not null)
            {
              if (strchr (fname, '/') is not null)
                {
                  DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
                    '500', 'SPARQL Request Failed',
                    full_query, '00000', sprintf ('The specified resource name "%.200s" contains illegal characters', fname), format);
                  return;
                }
            }
          ses := string_output ();
          add_http_headers := 0;
        }
      if (isstring (jsonp_callback))
        http (jsonp_callback || '(\n', ses);
      DB.DBA.SPARQL_RESULTS_WRITE (ses, metas, rset, accept, add_http_headers, status);
      if (isstring (jsonp_callback))
        http (')', ses);
      if (save_mode is not null)
        {
          declare sparql_uid integer;
          declare refresh_sec, ttl_sec integer;
          declare full_uri varchar;
          sparql_uid := (SELECT U_ID from DB.DBA.SYS_USERS where U_NAME = user_id);
          if (fname is null)
            {
              if (save_mode = 'tmpstatic')
                fname := sprintf ('%.100s - SPARQL result - made by %.100s', cast (now() as varchar), user_id);
              else
                fname := sprintf ('%.100s - cached and renewable SPARQL result - made by %.100s', cast (now() as varchar), user_id);
            }
          refresh_sec := case (save_mode) when 'tmpstatic' then null else __max (600, coalesce (hard_timeout, 1000)/100) end;
          ttl_sec := 172800;
          full_uri := concat ('http://', registry_get ('URIQADefaultHost'), DAV_SEARCH_PATH (save_dir_id, 'C'), fname);
          "DynaRes_INSERT_RESOURCE" (
	      detcol_id => save_dir_id,
	      fname => fname,
	      owner_uid => sparql_uid,
	      refresh_seconds => refresh_sec,
	      ttl_seconds => ttl_sec,
	      mime => accept,
	      exec_stmt => 'DB.DBA.SPARQL_REFRESH_DYNARES_RESULTS (?, ?, ?, ?, ?, ?, ?)',
	      exec_params => vector (full_query, qry_params, maxrows, accept, user_id, hard_timeout, jsonp_callback),
	      exec_uname => user_id,
	      content => ses
	  );

	  WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE();
	  http ('<head>\n');
	  WS.WS.SPARQL_ENDPOINT_HTML_HEAD('Virtuoso SPARQL Query Editor | Save to DAV');
	  WS.WS.SPARQL_ENDPOINT_STYLE();
	  http ('</head>\n');
	  http ('<body>\n');
	  http ('    <div id="header">\n');
	  http ('	<h1 id="title">Virtuoso SPARQL Query Editor</h1>\n');
	  http ('    </div>\n\n');
	  http ('<h3>Saved to DAV</h3>');
	  http ('<p>The SPARQL result is successfully saved in DAV storage as <a href="');
	  http_value (full_uri);
	  http ('">');
	  http_value (full_uri);
	  http ('</a></p>');
	  if (refresh_sec is not null)
	  http (sprintf ('<p>The content of the linked resource will be re-calculated on demand, and the result will be cached for %d minutes.</p>', refresh_sec/60));
	  if (ttl_sec is not null)
	  http (sprintf ('<p>The link will stay valid for %d days. To preserve the referenced document for future use, copy it to some other location before expiration.</p>', ttl_sec/(60*60*24)));
	  if (accept <> 'text/html')
	  http (sprintf ('<p>The resource MIME type is "%s". This type will be reported to the browser when you click on the link.
	  If the browser is unable to open the link itself it can prompt for action like launching an additional program.
	  The program may let you edit the loaded resource, in this case save the changed version should be saved to a different place, so use "Save As" command, not plain "Save".</p>', accept));
	  http ('</body></html>');
        }
    }
  else
    {
      if (save_mode is not null)
        {
          DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
            '500', 'SPARQL Request Failed',
            full_query, '00000', 'The result of the query can not be saved to a DAV resource', format);
          return;
        }
    }
return;

brief_help:
  WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE();

  http('<head>\n');
  WS.WS.SPARQL_ENDPOINT_HTML_HEAD('Virtuoso SPARQL Query Editor | About');
  WS.WS.SPARQL_ENDPOINT_STYLE ();
  http('</head>\n');

  http('<body>\n');
  http ('    <div id="header">\n');
  http('	<h1 id="title">Virtuoso SPARQL Query Editor | About</h1>\n');
  http ('    </div>\n\n');

  http ('    <div id="help">\n');
  if (help_topic='intro')
    {
      http('<h3>Intro</h3>');
      http('	<p>This page is designed to help you test the OpenLink Virtuoso SPARQL protocol endpoint.<br/>\n');
      http('	Consult the <a href="http://virtuoso.openlinksw.com/wiki/main/Main/VOSSparqlProtocol">Virtuoso Wiki page</a> describing the service \n');
      http('	or the <a href="http://docs.openlinksw.com/virtuoso/">Online Virtuoso Documentation</a> section <a href="http://docs.openlinksw.com/virtuoso/rdfandsparql.html">RDF Database and SPARQL</a>.</p>\n');
      http('	<p>There is also a rich Web based user interface with sample queries. \n');
      if (DB.DBA.VAD_CHECK_VERSION('iSPARQL') is null)
	  http('	In order to use it you must install the iSPARQL package (isparql_dav.vad).</p>\n');
      else
	  http('	You can access it at: <a href="/isparql">/isparql</a>.</p>\n');
      http('	<p>For your convenience we have a set of <a href="/sparql?nsdecl">predefined name space prefixes</a> and <a href="/sparql?rdfinf">inference rules</a></p>\n');

      http('	<h3>What is SPARQL?</h3>\n');
      http('	<p>SPARQL is the W3C''s declaritive query-language for Graph Model Databases and Stores.</p>\n');
      http('    <p>As is the case with regards to SQL for relational databases and XQUERY for XML databases, ');
      http('    SPARQL is database and host operating system independent.<p>\n');
      http('	<p>The development and evolution of this standard is overseen by the\n');
      http('	<a href="http://www.w3.org/2009/sparql/wiki/Main_Page">SPARQL Working Group</a> within W3C and\n');
      http('	while parts of the language are still in active <a href="http://www.w3.org/TR/2011/WD-sparql11-query-20110512/">development</a>, it is fully <a href="http://www.w3.org/TR/rdf-sparql-query/">documented</a> and <a href="http://www.w3.org/2009/05/sparql-phase-II-charter">publicly</a> available.</p>\n');
    }
  else if (help_topic='enable_sponge')
    {
      declare host_ur varchar;
      host_ur := registry_get ('URIQADefaultHost');
      host_ur := http_request_header (lines, 'Host', null, host_ur);
      http('<h3>How To Enable Sponge?</h3>
      <p>When a new Virtuoso server is installed, the default security restrictions do not allow SPARQL endpoint users to retrieve remote RDF data.
      To remove this restriction, the DBA should grant "SPARQL_SPONGE" privilege to "SPARQL" account.
      If you are the Database Administrator and want to enable this feature, you can perform the following steps:</p>\n');
      http('<ol>\n');
      http('<li>Go to the Virtuoso Administration Conductor i.e. \n');
      if (not isstring (host_ur))
          http('http://host:port/conductor .');
      else
          http( sprintf('<a href="http://%s/conductor">http://%s/conductor</a>.', host_ur, host_ur));
      http('</li>\n');
      http('<li>Login as dba user.</li>\n');
      http('<li>Go to System Admin->User Accounts->Roles</li>\n');
      http('<li>Click the link "Edit" for "SPARQL_SPONGE"</li>\n');
      http('<li>Select from the list of available user/groups "SPARQL" and click the ">>" button so to add it to the right-positioned list.\n</li>');
      http('<li>Click the button "Update"</li>\n');
      http('<li>Access again the sparql endpoint in order to be able to retrieve remote data.</li>\n');
      http('</ol>\n');
    }
  else if (help_topic='enable_cxml')
    {
      http('<h3>How To Enable CXML Support</h3>');
      http('<p>CXML is data exchange format for so-called "faceted view". It can be displayed by programs like Microsoft Pivot.</p>');
      http('<p>For best results, the result of the query should contain links to images associated with described data and follow some rules, described in the User&apos;s Guide.</p>');
      http('<p>This feature is supported by combination of four components:</p>\n');
      http('<ol>\n');
      http('<li>The Virtuoso Universal Server (Virtuoso Open Source does not contain some required functions)</li>\n');
      http('<li>The ImageMagick plugin (version 0.6 or newer) and optionally the QRcode plugin</li>\n');
      http('<li>The QRcode plugin (version 0.1 or newer)</li>\n');
      http('<li>The sparql_cxml VAD package (which in turn requires the &quot;RDF mappers&quot; package)</li>\n');
      http('</ol>\n');
      http('<p>As soon as all these components are installed, the SPARQL web service endpoint will add the &quot;CXML&quot; option to the list of available formats.</p>\n');
    }
  else if (help_topic='enable_det')
    {
      http('<h3>How To Let the SPARQL Endpoint Save Results In WebDAV?</h3>');
      http('<p>By default, the SPARQL endpoint can only sent the result back to the client. This can be inconvenient if the result should be accessible for programs like file managers and archivers.</p>');
      http('<p>The solution is to let the endpoint create &quot;dynamic&quot;resources in a WebDAV folder on the Virtuoso server. A WebDAV client, e.g. the built-in client of Windows Explorer, can connect to that storage and access these resources as if they are plain local files.</p>');
      http('<p>If you are the Database Administrator and want to enable this feature, you can perform the following steps:</p>\n');
      http('<ol>\n');
      http( sprintf('<li>This web service endpoint runs under the &quot;%.100s&quot; account. This user should have an access to WebDAV (U_DAV_ENABLE=1 in DB.DBA.SYS_USERS)</li>\n', user_id));
      http( sprintf('<li>A WebDAV home directory (e.g. <a href="/DAV/home/%.100s/">/DAV/home/%.100s/</a>) should be created and the path to it should be remembered in DB.DBA.SYS_USERS (U_HOME) field;<br />(do not forget the leading and the trailing slash chars).</li>\n', user_id, user_id));
      http( sprintf('<li>This home directory should contain a subdirectory named &quot;saved-sparql-results&quot;, and the subdirectory should be of &quot;DynaRes&quot; DAV Extension Type.</li>\n'));
      http('</ol>\n');
      http('<p>As soon as the appropriate directory exists, the SPARQL web service endpoint will show additional controls to choose how to save results.</p>\n');
    }
  else if (help_topic='enable_det')
    {
      DB.DBA.SPARQL_PROTOCOL_ERROR_REPORT (path, params, lines,
        '500', 'Request Failed',
        'Invalid help topic', format);
    }
  http('');
  http('<p>To close this help, press ');
  http ('<button type="button" name="back" value="Back" onclick="javascript:history.go(-1);">Back</button>\n');
  http(' or use the &quot;back&quot; button of the browser.</p>\n');
  http('</div>\n\n');
  WS.WS.SPARQL_ENDPOINT_FOOTER();
  http('</body>\n');
  http('</html>\n');
}
;

registry_set ('/!sparql/', 'no_vsp_recompile')
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_CRUD_BASE_EV_NEW_BLANK (inout g_iid IRI_ID, inout app_env any, inout res IRI_ID)
{
  res := min_bnode_iri_id ();
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_CRUD_BASE_EV_TRIPLE (
  inout g_iid IRI_ID, inout s_uri varchar, inout p_uri varchar,
  inout o_uri varchar,
  inout app_env any )
{
  signal ('22023', 'The graph URI is relative and can not be resolved using the submitted resource (base should be declared before data for the first triple)');
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_CRUD_BASE_EV_TRIPLE_L (
  inout g_iid IRI_ID, inout s_uri varchar, inout p_uri varchar,
  inout o_val any, inout o_type varchar, inout o_lang varchar,
  inout app_env any )
{
  signal ('22023', 'The graph URI is relative and can not be resolved using the submitted resource (base should be declared before data for the first triple)');
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_CRUD_BASE_EV_NEW_BASE (
  inout base_uri varchar,
  inout graph_uri varchar,
  inout app_env any )
{
  app_env[0] := DB.DBA.XML_URI_RESOLVE_LIKE_GET (base_uri, graph_uri);
  signal ('ok001', '');
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_CRUD_BASE_TTL (inout strg any, in graph_uri varchar, in flags integer := 255)
{
  declare app_env any;
  if (126 = __tag (strg))
    strg := cast (strg as varchar);
  app_env := vector (null);
  whenever sqlstate 'ok001' goto done;
  rdf_load_turtle (strg, '', graph_uri, flags,
    vector (
      '',
      'DB.DBA.SPARQL_CRUD_BASE_EV_NEW_BLANK',
      'DB.DBA.TTLP_EV_GET_IID',
      'DB.DBA.SPARQL_CRUD_BASE_EV_TRIPLE',
      'DB.DBA.SPARQL_CRUD_BASE_EV_TRIPLE_L',
      '',
      '',
      'DB.DBA.SPARQL_CRUD_BASE_EV_NEW_BASE' ),
    app_env);
done:
  return app_env[0];
}
;

--!AWK PUBLIC
create procedure DB.DBA.SPARQL_CRUD_BASE_RDFXML (in strg any, in graph_uri varchar)
{
  declare app_env any;
  app_env := vector (null);
  whenever sqlstate 'ok001' goto done;
  rdf_load_rdfxml (strg, 0,
    graph_uri,
    vector (
      '',
      'DB.DBA.SPARQL_CRUD_BASE_EV_NEW_BLANK',
      'DB.DBA.TTLP_EV_GET_IID',
      'DB.DBA.SPARQL_CRUD_BASE_EV_TRIPLE',
      'DB.DBA.SPARQL_CRUD_BASE_EV_TRIPLE_L',
      '',
      '',
      'DB.DBA.SPARQL_CRUD_BASE_EV_NEW_BASE' ),
    app_env );
done:
  return app_env[0];
}
;

create procedure WS.WS."/!sparql-graph-crud/" (inout path varchar, inout params any, inout lines any)
{
  declare user_id varchar;
  declare reqbegin varchar;
  declare graph_uri varchar;
  declare graph_uri_is_relative integer;
  -- dbg_obj_princ ('===============');
  -- dbg_obj_princ ('===============');
  -- dbg_obj_princ ('===============');
  -- dbg_obj_princ ('WS.WS."/!sparql-graph-crud/" (', path, params, lines, ')');
  set http_charset='utf-8';
  user_id := connection_get ('SPARQLUserId', 'SPARQL');
  reqbegin := lines[0];
  graph_uri := trim(get_keyword ('graph-uri', params, ''));
  if (isstring (get_keyword ('default', params)))
    {
      declare req_hosts varchar;
      declare req_hosts_split any;
      declare hctr integer;
      if (graph_uri <> '')
        signal ('22023', 'The request to SPARQL 1.1 Graph Store endpoint contains both "graph" and "default" params');
      req_hosts := http_request_header (lines, 'Host', null, null);
      req_hosts := replace (req_hosts, ', ', ',');
      req_hosts_split := split_and_decode (req_hosts, 0, '\0\0,');
      for (hctr := length (req_hosts_split) - 1; hctr >= 0; hctr := hctr - 1)
        {
          for (select top 1 SH_GRAPH_URI, SH_DEFINES from DB.DBA.SYS_SPARQL_HOST
          where req_hosts_split [hctr] like SH_HOST) do
            {
              if (length (SH_GRAPH_URI))
                {
                  graph_uri := SH_GRAPH_URI;
                  goto good_host_found;
                }
              goto bad_host_found;
            }
        }
bad_host_found:
      signal ('22023', 'The request to SPARQL 1.1 Graph Store endpoint contains "default" param but the endpoint is not configured to have default graph');
good_host_found:
      ;
    }
  if (graph_uri <> '')
    goto graph_processing;
  http_methods_set ('GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH');

  WS.WS.SPARQL_ENDPOINT_HTML_DOCTYPE();

  http('<head>\n');
  WS.WS.SPARQL_ENDPOINT_HTML_HEAD('Virtuoso SPARQL 1.1 Uniform RDF Graph Query Form');
  WS.WS.SPARQL_ENDPOINT_STYLE ();
  http('</head>\n');

  http('<body>\n');
  http('    <div id="header">\n');
  http('	<h1>Virtuoso SPARQL 1.1 Uniform RDF Graph Query Form</h1>\n');
  http('    </div>\n\n');
  http('    <div id="intro">\n');
  http('	<p>This page is designed to help you test support for <a href="http://www.w3.org/TR/sparql11-http-rdf-update">SPARQL 1.1 Graph Store HTTP Protocol</a> in OpenLink Virtuoso.</p>\n');
  http('    </div>\n\n');
  http('    <div id="main">\n');
  http('	<form action="" method="post" enctype="multipart/form-data">\n');
  http('	<fieldset>\n');
  http('		<label for="graph-uri">Graph URI</label>\n');
  http('		<br />\n');
  http('		<input type="text" name="graph-uri" id="graph-uri" ');
  http(sprintf ('value="%s" size="80"/>\n', coalesce ('')));
  http('		<br /><br />\n');
  http('		<label for="res-file">File to upload</label>\n');
  http('		<br />\n');
  http('		<input type="file" name="res-file" id="res-file"/>\n');
  http('		<br /><br />\n');
  http('		<input type="submit" value="Upload the resource"/>');
  http('	</fieldset>\n');
  http('	</form>\n');
  http('    </div>\n\n');
  WS.WS.SPARQL_ENDPOINT_FOOTER();
  http('</body>\n');
  http('</html>\n');
  return;
graph_processing:
  commit work;
  graph_uri_is_relative := neq (graph_uri, DB.DBA.XML_URI_RESOLVE_LIKE_GET ('zZz://example.com/', graph_uri));
  if (graph_uri_is_relative)
    {
      if (not (reqbegin like 'PUT%') and not (reqbegin like 'POST%'))
        signal ('22023', 'The graph URI <' || graph_uri || '> is relative and can be passed to SPARQL 1.1 Graph Store endpoint only in some PUT or POST requests');
    }
  if ((reqbegin like 'PUT%') or (reqbegin like 'POST%'))
    {
      declare res_file, res_content_type varchar;
      declare full_graph_uri varchar;
      declare graph_exists integer;
      set_user_id (user_id, 1);
      res_file := get_keyword ('res-file', params, '');
      -- dbg_obj_princ ('res_file/1=', cast (res_file as varchar));
      if (0 = length (res_file))
        res_file := get_keyword ('Content', params, '');
      -- dbg_obj_princ ('res_file/2=', string_output_string (res_file));
      if (0 = length (res_file))
        res_file := http_body_read();
      -- dbg_obj_princ ('res_file/3=', string_output_string (res_file));
      if (0 = length (res_file))
        res_file := http_body_read(1);
      -- dbg_obj_princ ('res_file/4=', string_output_string (res_file));
      res_content_type := DB.DBA.RDF_SPONGE_GUESS_CONTENT_TYPE (null, null, res_file);
      -- dbg_obj_princ ('res_content_type=', res_content_type);
      if (graph_uri_is_relative)
        {
          full_graph_uri := null;
          if (res_content_type = 'text/rdf+n3')
            full_graph_uri := DB.DBA.SPARQL_CRUD_BASE_TTL (res_file, graph_uri, 255);
          else if (res_content_type = 'application/rdf+xml')
            full_graph_uri := DB.DBA.SPARQL_CRUD_BASE_RDFXML (res_file, graph_uri);
          else
            signal ('22023', 'The graph URI <' || graph_uri || '> is relative and can not be resolved using the submitted resource of unsupported type ' || coalesce (res_content_type, ''));
          if (full_graph_uri is null)
            signal ('22023', 'The graph URI <' || graph_uri || '> is relative and can not be resolved using the submitted resource (resource does not contain any base)');
        }
      else
        full_graph_uri := graph_uri;
      commit work;
      graph_exists := (sparql define input:storage "" ask where { graph `iri(?:full_graph_uri)` { ?s ?p ?o }});
      if (res_content_type = 'text/rdf+n3')
        {
          if (reqbegin like 'PUT%')
            {
              sparql clear graph ?:full_graph_uri;
              commit work;
            }
          DB.DBA.TTLP (res_file, full_graph_uri, full_graph_uri);
        }
      else if (res_content_type = 'application/rdf+xml')
        {
          if (reqbegin like 'PUT%')
            {
              sparql clear graph ?:full_graph_uri;
              commit work;
            }
          DB.DBA.RDF_LOAD_RDFXML (res_file, full_graph_uri, full_graph_uri);
        }
      else if (res_content_type = 'text/microdata+html')
        {
          if (reqbegin like 'PUT%')
            {
              sparql clear graph ?:full_graph_uri;
              commit work;
            }
          DB.DBA.RDF_LOAD_XHTML_MICRODATA (res_file, full_graph_uri /* base */, full_graph_uri /* dest graph */);
        }
      else if (res_content_type = 'application/xhtml+xml')
        {
          if (reqbegin like 'PUT%')
            {
              sparql clear graph ?:full_graph_uri;
              commit work;
            }
          DB.DBA.RDF_LOAD_RDFA (res_file, full_graph_uri /* base */, full_graph_uri /* dest graph */);
        }
      else
        signal ('22023', 'The PUT request for graph <' || full_graph_uri || '> is rejected: the submitted resource is of unsupported type ' || coalesce (res_content_type, ''));
      if (graph_exists is null)
        http_request_status ('HTTP/1.1 201 Created');
      else if (length (res_file) <= 2)
        http_request_status ('HTTP/1.1 204 No Content');
      return;
    }
  else if (reqbegin like 'DELETE%')
    {
      set_user_id (user_id, 1);
      if (not (exists (sparql define input:storage "" select (1) where { graph `iri(?:graph_uri)` { ?s ?p ?o }})))
        {
          http_request_status ('HTTP/1.1 404 Not Found');
          return;
        }
      sparql clear graph ?:graph_uri;
      commit work;
      return;
    }
  else if (reqbegin like 'GET%')
    {
      if (not (exists (sparql define input:storage "" select (1) where { graph `iri(?:graph_uri)` { ?s ?p ?o }})))
        {
          http_request_status ('HTTP/1.1 404 Not Found');
          return;
        }
      connection_set ('SPARQL_crud_graph', graph_uri);
      WS.WS."/!sparql/" (path,
        vector_concat (
          vector ('query', 'define input:storage "" construct { ?s ?p ?o } where { graph `iri(bif:connection_get("SPARQL_crud_graph"))` { ?s ?p ?o }}'),
          params ), lines);
      return;
    }
  else
    {
      http_request_status ('HTTP/1.1 501 Method Not Implemented');
      return;
    }
}
;

registry_set ('/!sparql-graph-crud/', 'no_vsp_recompile')
;


create procedure DB.DBA.SPARQL_REFRESH_DYNARES_RESULTS (in full_query varchar, in qry_params any, in maxrows integer, in accept varchar, in user_id varchar, in hard_timeout integer, in jsonp_callback any)
{
  -- dbg_obj_princ ('DB.DBA.SPARQL_REFRESH_DYNARES_RESULTS (', full_query, qry_params, maxrows, accept, user_id, hard_timeout, ')');
  declare state, msg varchar;
  declare metas, rset any;
  declare RES any;
  declare ses any;
  result_names (RES);
  set_user_id (user_id, 1);
  if (hard_timeout >= 1000)
    set TRANSACTION_TIMEOUT = hard_timeout;
  set_user_id (user_id);
  state := '00000';
  exec ( concat ('sparql ', full_query), state, msg, qry_params, vector ('max_rows', maxrows, 'use_cache', 1), metas, rset);
  commit work;
  -- dbg_obj_princ ('exec metas=', metas, ', state=', state, ', msg=', msg);
  if (state <> '00000')
    signal (state, msg);
  ses := string_output ();
  if (isstring (jsonp_callback))
    http (jsonp_callback || '(\n', ses);
  DB.DBA.SPARQL_RESULTS_WRITE (ses, metas, rset, accept, 0, null);
  if (isstring (jsonp_callback))
    http (')', ses);
  result (ses);
}
;

-- SPARUL manipulation by remote resources.

--!AWK PUBLIC
create function DB.DBA.SPARQL_ROUTE_IF_DAV (in graph_iri varchar, in output_format_name varchar)
{
--                    0         1
--                    012345678901234567
  if (graph_iri like 'http://local.virt/DAV/%')
    return subseq (graph_iri, 17);
  return NULL;
}
;

create procedure DB.DBA.SPARQL_ROUTE_DICT_CONTENT_DAV (
  in graph_iri varchar,
  in opname varchar,
  in storage_name varchar,
  in output_storage_name varchar,
  in output_format_name varchar,
  in del_dict any,
  in ins_dict any,
  in env any,
  in uid varchar,
  in log_mode integer,
  in compose_report integer )
{
  declare split, in_mime, mime, perr, fake_content varchar;
  declare final_res, triples, out_ses, rc any;
   declare old_perms, pwd varchar;
  declare old_gid, old_uid any;
  declare dir any;
  split := DB.DBA.SPARQL_ROUTE_IF_DAV (graph_iri, output_format_name);
  -- uid := user;
  if ('dba' = uid)
    uid := 'dav';
  pwd := (select pwd_magic_calc (U_NAME, U_PASSWORD, 1) from SYS_USERS where U_NAME=uid);
  -- dbg_obj_princ ('SPARQL_ROUTE_DICT_CONTENT_DAV: uid=', uid, ', pwd=', pwd);
  if (split is not null)
    {
      dir := DAV_DIR_LIST (split, 0, uid, pwd);
      if (isinteger (dir) and (0 > dir))
        signal ('RDFXX', sprintf ('SPARUL %s can not get DAV directory info about "%.200s": %s', opname, split, DB.DBA.DAV_PERROR (dir)));
      if (1 = length (dir))
        {
          if ('c' = dir[0][1])
            signal ('RDFXX', sprintf ('SPARUL %s can not edit "%.200s": it is collection, not a resource', opname, split));
          old_perms := dir[0][5];
          old_gid := dir[0][6];
          old_uid := dir[0][7];
          in_mime := dir[0][9];
        }
      else
        signal ('RDFXX', sprintf ('SPARUL %s can not edit "%.200s": can not get directory listing with it', opname, split));
      fake_content := null;
      mime := DB.DBA.RDF_SPONGE_GUESS_CONTENT_TYPE (graph_iri, in_mime, fake_content);
      if ('application/rdf+xml' = mime)
        {
          if ((output_format_name is not null) and (output_format_name <> 'AUTO') and (output_format_name <> 'RDF/XML'))
            signal ('RDFXX', sprintf ('SPARUL can not update resource "%.200s" because its MIME type "%s" conflicts with directive output:format "%s"', graph_iri, coalesce (in_mime, mime), output_format_name));
        }
      else if ('text/rdf+n3' = mime)
        {
          if ((output_format_name is not null) and (output_format_name <> 'AUTO') and (output_format_name <> 'TURTLE') and (output_format_name <> 'TTL'))
            signal ('RDFXX', sprintf ('SPARUL can not update resource "%.200s" because its MIME type "%s" conflicts with directive output:format "%s"', graph_iri, coalesce (in_mime, mime), output_format_name));
        }
      else
        signal ('RDFXX', sprintf ('SPARUL can not update resource "%.200s" of MIME type "%s" because only "application/rdf+xml" and "text/rdf+n3" are supported', graph_iri, coalesce (in_mime, mime)));
    }
  if ('INSERT' = opname)
    final_res := DB.DBA.SPARQL_INSERT_DICT_CONTENT (graph_iri, ins_dict, uid, log_mode, compose_report);
  else if ('DELETE' = opname)
    final_res := DB.DBA.SPARQL_DELETE_DICT_CONTENT (graph_iri, del_dict, uid, log_mode, compose_report);
  else if ('MODIFY' = opname)
    final_res := DB.DBA.SPARQL_MODIFY_BY_DICT_CONTENTS (graph_iri, del_dict, ins_dict, uid, log_mode, compose_report);
  if (split is not null)
    {
      out_ses := string_output();
      triples := (select VECTOR_AGG (vector ("s", "p", "o")) from
          (sparql define input:storage "" define output:valmode "LONG"
            select ?s ?p ?o where {
                graph `iri(?:graph_iri)` { ?s ?p ?o } }
            order by (str(?s)) (str(?p)) ) as sub );
      if ('application/rdf+xml' = mime)
        DB.DBA.RDF_TRIPLES_TO_RDF_XML_TEXT (triples, 1, out_ses);
      else if (('text/rdf+n3' = mime) or ('text/rdf+ttl' = mime) or ('text/rdf+turtle' = mime) or ('text/turtle' = mime) or ('text/n3' = mime))
        DB.DBA.RDF_TRIPLES_TO_TTL (triples, out_ses);
      else if ('application/x-trig' = mime)
        DB.DBA.RDF_TRIPLES_TO_TRIG (triples, out_ses);
      else if ('text/plain' = mime or 'text/ntriples' = mime)
        DB.DBA.RDF_TRIPLES_TO_NT (triples, out_ses);
      else if (('application/json' = mime) or ('application/rdf+json' = mime) or ('application/x-rdf+json' = mime))
        DB.DBA.RDF_TRIPLES_TO_TALIS_JSON (triples, out_ses);
      else if ('application/x-json+ld' = mime)
        DB.DBA.RDF_TRIPLES_TO_JSON_LD (triples, out_ses);
      else if ('application/ld+json' = mime)
        DB.DBA.RDF_TRIPLES_TO_JSON_LD (triples, out_ses);
      else if ('application/xhtml+xml' = mime)
        DB.DBA.RDF_TRIPLES_TO_RDFA_XHTML (triples, out_ses);
      else if (('text/html' = mime) or ('text/microdata+html' = mime) or ('text/md+html' = mime))
        DB.DBA.RDF_TRIPLES_TO_HTML_MICRODATA (triples, out_ses);
      else if ('application/microdata+json' = mime)
        DB.DBA.RDF_TRIPLES_TO_JSON_MICRODATA (triples, out_ses);
      rc := DB.DBA.DAV_RES_UPLOAD (split, out_ses, mime, old_perms, old_uid, old_gid, uid, pwd);
      if (isinteger (rc) and rc < 0)
        signal ('RDFXX', sprintf ('Unable to change "%.200s" in DAV: %s', split, DB.DBA.DAV_PERROR (rc)));
    }
  if (not isinteger (final_res))
    return final_res;
}
;

-- WS handlers for .rq files (application/sparql-query)
create procedure
WS.WS.__http_handler_rq (in content any, in params any, in lines any, inout ipath_ostat any)
{
  return DB.DBA.http_rq_file_handler(content, params, lines, ipath_ostat);
}
;

create procedure
WS.WS.__http_handler_head_rq (in content any, in params any, in lines any, inout ipath_ostat any)
{
  return DB.DBA.http_rq_file_handler(content, params, lines, ipath_ostat);
}
;

create procedure
DB.DBA.http_rq_file_handler (in content any, in params any, in lines any, inout ipath_ostat any)
{
  declare accept varchar;
  declare _format varchar;

  accept := http_request_header (lines, 'Accept', null, '');

  _format := get_keyword('format', params, '');
  if (_format <> '')
    {
      _format := (
      case lower(_format)
      when 'json' then 'application/sparql-results+json'
      when 'js' then 'application/javascript'
      when 'html' then 'text/html'
      when 'spreadsheet' then 'application/vnd.ms-excel'
      when 'sparql' then 'application/sparql-results+xml'
      when 'xml' then 'application/sparql-results+xml'
      when 'rdf' then 'application/rdf+xml'
      when 'n3' then 'text/rdf+n3'
      when 'cxml' then 'text/cxml'
      when 'cxml+qrcode' then 'text/cxml+qrcode'
      when 'csv' then 'text/csv'
      else _format
      end);
    }

  if (_format <> '' or
      strcasestr (accept, 'application/sparql-results+json') is not null or
      strcasestr (accept, 'application/json') is not null or
      strcasestr (accept, 'application/sparql-results+xml') is not null or
      strcasestr (accept, 'text/rdf+n3') is not null or
      strcasestr (accept, 'text/rdf+ttl') is not null or
      strcasestr (accept, 'text/rdf+turtle') is not null or
      strcasestr (accept, 'text/turtle') is not null or
      strcasestr (accept, 'application/x-trig') is not null or
      strcasestr (accept, 'application/rdf+xml') is not null or
      strcasestr (accept, 'application/javascript') is not null or
      strcasestr (accept, 'application/soap+xml') is not null or
      strcasestr (accept, 'application/rdf+turtle') is not null or
      strcasestr (accept, 'text/cxml') is not null or
      strcasestr (accept, 'text/cxml+qrcode') is not null or
      strcasestr (accept, 'text/csv') is not null
     )
    {
      http_request_status ('HTTP/1.1 303 See Other');
      http_header (sprintf('Location: /sparql?query=%U&format=%U\r\n', content, accept));
      return '';
    }
  if (strcasestr (accept, 'application/sparql-query') is not null)
     http_header ('Content-Type: application/sparql-query\r\n');
  else
     http_header ('Content-Type: text/plain\r\n');
  http (content);
  return '';
}
;

create procedure DB.DBA.SPARQL_SD_TRIPLE (inout sd any, in s varchar, in p varchar, in o varchar)
{
  if (starts_with (s, '!')) s := __xml_nsexpand_iristr (subseq (s, 1)); else s := __box_flags_tweak (s, 1);
  if (starts_with (p, '!')) p := __xml_nsexpand_iristr (subseq (p, 1)); else p := __box_flags_tweak (p, 1);
  if (starts_with (o, '!')) o := __xml_nsexpand_iristr (subseq (o, 1)); else o := __box_flags_tweak (o, 1);
  vectorbld_acc (sd, vector (s, p, o));
}
;

create procedure DB.DBA.SPARQL_SD_TRIPLE_L (inout sd any, in s varchar, in p varchar, in o any)
{
  if (starts_with (s, '!')) s := __xml_nsexpand_iristr (subseq (s, 1)); else s := __box_flags_tweak (s, 1);
  if (starts_with (p, '!')) p := __xml_nsexpand_iristr (subseq (p, 1)); else p := __box_flags_tweak (p, 1);
  vectorbld_acc (sd, vector (s, p, o));
}
;

create procedure DB.DBA.SPARQL_SD_COMPOSE (inout sd any, in host varchar, in complete integer)
{
  declare service_iri varchar;
  service_iri := 'http://' || host || '/sparql-sd';
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!rdf:type', '!sd:Service');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:endpoint', 'http://' || host || '/sparql');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:endpoint', 'http://' || host || '/sparql-auth');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!virtrdf:graph-crud-endpoint', 'http://' || host || '/sparql-graph-crud');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!virtrdf:graph-crud-endpoint', 'http://' || host || '/sparql-graph-crud-auth');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:feature', '!sd:UnionDefaultGraph');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:feature', '!sd:RequiresDataset');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:feature', '!sd:EmptyGraphs');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:feature', '!sd:BasicFederatedQuery');
-- Results:
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/N3');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/N-triples');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/RDFa');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/RDF_XML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/SPARQL_Results_XML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/SPARQL_Results_JSON');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/SPARQL_Results_CSV');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', 'http://www.w3.org/ns/formats/Turtle');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_SPARQL_Results_HTML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_SPARQL_Results_Spreadsheet');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_SPARQL_Results_Javascript');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_SPARQL_Results_CXML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_SPARQL_Results_CXML_QR');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_RDF_JSON');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_XHTML_RDFa');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_ATOM_XML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_ODATA_JSON');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_HTML_list');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_HTML_table');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_HTML_Microdata');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_Microdata_JSON');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_CSV');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_CXML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Triples_CXML_QR');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:resultFormat', '!virtrdf:FileFormat_Quads_TriG');
-- Inputs:
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/N3');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/N-triples');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/RDFa');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/RDF_XML');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/SPARQL_Results_XML');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/SPARQL_Results_JSON');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/SPARQL_Results_CSV');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', 'http://www.w3.org/ns/formats/Turtle');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_SPARQL_Results_HTML');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_SPARQL_Results_Spreadsheet');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_SPARQL_Results_Javascript');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_SPARQL_Results_CXML');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_SPARQL_Results_CXML_QR');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_RDF_JSON');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_XHTML_RDFa');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_ATOM_XML');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_ODATA_JSON');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_HTML_list');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_HTML_table');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_HTML_Microdata');
  -- DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_Microdata_JSON');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_CSV');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_CXML');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Triples_CXML_QR');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:inputFormat', '!virtrdf:FileFormat_Quads_TriG');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:supportedLanguage', '!sd:SPARQL10Query');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:supportedLanguage', '!sd:SPARQL11Query');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:supportedLanguage', '!sd:SPARQL11Update');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_QUAD_MAP');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_OPTION');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_BREAKUP');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_PKSELFJOIN');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_RVR');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_IN');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_LIKE');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_GLOBALS');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_BI');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_VIRTSPECIFIC');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_SERVICE');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_TRANSIT');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:languageExtension', '!virtrdf:SSG_SD_SPARQL11_DRAFT');
  DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:propertyFeature', '!bif:contains');
  if (complete)
    { -- List of extension functions and aggregates --- TBD!
      DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:extensionFunction', '!bif:abs');
      DB.DBA.SPARQL_SD_TRIPLE (sd, service_iri, '!sd:extensionAggregate', '!sql:STDDEV');
    }
}
;

create procedure WS.WS."/!sparql-sd/" (inout path varchar, inout params any, inout lines any)
{
  declare sd, ses any;
  declare service_iri varchar;
  declare host, accept, formatter varchar;
  host := http_request_header (lines, 'Host', null, '');
  accept := http_request_header (lines, 'Accept', null, '');
  -- dbg_obj_princ ('WS.WS."/!sparql-sd/" (', path, params, lines, ')');
  if ((2 < length (params)) or (params[0] <> 'Content'))
    {
      WS.WS."/!sparql/" (path, params, lines);
      return;
    }
  vectorbld_init (sd);
  if (host is not null and host <> '')
    DB.DBA.SPARQL_SD_COMPOSE (sd, host, 1);
  if (isstring (registry_get ('URIQADefaultHost')))
    DB.DBA.SPARQL_SD_COMPOSE (sd, registry_get ('URIQADefaultHost'), 1);
  vectorbld_final (sd);
  ses := null;
  if (strstr (accept, 'text/rdf+n3') is not null)
    { http_header ('Content-Type: text/rdf+n3; charset=UTF-8\r\n');		DB.DBA.RDF_TRIPLES_TO_NT (sd, ses);	}
  else if (strstr (accept, 'text/rdf+ttl') is not null)
    { http_header ('Content-Type: text/rdf+ttl; charset=UTF-8\r\n');		DB.DBA.RDF_TRIPLES_TO_TTL (sd, ses);	}
  else if (strstr (accept, 'text/rdf+turtle') is not null)
    { http_header ('Content-Type: text/rdf+turtle; charset=UTF-8\r\n');		DB.DBA.RDF_TRIPLES_TO_TTL (sd, ses);	}
  else if (strstr (accept, 'text/turtle') is not null)
    { http_header ('Content-Type: text/turtle; charset=UTF-8\r\n');		DB.DBA.RDF_TRIPLES_TO_TTL (sd, ses);	}
  else if (strstr (accept, 'application/turtle') is not null)
    { http_header ('Content-Type: application/turtle; charset=UTF-8\r\n');	DB.DBA.RDF_TRIPLES_TO_TTL (sd, ses);	}
  else if (strstr (accept, 'application/turtle') is not null)
    { http_header ('Content-Type: application/x-turtle; charset=UTF-8\r\n');	DB.DBA.RDF_TRIPLES_TO_TTL (sd, ses);	}
  else
    { http_header ('Content-Type: text/turtle; charset=UTF-8\r\n');		DB.DBA.RDF_TRIPLES_TO_TTL (sd, ses);	}
}
;

registry_set ('/!sparql-sd/', 'no_vsp_recompile')
;

create procedure DB.DBA.RDF_GRANT_SPARQL_IO ()
{
  declare state, msg varchar;
  declare cmds any;
  cmds := vector (
    'grant execute on DB.DBA.SPARQL_REXEC to SPARQL_SELECT',
    'grant execute on DB.DBA.SPARQL_REXEC_TO_ARRAY to SPARQL_SELECT',
    'grant execute on DB.DBA.SPARQL_REXEC_WITH_META to SPARQL_SELECT',
    'grant execute on WS.WS."/!sparql/" to "SPARQL"',
    'grant execute on WS.WS."/!sparql-graph-crud/" to "SPARQL"',
    'grant execute on WS.WS."/!sparql-sd/" to "SPARQL"',
    'grant execute on DB.DBA.SPARQL_REFRESH_DYNARES_RESULTS to "SPARQL"',
    'grant execute on DB.DBA.SPARQL_ROUTE_DICT_CONTENT_DAV to SPARQL_UPDATE',
    'grant execute on DB.DBA.SPARQL_SD_PROBE to SPARQL_SPONGE',
    'grant execute on DB.DBA.SPARQL_SINV_IMP to SPARQL_SPONGE',
    'grant select on DB.DBA.SPARQL_SINV_2 to SPARQL_SPONGE' );
  foreach (varchar cmd in cmds) do
    {
      exec (cmd, state, msg);
    }
}
;

--!AFTER __PROCEDURE__ DB.DBA.USER_CREATE !
DB.DBA.RDF_GRANT_SPARQL_IO ()
;