summaryrefslogtreecommitdiff
path: root/storage/connect/tabxml.cpp
blob: c96e08444973013b0b6896495fab84c688c68f61 (plain)
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
/************* Tabxml C++ Program Source Code File (.CPP) **************/
/* PROGRAM NAME: TABXML                                                */
/* -------------                                                       */
/*  Version 3.0                                                        */
/*                                                                     */
/*  Author Olivier BERTRAND          2007 - 2017                       */
/*                                                                     */
/*  This program are the XML tables classes using MS-DOM or libxml2.   */
/***********************************************************************/

/***********************************************************************/
/*  Include required compiler header files.                            */
/***********************************************************************/
#include "my_global.h"
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#if defined(__WIN__)
#include <io.h>
#include <winsock2.h>
//#include <windows.h>
#include <comdef.h>
#else   // !__WIN__
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
//#include <ctype.h>
#include "osutil.h"
#define _O_RDONLY O_RDONLY
#endif  // !__WIN__
#include "resource.h"                        // for IDS_COLUMNS

#define INCLUDE_TDBXML
#define NODE_TYPE_LIST

/***********************************************************************/
/*  Include application header files:                                  */
/*  global.h    is header containing all global declarations.          */
/*  plgdbsem.h  is header containing the DB application declarations.  */
/*  tabdos.h    is header containing the TABDOS class declarations.    */
/***********************************************************************/
#include "global.h"
#include "plgdbsem.h"
//#include "reldef.h"
#include "xtable.h"
#include "colblk.h"
#include "mycat.h"
#include "xindex.h"
#include "plgxml.h"
#include "tabxml.h"
#include "tabmul.h"

extern "C" char version[];

#if defined(__WIN__) && defined(DOMDOC_SUPPORT)
#define XMLSUP "MS-DOM"
#else   // !__WIN__
#define XMLSUP "libxml2"
#endif  // !__WIN__

#define TYPE_UNKNOWN     12        /* Must be greater than other types */
#define XLEN(M)  sizeof(M) - strlen(M) - 1	       /* To avoid overflow*/

/***********************************************************************/
/* Class and structure used by XMLColumns.                             */
/***********************************************************************/
typedef class XMCOL *PXCL;

class XMCOL : public BLOCK {
 public:
  // Constructors
  XMCOL(void) {Next = NULL; 
               Name[0] = 0; 
               Fmt = NULL; 
               Type = 1;
               Len = Scale = 0;
               Cbn = false; 
               Found = true;}
  XMCOL(PGLOBAL g, PXCL xp, char *fmt, int i) {
               Next = NULL; 
               strcpy(Name, xp->Name);
               Fmt = (*fmt) ? PlugDup(g, fmt) : NULL; 
               Type = xp->Type;
               Len = xp->Len;
               Scale = xp->Scale;
               Cbn = (xp->Cbn || i > 1); 
               Found = true;}

  // Members
  PXCL  Next;
  char  Name[64];
  char *Fmt;
  int   Type;
  int   Len;
  int   Scale;
  bool  Cbn;
  bool  Found;
}; // end of class XMCOL

typedef struct LVL {
  PXNODE  pn;
  PXLIST  nl;
  PXATTR  atp;
  bool    b;
  long    k;
  int     m, n;
} *PLVL;

/***********************************************************************/
/* XMLColumns: construct the result blocks containing the description  */
/* of all the columns of a table contained inside an XML file.         */
/***********************************************************************/
PQRYRES XMLColumns(PGLOBAL g, char *db, char *tab, PTOS topt, bool info)
{
  static int  buftyp[] = {TYPE_STRING, TYPE_SHORT, TYPE_STRING, TYPE_INT, 
                          TYPE_INT, TYPE_SHORT, TYPE_SHORT, TYPE_STRING};
  static XFLD fldtyp[] = {FLD_NAME, FLD_TYPE, FLD_TYPENAME, FLD_PREC, 
                          FLD_LENGTH, FLD_SCALE, FLD_NULL, FLD_FORMAT};
  static unsigned int length[] = {0, 6, 8, 10, 10, 6, 6, 0};
  char    colname[65], fmt[129], buf[512];
  int     i, j, lvl, n = 0;
  int     ncol = sizeof(buftyp) / sizeof(int);
  bool    ok = true;
	PCSZ    fn, op;
  PXCL    xcol, xcp, fxcp = NULL, pxcp = NULL;
  PLVL   *lvlp, vp;
  PXNODE  node = NULL;
  PXMLDEF tdp;
  PTDBXML txmp;
  PQRYRES qrp;
  PCOLRES crp;

  if (info) {
    length[0] = 128;
    length[7] = 256;
    goto skipit;
    } // endif info

	if (GetIntegerTableOption(g, topt, "Multiple", 0)) {
		strcpy(g->Message, "Cannot find column definition for multiple table");
		return NULL;
	}	// endif Multiple

	/*********************************************************************/
  /*  Open the input file.                                             */
  /*********************************************************************/
  if (!(fn = GetStringTableOption(g, topt, "Filename", NULL))) {
    strcpy(g->Message, MSG(MISSING_FNAME));
    return NULL;
  } else {
    lvl = GetIntegerTableOption(g, topt, "Level", 0);
    lvl = (lvl < 0) ? 0 : (lvl > 16) ? 16 : lvl;
  } // endif fn

  if (trace(1))
    htrc("File %s lvl=%d\n", topt->filename, lvl);

  tdp = new(g) XMLDEF;
  tdp->Fn = fn;

	if (!(tdp->Database = SetPath(g, db)))
		return NULL;

  tdp->Tabname = tab;
	tdp->Zipped = GetBooleanTableOption(g, topt, "Zipped", false);
	tdp->Entry = GetStringTableOption(g, topt, "Entry", NULL);

  if (!(op = GetStringTableOption(g, topt, "Xmlsup", NULL)))
#if defined(__WIN__)
    tdp->Usedom = true;
#else   // !__WIN__
    tdp->Usedom = false;
#endif  // !__WIN__
  else
    tdp->Usedom = (toupper(*op) == 'M' || toupper(*op) == 'D');

  txmp = new(g) TDBXML(tdp);

  if (txmp->Initialize(g))
    goto err;

  xcol = new(g) XMCOL;
  colname[64] = 0;
  fmt[128] = 0;
  lvlp = (PLVL*)PlugSubAlloc(g, NULL, sizeof(PLVL) * (lvl + 1));

  for (j = 0; j <= lvl; j++)
    lvlp[j] = (PLVL)PlugSubAlloc(g, NULL, sizeof(LVL));

  /*********************************************************************/
  /*  Analyse the XML tree and define columns.                         */
  /*********************************************************************/
  for (i = 1; ; i++) {
    // Get next row
    switch (txmp->ReadDB(g)) {
      case RC_EF:
        vp = NULL;
        break;
      case RC_FX:
        goto err;
      default:
        vp = lvlp[0];
        vp->pn = txmp->RowNode;
        vp->atp = vp->pn->GetAttribute(g, NULL);
        vp->nl = vp->pn->GetChildElements(g);
        vp->b = true;
        vp->k = 0;
        vp->m = vp->n = 0;
        j = 0;
      } // endswitch ReadDB

    if (!vp)
      break;

    while (true) {
      if (!vp->atp &&
				!(node = (vp->nl) ? vp->nl->GetItem(g, vp->k++, tdp->Usedom ? node : NULL)
				                  : NULL))
        if (j) {
          vp = lvlp[--j];

          if (!tdp->Usedom)    // nl was destroyed
            vp->nl = vp->pn->GetChildElements(g);

          if (!lvlp[j+1]->b) {
            vp->k--;
            ok = false;
            } // endif b

          continue;
        } else
          break;

      xcol->Name[vp->n] = 0;
      fmt[vp->m] = 0;

     more:
      if (vp->atp) {
        strncpy(colname, vp->atp->GetName(g), sizeof(colname));
				strncat(xcol->Name, colname, XLEN(xcol->Name));

        switch (vp->atp->GetText(g, buf, sizeof(buf))) {
          case RC_INFO:
            PushWarning(g, txmp);
          case RC_OK:
            strncat(fmt, "@", XLEN(fmt));
            break;
          default:
            goto err;
          } // enswitch rc

        if (j)
          strncat(fmt, colname, XLEN(fmt));

      } else {
        if (tdp->Usedom && node->GetType() != 1)
          continue;

        strncpy(colname, node->GetName(g), sizeof(colname));
				strncat(xcol->Name, colname, XLEN(xcol->Name));

        if (j)
          strncat(fmt, colname, XLEN(fmt));

        if (j < lvl && ok) {
          vp = lvlp[j+1];
          vp->k = 0;
					vp->pn = node;
					vp->atp = node->GetAttribute(g, NULL);
          vp->nl = node->GetChildElements(g);

          if (tdp->Usedom && vp->nl->GetLength() == 1) {
            node = vp->nl->GetItem(g, 0, node);
            vp->b = (node->GetType() == 1);   // Must be ab element
          } else
            vp->b = (vp->nl && vp->nl->GetLength());

          if (vp->atp || vp->b) {
            if (!vp->atp)
							node = vp->nl->GetItem(g, vp->k++, tdp->Usedom ? node : NULL);

						strncat(fmt, colname, XLEN(fmt));
						strncat(fmt, "/", XLEN(fmt));
						strncat(xcol->Name, "_", XLEN(xcol->Name));
						j++;
            vp->n = (int)strlen(xcol->Name);
            vp->m = (int)strlen(fmt);
            goto more;
          } else {
            vp = lvlp[j];

            if (!tdp->Usedom)    // nl was destroyed
              vp->nl = vp->pn->GetChildElements(g);

          } // endif vp

        } else
          ok = true;

        switch (node->GetContent(g, buf, sizeof(buf))) {
          case RC_INFO:
            PushWarning(g, txmp);
          case RC_OK:
            break;
          default:
            goto err;
          } // enswitch rc

      } // endif atp;

      xcol->Len = strlen(buf);

      // Check whether this column was already found
      for (xcp = fxcp; xcp; xcp = xcp->Next)
        if (!strcmp(xcol->Name, xcp->Name))
          break;
  
      if (xcp) {
        if (xcp->Type != xcol->Type)
          xcp->Type = TYPE_STRING;

        if (*fmt && (!xcp->Fmt || strlen(xcp->Fmt) < strlen(fmt))) {
          xcp->Fmt = PlugDup(g, fmt);
          length[7] = MY_MAX(length[7], strlen(fmt));
          } // endif *fmt

        xcp->Len = MY_MAX(xcp->Len, xcol->Len);
        xcp->Scale = MY_MAX(xcp->Scale, xcol->Scale);
        xcp->Cbn |= xcol->Cbn;
        xcp->Found = true;
      } else {
        // New column
        xcp = new(g) XMCOL(g, xcol, fmt, i);
        length[0] = MY_MAX(length[0], strlen(xcol->Name));
        length[7] = MY_MAX(length[7], strlen(fmt));
  
        if (pxcp) {
          xcp->Next = pxcp->Next;
          pxcp->Next = xcp;
        } else
          fxcp = xcp;

        n++;
      } // endif xcp

      pxcp = xcp;

      if (vp->atp)
        vp->atp = vp->atp->GetNext(g);

      } // endwhile

    // Missing column can be null
    for (xcp = fxcp; xcp; xcp = xcp->Next) {
      xcp->Cbn |= !xcp->Found;
      xcp->Found = false;
      } // endfor xcp

    } // endor i

  txmp->CloseDB(g);

 skipit:
  if (trace(1))
    htrc("XMLColumns: n=%d len=%d\n", n, length[0]);

  /*********************************************************************/
  /*  Allocate the structures used to refer to the result set.         */
  /*********************************************************************/
  qrp = PlgAllocResult(g, ncol, n, IDS_COLUMNS + 3,
                          buftyp, fldtyp, length, false, false);

  crp = qrp->Colresp->Next->Next->Next->Next->Next->Next;
  crp->Name = "Nullable";
  crp->Next->Name = "Xpath";

  if (info || !qrp)
    return qrp;

  qrp->Nblin = n;

  /*********************************************************************/
  /*  Now get the results into blocks.                                 */
  /*********************************************************************/
  for (i = 0, xcp = fxcp; xcp; i++, xcp = xcp->Next) {
    if (xcp->Type == TYPE_UNKNOWN)            // Void column
      xcp->Type = TYPE_STRING;

    crp = qrp->Colresp;                    // Column Name
    crp->Kdata->SetValue(xcp->Name, i);
    crp = crp->Next;                       // Data Type
    crp->Kdata->SetValue(xcp->Type, i);
    crp = crp->Next;                       // Type Name
    crp->Kdata->SetValue(GetTypeName(xcp->Type), i);
    crp = crp->Next;                       // Precision
    crp->Kdata->SetValue(xcp->Len, i);
    crp = crp->Next;                       // Length
    crp->Kdata->SetValue(xcp->Len, i);
    crp = crp->Next;                       // Scale (precision)
    crp->Kdata->SetValue(xcp->Scale, i);
    crp = crp->Next;                       // Nullable
    crp->Kdata->SetValue(xcp->Cbn ? 1 : 0, i);
    crp = crp->Next;                       // Field format

    if (crp->Kdata)
      crp->Kdata->SetValue(xcp->Fmt, i);

    } // endfor i

  /*********************************************************************/
  /*  Return the result pointer.                                       */
  /*********************************************************************/
  return qrp;

err:
  txmp->CloseDB(g);
  return NULL;
  } // end of XMLColumns

