File: XMLMessage.pm

package info (click to toggle)
libdbix-xmlmessage-perl 0.05-11
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 188 kB
  • sloc: perl: 1,146; makefile: 2
file content (2055 lines) | stat: -rw-r--r-- 69,725 bytes parent folder | download | duplicates (6)
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
#
#   DBIx::XMLMessage
#
#   Copyright (c) 2000-2001 Andrei Nossov. All rights reserved.
#   This program is free software; you can redistribute it and/or
#   modify it under the same terms as Perl itself.
# _________________________________________________________________________
#   Modifications Log
#
#   Version Date    Author          Notes
# _________________________________________________________________________
#   0.04    3/01    Andrei Nossov   Root compound key bug fixed
#   0.03    11/00   Andrei Nossov   Bug fixes, more documentation
#   0.02    10/00   Andrei Nossov   Documentation improved
#   0.01    8/00    Andrei Nossov   First cut
# _________________________________________________________________________

require 5.003;

use Exporter;
use HTML::Entities ();
use POSIX;
use DBI;
use Data::Dumper;
use strict;

# _________________________________________________________________________
#   XMLMessage: head package
#
package DBIx::XMLMessage;

use Carp;
use XML::Parser;
use vars qw (@ISA %EXPORT_TAGS $TRACELEVEL $PACKAGE $VERSION);
$PACKAGE = 'DBIx::XMLMessage';
$VERSION  = '0.04';
$TRACELEVEL = 0;        # Don't trace by default
@ISA = qw ( Exporter );

%EXPORT_TAGS = ( 'elements' => ['VERSION', 'TRACELEVEL', '%TEMPLATE::',
        '%REFERENCE::', '%CHILD::', '%KEY::', '%COLUMN::', '%PARAMETER::']);
Exporter::export_ok_tags ('elements');

# _________________________________________________________________________
#   Allow to create via 'new'
#
sub new {
    my ($class, %args) = @_;
    my $self = bless {}, $class;

    # Check if the external code references are correct
    # So far have: _OnError, _OnTrace
    foreach (keys %args) {
        if ( /^_On/ ) {     # Should be a CODE reference
            if ( (ref $args{$_}) ne 'CODE' ) {
                $self->error ("Argument $_ should be a CODE reference");
            } else {
                $self->{$_} = $args{$_};
            }
        } elsif ( /^Handlers$/ ) {
            $self->set_handlers ($self->{Handlers});
        } elsif ( /^TemplateString$/ ) {
            $self->prepare_template ($args{TemplateString});
        } elsif ( /^TemplateFile$/ ) {
            $self->prepare_template_from_file ($args{TemplateFile});
        }
    }
    return $self;
}   # -new

# _________________________________________________________________________
#   Set expat handlers
#
#   This is needed as a separate function, as Handlers for input_xml and
#   prepare_template can be different
#
sub set_handlers {
    my $self = shift;
    my $handlers_ref = shift;

    my $old_handlers = $self->{Handlers};
    # Check if Handlers is a hash referernce
    if ( $handlers_ref && (ref $handlers_ref) ne 'HASH' ) {
        $self->error ("Argument Handlers should be a HASH reference");
    } else {
        $self->{Handlers} = $handlers_ref;
    }
    return $old_handlers;
}

# _________________________________________________________________________
#   Error method: invoke $self->{_OnError} and die, otherwise croak
#
sub error {
    my $self = shift;

    if ( $self->{_OnError} ) {
        &{$self->{_OnError}} (@_);
        die;
    } else {
        croak (@_);
    }
}   # -error

# _________________________________________________________________________
#   trace method: invoke $self->{_OnTrace}, otherwise print to STDERR
#
sub trace {
    my $self = shift;

    if ( $TRACELEVEL || defined $self->{_OnTrace} ) {
        if ( $self->{_OnTrace} ) {
            &{$self->{_OnTrace}} (@_);
        } else {
            print STDERR @_;
    }   }
}   # -trace

# _________________________________________________________________________
#   Prepare template for the message type
#
sub prepare_template {
    my $self = shift;
    my $tplcontents = shift;

    my $parser = new XML::Parser (Style => 'Objects',
            Pkg => $PACKAGE, Handlers => $self->{Handlers});
    my $parsed;
    eval { $parsed = $parser->parse ($tplcontents) };
    if ( $@ ) {
        $self->error ($@);
    }
    $self->mk_refs ($parsed->[0]);
    $self->{_Template} = $parsed->[0];

    return $self->{_Template};

}   # -prepare_template

# _________________________________________________________________________
#   Prepare template for the message type
#
#   If no filename given, try to derive it from the _MessageType set by the
#   input_xml and SQLM_TEMPLATE_DIR environment variable
#
sub prepare_template_from_file {
    my $self = shift;   # XMLMessage
    my $fname = shift;  # Template file name

    if ( ! defined $fname ) {   # Full filename expected
        # If there's no name, try to derive it from the message type.
        # This hopefully makes things a little bit more flexible
        $fname = $self->{_MessageType} . '.xml';
        if ( $ENV{SQLM_TEMPLATE_DIR} ) {
            $fname = "$ENV{SQLM_TEMPLATE_DIR}/$fname";
        }
        $self->error ("Template file name not defined") unless -f $fname;
    }
    my $parser = new XML::Parser (Style => 'Objects',
            Pkg => $PACKAGE, Handlers => $self->{Handlers});
    my $parsed;
    eval { $parsed = $parser->parsefile ($fname) };
    if ( $@ ) {
        $self->error ($@);
    }
    $self->mk_refs ($parsed->[0]);
    $self->{_Template} = $parsed->[0];
    return $self->{_Template};
}   # -prepare_template_from_file

#__________________________________________________________________________
#   Parse the input request
#
sub input_xml {
    my $self = shift;
    my $content = shift;

    my $p = new XML::Parser (Style => 'Tree',
            Handlers => $self->{Handlers});
    $self->{_MessageTree} = $p->parse ($content);
    $self->{_MessageType} = undef;
    $self->{_MessageAttr} = undef;
    $self->{_MessageKids} = undef;
    foreach my $el (@{$self->{_MessageTree}}) {
        if ( (ref $el) =~ /HASH/ )  {
            $self->{_MessageAttr} = $el;
        } elsif ( (ref $el) =~ /ARRAY/ ) {
            $self->{_MessageKids} = $el;
        } elsif ( $el && !(ref $el) ) {
            $self->{_MessageType} = $el;
        } else {
            $self->error ("Unknown element type encountered: $el\n");
        }
    }

    return $self->{_MessageType};
}   ##input_xml

#__________________________________________________________________________
#   Parse the input file
#
sub input_xml_file {
    my $self = shift;
    my $fname = shift;

    my $p = new XML::Parser (Style => 'Tree',
            Handlers => $self->{Handlers});
    $self->{_MessageTree} = $p->parsefile ($fname);
    $self->{_MessageType} = undef;
    $self->{_MessageAttr} = undef;
    $self->{_MessageKids} = undef;
    foreach my $el (@{$self->{_MessageTree}}) {
        if ( (ref $el) =~ /HASH/ )  {
            $self->{_MessageAttr} = $el;
        } elsif ( (ref $el) =~ /ARRAY/ ) {
            $self->{_MessageKids} = $el;
        } elsif ( $el && !(ref $el) ) {
            $self->{_MessageType} = $el;
        } else {
            $self->error ("Unknown element type encountered: $el\n");
        }
    }
    return $self->{_MessageType};
}   # -input_xml_file

#__________________________________________________________________________
#
#   Store the values in the according objects
#
#   E.g.:
#   [   ServiceIncident,
#       [   {VERSION => "1.0"},
#           Service,
#           [   {},
#               0, "",
#               Case,
#               [   {},
#                   0, "",
#                   ID,
#                   [ {}, 0, "8014"
#                   ],
#                   0, ""
#               ]
#           ],
#           0, ""
#           ServiceTransaction,
#           [   {},
#               0, "",
#               DispStatus,
#               [   {}, 0, "In Progress"
#               ]
#           ]
#           0, ""
#       ]
#       0, ""
#   ]
#
# ------------------------------------------------------------------------
#
# FIXME: Buggy..
#
sub populate_objects {
    my $self = shift;       # XMLMessage
    my $ghash = shift;      # Global hash
    my $obj = shift;        # The matching object for this tag
    my $tag = shift;        # The tag name
    my $content = shift;    # Reference to the array of kids, hash is attrs
    my $parix = shift || 0; # Parent input set index
    my ($el, $attr, $i, $text, $kid, $kidcont, $papa);

    # Initialize the first object from _Template
    if ( !defined $obj ) {
        if ( $self->{_Template} ) {
            $obj = $self->{_Template};
        } else {
            $self->error ("Error: the template is empty"
                    . " (have you run prepare_template?)");
    }   }

    # Initialize the first tag name from _MessageType and the
    # first content -- from the _MessageKids
    if ( ! defined $tag && ! defined $content ) {
        $tag = $self->{_MessageType};
        $content = $self->{_MessageKids};
    }
    # Log the entry at this point.. Hopefully nothing will happen before..
    $self->trace ("populate_objects: $tag, $parix\n");

    # Figure out its own _INIX
    $obj->{_INIX} = (defined $obj->{_INIX}) ? ++$obj->{_INIX} : 0;

    # Verify that the object matches w/ the tag
    if ( $tag ne $obj->{NAME} )  {
        croak "Error: $tag doesn't match with the template ($obj->{NAME})";
    }
    $text = undef;

    for ( $i=0; defined $content->[$i]; $i++ ) {
    # while ( defined ($kid = shift @$content) ) {
        $kid = $content->[$i];
        if ( (ref $kid) =~ /HASH/ ) {   # Attributes -- verify
            foreach $attr ( keys %$kid ) {
                if ( $obj->{$attr} && $kid->{$attr} ne $obj->{$attr} )  {
                    $obj->error ("Error: $attr of the message $el->{$attr}"
                        . " don't match with that of the template"
                        . " ($obj->{$attr})");
            }   }
        } else {
            #<<<<<<<<
    $kidcont = $content->[++$i];
    if ( ref $kid ) {         # ?? Error
        $self->error ("Error: Unexpected reference $kid");
    } elsif (!$kid) {               # 0 -- text
        $kidcont =~ s/[\n\s]*$//;
        $text .= $kidcont;
    } else {                        # Not 0 -- tag
        undef $el;
        foreach my $typ (qw (CHI REF COL PAR KEY)) {
            if ( $obj->{"_$typ" . 'LIST'} && $obj->{"_$typ".'LIST'}->{$kid} ) {
                $el = $obj->{"_$typ" . 'LIST'}->{$kid};
                last;
        }   }
        if ( $el ) {    # Found
            $self->populate_objects ($ghash,$el,$kid,$kidcont,$obj->{_INIX});
        } else {
            # Kid not found -- see if we can dynamically create it..
            if ( $obj->{TOLERANCE} && $obj->{TOLERANCE} =~ /^CREATE/ ) {
                                                        # CREATE
                my $type = 'COLUMN';
                if ( $obj->{TOLERANCE} =~ /^CREATE (.+)$/ ) {
                    $type = $1;
                }
                # Dynamic creation
                $el = new "$PACKAGE::$type";
                $el->{NAME} = $kid;
                $el->{_PARENT_TAG} = $obj;
                push @{$obj->{Kids}}, $el;
                $obj->{_COLLIST}->{$kid} = $el;
                $self->populate_objects ($ghash,$el,$kid,$kidcont,$obj->{_INIX});
            } elsif ( $obj->{TOLERANCE}
                    && $obj->{TOLERANCE} eq 'REJECT' ) {# REJECT
                $self->error ("$obj->{NAME} doesn't allow child $kid");
            } else {                                    # IGNORE
                $self->trace ("$kid kid not found in the template"
                        . " for $obj->{NAME}, ignoring");
    }   }   }   }
            #<<<<<<<<
    }   ## while kid
    # Tweak up the text if there's a built-in..
    if ( $text && $obj->{BLTIN} ) {
        my $bltin = $obj->{BLTIN};
        @_ = ($self,$obj,$text);
        my $cmd = '$text = &' . $bltin . ';';
        eval $cmd || die "Error in BUILT-IN $bltin of $obj->{NAME}: $@";
    }
    # Figure out what to do w/ the text..
    if ( (ref $obj) =~ /::COLUMN$/ || (ref $obj) =~ /::PARAMETER$/
            || (ref $obj) =~ /::KEY$/ ) {
        $papa = $obj->{_PARENT_TAG};
        $papa->{_INVALUES}->[$parix]->{$tag} = $text;
    }

}   # -populate_objects

#__________________________________________________________________________
#   Debugging subroutine: Print the tree
#
sub pr_tree {
    my $self = shift;       # XMLMessage
    my $ref = shift;        # Root node of this subtree
    my $level = shift || 0; # Level of this root node
    my ($el, $i);

    if ( (ref $ref) =~ /ARRAY/ ) {
        foreach $el (@$ref) {
            $self->pr_tree ($el, $level+1);
        }
    } elsif ( (ref $ref) =~ /HASH/ ) {
        # Attributes only
        foreach $el ( keys %$ref ) {
            for ($i=0; $i<$level; $i++) { $self->trace ("  "); }
            $self->trace ("$el = $ref->$el\n");
        }
    } else {
        if ( $ref ) {
            for ($i=0; $i<$level; $i++) { $self->trace ("  "); }
            if ( $ref =~ /(.*)(\s+)$/ ) {
                $ref = $1;
            }
            if ( $ref =~ /(.*)(\n+)$/ ) {
                $ref = $1;
            }
            $self->trace ("$ref\n");
        }
    }
}   # -pr_tree

# _________________________________________________________________________
#   Create the necessary internal structures
#
sub mk_refs {
    my $self = shift;   # XMLMessage
    my $root = shift;   # Element

    foreach my $el (@{$root->{'Kids'}}) {
        if ( (ref $el) =~ /::(\w+)$/ && (ref $el) !~ /::Characters/ ) {
            # Create the parent references
            $el->{_PARENT_TAG} = $root;
            # Store the object type lists in hashes
            # Constructs: _COLLIST, _KEYLIST, _PARLIST, _REFLIST, _CHILIST
            # The assumption here is that the tag name within an object
            # type is unique (i.e. there couldn't be two COLUMNs with the
            # same name)
            my $listname = "_" . substr($1,0,3) . "LIST";
            if ( $root->{$listname}->{$el->{NAME}} ) {
                $self->error ("$1 $el->{NAME} is defined more"
                        . " than once under $root->{NAME}");
            } else {
                $root->{$listname}->{$el->{NAME}} = $el;
            }
            $self->mk_refs($el);
    }   }

}   # -mk_refs

# _________________________________________________________________________
#   Get the value from global hash (not a method!)
#
sub get_hashval {
    my $href = shift;       # Hash reference
    my $name = shift;       # Name to look for
    my $resix = shift || 0; # Index to look for

    # Note: This function doesn't have to have a $inix argument, as the only
    # linkage to the higher level is $resix.
    #
    my $val = undef;
    if ( $href && defined $href->{$name} ) {
        if ( (ref $href->{$name}) eq 'CODE' )  {
            $val = &{$href->{$name}}($resix);
        } elsif ( (ref $href->{$name}) eq 'ARRAY' )  {
            return $href->{$name}->[$resix];
        } elsif ( !(ref $href->{$name}) && $resix == 0 ) {
            # Just a single value, only return if the index is 0
            $val = $href->{$name};
        }
    }
    return $val;
}   # -get_hashval

# _________________________________________________________________________
#   THESE ARE METHODS FOR THE ELEMENTS
#

# _________________________________________________________________________
#   Get the *parent* result value #n
#
sub get_resval {
    my $self = shift;           # XMLMessage
    my $node = shift;           # TEMPLATE | REFERENCE | CHILD
    my $name = shift;           # (COLUMN) name
    my $resix = shift || 0;     # Result set index

    $self->trace ("      get_resval ($node->{NAME},$name,$resix)\n");
    my $papa = $node->{_PARENT_TAG} || return undef;
    my $rref = $papa->{_RESULTS} || return undef;

    if ( (ref $rref) eq 'CODE' ) {
        # Should this work for global hash?
        return &{$rref}($resix);
    } elsif ( (ref $rref) eq 'ARRAY' ) {
        if ( $rref->[$resix] && defined $rref->[$resix]->{$name} ) {
            return $rref->[$resix]->{$name};
        }
    } elsif ( (ref $rref) eq 'HASH' && $rref->{$name} && $resix == 0 ) {
        # Should work for global hash as well?
        return $rref->{$name};
    }
    return undef;
}   # -get_resval

# _________________________________________________________________________
#   Get the parameter (input value) #n
#
sub get_inval {
    my $self = shift;           # XMLMessage
    my $node = shift;           # TEMPLATE|CHILD|REFERENCE
    my $name = shift;           # Name to look for
    my $ix = shift || 0;        # Input value set index

    $self->trace ("      get_inval ($node->{NAME},$name,$ix)\n");
    my $val = $node->{_INVALUES}
            ? $node->{_INVALUES}->[$ix]
                ? $node->{_INVALUES}->[$ix]->{$name}
                : undef
            : undef;
    return $val;
}   # -get_inval