/* -------------- Implementation of the XMLDEF class  ---------------- */

/***********************************************************************/
/*  Constructor.                                                       */
/***********************************************************************/
XMLDEF::XMLDEF(void)
  {
  Pseudo = 3;
  Fn = NULL;
  Encoding = NULL;
  Tabname = NULL;
  Rowname = NULL;
  Colname = NULL;
  Mulnode = NULL;
  XmlDB = NULL;
  Nslist = NULL;
  DefNs = NULL;
  Attrib = NULL;
  Hdattr = NULL;
	Entry = NULL;
  Coltype = 1;
  Limit = 0;
  Header = 0;
  Xpand = false;
  Usedom = false;
	Zipped = false;
	Mulentries = false;
  } // end of XMLDEF constructor

/***********************************************************************/
/*  DefineAM: define specific AM block values from XDB file.           */
/***********************************************************************/
bool XMLDEF::DefineAM(PGLOBAL g, LPCSTR am, int poff)
  {
	PCSZ defrow, defcol;
	char buf[10];

  Fn = GetStringCatInfo(g, "Filename", NULL);
  Encoding = GetStringCatInfo(g, "Encoding", "UTF-8");

  if (*Fn == '?') {
    strcpy(g->Message, MSG(MISSING_FNAME));
    return true;
    } // endif fn

  if ((signed)GetIntCatInfo("Flag", -1) != -1) {
    strcpy(g->Message, MSG(DEPREC_FLAG));
    return true;
    } // endif flag

  defrow = defcol = NULL;
  GetCharCatInfo("Coltype", "", buf, sizeof(buf));

  switch (toupper(*buf)) {
    case 'A':                          // Attribute
    case '@':
    case '0':
      Coltype = 0;
      break;
    case '\0':                         // Default
    case 'T':                          // Tag
    case 'N':                          // Node
    case '1':
      Coltype = 1;
      break;
    case 'C':                          // Column
    case 'P':                          // Position
    case 'H':                          // HTML
    case '2':
      Coltype = 2;
      defrow = "TR";
      defcol = "TD";
      break;
    default:
      sprintf(g->Message, MSG(INV_COL_TYPE), buf);
      return true;
    } // endswitch typname

  Tabname = GetStringCatInfo(g, "Name", Name);  // Deprecated
  Tabname = GetStringCatInfo(g, "Table_name", Tabname); // Deprecated
  Tabname = GetStringCatInfo(g, "Tabname", Tabname);
  Rowname = GetStringCatInfo(g, "Rownode", defrow);
  Colname = GetStringCatInfo(g, "Colnode", defcol);
  Mulnode = GetStringCatInfo(g, "Mulnode", NULL);
  XmlDB = GetStringCatInfo(g, "XmlDB", NULL);
  Nslist = GetStringCatInfo(g, "Nslist", NULL);
  DefNs = GetStringCatInfo(g, "DefNs", NULL);
  Limit = GetIntCatInfo("Limit", 10);
  Xpand = GetBoolCatInfo("Expand", false);
  Header = GetIntCatInfo("Header", 0);
  GetCharCatInfo("Xmlsup", "*", buf, sizeof(buf));

  // Note that if no support is specified, the default is MS-DOM
  // on Windows and libxml2 otherwise
  if (*buf == '*')
#if defined(__WIN__)
    Usedom = true;
#else   // !__WIN__
    Usedom = false;
#endif  // !__WIN__
  else
    Usedom = (toupper(*buf) == 'M' || toupper(*buf) == 'D');

  // Get eventual table node attribute
  Attrib = GetStringCatInfo(g, "Attribute", NULL);
  Hdattr = GetStringCatInfo(g, "HeadAttr", NULL);

	// Specific for zipped files
	if ((Zipped = GetBoolCatInfo("Zipped", false)))
		Mulentries = ((Entry = GetStringCatInfo(g, "Entry", NULL)))
		? strchr(Entry, '*') || strchr(Entry, '?')
		: GetBoolCatInfo("Mulentries", false);

	return false;
  } // end of DefineAM

/***********************************************************************/
/*  GetTable: makes a new TDB of the proper type.                      */
/***********************************************************************/
PTDB XMLDEF::GetTable(PGLOBAL g, MODE m)
  {
  if (Catfunc == FNC_COL)
    return new(g) TDBXCT(this);

	if (Zipped && !(m == MODE_READ || m == MODE_ANY)) {
		strcpy(g->Message, "ZIpped XML tables are read only");
		return NULL;
	}	// endif Zipped

  PTDBASE tdbp = new(g) TDBXML(this);

  if (Multiple)
    tdbp = new(g) TDBMUL(tdbp);

  return tdbp;
  } // end of GetTable