#__________________________________________________________________________
#   Get the key value #($inix,$resix)
#
sub get_keyval {
    my $self = shift;           # XMLMessage
    my $node = shift;           # Key reference
    my $href = shift;           # External hash reference
    my $inix = shift || 0;      # Input set index
    my $resix = shift || 0;     # Parent result set index

    $self->trace ("    get_keyval ($node->{NAME},$inix,$resix)\n");
    my ($tag, $papa, $kname, $val);
    $tag = $node->{_PARENT_TAG};
    # Any key should have a parent TEMPLATE|CHILD|REFERENCE
    if ( !$tag )  {
        $self->error ("Internal error: Key $node->{NAME} has no parent");
    }
    # Find the corresponding name a level up
    $kname = $node->{PARENT_NAME} ? $node->{PARENT_NAME} : $node->{NAME};
    # Check itself
    # Keys are stored in a 2-dimensional array:
    # _____________________________________________________________________
    #      resix    0   1   2   3   ...
    # inix
    #    0          A   B   C   D
    #    1          E   F
    #    2          G   H   I
    #   ...
    # _____________________________________________________________________
    #   Thus, inix 0 should be always there and it's fake..
    #
    if ( $tag->{_KEYS} && $tag->{_KEYS}->[$inix]
            && defined $tag->{_KEYS}->[$inix]->[$resix]
            && defined $tag->{_KEYS}->[$inix]->[$resix]->{$kname} ) {
        $val = $self->format_value ($node,$tag->{_KEYS}->[$inix]->[$resix]->{$kname});
        $self->trace ("    *get_keyval = $val\n");
        return $val;
    }
    # Find the tag's parent (all but TEMPLATE should have)
    if ( $tag->{_PARENT_TAG} ) {
        $papa = $tag->{_PARENT_TAG};
    } elsif ( (ref $tag) !~ /::TEMPLATE$/ ) {
        $self->error ("Internal error: Tag $tag->{NAME} has no parent");
    }
    # Try to get from input values and parent results
    my $val1 = $self->get_inval ($tag, $node->{NAME}, $inix);
    # Get the parent result
    my $val2 = $self->get_resval ($tag, $kname, $resix);
    # Compare values
    if ( defined $val1 ) {
        if ( defined $val2 && $val1 ne $val2 ) {
            $self->error ("Key $node->{NAME} values don't"
                . " match in parent result set and input");
        }
        $val = $val1;
    } else {
        $val = $val2;
    }
    # If still undefined, then try the global hash
    if ( !defined $val ) {
        # None defined -- try the global hash
        $val = &get_hashval ($href, $kname, $resix);
    }
    if ( defined $val ) {
        $tag->{_KEYS}->[$inix]->[$resix]->{$kname} = $val;
    }
    $val = (defined $val) ? $self->format_value($node,$val) : undef;
    $self->trace ("    get_keyval = $val\n");
    return $val;

    # Should be able to have two references from two different columns
    # to the same table.. (I recall this idea seemed important..why?;^)

}   # -get_keyval

#__________________________________________________________________________
#   Get the parameter value #ix
#
sub get_parval {
    my $self = shift;           # XMLMessage
    my $node = shift;           # PARAMETER
    my $href = shift;           # External hash reference
    my $inix = shift || 0;      # Input value set index, real starts at 1
    my $resix = shift || 0;     # Parent result set index

    my $val = undef;
    my $tag = $node->{_PARENT_TAG};  # Parameter's tag
    if ( !$tag )  {
        $self->error ("Parameter $node->{NAME} has no parent tag");
    }

    # Try to get from input values and parent results
    my $val1 = $self->get_inval ($tag, $node->{NAME}, $inix);
    # Find the corresponding name a level up
    my $pname = $node->{PARENT_NAME} ? $node->{PARENT_NAME} : $node->{NAME};
    # Get the parent result
    my $val2 = $self->get_resval ($tag, $pname, $resix);
    # Compare values
    if ( defined $val1 ) {
        if ( defined $val2 && $val1 ne $val2 ) {
            $self->error ("Parameter $node->{NAME} values"
                . " don't match in parent result set and input");
        }
        $val = $val1;
    } else {
        $val = $val2;
    }
    # If still undefined, then try the global hash
    if ( !defined $val ) {
        $val = &get_hashval ($href, $pname, $resix);
    }
    if ( defined $val ) {
        $val = $self->format_value($node,$val);
    } else {
        if ( !defined $val && defined $node->{DEFAULT} )  {
            $val = $self->{DEFAULT};
    }   }
    return $val;
}   ##get_parval

#__________________________________________________________________________
#   Get and format the column value #($inix,$resix)
#
sub get_colval {
    my $self = shift;       # XMLMessage
    my $node = shift;       # COLUMN
    my $dbh = shift;        # Database handle
    my $href = shift;       # External hash reference
    my $inix = shift || 0;  # Input value set index
    my $resix = shift || 0; # Parent result set index

    $self->trace ("    get_colval ($node->{NAME},$inix,$resix)\n");
    my $tag = $node->{_PARENT_TAG};  # Parameter's tag
    if ( !$tag )  {
        $self->error ("Internal error: Column $node->{NAME} has no parent");
    }
    my $val = undef;
    # Find the tag's parent (all but TEMPLATE should have)
    my $papa;
    if ( $tag->{_PARENT_TAG} ) {
        $papa = $tag->{_PARENT_TAG};
    } elsif ( (ref $tag) =~ /::TEMPLATE$/ ) {
        $papa = $href;
    } else {
        die ("Internal error: Tag $tag->{NAME} has no parent");
    }
    # Look for the input value and parent result
    my $val1 = $self->get_inval ($tag, $node->{NAME}, $inix);
    my $val2 = $self->get_resval ($node, $node->{NAME}, $resix);
    $self->trace ("    inval=" . (defined $val1 ? $val1 : "UNDEF")
           . ", resval=" . (defined $val2 ? $val2 : "UNDEF") . "\n");
    if ( defined $val1 && length($val1) > 0 ) {
        if ( defined $val2 && length($val2) > 0 ) {
            if ( $val1 eq $val2 ) {
                $val = $val1
            } else {
                die ("Internal error: $node->{NAME} column values don't "
                    . "match in parent result set and input ($val1,$val2)");
            }
        } else {
            $val = $val1;
        }
    } else {
        $val = $val2;
    }
 # print "   val=$val\n";
    # Also try the keys with matching EXPR|NAME
    # as they might get pushed
    # from the lower levels (not anymore ;^))
    if ( !defined $val ) {
        if ( $node->{EXPR} && $tag->{_KEYLIST}->{$node->{EXPR}} ) {
            my $key = $tag->{_KEYLIST}->{$node->{EXPR}};
            $val = $self->get_keyval ($key,$href,$inix,$resix);
        } elsif ( $tag->{_KEYLIST}->{$node->{NAME}} ) {
            my $key = $tag->{_KEYLIST}->{$node->{NAME}};
            $val = $self->get_keyval ($key,$href,$inix,$resix);
    }   }

    if ( $val )  {
        $val = $self->format_value ($node,$val);
    } elsif ( $node->{GENERATE_PK} ) {
        if ( $node->{GENERATE_PK} eq 'HASH' ) {
            $val = &get_hashval ($href,"$tag->{TABLE}",$inix,$resix);
        } else {
            # Should contain a SQL that selects 1 value
            if ( $dbh ) {
                my $idtab = $tag->{TABLE} . "_ID";
                my $sql = $node->{GENERATE_PK};
                my $sth = $dbh->prepare ($sql) || die $DBI::errstr;
                my $rc = $sth->execute() || die $DBI::errstr;
                $rc = $sth->fetchall_arrayref();
                $val = $rc->[0]->[0];
                $rc  = $sth->finish();
            } elsif ( $self->{NODBH} eq 'OK' ) {
                # No database handle: Try hash anyway
                $self->trace ("Trying to get PK without database handle");
                $val = &get_hashval ($href,"$tag->{TABLE}",$inix,$resix);
            } else {
                $self->error (
                    "Can not generate primary key for table $tag->{TABLE}");
        }   }
    } elsif ( defined $node->{DEFAULT} )  {
        $val = $node->{DEFAULT};    # This goes as-is
    }
    return $val;
}   # -get_colval

#__________________________________________________________________________
#   Format element value according to its datatype
#
sub format_value {
    my $self = shift;
    my $node = shift;
    my $val = shift;

    # DATATYPE is CHAR by default
    if ( !$node->{DATATYPE} || $node->{DATATYPE} =~ /(CHAR|DATE|TIME)/ ) {
        if ( $val !~ /^\'(.*)\'$/ && $val !~ /^\"(.*)\"$/ )  {
            $val =~ s/\'/\'\'/g;
            $val = "'$val'";
    }   }
    return $val;
}   # -format_value

#__________________________________________________________________________
#   Create the WHERE clause for SELECT/UPDATE
#
sub create_where {
    my $self = shift;           # XMLMessage
    my $node = shift;           # TEMPLATE|CHILD|REFERENCE
    my $href = shift;           # Global hash reference
    my $inix = shift || 0;      # Key set index
    my $resix = shift || 0;     # Parent result set index

    $self->trace ("   create_where ($node->{NAME},$inix,$resix)\n");
    my ($el, $where);
    # Construct WHERE clause
    foreach ( keys %{$node->{_KEYLIST}} ) {
        $el = $node->{_KEYLIST}->{$_};
        my $val =  $self->get_keyval ($el,$href,$inix,$resix);
        if ( !defined $val ) {
            $self->error ("$el->{NAME}: Key value #($inix,$resix) not found");
        }
        $where .= " and ";
        if ( defined $el->{EXPR} )  {
            $where .= $el->{EXPR};
        } else {
            $where .= $el->{NAME};
        }
        if ( !$el->{DATATYPE} || $el->{DATATYPE} =~ /CHAR/ ) {
            $where .= " like ";
        } else {
            $where .= " = ";
        }
        $val = $self->format_value($el,$val);
        $where .= $val;
    }
    # Check if there is additional WHERE clause
    if ( $node->{'WHERE_CLAUSE'} ) {
        $where .= " and " if ( $where );
        $where .= $node->{'WHERE_CLAUSE'};
    }
    # Cut off the initial 'and'
    $where = substr ($where, 4) if ($where);
    return $where;
}   # -create_where

# _________________________________________________________________________
#   Construct SELECT statement
#
sub create_select {
    my $self = shift;       # XMLMessage
    my $node = shift;       # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;        # Database handle
    my $href = shift;       # Global hash reference
    my $inix = shift || 0;  # Input value set index
    my $resix = shift || 0; # Parent result set index

    $self->trace ("  create_select ($node->{NAME},$inix,$resix)\n");
    my ($el, $colexpr, $sql);
    # Construct column list, possibly with aliases
    foreach ( keys %{$node->{_COLLIST}} ) {
        # $self->trace ("  create_select: found column $_\n");
        $el = $node->{_COLLIST}->{$_};
        # Include expression if present
        if ( $el->{'EXPR'} ) {
            $colexpr = $el->{EXPR};
        } else {
            $colexpr = $el->{NAME};
        }
        # Include name if not the same
        if ( $el->{'NAME'} ne $colexpr ) {
            $colexpr .= " " if ($colexpr);
            $colexpr .= $el->{'NAME'};
        }
        # Add to the SQL if not empty
        $sql .= "\n\t$colexpr," if ($colexpr);
    }
    if ( $sql )  {
        chop ($sql);    # Chop the last comma
        $sql = "SELECT $sql";
    }
    if ( $sql && $node->{TABLE} )  {
        $sql .= "\nFROM\n\t" . $node->{'TABLE'};
        # WHERE clause doesn't make sence without FROM
        my $where = $self->create_where ($node, $href, $inix, $resix);
        $sql .= "\nWHERE $where";
    }
    return $sql;
}   # -create_select

# _________________________________________________________________________
#   Construct INSERT statement
#
sub create_insert {
    my $self = shift;       # XMLMessage
    my $node = shift;       # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;        # Database handle
    my $href = shift;       # Global hash reference
    my $inix = shift || 0;  # Input value set index
    my $resix = shift || 0; # Parent result set index

    my ($el, $colexpr, $colval, $sql, $sql1);
    $self->error ("$node->{NAME}: Cannot INSERT without TABLE")
            if(!$node->{TABLE});
    # Construct the list of columns and list of values
    foreach ( keys %{$node->{_COLLIST}} ) {
        $el = $node->{_COLLIST}->{$_};
        # Use EXPR if present
        if ( $el->{'EXPR'} ) {
            $colexpr = $el->{EXPR};
        } else {
            $colexpr = $el->{NAME};
        }
        $colval = $self->get_colval ($el, $dbh, $href, $inix, $resix);
        if ( defined $colval && $colval ne '' )  {
            # Add to the SQL if not empty
            $sql  .= "\n\t$colexpr," if ($colexpr);
            $sql1 .= "\n\t$colval,";
        } else {
            my $er = "Value #($inix,$resix) for col $colexpr not found";
            # For INSERT all column values are required
            $self->trace ("* $er\n");
            if ($node->{CARDINALITY} && $node->{CARDINALITY} eq 'OPTIONAL'){
                return 1;
            } else {
                $self->error ("$er\n");
    }   }   }
    if ( $sql )  {
        chop $sql;
        chop $sql1;
        $sql = "INSERT INTO $node->{TABLE} ($sql\n) VALUES ($sql1)";
    }
    return $sql;

}   # -create_insert

# _________________________________________________________________________
#   Construct UPDATE statement
#
sub create_update {
    my $self = shift;       # XMLMessage
    my $node = shift;       # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;        # Database handle
    my $href = shift;       # Global hash reference
    my $inix = shift || 0;  # Input value set index
    my $resix = shift || 0; # Parent result set index

    $self->trace ("   create_update ($node->{NAME},$inix,$resix)\n");
    my ($el, $colexpr, $sql);
    $self->error ("$node->{NAME}: Cannot UPDATE without TABLE")
            if (!$node->{TABLE});
    # Construct the list of columns with value assignments
    undef $sql;
    foreach ( keys %{$node->{_COLLIST}} ) {
        $el = $node->{_COLLIST}->{$_};
# print "   -el = $el->{NAME}\n";
        $colexpr = $self->get_colval ($el, $href, $dbh, $inix, $resix);
# print "   -colval = $colexpr\n";
        if ( defined $colexpr && $colexpr ne "" )  {
            if ( $el->{EXPR} )  {
                $colexpr = "\n\t" . $el->{EXPR} . " = $colexpr,";
            } else {
                $colexpr = "\n\t" . $el->{NAME} . " = $colexpr,";
            }
            $sql .= $colexpr;
# print "   -sql = $sql\n";
    }   }
    # If anything was created
    if ( $sql )  {
        chop $sql;
        my $where = $self->create_where ($node, $href, $inix, $resix);
        $sql = "UPDATE $node->{TABLE} set $sql where $where";
    }
    return $sql;
}   # -create_update

# _________________________________________________________________________
#   Construct EXEC statement (only works with Sybase/SQL Server I suspect)
#
sub create_exec {
    my $self = shift;       # XMLMessage
    my $node = shift;       # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;        # Database handle
    my $href = shift;       # Global hash reference
    my $inix = shift || 0;  # Input value set index
    my $resix = shift || 0; # Parent result set index

    my ($el, $val, $sql, $dbdriver);
    if ( !defined $node->{PROC} )  {
        $self->error ("$node->{NAME}: PROC required where ACTION is EXEC");
    }
    # Retrieve the driver name
    # $dbdriver = $dbh->{Driver}->{Name};

    # Collect the parameters
    foreach my $pname ( keys %{$node->{_PARLIST}} ) {
        my $el = $node->{_PARLIST}->{$pname};
        my $val = $self->get_parval($el,$href,$inix,$resix);
        if ( !defined $val ) {
            if ($node->{CARDINALITY} && $node->{CARDINALITY} eq 'OPTIONAL'){
                $self->trace ("Value #($inix,$resix) for $pname not found, "
                        ."but the tag is optional -- skipping");
                return 1;
            } else {
                $self->error (
                    "$el->{NAME}: $pname value #($inix,$resix) not found");
            }
        } else {
            $sql .= " \@$el->{NAME} = $val,"
    }   }
    if ( $sql ) {
        chop ($sql);
    }
    $sql = "EXEC $node->{PROC} $sql";
    return $sql;
}   # -create_exec

#__________________________________________________________________________
#   Execute the SQL for one index pair
#
sub execute_sql {
    my $self = shift;           # XMLMessage
    my $node = shift;           # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;            # Database handle
    my $href = shift;           # External hash reference for parameters
    my $inix = shift || 0;      # Input vector index
    my $resix = shift || 0;     # Parent result set index

    my ($sql, $sth, $rc, $row);
    $self->trace ("  execute_sql ($node->{NAME},$inix,$resix)\n");
    # Verify that all key values are available
    foreach my $el ( keys %{$node->{_KEYLIST}} ) {
        my $val = $self->get_keyval ($node->{_KEYLIST}->{$el},$href,$inix,$resix);
        if ( !defined $val ) {
            if ($node->{CARDINALITY} && $node->{CARDINALITY} eq 'OPTIONAL'){
                # Skipping the whole thing..
                return 1;
            } else {
                $self->error ("$node->{NAME}: $el value #($inix,$resix) not found");
    }   }   }
    #
    # Construct and execute SQL statement
    #
    # For different ACTIONs
    my $action = $node->{ACTION} ? $node->{ACTION} : 'SELECT';
    for ( $action ) {
        if ( /INSERT/ ) {
            $sql = $self->create_insert ($node,$href,$dbh,$inix,$resix);
            $self->trace ("SQL = $sql\n");
            $rc = $dbh->do ($sql) || croak ("$sql:\n" . $dbh->errstr);
            my %rowh = ();
            if ( $rc > 0 ) {
                $self->process_result($node,$dbh,\%rowh,$href,$inix,$resix);
            }
        } elsif ( /UPDATE/ ) {
            $sql = $self->create_update ($node,$href,$dbh,$inix,$resix);
            $self->trace ("SQL = $sql\n");
            &{$self->{_OnPreDoSQL}} ($dbh) if ($self->{_OnPreDoSQL});
            $rc = $dbh->do ($sql) || $self->error ("$sql\n".$dbh->errstr);
            &{$self->{_OnPostDoSQL}} ($dbh) if ($self->{_OnPostDoSQL});
            my %rowh = ();
            if ( $rc > 0 ) {
                $self->process_result($node,$dbh,\%rowh,$href,$inix,$resix);
            }
        } elsif ( /SAVE/ ) {
            # Logic of the SAVE operation: update if found, insert if not
            $sql = $self->create_select ($node, $href, $dbh, $inix, $resix);
            $self->trace ("SQL = $sql\n");
            $sth = $dbh->prepare ($sql)
                    || $self->error ("$sql\n".$dbh->errstr);
            $rc = $sth->execute() || croak ("$sql\n" . $dbh->errstr);
            if ( $row = $sth->fetchrow_hashref() ) {
                $sql = $self->create_update ($node,$href,$dbh,$inix,$resix);
                $self->trace ("SQL = $sql\n");
                $rc = $dbh->do ($sql)
                        || $self->error("$sql\n".$dbh->errstr);
            } else {
                $sql = $self->create_insert ($node,$href,$dbh,$inix,$resix);
                $self->trace ("SQL = $sql\n");
                $rc = $dbh->do($sql) || $self->error("$sql\n".$dbh->errstr);
            }
            my %rowh = ();
            if ( $rc > 0 ) {
                $self->process_result($node,$dbh,\%rowh,$href,$inix,$resix);
            }
        } elsif ( /EXEC/ ) {
            $sql = $self->create_exec ($node, $href, $dbh, $inix, $resix);
            $self->trace ("SQL = $sql\n");
            $sth = $dbh->prepare ($sql)
                    || $self->error ("$sql:\n" . $dbh->errstr);
            #
            # FIXME: we can analyze if the stored procedure does any selects
            # and fetch only for those. If there are no selects, we probably
            # should follow the INSERT/UPDATE schema and create one result
            # row..
            #
            $rc = $sth->execute() || $self->error ("$sql:\n".$dbh->errstr);
            while ( $row = $sth->fetchrow_hashref() ) {
                $self->process_result ($node,$dbh,$row,$href,$inix,$resix);
            }
        } elsif ( /SELECT/ || !defined $_ ) {
            $sql = $self->create_select ($node, $href, $dbh, $inix, $resix);
            $self->trace ("SQL = $sql\n");
            if ( !length $sql ) {
                $self->error ("ERROR: Unable to create a SQL statement");
            }
            $sth = $dbh->prepare ($sql)
                    || $self->error ("$sql\n" . $dbh->errstr);
            $rc = $sth->execute()
                    || $self->error ("$sql\n" . $dbh->errstr);
            while ( $row = $sth->fetchrow_hashref() ) {
                $self->process_result ($node,$dbh,$row,$href,$inix,$resix);
            }
        } else {
            $self->error ("$_: Unsupported action");
        }
    }

}   # -execute_sql