/* ------------------------- TDBXML Class ---------------------------- */

/***********************************************************************/
/*  Implementation of the TDBXML constuctor.                           */
/***********************************************************************/
TDBXML::TDBXML(PXMLDEF tdp) : TDBASE(tdp)
  {
  Docp = NULL;
  Root = NULL;
  Curp = NULL;
  DBnode = NULL;
  TabNode = NULL;
  RowNode = NULL;
  ColNode = NULL;
  Nlist = NULL;
  Clist = NULL;
  To_Xb = NULL;
  Colp = NULL;
  Xfile = tdp->Fn;
  Enc = tdp->Encoding;
  Tabname = tdp->Tabname;
#if 0 // why all these?
  Rowname = (tdp->Rowname) ? tdp->Rowname : NULL;
  Colname = (tdp->Colname) ? tdp->Colname : NULL;
  Mulnode = (tdp->Mulnode) ? tdp->Mulnode : NULL;
  XmlDB = (tdp->XmlDB) ? tdp->XmlDB : NULL;
  Nslist = (tdp->Nslist) ? tdp->Nslist : NULL;
  DefNs = (tdp->DefNs) ? tdp->DefNs : NULL;
  Attrib = (tdp->Attrib) ? tdp->Attrib : NULL;
  Hdattr = (tdp->Hdattr) ? tdp->Hdattr : NULL;
#endif // 0
	Rowname = tdp->Rowname;
	Colname = tdp->Colname;
	Mulnode = tdp->Mulnode;
	XmlDB = tdp->XmlDB;
	Nslist = tdp->Nslist;
	DefNs = tdp->DefNs;
	Attrib = tdp->Attrib;
	Hdattr = tdp->Hdattr;
	Entry = tdp->Entry;
	Coltype = tdp->Coltype;
  Limit = tdp->Limit;
  Xpand = tdp->Xpand;
	Zipped = tdp->Zipped;
	Mulentries = tdp->Mulentries;
	Changed = false;
  Checked = false;
  NextSame = false;
  NewRow = false;
  Hasnod = false;
  Write = false;
  Bufdone = false;
  Nodedone = false;
  Void = false;
  Usedom = tdp->Usedom;
  Header = tdp->Header;
  Multiple = tdp->Multiple;
  Nrow = -1;
  Irow = Header - 1;
  Nsub = 0;
  N = 0;
  } // end of TDBXML constructor

TDBXML::TDBXML(PTDBXML tdbp) : TDBASE(tdbp)
  {
  Docp = tdbp->Docp;
  Root = tdbp->Root;
  Curp = tdbp->Curp;
  DBnode = tdbp->DBnode;
  TabNode = tdbp->TabNode;
  RowNode = tdbp->RowNode;
  ColNode = tdbp->ColNode;
  Nlist = tdbp->Nlist;
  Clist = tdbp->Clist;
  To_Xb = tdbp->To_Xb;
  Colp = tdbp->Colp;
  Xfile = tdbp->Xfile;
  Enc = tdbp->Enc;
  Tabname = tdbp->Tabname;
  Rowname = tdbp->Rowname;
  Colname = tdbp->Colname;
  Mulnode = tdbp->Mulnode;
  XmlDB = tdbp->XmlDB;
  Nslist = tdbp->Nslist;
  DefNs = tdbp->DefNs;
  Attrib = tdbp->Attrib;
  Hdattr = tdbp->Hdattr;
	Entry = tdbp->Entry;
	Coltype = tdbp->Coltype;
  Limit = tdbp->Limit;
  Xpand = tdbp->Xpand;
	Zipped = tdbp->Zipped;
	Mulentries = tdbp->Mulentries;
	Changed = tdbp->Changed;
  Checked = tdbp->Checked;
  NextSame = tdbp->NextSame;
  NewRow = tdbp->NewRow;
  Hasnod = tdbp->Hasnod;
  Write = tdbp->Write;
  Void = tdbp->Void;
  Usedom = tdbp->Usedom;
  Header = tdbp->Header;
  Multiple = tdbp->Multiple;
  Nrow = tdbp->Nrow;
  Irow = tdbp->Irow;
  Nsub = tdbp->Nsub;
  N = tdbp->N;
  } // end of TDBXML copy constructor

// Used for update
PTDB TDBXML::Clone(PTABS t)
  {
  PTDB    tp;
  PXMLCOL cp1, cp2;
  PGLOBAL g = t->G;

  tp = new(g) TDBXML(this);

  for (cp1 = (PXMLCOL)Columns; cp1; cp1 = (PXMLCOL)cp1->GetNext()) {
    cp2 = new(g) XMLCOL(cp1, tp);  // Make a copy
    NewPointer(t, cp1, cp2);
    } // endfor cp1

  return tp;
  } // end of Clone

/***********************************************************************/
/*  Allocate XML column description block.                             */
/***********************************************************************/
PCOL TDBXML::MakeCol(PGLOBAL g, PCOLDEF cdp, PCOL cprec, int n)
  {
  if (trace(1))
    htrc("TDBXML: MakeCol %s n=%d\n", (cdp) ? cdp->GetName() : "<null>", n);

  return new(g) XMLCOL(cdp, this, cprec, n);
  } // end of MakeCol

/***********************************************************************/
/*  InsertSpecialColumn: Put a special column ahead of the column list.*/
/***********************************************************************/
PCOL TDBXML::InsertSpecialColumn(PCOL colp)
  {
  if (!colp->IsSpecial())
    return NULL;

//if (Xpand && ((SPCBLK*)colp)->GetRnm())
//  colp->SetKey(0);               // Rownum is no more a key

  colp->SetNext(Columns);
  Columns = colp;
  return colp;
  } // end of InsertSpecialColumn

/***********************************************************************/
/*  LoadTableFile: Load and parse an XML file.                         */
/***********************************************************************/
int TDBXML::LoadTableFile(PGLOBAL g, char *filename)
  {
  int     rc = RC_OK, type = (Usedom) ? TYPE_FB_XML : TYPE_FB_XML2;
  PFBLOCK fp = NULL;
  PDBUSER dup = (PDBUSER)g->Activityp->Aptr;

  if (Docp)
    return rc;               // Already done

  if (trace(1))
    htrc("TDBXML: loading %s\n", filename);

  /*********************************************************************/
  /*  Firstly we check whether this file have been already loaded.     */
  /*********************************************************************/
  if ((Mode == MODE_READ || Mode == MODE_ANY) && !Zipped) 
    for (fp = dup->Openlist; fp; fp = fp->Next)
      if (fp->Type == type && fp->Length && fp->Count)
        if (!stricmp(fp->Fname, filename))
          break;

  if (fp) {
    /*******************************************************************/
    /*  File already loaded. Just increment use count and get pointer. */
    /*******************************************************************/
    fp->Count++;
    Docp = (Usedom) ? GetDomDoc(g, Nslist, DefNs, Enc, fp)
                    : GetLibxmlDoc(g, Nslist, DefNs, Enc, fp);
  } else {
    /*******************************************************************/
    /*  Parse the XML file.                                            */
    /*******************************************************************/
    if (!(Docp = (Usedom) ? GetDomDoc(g, Nslist, DefNs, Enc)
                          : GetLibxmlDoc(g, Nslist, DefNs, Enc)))
      return RC_FX;

    // Initialize the implementation
    if (Docp->Initialize(g, Entry, Zipped)) {
      sprintf(g->Message, MSG(INIT_FAILED), (Usedom) ? "DOM" : "libxml2");
      return RC_FX;
      } // endif init

    if (trace(1))
      htrc("TDBXML: parsing %s rc=%d\n", filename, rc);

    // Parse the XML file
    if (Docp->ParseFile(g, filename)) {
      // Does the file exist?
      int h= global_open(g, MSGID_NONE, filename, _O_RDONLY);

      if (h != -1) {
        rc = (!_filelength(h)) ? RC_EF : RC_INFO;
        close(h);
      } else
        rc = (errno == ENOENT) ? RC_NF : RC_INFO;

      // Cannot make a Xblock until document is made
      return rc;
      } // endif Docp

    /*******************************************************************/
    /*  Link a Xblock. This make possible to reuse already opened docs */
    /*  and also to automatically close them in case of error g->jump. */
    /*******************************************************************/
    fp = Docp->LinkXblock(g, Mode, rc, filename);
  } // endif xp

  To_Xb = fp;                                  // Useful when closing
  return rc;
  } // end of LoadTableFile