#__________________________________________________________________________
#   Function to be inoked per retrieved row
#   Adds 2 pseudo-columns to the row:
#       ->{_INIX}
#       ->{_RESIX}
#
sub process_result {
    my $self = shift;           # XMLMessage
    my $node = shift;           # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;            # DBI database handle
    my $results = shift;        # Result row hash reference
    my $href = shift;           # Global hash reference
    my $inix = shift || 0;      # Input value set index
    my $resix = shift || 0;     # Parent result set index

    my ($colname, $val, $el);

    # Collect the results on a per-colunm basis
    foreach $colname ( keys %{$node->{_COLLIST}} ) {
        $el = $node->{_COLLIST}->{$colname};
        if ( !defined $results->{$colname} )  {
            $val = $self->get_colval ($el, $dbh, $href, $inix, $resix);
            # De-format default values..
            if ( defined $val && $val =~ /^\'(.*)\'$/ ) {
                $val = $1;
                $val =~ s/\'\'/'/g;
            } elsif ( defined $val &&  $val =~ /^\"(.*)\"$/ ) {
                $val = $1;
                $val =~ s/\"\"/"/g;
            }
            if ( 'NULL' eq uc($val) ) {
                $val = undef;
            }
            $results->{$colname} = $val;
    }   }
    # Now look from the results' perspective
    foreach $colname ( keys %$results ) {
        $results->{$colname} =~ s/\s*$// if (defined $results->{$colname});
        my $col = $node->{_COLLIST}->{$colname};
        if ( !$col )  {  # Column does not exist
            # Should we tolerate undefined results?
            if ( $node->{TOLERANCE} && $node->{TOLERANCE} eq 'CREATE'
                    && $colname !~ /^_/ )  {
                $col = new "$PACKAGE::Element::COLUMN";
                $col->{NAME} = $colname;
                $col->{_PARENT_TAG} = $node;
                push @{$node->{Kids}}, $col;
                $self->{_COLLIST}->{$colname} = $col;
            } elsif ( $node->{TOLERANCE} && $node->{TOLERANCE} eq 'REJECT' ) {
                $self->error (
                    "ERROR: Unknown column $colname in the result set");
            # } elsif ( $self->{TOLERANCE}  eq 'IGNORE' )  {
            } else {    # IGNORE by default
                delete $$results{$colname};
        }   }
    }

    # And push it into results array
    # ... BUT COPY FIRST ...
    my $rescopy;
    foreach $colname ( keys %$results ) {
        $rescopy->{$colname} = $results->{$colname};
        if ( $rescopy->{$colname} &&
                $node->{_COLLIST}->{$colname}->{BLTIN} ) { # Builtin
            my $bltin = $node->{_COLLIST}->{$colname}->{BLTIN};
            $self->trace ("BUILTIN func: $bltin\n");
            my $cmd = '$rescopy->{$colname} = &' . $bltin . ';';
            @_ = ($self,$node,$rescopy->{$colname});
            $self->trace ("BUILTIN: $cmd\n");
            eval $cmd;
            $self->error("Error in BUILT-IN $bltin of $colname: $@") if($@);
        }
    }
    $rescopy->{_INIX} = $inix;
    $rescopy->{_RESIX} = $resix;
    push @{$node->{_RESULTS}}, $rescopy;

}   # -process_result

#__________________________________________________________________________
#   Execute the SQL for all parent results and input values
#
sub exec {
    my $self = shift;   # XMLMessage
    my $node = shift;   # TEMPLATE|CHILD|REFERENCE
    my $dbh = shift;    # Database handle
    my $href = shift;   # External hash reference for parameters

    $self->trace ("\n  exec $node->{NAME}\n");
    my $success = 1;
    my $papa = $node->{_PARENT_TAG};

    my $nres;
    if ( $papa ) {
        $nres = $papa->{_RESULTS} ? scalar @{$papa->{_RESULTS}} : 0;
    } else {
        # No parent tag -- pick up the key #0 and count number of values.
        my @keynames = defined $node->{_KEYLIST}
                ? keys %{$node->{_KEYLIST}} : ();
        my $key0 = scalar @keynames
                ? $node->{_KEYLIST}->{$keynames[0]}->{PARENT_NAME}
                        ? $node->{_KEYLIST}->{$keynames[0]}->{PARENT_NAME}
                        : $keynames[0]
                : undef;
        $nres = defined $key0
                ? scalar @{$href->{$key0}} : 1; # No keys -- execute once
    }

    my $nval = $node->{_INVALUES} ? scalar @{$node->{_INVALUES}} : 0;
    my $inix = 0;
    $self->trace ("  nval = $nval\n");
    do {    # Execute once with no input values
        for ( my $resix=0; $resix<$nres; $resix++ ) {
            # But not without results
            $success &= $self->execute_sql($node,$dbh,$href,$inix,$resix);
        }
    } while ( ++$inix < $nval );

    $success;
}   # -exec

#__________________________________________________________________________
#   Recursively execute SQL statements for all
#
sub rexec {
    my $self = shift;   # XMLMessage
    my $dbh = shift;    # database handle
    my $href = shift;   # External hash reference for parameters
    my $node = shift;   # TEMPLATE|CHILD|REFERENCE

    $node = $self->{_Template} if (!$node);
    $self->trace ("\nrexec $node->{NAME}\n");
    my ($el, $success);
    if ( !$dbh ) {
        #
        # FIXME: Allow for NODBH invocation
        #
        $self->error ("No database handle");
    }
    # Execute for yourself
    $success = $self->exec ($node, $dbh, $href);
    foreach $el ( @{$node->{'Kids'}} ) {
        if ( (ref $el) =~ /::REFERENCE$/ || (ref $el) =~ /::CHILD$/ ) {
            $success &= $self->rexec ($dbh, $href, $el);
    }   }

    $success;
}   # -rexec

#__________________________________________________________________________
#   Output the message
#
sub output_message {
    my $self = shift;   # XMLMessage

    #if ( $self->{TYPE} eq 'XML' ) {
        return $self->output_xml();
    #} else {
    #    print $self->{TYPE} . ": not implemented\n"
    #}
}