/***********************************************************************/
/*  Initialize the processing of the XML file.                         */
/*  Note: this function can be called several times, eventally before  */
/*  the columns are known (from TBL for instance)                      */
/***********************************************************************/
bool TDBXML::Initialize(PGLOBAL g)
  {
  int     rc;
  PXMLCOL colp;

  if (Void)
    return false;

  if (Columns && !Bufdone) {
    // Allocate the buffers that will contain node values
    for (colp = (PXMLCOL)Columns; colp; colp = (PXMLCOL)colp->GetNext())
      if (!colp->IsSpecial())            // Not a pseudo column
        if (colp->AllocBuf(g, Mode == MODE_INSERT))
          return true;

    Bufdone = true;
    } // endif Bufdone

#if !defined(UNIX)
  if (!Root) try {
#else
  if (!Root) {
#endif
    char tabpath[64], filename[_MAX_PATH];

    //  We used the file name relative to recorded datapath
    PlugSetPath(filename, Xfile, GetPath());

    // Load or re-use the table file
    rc = LoadTableFile(g, filename);

    if (rc == RC_OK) {
      // Get root node
      if (!(Root = Docp->GetRoot(g))) {
        // This should never happen as load should have failed
        strcpy(g->Message, MSG(EMPTY_DOC));
        goto error;
        } // endif Root

      // If tabname is not an Xpath,
      // construct one that will find it anywhere
      if (!strchr(Tabname, '/'))
        strcat(strcpy(tabpath, "//"), Tabname);
      else
        strcpy(tabpath, Tabname);

      // Evaluate table xpath
      if ((TabNode = Root->SelectSingleNode(g, tabpath))) {
        if (TabNode->GetType() != XML_ELEMENT_NODE) {
          sprintf(g->Message, MSG(BAD_NODE_TYPE), TabNode->GetType());
          goto error;
          } // endif Type

      } else if (Mode == MODE_INSERT && XmlDB) {
        // We are adding a new table to a multi-table file

        // If XmlDB is not an Xpath,
        // construct one that will find it anywhere
        if (!strchr(XmlDB, '/'))
          strcat(strcpy(tabpath, "//"), XmlDB);
        else
          strcpy(tabpath, XmlDB);

        if (!(DBnode = Root->SelectSingleNode(g, tabpath))) {
          // DB node does not exist yet; we cannot create it
          // because we don't know where it should be placed
          sprintf(g->Message, MSG(MISSING_NODE), XmlDB, Xfile);
          goto error;
          } // endif DBnode

        if (!(TabNode = DBnode->AddChildNode(g, Tabname))) {
          sprintf(g->Message, MSG(FAIL_ADD_NODE), Tabname);
          goto error;
          } // endif TabNode

        DBnode->AddText(g, "\n");
      } else
        TabNode = Root;              // Try this ?

    } else if (rc == RC_NF || rc == RC_EF) {
      // The XML file does not exist or is void
      if (Mode == MODE_INSERT) {
        // New Document
        char buf[64];

        // Create the XML node
        if (Docp->NewDoc(g, "1.0")) {
          strcpy(g->Message, MSG(NEW_DOC_FAILED));
          goto error;
          } // endif NewDoc

        //  Now we can link the Xblock
        To_Xb = Docp->LinkXblock(g, Mode, rc, filename);

        // Add a CONNECT comment node
        strcpy(buf, " Created by the MariaDB CONNECT Storage Engine");
        Docp->AddComment(g, buf);

        if (XmlDB) {
          // This is a multi-table file
          DBnode = Root = Docp->NewRoot(g, XmlDB);
          DBnode->AddText(g, "\n");
          TabNode = DBnode->AddChildNode(g, Tabname);
          DBnode->AddText(g, "\n");
        } else
          TabNode = Root = Docp->NewRoot(g, Tabname);

        if (TabNode == NULL || Root == NULL) {
          strcpy(g->Message, MSG(XML_INIT_ERROR));
          goto error;
        } else if (SetTabNode(g))
          goto error;

      } else {
        sprintf(g->Message, MSG(FILE_UNFOUND), Xfile);

        if (Mode == MODE_READ) {
          PushWarning(g, this);
          Void = true;
          } // endif Mode

        goto error;
      } // endif Mode

    } else if (rc == RC_INFO) {
      // Loading failed
      sprintf(g->Message, MSG(LOADING_FAILED), Xfile);
      goto error;
    } else // (rc == RC_FX)
      goto error;

    // Get row node list
    if (Rowname)
      Nlist = TabNode->SelectNodes(g, Rowname);
    else
      Nlist = TabNode->GetChildElements(g);

    Docp->SetNofree(true);       // For libxml2
#if defined(__WIN__)
  } catch(_com_error e) {
    // We come here if a DOM command threw an error
    char   buf[128];

    rc = WideCharToMultiByte(CP_ACP, 0, e.Description(), -1,
                             buf, sizeof(buf), NULL, NULL);

    if (rc)
      sprintf(g->Message, "%s: %s", MSG(COM_ERROR), buf);
    else
      sprintf(g->Message, "%s hr=%x", MSG(COM_ERROR), e.Error());

    goto error;
#endif   // __WIN__
#if !defined(UNIX)
  } catch(...) {
    // Other errors
    strcpy(g->Message, MSG(XMLTAB_INIT_ERR));
    goto error;
#endif
  } // end of try-catches

  if (Root && Columns && (Multiple || !Nodedone)) {
    // Allocate class nodes to avoid dynamic allocation
    for (colp = (PXMLCOL)Columns; colp; colp = (PXMLCOL)colp->GetNext())
      if (!colp->IsSpecial())            // Not a pseudo column
        colp->AllocNodes(g, Docp);

    Nodedone = true;
    } // endif Nodedone

  if (Nrow < 0)
    Nrow = (Nlist) ? Nlist->GetLength() : 0;
 
  // Init is Ok
  return false;

error:
  if (Docp)
    Docp->CloseDoc(g, To_Xb);

  return !Void;
} // end of Initialize

/***********************************************************************/
/*  Set TabNode attributes or header.                                  */
/***********************************************************************/
bool TDBXML::SetTabNode(PGLOBAL g)
  {
  assert(Mode == MODE_INSERT);

  if (Attrib)
    SetNodeAttr(g, Attrib, TabNode);

  if (Header) {
    PCOLDEF cdp;
    PXNODE  rn, cn;

    if (Rowname) {
      TabNode->AddText(g, "\n\t");
      rn = TabNode->AddChildNode(g, Rowname, NULL);
    } else {
      strcpy(g->Message, MSG(NO_ROW_NODE));
      return true;
    } // endif Rowname

    if (Hdattr)
      SetNodeAttr(g, Hdattr, rn);

    for (cdp = To_Def->GetCols(); cdp; cdp = cdp->GetNext()) {
      rn->AddText(g, "\n\t\t");
      cn = rn->AddChildNode(g, "TH", NULL);
      cn->SetContent(g, (char *)cdp->GetName(), 
                         strlen(cdp->GetName()) + 1);
      } // endfor cdp

    rn->AddText(g, "\n\t");
    } // endif ColType

  return false;
  } // end of SetTabNode

/***********************************************************************/
/*  Set attributes of a table or header node.                          */
/***********************************************************************/
void TDBXML::SetNodeAttr(PGLOBAL g, char *attr, PXNODE node)
  {
  char  *p, *pa, *pn = attr;
  PXATTR an;

  do {
    if ((p = strchr(pn, '='))) {
      pa = pn;
      *p++ = 0;
  
      if ((pn =   strchr(p, ';')))
        *pn++ = 0;
  
      an = node->AddProperty(g, pa, NULL);
      an->SetText(g, p, strlen(p) + 1);
    } else
      break;

    } while (pn);

  } // end of SetNodeAttr

/***********************************************************************/
/*  XML Cardinality: returns table cardinality in number of rows.      */
/*  This function can be called with a null argument to test the       */
/*  availability of Cardinality implementation (1 yes, 0 no).          */
/***********************************************************************/
int TDBXML::Cardinality(PGLOBAL g)
  {
  if (!g)
    return (Multiple || Xpand || Coltype == 2) ? 0 : 1;

  if (Multiple)
    return 10;

  if (Nrow < 0)
    if (Initialize(g))
      return -1;

  return (Void) ? 0 : Nrow - Header;
  } // end of Cardinality

/***********************************************************************/
/*  XML GetMaxSize: returns the number of tables in the database.      */
/***********************************************************************/
int TDBXML::GetMaxSize(PGLOBAL g)
  {
  if (MaxSize < 0) {
    if (!Multiple)
      MaxSize = Cardinality(g) * ((Xpand) ? Limit : 1);
    else
      MaxSize = 10;

    } // endif MaxSize

  return MaxSize;
  } // end of GetMaxSize

/***********************************************************************/
/*  Return the position in the table.                                  */
/***********************************************************************/
int TDBXML::GetRecpos(void)
  {
  union {
    uint Rpos;
    BYTE Spos[4];
    };

  Rpos = htonl(Irow);
  Spos[0] = (BYTE)Nsub;
  return Rpos;
  } // end of GetRecpos

/***********************************************************************/
/*  RowNumber: return the ordinal number of the current row.           */
/***********************************************************************/
int TDBXML::RowNumber(PGLOBAL g, bool b)
  {
  if (To_Kindex && (Xpand || Coltype == 2) && !b) {
    /*******************************************************************/
    /*  Don't know how to retrieve RowID for expanded XML tables.      */
    /*******************************************************************/
    sprintf(g->Message, MSG(NO_ROWID_FOR_AM),
                        GetAmName(g, GetAmType()));
    return 0;          // Means error
  } else
    return (b || !(Xpand || Coltype == 2)) ? Irow - Header + 1 : N;

  } // end of RowNumber

/***********************************************************************/
/*  XML Access Method opening routine.                                 */
/***********************************************************************/
bool TDBXML::OpenDB(PGLOBAL g)
  {
  if (Use == USE_OPEN) {
    /*******************************************************************/
    /*  Table already open replace it at its beginning.                */
    /*******************************************************************/
    if (!To_Kindex) {
      Irow = Header - 1;
      Nsub = 0;
    } else
      /*****************************************************************/
      /*  Table is to be accessed through a sorted index table.        */
      /*****************************************************************/
      To_Kindex->Reset();

    return false;
    } // endif use

  /*********************************************************************/
  /*  OpenDB: initialize the XML file processing.                      */
  /*********************************************************************/
  Write = (Mode == MODE_INSERT || Mode == MODE_UPDATE);

  if (Initialize(g))
    return true;

  NewRow = (Mode == MODE_INSERT);
  Nsub = 0;
  Use = USE_OPEN;       // Do it now in case we are recursively called
  return false;
  } // end of OpenDB

/***********************************************************************/
/*  Data Base read routine for XML access method.                      */
/***********************************************************************/
int TDBXML::ReadDB(PGLOBAL g)
  {
  bool same;

  if (Void)
    return RC_EF;

  /*********************************************************************/
  /*  Now start the pseudo reading process.                            */
  /*********************************************************************/
  if (To_Kindex) {
    /*******************************************************************/
    /*  Reading is by an index table.                                  */
    /*******************************************************************/
    union {
      uint Rpos;
      BYTE Spos[4];
      };

    int recpos = To_Kindex->Fetch(g);

    switch (recpos) {
      case -1:           // End of file reached
        return RC_EF;
      case -2:           // No match for join
        return RC_NF;
      case -3:           // Same record as last non null one
        same = true;
        return RC_OK;
      default:
        Rpos = recpos;
        Nsub = Spos[0];
        Spos[0] = 0;

        if (Irow != (signed)ntohl(Rpos)) {
          Irow = ntohl(Rpos);
          same = false;
        } else
          same = true;

      } // endswitch recpos

  } else {
    if (trace(1))
      htrc("TDBXML ReadDB: Irow=%d Nrow=%d\n", Irow, Nrow);

    // This is to force the table to be expanded when constructing
    // an index for which the expand column is not specified.
    if (Colp && Irow >= Header) {
      Colp->Eval(g);
      Colp->Reset();
      } // endif Colp

    if (!NextSame) {
      if (++Irow == Nrow)
        return RC_EF;

      same = false;
      Nsub = 0;
    } else {
      // Not sure the multiple column read will be called
      NextSame = false;
      same = true;
      Nsub++;
    } // endif NextSame

    N++;                          // RowID
  } // endif To_Kindex

  if (!same) {
    if (trace(2))
      htrc("TDBXML ReadDB: Irow=%d RowNode=%p\n", Irow, RowNode);

    // Get the new row node
    if ((RowNode = Nlist->GetItem(g, Irow, RowNode)) == NULL) {
      sprintf(g->Message, MSG(MISSING_ROWNODE), Irow);
      return RC_FX;
      } // endif RowNode

    if (Colname && Coltype == 2)
      Clist = RowNode->SelectNodes(g, Colname, Clist);

    } // endif same

  return RC_OK;
  } // end of ReadDB

/***********************************************************************/
/*  CheckRow: called On Insert and Update. Must create the Row node    */
/*  if it does not exist (Insert) and update the Clist if called by    */
/*  a column having an Xpath because it can use an existing node that  */
/*  was added while inserting or Updating this row.                    */
/***********************************************************************/
bool TDBXML::CheckRow(PGLOBAL g, bool b)
  {
  if (NewRow && Mode == MODE_INSERT)
    if (Rowname) {
      TabNode->AddText(g, "\n\t");
      RowNode = TabNode->AddChildNode(g, Rowname, RowNode);
    } else {
      strcpy(g->Message, MSG(NO_ROW_NODE));
      return true;
    } // endif Rowname

  if (Colname && (NewRow || b))
    Clist = RowNode->SelectNodes(g, Colname, Clist);

  return NewRow = false;
  } // end of CheckRow

/***********************************************************************/
/*  WriteDB: Data Base write routine for XDB access methods.           */
/***********************************************************************/
int TDBXML::WriteDB(PGLOBAL g)
  {
  if (Mode == MODE_INSERT) {
    if (Hasnod)
      RowNode->AddText(g, "\n\t");

    NewRow = true;
    } // endif Mode

  // Something was changed in the document
  Changed = true;
  return RC_OK;
  } // end of WriteDB

/***********************************************************************/
/*  Data Base delete line routine for XDB access methods.              */
/***********************************************************************/
int TDBXML::DeleteDB(PGLOBAL g, int irc)
  {
  if (irc == RC_FX) {
    // Delete all rows
    for (Irow = 0; Irow < Nrow; Irow++)
      if ((RowNode = Nlist->GetItem(g, Irow, RowNode)) == NULL) {
        sprintf(g->Message, MSG(MISSING_ROWNODE), Irow);
        return RC_FX;
      } else {
        TabNode->DeleteChild(g, RowNode);

        if (Nlist->DropItem(g, Irow))
          return RC_FX;

      } // endif RowNode

    Changed = true;
  } else if (irc != RC_EF) {
    TabNode->DeleteChild(g, RowNode);

    if (Nlist->DropItem(g, Irow))
      return RC_FX;

    Changed = true;
  } // endif's irc

  return RC_OK;
  } // end of DeleteDB

/***********************************************************************/
/*  Data Base close routine for XDB access methods.                    */
/***********************************************************************/
void TDBXML::CloseDB(PGLOBAL g)
  {
  if (Docp) {
    if (Changed) {
      char filename[_MAX_PATH];

      // We used the file name relative to recorded datapath
      PlugSetPath(filename, Xfile, GetPath());

      if (Mode == MODE_INSERT)
        TabNode->AddText(g, "\n");

      // Save the modified document
      if (Docp->DumpDoc(g, filename)) {
        PushWarning(g, this);
        Docp->CloseDoc(g, To_Xb);

        // This causes a crash in Diagnostics_area::set_error_status
//				throw (int)TYPE_AM_XML;
			} // endif DumpDoc
      
      } // endif Changed

    // Free the document and terminate XML processing
    Docp->CloseDoc(g, To_Xb);
    } // endif docp

  if (Multiple) {
    // Reset all constants to start a new parse
    Docp = NULL;
    Root = NULL;
    Curp = NULL;
    DBnode = NULL;
    TabNode = NULL;
    RowNode = NULL;
    ColNode = NULL;
    Nlist = NULL;
    Clist = NULL;
    To_Xb = NULL;
    Colp = NULL;
    Changed = false;
    Checked = false;
    NextSame = false;
    NewRow = false;
    Hasnod = false;
    Write = false;
    Nodedone = false;
    Void = false;
    Nrow = -1;
    Irow = Header - 1;
    Nsub = 0;
    N = 0;
    } // endif Multiple

  } // end of CloseDB

// ------------------------ XMLCOL functions ----------------------------

/***********************************************************************/
/*  XMLCOL public constructor.                                        */
/***********************************************************************/
XMLCOL::XMLCOL(PCOLDEF cdp, PTDB tdbp, PCOL cprec, int i, PCSZ am)
      : COLBLK(cdp, tdbp, i)
  {
  if (cprec) {
    Next = cprec->GetNext();
    cprec->SetNext(this);
  } else {
    Next = tdbp->GetColumns();
    tdbp->SetColumns(this);
  } // endif cprec

  // Set additional XML access method information for column.
  Tdbp = (PTDBXML)tdbp;
  Nl = NULL;
  Nlx = NULL;
  ColNode = NULL;
  ValNode = NULL;
  Cxnp = NULL;
  Vxnp = NULL;
  Vxap = NULL;
  AttNode = NULL;
  Nodes = NULL;
  Nod = 0;
  Inod = -1;
  Mul = false;
  Checked = false;
  Xname = cdp->GetFmt();
  Long = cdp->GetLong();
  Rank = cdp->GetOffset();
  Type = Tdbp->Coltype;
  Nx = -1;
  Sx = -1;
  N = 0;
  Valbuf = NULL;
  To_Val = NULL;
  } // end of XMLCOL constructor

/***********************************************************************/
/*  XMLCOL constructor used for copying columns.                       */
/*  tdbp is the pointer to the new table descriptor.                   */
/***********************************************************************/
XMLCOL::XMLCOL(XMLCOL *col1, PTDB tdbp) : COLBLK(col1, tdbp)
  {
  Tdbp = col1->Tdbp;
  Nl = col1->Nl;
  Nlx = col1->Nlx;
  ColNode = col1->ColNode;
  ValNode = col1->ValNode;
  Cxnp = col1->Cxnp;
  Vxnp = col1->Vxnp;
  Vxap = col1->Vxap;
  AttNode = col1->AttNode;
  Nodes = col1->Nodes;
  Nod = col1->Nod;
  Inod = col1->Inod;
  Mul = col1->Mul;
  Checked = col1->Checked;
  Xname = col1->Xname;
  Valbuf = col1->Valbuf;
  Long = col1->Long;
  Rank = col1->Rank;
  Nx = col1->Nx;
  Sx = col1->Sx;
  N = col1->N;
  Type = col1->Type;
  To_Val = col1->To_Val;
  } // end of XMLCOL copy constructor

/***********************************************************************/
/*  Allocate a buffer of the proper size.                              */
/***********************************************************************/
bool XMLCOL::AllocBuf(PGLOBAL g, bool mode)
  {
  if (Valbuf)
    return false;                       // Already done

  return ParseXpath(g, mode);
  } // end of AllocBuf

/***********************************************************************/
/*  Parse the eventual passed Xpath information.                       */
/*  This information can be specified in the Xpath (or Fieldfmt)       */
/*  column option when creating the table. It permits to indicate the  */
/*  position of the node corresponding to that column in a Xpath-like  */
/*  language (but not a truly compliant one).                          */
/***********************************************************************/
bool XMLCOL::ParseXpath(PGLOBAL g, bool mode)
  {
  char *p, *p2, *pbuf = NULL;
  int   i, n = 1, len = strlen(Name);

  len += ((Tdbp->Colname) ? strlen(Tdbp->Colname) : 0);
  len += ((Xname) ? strlen(Xname) : 0);
  pbuf = (char*)PlugSubAlloc(g, NULL, len + 3);
  *pbuf = '\0';

  if (!mode)
    // Take care of an eventual extra column node a la html
    if (Tdbp->Colname) {
      sprintf(pbuf, Tdbp->Colname, Rank + ((Tdbp->Usedom) ? 0 : 1));
      strcat(pbuf, "/");
      } // endif Colname

  if (Xname) {
    if (Type == 2) {
      sprintf(g->Message, MSG(BAD_COL_XPATH), Name, Tdbp->Name);
      return true;
    } else
      strcat(pbuf, Xname);

    if (trace(1))
      htrc("XMLCOL: pbuf=%s\n", pbuf);

    // For Update or Insert the Xpath must be analyzed
    if (mode) {
      for (i = 0, p = pbuf; (p = strchr(p, '/')); i++, p++)
        Nod++;                       // One path node found

      if (Nod)
        Nodes = (char**)PlugSubAlloc(g, NULL, Nod * sizeof(char*));

      } // endif mode

    // Analyze the Xpath for this column
    for (i = 0, p = pbuf; (p2 = strchr(p, '/')); i++, p = p2 + 1) {
      if (Tdbp->Mulnode && !strncmp(p, Tdbp->Mulnode, p2 - p))
        if (!Tdbp->Xpand && mode) {
          strcpy(g->Message, MSG(CONCAT_SUBNODE));
          return true;
        } else
          Inod = i;                  // Index of multiple node

      if (mode) {
        // For Update or Insert the Xpath must be explicit
        if (strchr("@/.*", *p)) {
          sprintf(g->Message, MSG(XPATH_NOT_SUPP), Name);
          return true;
        } else
          Nodes[i] = p;

        *p2 = '\0';
        } // endif mode

      } // endfor i, p

    if (*p == '/' || *p == '.') {
      sprintf(g->Message, MSG(XPATH_NOT_SUPP), Name);
      return true;
    } else if (*p == '@') {
      p++;                           // Remove the @ if mode
      Type = 0;                      // Column is an attribute
    } else
      Type = 1;                      // Column is a node

    if (!*p)
      strcpy(p, Name);               // Xname is column name

    if (Type && Tdbp->Mulnode && !strcmp(p, Tdbp->Mulnode))
      Inod = Nod;                    // Index of multiple node

    if (mode)                        // Prepare Xname
      pbuf = p;

  } else if (Type == 2) {
    // HTML like table, columns are retrieved by position
    new(this) XPOSCOL(Value);        // Change the class of this column
    Inod = -1;
  } else if (Type == 0 && !mode) {
    strcat(strcat(pbuf, "@"), Name);
  } else {                           // Type == 1
    if (Tdbp->Mulnode && !strcmp(Name, Tdbp->Mulnode))
      Inod = 0;                      // Nod

    strcat(pbuf, Name);
  } // endif,s

  if (Inod >= 0) {
    Tdbp->Colp = this;               // To force expand

    if (Tdbp->Xpand)
      n = Tdbp->Limit;

    new(this) XMULCOL(Value);        // Change the class of this column
    } // endif Inod

  Valbuf = (char*)PlugSubAlloc(g, NULL, n * (Long + 1));

  for (i = 0; i < n; i++)
    Valbuf[Long + (i * (Long + 1))] = '\0';

  if (Type || Nod)
    Tdbp->Hasnod = true;

  if (trace(1))
    htrc("XMLCOL: Xname=%s\n", pbuf);

  // Save the calculated Xpath
  Xname = pbuf;
  return false;
  } // end of ParseXpath

/***********************************************************************/
/*  SetBuffer: prepare a column block for write operation.             */
/***********************************************************************/
bool XMLCOL::SetBuffer(PGLOBAL g, PVAL value, bool ok, bool check)
  {
  if (!(To_Val = value)) {
    sprintf(g->Message, MSG(VALUE_ERROR), Name);
    return true;
  } else if (Buf_Type == value->GetType()) {
    // Values are of the (good) column type
    if (Buf_Type == TYPE_DATE) {
      // If any of the date values is formatted
      // output format must be set for the receiving table
      if (GetDomain() || ((DTVAL *)value)->IsFormatted())
        goto newval;          // This will make a new value;

    } else if (Buf_Type == TYPE_DOUBLE)
      // Float values must be written with the correct (column) precision
      // Note: maybe this should be forced by ShowValue instead of this ?
      value->SetPrec(GetScale());

    Value = value;            // Directly access the external value
  } else {
    // Values are not of the (good) column type
    if (check) {
      sprintf(g->Message, MSG(TYPE_VALUE_ERR), Name,
              GetTypeName(Buf_Type), GetTypeName(value->GetType()));
      return true;
      } // endif check

 newval:
    if (InitValue(g))         // Allocate the matching value block
      return true;

  } // endif's Value, Buf_Type

  // Because Colblk's have been made from a copy of the original TDB in
  // case of Update, we must reset them to point to the original one.
  if (To_Tdb->GetOrig()) {
    To_Tdb = (PTDB)To_Tdb->GetOrig();
    Tdbp = (PTDBXML)To_Tdb;   // Specific of XMLCOL

    // Allocate the XML buffer
    if (AllocBuf(g, true))      // In Write mode
      return true;

    } // endif GetOrig

  // Set the Column
  Status = (ok) ? BUF_EMPTY : BUF_NO;
  return false;
  } // end of SetBuffer

/***********************************************************************/
/*  Alloc the nodes that will be used during the whole process.        */
/***********************************************************************/
void XMLCOL::AllocNodes(PGLOBAL g, PXDOC dp)
{
  Cxnp = dp->NewPnode(g);
  Vxnp = dp->NewPnode(g);
  Vxap = dp->NewPattr(g);
} // end of AllocNodes

/***********************************************************************/
/*  ReadColumn: what this routine does is to access the column node    */
/*  from the corresponding table, extract from it the node text and    */
/*  convert it to the column type.                                     */
/***********************************************************************/
void XMLCOL::ReadColumn(PGLOBAL g)
  {
  if (Nx == Tdbp->Irow)
    return;                         // Same row than the last read

  ValNode = Tdbp->RowNode->SelectSingleNode(g, Xname, Vxnp);

  if (ValNode) {
    if (ValNode->GetType() != XML_ELEMENT_NODE &&
        ValNode->GetType() != XML_ATTRIBUTE_NODE) {
      sprintf(g->Message, MSG(BAD_VALNODE), ValNode->GetType(), Name);
			throw (int)TYPE_AM_XML;
		} // endif type

    // Get the Xname value from the XML file
    switch (ValNode->GetContent(g, Valbuf, Long + 1)) {
      case RC_OK:
        break;
      case RC_INFO:
        PushWarning(g, Tdbp);
        break;
      default:
				throw (int)TYPE_AM_XML;
		} // endswitch

    Value->SetValue_psz(Valbuf);
  } else {
    if (Nullable)
      Value->SetNull(true);

    Value->Reset();              // Null value
  } // endif ValNode

  Nx = Tdbp->Irow;
  } // end of ReadColumn

/***********************************************************************/
/*  WriteColumn: what this routine does is to access the last row of   */
/*  the corresponding table, and rewrite the content corresponding     */
/*  to this column node from the column buffer and type.               */
/***********************************************************************/
void XMLCOL::WriteColumn(PGLOBAL g)
  {
  char  *p, buf[16];
  int    done = 0;
  int   i, n, k = 0;
  PXNODE TopNode = NULL;

  if (trace(2))
    htrc("XML WriteColumn: col %s R%d coluse=%.4X status=%.4X\n",
          Name, Tdbp->GetTdb_No(), ColUse, Status);

  /*********************************************************************/
  /*  Check whether this node must be written.                         */
  /*********************************************************************/
  if (Value != To_Val)
    Value->SetValue_pval(To_Val, false);    // Convert the updated value

  /*********************************************************************/
  /*  If a check pass was done while updating, all node contruction    */
  /*  has been already one.                                            */
  /*********************************************************************/
  if (Status && Tdbp->Checked && !Value->IsNull()) {
    assert (ColNode != NULL);
    assert ((Type ? (void *)ValNode : (void *)AttNode) != NULL);
    goto fin;
    } // endif Checked

  /*********************************************************************/
  /*  On Insert, a Row node must be created for each row;              */
  /*  For columns having an Xpath, the Clist must be updated.          */
  /*********************************************************************/
  if (Tdbp->CheckRow(g, Nod || Tdbp->Colname))
		throw (int)TYPE_AM_XML;

  /*********************************************************************/
  /*  Null values are represented by no node.                          */
  /*********************************************************************/
	if (Value->IsNull())
    return;

  /*********************************************************************/
  /*  Find the column and value nodes to update or insert.             */
  /*********************************************************************/
  if (Tdbp->Clist) {
    n =  Tdbp->Clist->GetLength();
    ColNode = NULL;
  } else {
    n = 1;
    ColNode = Tdbp->RowNode->Clone(g, ColNode);
  } // endif Clist

  ValNode = NULL;

  for (i = 0; i < n; i++) {
    if (Tdbp->Clist)
      ColNode = Tdbp->Clist->GetItem(g, i, Cxnp);

    /*******************************************************************/
    /*  Check whether an Xpath was provided to go to the column node.  */
    /*******************************************************************/
    for (k = 0; k < Nod; k++)
      if ((ColNode = ColNode->SelectSingleNode(g, Nodes[k], Cxnp)))
        TopNode = ColNode;
      else
        break;

    if (ColNode)
      if (Type)
        ValNode = ColNode->SelectSingleNode(g, Xname, Vxnp);
      else
        AttNode = ColNode->GetAttribute(g, Xname, Vxap);

    if (TopNode || ValNode || AttNode)
      break;                      // We found the good column
    else if (Tdbp->Clist)
      ColNode = NULL;

    } // endfor i

  /*********************************************************************/
  /*  Create missing nodes.                                            */
  /*********************************************************************/
  if (ColNode == NULL) {
    if (TopNode == NULL)
      if (Tdbp->Clist) {
        Tdbp->RowNode->AddText(g, "\n\t\t");
        ColNode = Tdbp->RowNode->AddChildNode(g, Tdbp->Colname);
        done = 2;
        TopNode = ColNode;
      } else
        TopNode = Tdbp->RowNode;

    for (; k < Nod && TopNode; k++) {
      if (!done) {
        TopNode->AddText(g, "\n\t\t");
        done = 1;
        } // endif done

      ColNode = TopNode->AddChildNode(g, Nodes[k], Cxnp);
      TopNode = ColNode;
      } // endfor k

    if (ColNode == NULL) {
      strcpy(g->Message, MSG(COL_ALLOC_ERR));
			throw (int)TYPE_AM_XML;
		} // endif ColNode

    } // endif ColNode

  if (Type == 1) {
    if (ValNode == NULL) {
      if (done < 2)
        ColNode->AddText(g, "\n\t\t");

      ValNode = ColNode->AddChildNode(g, Xname, Vxnp);
      } // endif ValNode

  } else // (Type == 0)
    if (AttNode == NULL)
      AttNode = ColNode->AddProperty(g, Xname, Vxap);

  if (ValNode == NULL && AttNode == NULL) {
    strcpy(g->Message, MSG(VAL_ALLOC_ERR));
    throw (int)TYPE_AM_XML;
    } // endif ValNode

  /*********************************************************************/
  /*  Get the string representation of Value according to column type. */
  /*********************************************************************/
  p = Value->GetCharString(buf);

  if (strlen(p) > (unsigned)Long) {
    sprintf(g->Message, MSG(VALUE_TOO_LONG), p, Name, Long);
		throw (int)TYPE_AM_XML;
	} else
    strcpy(Valbuf, p);

  /*********************************************************************/
  /*  Updating must be done only when not in checking pass.            */
  /*********************************************************************/
 fin:
  if (Status) {
    if (Type) {
      ValNode->SetContent(g, Valbuf, Long);
    } else
      AttNode->SetText(g, Valbuf, Long);

    } // endif Status

  } // end of WriteColumn

// ------------------------ XMULCOL functions ---------------------------

/***********************************************************************/
/*  ReadColumn: what this routine does is to access the column node    */
/*  from the corresponding table, extract from it the node text and    */
/*  convert it to the column type.                                     */
/***********************************************************************/
void XMULCOL::ReadColumn(PGLOBAL g)
  {
  char *p;
  int   i, len;
  bool  b = Tdbp->Xpand;

  if (Nx != Tdbp->Irow) {                     // New row
    Nl = Tdbp->RowNode->SelectNodes(g, Xname, Nl);

    if ((N = Nl->GetLength())) {
      *(p = Valbuf) = '\0';
      len = Long;

      if (N > Tdbp->Limit) {
        N = Tdbp->Limit;
        sprintf(g->Message, "Mutiple values limited to %d", Tdbp->Limit);
        PushWarning(g, Tdbp);
        } // endif N

      for (i = 0; i < N; i++) {
        ValNode = Nl->GetItem(g, i, Vxnp);

        if (ValNode->GetType() != XML_ELEMENT_NODE &&
            ValNode->GetType() != XML_ATTRIBUTE_NODE) {
          sprintf(g->Message, MSG(BAD_VALNODE), ValNode->GetType(), Name);
					throw (int)TYPE_AM_XML;
				} // endif type

        // Get the Xname value from the XML file
        switch (ValNode->GetContent(g, p, (b ? Long : len))) {
          case RC_OK:
            break;
          case RC_INFO:
            PushWarning(g, Tdbp);
            break;
          default:
            throw (int)TYPE_AM_XML;
          } // endswitch

        if (!b) {
          // Concatenate all values
          if (N - i > 1)
            strncat(Valbuf, ", ", len - strlen(p));

          if ((len -= strlen(p)) <= 0)
            break;

          p += strlen(p);
        } else            // Xpand
          p += (Long + 1);

        } // endfor i

      Value->SetValue_psz(Valbuf);
    } else {
      if (Nullable)
        Value->SetNull(true);

      Value->Reset();              // Null value
    } // endif ValNode

  } else if (Sx == Tdbp->Nsub)
    return;                        // Same row
  else                             // Expanded value
    Value->SetValue_psz(Valbuf + (Tdbp->Nsub * (Long + 1)));

  Nx = Tdbp->Irow;
  Sx = Tdbp->Nsub;
  Tdbp->NextSame = (Tdbp->Xpand && N - Sx > 1);
  } // end of ReadColumn

/***********************************************************************/
/*  WriteColumn: what this routine does is to access the last line     */
/*  read from the corresponding table, and rewrite the field           */
/*  corresponding to this column from the column buffer and type.      */
/***********************************************************************/
void XMULCOL::WriteColumn(PGLOBAL g)
  {
  char  *p, buf[16];
  int    done = 0;
  int   i, n, len, k = 0;
  PXNODE TopNode = NULL;

  if (trace(1))
    htrc("XML WriteColumn: col %s R%d coluse=%.4X status=%.4X\n",
          Name, Tdbp->GetTdb_No(), ColUse, Status);

  /*********************************************************************/
  /*  Check whether this node must be written.                         */
  /*********************************************************************/
  if (Value != To_Val)
    Value->SetValue_pval(To_Val, false);    // Convert the updated value

  if (Value->IsNull())
    return;

  /*********************************************************************/
  /*  If a check pass was done while updating, all node contruction    */
  /*  has been already one.                                            */
  /*********************************************************************/
  if (Status && Tdbp->Checked) {
    assert (ColNode);
    assert ((Type ? (void *)ValNode : (void *)AttNode) != NULL);
    goto fin;
    } // endif Checked

  /*********************************************************************/
  /*  On Insert, a Row node must be created for each row;              */
  /*  For columns having an Xpath, the Clist must be updated.          */
  /*********************************************************************/
  if (Tdbp->CheckRow(g, Nod))
		throw (int)TYPE_AM_XML;

  /*********************************************************************/
  /*  Find the column and value nodes to update or insert.             */
  /*********************************************************************/
  if (Tdbp->Clist) {
    n =  Tdbp->Clist->GetLength();
    ColNode = NULL;
  } else {
    n = 1;
    ColNode = Tdbp->RowNode->Clone(g, ColNode);
  } // endif Clist

  ValNode = NULL;

  for (i = 0; i < n; i++) {
    if (Tdbp->Clist)
      ColNode = Tdbp->Clist->GetItem(g, i, Cxnp);

    /*******************************************************************/
    /*  Check whether an Xpath was provided to go to the column node.  */
    /*******************************************************************/
    for (k = 0; k < Nod; k++) {
      if (k == Inod) {
        // This is the multiple node
        Nlx = ColNode->SelectNodes(g, Nodes[k], Nlx);
        ColNode = Nlx->GetItem(g, Tdbp->Nsub, Cxnp);
      } else
        ColNode = ColNode->SelectSingleNode(g, Nodes[k], Cxnp);

      if (ColNode == NULL)
        break;

      TopNode = ColNode;
      } // endfor k

    if (ColNode)
      if (Inod == Nod) {
        /***************************************************************/
        /*  The node value can be multiple.                            */
        /***************************************************************/
        assert (Type);

        // Get the value Node from the XML list
        Nlx = ColNode->SelectNodes(g, Xname, Nlx);
        len = Nlx->GetLength();

        if (len > 1 && !Tdbp->Xpand) {
          sprintf(g->Message, MSG(BAD_VAL_UPDATE), Name);
					throw (int)TYPE_AM_XML;
				} else
          ValNode = Nlx->GetItem(g, Tdbp->Nsub, Vxnp);

      } else  // Inod != Nod
        if (Type)
          ValNode = ColNode->SelectSingleNode(g, Xname, Vxnp);
        else
          AttNode = ColNode->GetAttribute(g, Xname, Vxap);

    if (TopNode || ValNode || AttNode)
      break;                     // We found the good column
    else if (Tdbp->Clist)
      ColNode = NULL;

    } // endfor i

  /*********************************************************************/
  /*  Create missing nodes.                                            */
  /*********************************************************************/
  if (ColNode == NULL) {
    if (TopNode == NULL)
      if (Tdbp->Clist) {
        Tdbp->RowNode->AddText(g, "\n\t\t");
        ColNode = Tdbp->RowNode->AddChildNode(g, Tdbp->Colname);
        done = 2;
        TopNode = ColNode;
      } else
        TopNode = Tdbp->RowNode;

    for (; k < Nod && TopNode; k++) {
      if (!done) {
        TopNode->AddText(g, "\n\t\t");
        done = 1;
        } // endif done

      ColNode = TopNode->AddChildNode(g, Nodes[k], Cxnp);
      TopNode = ColNode;
      } // endfor k

    if (ColNode == NULL) {
      strcpy(g->Message, MSG(COL_ALLOC_ERR));
			throw (int)TYPE_AM_XML;
		} // endif ColNode

    } // endif ColNode

  if (Type == 1) {
    if (ValNode == NULL) {
      if (done < 2)
        ColNode->AddText(g, "\n\t\t");

      ValNode = ColNode->AddChildNode(g, Xname, Vxnp);
      } // endif ValNode

  } else // (Type == 0)
    if (AttNode == NULL)
      AttNode = ColNode->AddProperty(g, Xname, Vxap);

  if (ValNode == NULL && AttNode == NULL) {
    strcpy(g->Message, MSG(VAL_ALLOC_ERR));
		throw (int)TYPE_AM_XML;
	} // endif ValNode

  /*********************************************************************/
  /*  Get the string representation of Value according to column type. */
  /*********************************************************************/
  p = Value->GetCharString(buf);

  if (strlen(p) > (unsigned)Long) {
    sprintf(g->Message, MSG(VALUE_TOO_LONG), p, Name, Long);
		throw (int)TYPE_AM_XML;
	} else
    strcpy(Valbuf, p);

  /*********************************************************************/
  /*  Updating must be done only when not in checking pass.            */
  /*********************************************************************/
 fin:
  if (Status) {
    if (Type) {
      ValNode->SetContent(g, Valbuf, Long);
    } else
      AttNode->SetText(g, Valbuf, Long);

    } // endif Status

  } // end of WriteColumn

/* ------------------------ XPOSCOL functions ------------------------ */

/***********************************************************************/
/*  ReadColumn: what this routine does is to access the column node    */
/*  from the corresponding table, extract from it the node text and    */
/*  convert it to the column type.                                     */
/***********************************************************************/
void XPOSCOL::ReadColumn(PGLOBAL g)
  {
  if (Nx == Tdbp->Irow)
    return;                         // Same row than the last read

  if (Tdbp->Clist == NULL) {
    strcpy(g->Message, MSG(MIS_TAG_LIST));
		throw (int)TYPE_AM_XML;
	} // endif Clist

  if ((ValNode = Tdbp->Clist->GetItem(g, Rank, Vxnp))) {
    // Get the column value from the XML file
    switch (ValNode->GetContent(g, Valbuf, Long + 1)) {
      case RC_OK:
        break;
      case RC_INFO:
        PushWarning(g, Tdbp);
        break;
      default:
				throw (int)TYPE_AM_XML;
		} // endswitch

    Value->SetValue_psz(Valbuf);
  } else {
    if (Nullable)
      Value->SetNull(true);

    Value->Reset();              // Null value
  } // endif ValNode

  Nx = Tdbp->Irow;
  } // end of ReadColumn

/***********************************************************************/
/*  WriteColumn: what this routine does is to access the last line     */
/*  read from the corresponding table, and rewrite the field           */
/*  corresponding to this column from the column buffer and type.      */
/***********************************************************************/
void XPOSCOL::WriteColumn(PGLOBAL g)
  {
  char          *p, buf[16];
  int           i, k, n;

  if (trace(1))
    htrc("XML WriteColumn: col %s R%d coluse=%.4X status=%.4X\n",
          Name, Tdbp->GetTdb_No(), ColUse, Status);

  /*********************************************************************/
  /*  Check whether this node must be written.                         */
  /*********************************************************************/
  if (Value != To_Val)
    Value->SetValue_pval(To_Val, false);    // Convert the updated value

  if (Value->IsNull())
    return;

  /*********************************************************************/
  /*  If a check pass was done while updating, all node contruction    */
  /*  has been already one.                                            */
  /*********************************************************************/
  if (Status && Tdbp->Checked) {
    assert (ValNode);
    goto fin;
    } // endif Checked

  /*********************************************************************/
  /*  On Insert, a Row node must be created for each row;              */
  /*  For all columns the Clist must be updated.                       */
  /*********************************************************************/
  if (Tdbp->CheckRow(g, true))
		throw (int)TYPE_AM_XML;

  /*********************************************************************/
  /*  Find the column and value nodes to update or insert.             */
  /*********************************************************************/
  if (Tdbp->Clist == NULL) {
    strcpy(g->Message, MSG(MIS_TAG_LIST));
		throw (int)TYPE_AM_XML;
	} // endif Clist

  n =  Tdbp->Clist->GetLength();
  k = Rank;

  if (!(ValNode = Tdbp->Clist->GetItem(g, k, Vxnp))) {
    /*******************************************************************/
    /*  Create missing column nodes.                                   */
    /*******************************************************************/
    Tdbp->RowNode->AddText(g, "\n\t\t");

    for (i = n; i <= k; i++)
      ValNode = Tdbp->RowNode->AddChildNode(g, Tdbp->Colname, Vxnp);

    assert (ValNode);
    } // endif ValNode

  /*********************************************************************/
  /*  Get the string representation of Value according to column type. */
  /*********************************************************************/
  p = Value->GetCharString(buf);

  if (strlen(p) > (unsigned)Long) {
    sprintf(g->Message, MSG(VALUE_TOO_LONG), p, Name, Long);
		throw (int)TYPE_AM_XML;
	} else
    strcpy(Valbuf, p);

  /*********************************************************************/
  /*  Updating must be done only when not in checking pass.            */
  /*********************************************************************/
 fin:
  if (Status)
    ValNode->SetContent(g, Valbuf, Long);

  } // end of WriteColumn

/* ---------------------------TDBXCT class --------------------------- */

/***********************************************************************/
/*  TDBXCT class constructor.                                          */
/***********************************************************************/
TDBXCT::TDBXCT(PXMLDEF tdp) : TDBCAT(tdp)
  {
  Topt = tdp->GetTopt();
  Db = (char*)tdp->GetDB();
  Tabn = tdp->Tabname;
  } // end of TDBXCT constructor

/***********************************************************************/
/*  GetResult: Get the list the JSON file columns.                     */
/***********************************************************************/
PQRYRES TDBXCT::GetResult(PGLOBAL g)
  {
  return XMLColumns(g, Db, Tabn, Topt, false);
  } // end of GetResult

/* ------------------------ End of Tabxml ---------------------------- */