#__________________________________________________________________________
#   Should have executed prior to this
#
#   FIXME: Prints multuple childs
#
#
sub output_xml {
    my $self = shift;           # XMLMessage
    my $level = shift || 0;     # Level
    my $resix = shift || 0;     # Parent result set index
    my $node = shift || $self->{_Template}; # TEMPLATE|CHILD|REFERENCE

    my ($r, $i, $j, $el, $el1, $res, $rref, $xml);
    $xml = "";  # Target string

    # see if there's anything to output
    my $found = 0;
    foreach (@{$node->{_RESULTS}}) {
        if ( $_->{_RESIX} == $resix ) {
            $found = 1;
    }   }
    if ( !$found ) {
        if ( (ref $node) =~ /::TEMPLATE$/ ) {   # Always print the template
            for ( $j=0;$j<$level;$j++ ) { $xml .= "  "; }
            $xml .= "<$node->{NAME} />\n";
            return $xml;
        } else {                                # ... but nothing else!
            return $xml;
    }   }
    $i = 0; # Initial input value. The loop will execute once always
    do {
        for ( $r=0; $node->{_RESULTS}->[$r]; $r++ ) {   # $r is resix for kids
            # >>>>>>>>>>
  $rref = $node->{_RESULTS}->[$r];
  if ( $rref->{_INIX} == $i && $rref->{_RESIX} == $resix
        # FIXME: this is a hack...
        && !$rref->{_PRINTED} ) {
      # Output the tag
      for ( $j=0;$j<$level;$j++ ) { $xml .= "  "; }
      $xml .= "<$node->{NAME}";
      # Output columns with the face of 'ATTRIBUTE' as attributes
      foreach my $elname ( keys %{$node->{_COLLIST}} ) {
          $el = $node->{_COLLIST}->{$elname};
          if ( $el->{FACE} && $el->{FACE} eq 'ATTRIBUTE' ) {
              if (defined $rref->{$el->{NAME}} && $rref->{$el->{NAME}} ne ''){
                  $xml .= " $el->{'NAME'}=\"" .
                  HTML::Entities::encode($rref->{$el->{NAME}},'&<>"').'"';
      }   }   }
      $xml .= ">\n";
      # Output the rest of the stuff
      foreach $el ( @{$node->{'Kids'}} ) {
          if ( (ref $el) =~ /::COLUMN$/ &&
                  (!defined $el->{FACE} || $el->{FACE} eq 'TAG') ) {
              if ( !$el->{'HIDDEN'} ) {
                  for ( $j=0;$j<$level+1;$j++ ) { $xml .= "  "; }
                  if ( defined $rref->{$el->{NAME}}
                          && $rref->{$el->{NAME}} ne '' ) {
                      $xml .= "<$el->{'NAME'}>"
                      . HTML::Entities::encode($rref->{$el->{NAME}},"&<>")
                      . "</$el->{'NAME'}>\n";
                  } else {
                      $xml .= "<$el->{'NAME'} />\n";
                  }
              }
          } elsif ((ref $el)=~ /::REFERENCE$/ || (ref $el)=~ /::CHILD$/) {
              my $niter  = (defined $el->{_INVALUES})
                    ? scalar @{$el->{_INVALUES}}
                    : 0;
              for ( $i=0; $i<scalar @{$node->{_RESULTS}}; $i++ ) {
                  $j = 0;
                  do {
                      $xml .= $self->output_xml ($level+1,$r,$el);
                  } while ( $j++ < $niter );
              }
          }
      }
      for ( $j=0;$j<$level;$j++ ) { $xml .= "  "; }
      $xml .= "</$node->{'NAME'}>\n";
      # FIXME: this is the second part of the hack.. See above..
      $rref->{_PRINTED} = 1;
  }
            # >>>>>>>>>>
        }   ##for $r
    } while ( $node->{_INVALUES}->[$i++] );

    return $xml;
}   # -output_xml

#__________________________________________________________________________
#   Test BUILT-IN
#
sub t_bltin {
    print "t_bltin:";
    foreach (@_) {
        print "\t$_\n";
    }
    return "returned by t_bltin";
}

#__________________________________________________________________________
#   Fix the GMTIME values
#
sub fix_gmdatetime {
    my $self = shift;           # XMLMessage
    my $node = shift;           # TEMPLATE | CHILD | REFERENCE
    my $val = shift || undef;

    if ( !defined $val ) {
        return undef;
    }
    my $direction = $node->{_PARENT_TAG}->{ACTION}
        ? $node->{_PARENT_TAG}->{ACTION} eq 'SELECT'
            ? 'TOGMT'
            : 'FROMGMT'
        : 'TOGMT';
    my $curfmt = '';
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
    my $hmon = { 'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3,
        'May' => 4, 'Jun' => 5, 'Jul' => 6, 'Aug' => 7,
        'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11
    };
    if ($val =~ /^\s*(\d{4})\/(\d{1,2})\/(\d{1,2})\s*(\d{1,2}):(\d{1,2})/ ||
            $val =~ /^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s*(\d{1,2}):(\d{1,2})/
            ) {
        # E.g. 2000-3-21 12:05
        $curfmt = 'GMT';    # SES/SIS GMT
    } elsif ( $val =~  /^\s*(\d{8})\s*(\d{4})/ ) {
        # E.g. 20000321 1205
        $curfmt = 'GMTSHORT';   # Mark sends it like this..
    } elsif ( $val =~
            /^\s*(\D{3})\s*(\d{1,2})\s*(\d{4})\s*(\d{1,2}):(\d{2})(\D{2})/
            ) {
        # E.g. Mar 21 2000 12:05:46:350PM
        $curfmt = 'SYBASE'; # As delivered by the Sybase DB engine
    }
    if ( $direction eq 'TOGMT' && $curfmt eq 'SYBASE' ) {
        # - Transform from SYBASE to GMT
        # This time is received from database and it's local,
        # most probably according to the TZ environment variable
        # - Calculate the time difference to GMT
        my $ctime = time();
        ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
                = gmtime($ctime);
        my $time_t = POSIX::mktime ($sec,$min,$hour,$mday,$mon,$year);
        my $tdiff = $ctime - $time_t;
        ($year,$mon,$mday,$hour,$min) = ($3, $1, $2, $4, $5);
        $mon = $hmon->{$mon} ? $hmon->{$mon} : 0;
        $hour += 12 if ( $6 && $6 eq 'PM' && $hour != 12 );
        $year -= 1900;
        $time_t = POSIX::mktime (0,$min,$hour,$mday,$mon,$year);
        $val = POSIX::strftime "%Y/%m/%d %H:%M", gmtime($time_t-$tdiff);
        # print "Date = ", POSIX::ctime($time_t);
    } elsif ( $direction eq 'FROMGMT' && $curfmt eq 'GMT' ) {
        # - Transform from GMT to SYBASE
        ($year,$mon,$mday,$hour,$min) = ($1, $2, $3, $4, $5);
        $mon--;
        $year -= 1900;
        my $time_t = POSIX::mktime (0,$min,$hour,$mday,$mon,$year);
        if ( $node->{DATATYPE} eq 'DATE' ) {
            $val = POSIX::strftime "%b %d %Y", localtime($time_t);
        } elsif ( $node->{DATATYPE} eq 'TIME' ) {
            $val = POSIX::strftime "%I:%M", localtime($time_t);
        } else {
            $val = POSIX::strftime "%b %d %Y %I:%M:00:000%p",
                    localtime($time_t);
        }
    } elsif ( $direction eq 'FROMGMT' && $curfmt eq 'GMTSHORT' ) {
        # - Transform from GMTSHORT to SYBASE
        my ($ymd,$hmi) = ($1,$2);
        $year = substr ($ymd,0,4);
        $mon  = substr ($ymd,4,2);
        $mday = substr ($ymd,6,2);
        $hour = substr ($hmi,0,2);
        $min  = substr ($hmi,2,2);
        $mon--;
        $year -= 1900;
        my $time_t = POSIX::mktime (0,$min,$hour,$mday,$mon,$year);
        if ( $node->{DATATYPE} eq 'DATE' ) {
            $val = POSIX::strftime "%b %d %Y", localtime($time_t);
        } elsif ( $node->{DATATYPE} eq 'TIME' ) {
            $val = POSIX::strftime "%I:%M:00:000%p", localtime($time_t);
        } else {
            $val = POSIX::strftime "%b %d %Y %I:%M:00:000%p",
                    localtime($time_t);
        }
    }   # Otherwise don't touch
    return $val;
}   ##fix_gmdatetime



1;
# -package DBIx::XMLMessage;



# _________________________________________________________________________
#   Tag Prototype
#
package DBIx::XMLMessage::Element;

use strict;
use vars qw (@ISA %EXPORT_TAGS $VERSION @rattrs);
$VERSION  = '0.01';
@ISA = qw ( Exporter );
%EXPORT_TAGS = ('elements' => [ 'VERSION', '%TEMPLATE::',
        '%REFERENCE::', '%CHILD::', '%KEY::', '%COLUMN::', '%PARAMETER::']);
Exporter::export_ok_tags ('elements');
@rattrs = qw (NAME);
1;

#__________________________________________________________________________
#   Tag TEMPLATE
#
package DBIx::XMLMessage::TEMPLATE;

use vars qw (@ISA %EXPORT_TAGS @rattrs @oattrs @rkids @okids);
@ISA = qw (DBIx::XMLMessage::Element);
@rattrs = qw (NAME VERSION TYPE);
@oattrs = qw (
    ACTION
    DEBUG
    PROC
    RTRIMTEXT
    TABLE
    TOLERANCE
    _CHILIST
    _COLLIST
    _KEYLIST
    _PARENT_TAG
    _PARLIST
    _REFLIST
);
@okids  = qw (COLUMN REFERENCE CHILD PARAMETER KEY);

sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
1;

#__________________________________________________________________________
#   Tag KEY
#
package DBIx::XMLMessage::KEY;
use vars qw (@ISA %EXPORT_TAGS @rattrs @oattrs @rkids @okids);
@ISA = qw (DBIx::XMLMessage::Element);
@rattrs = qw (NAME);
@oattrs = qw (_PARENT_TAG DATATYPE RTRIMTEXT DEFAULT PARENT_NAME);

sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
1;

#__________________________________________________________________________
#   Tag COLUMN
#
package DBIx::XMLMessage::COLUMN;
use vars qw (@ISA %EXPORT_TAGS @rattrs @oattrs @rkids @okids);
@ISA = qw (DBIx::XMLMessage::Element);
@rattrs = qw (NAME);
@oattrs = qw (
    ACTION
    BLTIN
    CARDINALITY
    DATATYPE
    DEBUG
    DEFAULT
    EXPR
    FACE
    GENERATE_PK
    HIDDEN
    RTRIMTEXT
    TOLERANCE
    _PARENT_TAG
);

sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
1;

#__________________________________________________________________________
#   Tag REFERENCE
#
package DBIx::XMLMessage::REFERENCE;
use vars qw (@ISA %EXPORT_TAGS @rattrs @oattrs @rkids @okids);
@ISA = qw (DBIx::XMLMessage::Element);
@rattrs = qw (NAME);
@oattrs = qw (
    ACTION
    CARDINALITY
    DEBUG
    PROC
    RTRIMTEXT
    TABLE
    TOLERANCE
    WHERE_CLAUSE
    _CHILIST
    _COLLIST
    _KEYLIST
    _PARENT_TAG
    _PARLIST
    _REFLIST
);
@okids = qw (COLUMN REFERENCE CHILD PARAMETER KEY);

sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
1;

#__________________________________________________________________________
#   Tag CHILD
#
package DBIx::XMLMessage::CHILD;
use vars qw (@ISA %EXPORT_TAGS @rattrs @oattrs @rkids @okids);
@ISA = qw (DBIx::XMLMessage::Element);
@rattrs = qw (NAME);
@oattrs = qw (
    ACTION
    CARDINALITY
    DEBUG
    MAXROWS
    PROC
    RTRIMTEXT
    TABLE
    TOLERANCE
    WHERE_CLAUSE
    _CHILIST
    _COLLIST
    _KEYLIST
    _PARENT_TAG
    _PARLIST
    _REFLIST
);
@okids = qw (COLUMN REFERENCE CHILD PARAMETER KEY);

sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
1;

#__________________________________________________________________________
#   Tag PARAMETER
#
package DBIx::XMLMessage::PARAMETER;
use vars qw (@ISA %EXPORT_TAGS @rattrs @oattrs @rkids @okids);
@ISA = qw (DBIx::XMLMessage::Element);
@rattrs = qw (NAME);
@oattrs = qw (
    CARDINALITY
    DATATYPE
    DEFAULT
    EXPR
    RTRIMTEXT
    _PARENT_TAG
);

sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
1;

__END__

=head1 NAME

DBIx::XMLMessage - XML Message exchange between DBI data sources

=head1 SYNOPSIS

=head2 OUTBOUND MESSAGE

    #!/usr/bin/perl

    use DBI;
    use DBIx::XMLMessage;

    # Template string
    my $tpl_str =<< "_EOT_";
    <?xml version="1.0" encoding="UTF-8" ?>
    <TEMPLATE NAME='SysLogins' TYPE='XML' VERSION='1.0' TABLE='syslogins'>
    <KEY NAME='suid' DATATYPE='NUMERIC' PARENT_NAME='OBJECT_ID' />
    <COLUMN NAME='LoginId' EXPR='suid' DATATYPE='NUMERIC' />
    <COLUMN NAME='PasswordDate' EXPR='pwdate' DATATYPE='DATETIME'
        BLTIN="fix_gmdatetime" />
    <CHILD NAME='SysUsers' TABLE='sysusers'>
        <KEY NAME='suid' PARENT_NAME='LoginId' DATATYPE='NUMERIC' />
        <COLUMN NAME='UserId' EXPR='uid' DATATYPE='NUMERIC' />
        <COLUMN NAME='UserName' EXPR='name' />
    </CHILD>
    </TEMPLATE>
    _EOT_
    my $msg = new DBIx::XMLMessage ('TemplateString' => $tpl_str);
    my $ghash = { 'OBJECT_ID' => [ 1, 2 ] };
    my $dbh = DBI->connect('dbi:Sybase:server=x;database=master','sa','secret');
    $msg->rexec ($dbh, $ghash);

    print "\n\n", $msg->output_xml(0,0);
    print "\n\n", $msg->output_xml(0,1);


=head2 INBOUND MESSAGE

    #!/usr/bin/perl

    use DBI;
    use DBIx::XMLMessage;

    my $template_xml =<< "_EOD1_";
    <?xml version="1.0" encoding="UTF-8" ?>
    <TEMPLATE NAME='SysLogins' TYPE='XML' VERSION='1.0' TABLE='syslogins'
        ACTION='SAVE'>
    <KEY NAME='suid' DATATYPE='NUMERIC' PARENT_NAME='OBJECT_ID' />
    <COLUMN NAME='LoginId' EXPR='suid' DATATYPE='NUMERIC' />
    <COLUMN NAME='PasswordDate' EXPR='pwdate' DATATYPE='DATETIME'
        BLTIN="fix_gmdatetime" />
    <CHILD NAME='SysUsers' TABLE='sysusers'>
        <KEY NAME='suid' PARENT_NAME='LoginId' DATATYPE='NUMERIC' />
        <COLUMN NAME='UserId' EXPR='uid' DATATYPE='NUMERIC' />
        <COLUMN NAME='UserName' EXPR='name' />
    </CHILD>
    </TEMPLATE>
    _EOD1_

    my $message_xml =<< "_EOD2_";
    <?xml version="1.0" encoding="UTF-8"?>
    <SysLogins>
    <LoginId>1</LoginId>
    <PasswordDate>1999/08/17 08:31</PasswordDate>
    <SysUsers>
        <UserId>1</UserId>
        <UserName>sa</UserName>
    </SysUsers>
    </SysLogins>
    _EOD2_

    my $xmlmsg = new DBIx::XMLMessage ('TemplateString' => $template_xml);
    my $msgtype = $xmlmsg->input_xml($message_xml);
    my $ghash = {
        'OBJECT_ID' => [ 1 ]
    };
    $xmlmsg->populate_objects ($ghash);

    my $dbh = DBI->connect('dbi:Sybase:server=x;database=master','sa','secret');
    $xmlmsg->rexec ($dbh, $ghash);
    print $xmlmsg->output_message();


=head1 DESCRIPTION

The package maintains simple XML templates that describe object structure.

The package is capable of generating SQL statements based on these templates
and executing them against DBI data sources. After executing the SQL, the
package formats the data results into XML strings. E.g. the following simple
template

    <TEMPLATE NAME='SysLogins' TYPE='XML' VERSION='1.0' TABLE='syslogins'
        ACTION='SAVE'>
    <KEY NAME='suid' DATATYPE='NUMERIC' PARENT_NAME='OBJECT_ID' />
    <COLUMN NAME='LoginId' EXPR='suid' DATATYPE='NUMERIC' />
    </TEMPLATE>

being executed with key value = 1, will be tranlated into this SQL:

SELECT suid LoginId FROM syslogins where suid = 1

and the result will be formatted into this XML string:

    <SysLogins>
        <LoginId>1<LoginId>
    </SysLogins>

Inbound messages can be processed according to the same kind of templates
and the database is updated accordingly. Templates are capable of defining
the SQL operators, plus new SAVE operation which is basically a combination
of SELECT and either INSERT or UPDATE depending on whether the record was
found by the compound key value or not.

=head1 SALES PITCH

This package allows for objects exchange between different databases. They
could be from different vendors, as long as they both have DBD drivers. In
certain cases it is even possible to exchange objects between databases with
different data models. Publishing of databases on the web could
potentially be one of the applications as well.

=head1 TEMPLATE TAGS

=head2 TEMPLATE

This is manadatory top-level tag. It can correspond to a certain table and
be processed just like table-level REFERENCE and CHILD attributes described
below. Some of TEMPLATE attributes are related to the whole template (e.g.
TYPE or VERSION) while others desribe the table ti's based on (e.g. TABLE)

If the TABLE attribute is defined, the generated SQL is going to run against
some table. Otherwise a SQL with no table will be generated. This only makes
sense for outbound messages and only possible on certain engines, like
Sybase. Also, the immediate child columns should contain constants only for
apparent reasons.

=head2 REFERENCE

REFERENCE is a table-level tag. It's meant to represent a single record from
another table that's retrieved by unique key. E.g. if my current table is
EMPL then DEPARTMENT would be a REFERENCE since employee can have no more
than one departament.

=head2 CHILD

This tag meant to represent a number of child records usually retrieved by
a foreign key value (probably primary key of the current table). Right now
there's no difference in processing between CHILD and REFERENCE, but it may
appear in the future releases.

=head2 COLUMN

This tag is pretty self-explanatory. Each COLUMN tag will appear on the
SELECT, INSERT or UPDATE list of the generated SQL.

=head2 KEY

Key represents linkage of this table's records to the parent table. All
KEY's will appear on the WHERE clause as AND components. This way of linkage
is typical for most of relational systems and considered to be a good style.
I guess it shouldn't be much of a restriction anyway. If it gets that, you
could try tweak up the WHERE_CLAUSE attribute..

=head2 PARAMETER

This tag represents a parameter that will be passsed to a stored procedure.
Currently, only Sybase-style stored procedures are supported, i.e.

exec proc_name @param_name = 'param_value', ...

Fixes for Oracle, DB2 and Informix are welcome..



=head1 TEMPLATE TAG ATTRIBUTES

=head2 NAME

    Applicable to:  All template tags
    Required for:   All template tags

NAME is the only required attribute for all of the template tags. The main
purpose of it is to specify the tag name as it will appear in the resulting
XML document. Also, depending on the template tag type (COLUMN, PARAMETER
and KEY) it may serve as default value for EXPR discussed below. Here's a
small example of how it works. If my column is represented in the template
like this:

    <COLUMN NAME='ObjectId' />

the resulting SQL will contain

    SELECT ObjectID, ...

whereas if I have

    <COLUMN NAME='ObjectId' EXPR='igObjectId' />

it will generate the following SQL:

    SELECT igObjectId ObjectID, ...

I.e. in the latter example, NAME used as an alias and EXPR as a real
database column name. The column in the first example has no alias.


=head2 ACTION

    Applicable to:  TEMPLATE, REFERENCE, CHILD
    Required for:   None

Possible values for this attibute are SELECT, INSERT, UPDATE, EXEC and SAVE.
If action is not provided, it is assumed that t he action should be SELECT.
The first 4 values correspond to SQL data management operators (EXEC is
vendor-specific and represents execution of a stored procedure). The fifth
value, SAVE, is basically a combination of SELECT and either INSERT or
UPDATE, depending on whether the record was found by the compound key value
or not. This often helps to avoid usage of complicated stored procedures
with primary key generation and keep things generic and scalable. Primary
key generation issue is addressed separately by using of the GENERATE_PK
attribute (see below).

=head2 BLTIN

    Applicable to:  COLUMN
    Required for:   None

Represents a perl built-in function. before invocation of this subroutine
the package prepares array @_ and makes it visible to the built-in function.
The 3 arguments received by the built-in are:
    $self   -  DBIx::XMLMessage object
    $node   -  Correspondent DBIx::XMLMessage::COLUMN object. You
               can use it to obtain other column attributes, e.g.
               $node->{DATATYPE}
    $value  -  The column value

Meaning of the value depends on direction of the message, i.e. whether the
message is inbound or outbound. In case of inbound message, this is the
value received by the package from outside world; if the message is inbound
then this is the value selected from database. There's one built-in function
that comes with the package -- fix_gmdatetime. It converts date and time to
GMT for outbound messages and from GMT to the database date/time for inbound
messages. Just add one attribute to your datetime column:

    ... BLTIN="fix_gmdatetime" ...

=head2 CARDINALITY

    Applicable to:   KEY, PARAMETER, REFERENCE, CHILD
    Required for:    None
    Possible values: REQUIRED, OPTIONAL
    Default:         REQUIRED

This parameter has different meaning for different element types. Optional
KEYs and PARAMETERs allow to proceed execution if the value for it was not
found at some point of execution. Optional CHILDs and REFERENCEs will be
skipped from execution, and hence from output, if the package failed to
collect all the key values.

=head2 DATATYPE

    Applicable to:   KEY, PARAMETER, COLUMN
    Required for:    None
    Possible values: CHAR, VARCHAR, VARCHAR2, DATE, DATETIME, NUMERIC
    Default:         CHAR

This attribute loosely corresponds to the database column type. The only
processing difference in the core package is quoting of the non-numeric
datatypes, particularly those containign substrings CHAR, DATE or TIME.
The built-in fix_gmdatetime utilizes this attribute more extensively.

=head2 DEBUG

Recognized but not currently supported

=head2 DEFAULT

    Applicable to:   PARAMETER, COLUMN
    Required for:    None
    Possible values: Any string or number

This attribute allows to provide a default value for COLUMNs and PARAMETERS.
Please note that default values are not being formatted, so they have to
represent the literal value. E.g. if you want to provide a string DEFAULT
it would look somewhat like this:
    ... DEFAULT = "'UNKNOWN'"


=head2 EXPR

    Applicable to:  All template tags
    Required for:   None

For COLUMN and KEY this attribute represents the actual database column name
or a constant. For PARAMETER


=head2 FACE

    Applicable to:   COLUMN
    Required for:    None
    Possible values: ATTRIBUTE, TAG
    Default:         TAG

This attribute allows to output certain columns as attributes, as opposed
to the default TAG-fasion output. Since it's not supported for inbound
messages yet, usage of this feature is not recommended.


=head2 GENERATE_PK

    Applicable to:   COLUMN
    Required for:    None
    Possible values: HASH, SQL returning one value or name

This attribute allows you to specify how to generate primary key values. You
have 2 options here:

1. You can write your own Perl function, put its reference to the global
hash under the name of the table for which you intend to generate primary
key values and provide the value of 'HASH' as the GENERATE_PK value

2. You can put the generating SQL block/statement into the GENERATE_PK value


=head2 HIDDEN

    Applicable to:   COLUMN

Indicates that the column will be excluded from the output. This attribute
only makes sense for outbound messages.

=head2 MAXROWS

Currently not supported. In future, intends to limits the number of selected
rows.

=head2 PARENT_NAME

    Applicable to:   KEY

Indicates the name of the tag one level up to which this one tag is
corresponding. E.g.

    ...
    <COLUMN NAME='OBJECT_ID'/>
    <REFERENCE ...>
        <KEY NAME='nOrderId' PARENT_NAME='OBJECT_ID'/>
    </REFERENCE>

This feature is a workaround allowing to have two columns descending from
the same parent column at the same level. There was some other prolem it
was helping to resolve, but I forgot what it was ;^)


=head2 PROC

    Applicable to:   TEMPLATE, REFERENCE, CHILD

Used in conjunction with ACTION='PROC'. Defines the name of the stored
procedure to invoke.

=head2 RTRIMTEXT

Currently not supported. The package does automatic right-trimming for all
the character data.

=head2 TABLE

Name of the table against which the SQL will be run.

=head2 TOLERANCE

    Applicable to:   TEMPLATE, REFERENCE, CHILD
    Possible values: IGNORE, CREATE, REJECT
    Default:         IGNORE

Allows to adjust package behaviour when SQL execution produces unexpected
result columns. E.g. if there's a stored procedure that will return the
results for your message, you can omit describing of all the resulting
COLUMNS in the template and instead specify
    ... TOLERANCE='CREATE'
Whatever columns are returned by the stored procedure (Sybase & MS SQL) will
be added on-the-fly and available for the output.


=head2 WHERE_CLAUSE

Additional where clause. Added as an AND component at the end of generated
where clause.


=head1 METHODS

=head2 new

    my $xmsg = new DBIx::XMLMessage (
        [ _OnError => $err_coderef, ]
        [ _OnTrace => $trace_coderef, ]
        [ Handlers => $expat_handlers_hashref, ]
        [ TemplateString => $xml_template_as_a_string, ]
        [ TemplateFile => $xml_template_file_name, ]
    )

You can specify either TemplateString or TemplateFile, but not both. If any
of those specified, the template will be parsed.

=head2 set_handlers

    $xmsg->set_handlers ($expat_handlers_hashref)

Set additional expat handlers, see XML::Parser::Expat. Normally you won't
use this. The only case I could think of is processing of encoding..

=head2 prepare_template

    $xmsg->prepare_template ($template_xml_string)

This method can be invoked if the template was not specified in the 'new'
method invocation.

=head2 prepare_template_from_file

    $xmsg->prepare_template_from_file ($template_file_name)

Same as above, but template is read from file here.

=head2 input_xml

    $xmsg->input_xml ($inbound_xml_message_content)

Parse an inbound XML message. The values form this message will be used to
fill in COLUMNS and PARAMETERS. The structure of this message should comply
with template. Uses Tree parsing style.

=head2 input_xml_file

    $xmsg->input_xml_file ($inbound_xml_message_file_name)

Same as above, but the XML message is read from a file.

=head2 populate_objects

    $xmsg->populate_objects ($global_hash_ref [, $matching_object
        [, $tag_name [, $tag_content, [$parameter_index]]]])

This method is trying to stuff the existing template with the inbound
message previously parsed by one of the 'input_xml' methods. The only
mandatory attribute is global hash reference, which has to contain key
values for the topmost tag TEMPLATE.

=head2 rexec

    $xmsg->rexec ($dbh, $global_hash_ref)

This method is running the created query against a DBI/DBD source and fills
in the template with results in order to make them available for subsequent
output_message call. In case of INSERT/UPDATE operations only key values
will be filled in.

=head2 output_message

This method returns a string with query results in XML format suitable for
printing or whatever manupulations seem appropriate.


=head1 SEE ALSO

    XML::Parser
    XML::Parser::Expat

=head1 AUTHORS

  Andrei Nossov <andrein@andrein.com>

This library is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=cut