summaryrefslogtreecommitdiffstats
path: root/connectivity/source/parse/sqliterator.cxx
blob: fcebd2879a4ff9dda91b7c849bf8cb4be0c6a0a2 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <connectivity/sqliterator.hxx>
#include <connectivity/sdbcx/VTable.hxx>
#include <connectivity/sqlparse.hxx>
#include <sqlbison.hxx>
#include <connectivity/dbtools.hxx>
#include <connectivity/sqlerror.hxx>
#include <com/sun/star/sdbc/ColumnValue.hpp>
#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/sdb/ErrorCondition.hpp>
#ifdef SQL_TEST_PARSETREEITERATOR
#include <iostream>
#endif
#include <connectivity/PColumn.hxx>
#include <tools/diagnose_ex.h>
#include <TConnection.hxx>
#include <comphelper/types.hxx>
#include <connectivity/dbmetadata.hxx>
#include <com/sun/star/sdb/SQLFilterOperator.hpp>
#include <o3tl/safeint.hxx>
#include <sal/log.hxx>

#include <iterator>
#include <memory>

using namespace ::comphelper;
using namespace ::connectivity;
using namespace ::connectivity::sdbcx;
using namespace ::dbtools;
using namespace ::connectivity::parse;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;

namespace connectivity
{
    struct OSQLParseTreeIteratorImpl
    {
        std::vector< TNodePair >      m_aJoinConditions;
        Reference< XConnection >        m_xConnection;
        Reference< XDatabaseMetaData >  m_xDatabaseMetaData;
        Reference< XNameAccess >        m_xTableContainer;
        Reference< XNameAccess >        m_xQueryContainer;

        std::shared_ptr< OSQLTables >   m_pTables;      // all tables which participate in the SQL statement
        std::shared_ptr< OSQLTables >   m_pSubTables;   // all tables from sub queries not the tables from the select tables
        std::shared_ptr< QueryNameSet > m_pForbiddenQueryNames;

        TraversalParts                  m_nIncludeMask;

        bool                            m_bIsCaseSensitive;

        OSQLParseTreeIteratorImpl( const Reference< XConnection >& _rxConnection, const Reference< XNameAccess >& _rxTables )
            :m_xConnection( _rxConnection )
            ,m_nIncludeMask( TraversalParts::All )
            ,m_bIsCaseSensitive( true )
        {
            OSL_PRECOND( m_xConnection.is(), "OSQLParseTreeIteratorImpl::OSQLParseTreeIteratorImpl: invalid connection!" );
            m_xDatabaseMetaData = m_xConnection->getMetaData();

            m_bIsCaseSensitive = m_xDatabaseMetaData.is() && m_xDatabaseMetaData->supportsMixedCaseQuotedIdentifiers();
            m_pTables = std::make_shared<OSQLTables>( m_bIsCaseSensitive );
            m_pSubTables = std::make_shared<OSQLTables>( m_bIsCaseSensitive );

            m_xTableContainer = _rxTables;

            DatabaseMetaData aMetaData( m_xConnection );
            if ( aMetaData.supportsSubqueriesInFrom() )
            {
                // connections might support the XQueriesSupplier interface, if they implement the css.sdb.Connection
                // service
                Reference< XQueriesSupplier > xSuppQueries( m_xConnection, UNO_QUERY );
                if ( xSuppQueries.is() )
                    m_xQueryContainer = xSuppQueries->getQueries();
            }
        }

    public:
        bool    isQueryAllowed( const OUString& _rQueryName )
        {
            if ( !m_pForbiddenQueryNames )
                return true;
            if ( m_pForbiddenQueryNames->find( _rQueryName ) == m_pForbiddenQueryNames->end() )
                return true;
            return false;
        }
    };

    namespace {

    /** helper class for temporarily adding a query name to a list of forbidden query names
    */
    class ForbidQueryName
    {
        std::shared_ptr< QueryNameSet >&    m_rpAllForbiddenNames;
        OUString                         m_sForbiddenQueryName;

    public:
        ForbidQueryName( OSQLParseTreeIteratorImpl& _rIteratorImpl, const OUString& _rForbiddenQueryName )
            :m_rpAllForbiddenNames( _rIteratorImpl.m_pForbiddenQueryNames )
            ,m_sForbiddenQueryName( _rForbiddenQueryName )
        {
            if ( !m_rpAllForbiddenNames )
                m_rpAllForbiddenNames = std::make_shared<QueryNameSet>();
            m_rpAllForbiddenNames->insert( m_sForbiddenQueryName );
        }

        ~ForbidQueryName()
        {
            m_rpAllForbiddenNames->erase( m_sForbiddenQueryName );
        }
    };

    }
}

OSQLParseTreeIterator::OSQLParseTreeIterator(const Reference< XConnection >& _rxConnection,
                                             const Reference< XNameAccess >& _rxTables,
                                             const OSQLParser& _rParser )
    :m_rParser( _rParser )
    ,m_pImpl( new OSQLParseTreeIteratorImpl( _rxConnection, _rxTables ) )
{
    setParseTree(nullptr);
}


OSQLParseTreeIterator::OSQLParseTreeIterator( const OSQLParseTreeIterator& _rParentIterator, const OSQLParser& _rParser, const OSQLParseNode* pRoot )
    :m_rParser( _rParser )
    ,m_pImpl( new OSQLParseTreeIteratorImpl( _rParentIterator.m_pImpl->m_xConnection, _rParentIterator.m_pImpl->m_xTableContainer ) )
{
    m_pImpl->m_pForbiddenQueryNames = _rParentIterator.m_pImpl->m_pForbiddenQueryNames;
    setParseTree( pRoot );
}


OSQLParseTreeIterator::~OSQLParseTreeIterator()
{
    dispose();
}


const OSQLTables& OSQLParseTreeIterator::getTables() const
{
    return *m_pImpl->m_pTables;
}


bool OSQLParseTreeIterator::isCaseSensitive() const
{
    return m_pImpl->m_bIsCaseSensitive;
}


void OSQLParseTreeIterator::dispose()
{
    m_aSelectColumns    = nullptr;
    m_aGroupColumns     = nullptr;
    m_aOrderColumns     = nullptr;
    m_aParameters       = nullptr;
    m_pImpl->m_xTableContainer  = nullptr;
    m_pImpl->m_xDatabaseMetaData = nullptr;
    m_aCreateColumns    = nullptr;
    m_pImpl->m_pTables->clear();
    m_pImpl->m_pSubTables->clear();
}

void OSQLParseTreeIterator::setParseTree(const OSQLParseNode * pNewParseTree)
{
    m_pImpl->m_pTables->clear();
    m_pImpl->m_pSubTables->clear();

    m_aSelectColumns = new OSQLColumns();
    m_aGroupColumns = new OSQLColumns();
    m_aOrderColumns = new OSQLColumns();
    m_aParameters    = new OSQLColumns();
    m_aCreateColumns = new OSQLColumns();

    m_pParseTree = pNewParseTree;
    if (!m_pParseTree)
    {
        m_eStatementType = OSQLStatementType::Unknown;
        return;
    }

    // If m_pParseTree, but no connection then return
    if ( !m_pImpl->m_xTableContainer.is() )
        return;

    m_xErrors.reset();


    // Determine statement type ...
    if (SQL_ISRULE(m_pParseTree,select_statement) || SQL_ISRULE(m_pParseTree,union_statement) )
    {
        m_eStatementType = OSQLStatementType::Select;
    }
    else if (SQL_ISRULE(m_pParseTree,insert_statement))
    {
        m_eStatementType = OSQLStatementType::Insert;
    }
    else if (SQL_ISRULE(m_pParseTree,update_statement_searched))
    {
        m_eStatementType = OSQLStatementType::Update;
    }
    else if (SQL_ISRULE(m_pParseTree,delete_statement_searched))
    {
        m_eStatementType = OSQLStatementType::Delete;
    }
    else if (m_pParseTree->count() == 3 && SQL_ISRULE(m_pParseTree->getChild(1),odbc_call_spec))
    {
        m_eStatementType = OSQLStatementType::OdbcCall;
    }
    else if (SQL_ISRULE(m_pParseTree->getChild(0),base_table_def))
    {
        m_eStatementType = OSQLStatementType::CreateTable;
        m_pParseTree = m_pParseTree->getChild(0);
    }
    else
    {
        m_eStatementType = OSQLStatementType::Unknown;
        //aIteratorStatus.setInvalidStatement();
        return;
    }
}


namespace
{

    void impl_getRowString( const Reference< XRow >& _rxRow, const sal_Int32 _nColumnIndex, OUString& _out_rString )
    {
        _out_rString = _rxRow->getString( _nColumnIndex );
        if ( _rxRow->wasNull() )
            _out_rString.clear();
    }


    OUString lcl_findTableInMetaData(
        const Reference< XDatabaseMetaData >& _rxDBMeta, const OUString& _rCatalog,
        const OUString& _rSchema, const OUString& _rTableName )
    {
        OUString sComposedName;

        static constexpr OUStringLiteral s_sWildcard = u"%" ;

        // we want all catalogues, all schemas, all tables
        Sequence< OUString > sTableTypes { "VIEW", "TABLE", s_sWildcard }; // this last one just to be sure to include anything else...

        if ( _rxDBMeta.is() )
        {
            sComposedName.clear();

            Reference< XResultSet> xRes = _rxDBMeta->getTables(
                !_rCatalog.isEmpty() ? Any( _rCatalog ) : Any(), !_rSchema.isEmpty() ? _rSchema : s_sWildcard, _rTableName, sTableTypes );

            Reference< XRow > xCurrentRow( xRes, UNO_QUERY );
            if ( xCurrentRow.is() && xRes->next() )
            {
                OUString sCatalog, sSchema, sName;

                impl_getRowString( xCurrentRow, 1, sCatalog );
                impl_getRowString( xCurrentRow, 2, sSchema );
                impl_getRowString( xCurrentRow, 3, sName );

                sComposedName = ::dbtools::composeTableName(
                    _rxDBMeta,
                    sCatalog,
                    sSchema,
                    sName,
                    false,
                    ::dbtools::EComposeRule::InDataManipulation
                );
            }
        }
        return sComposedName;
    }
}


void OSQLParseTreeIterator::impl_getQueryParameterColumns( const OSQLTable& _rQuery  )
{
    if ( !( m_pImpl->m_nIncludeMask & TraversalParts::Parameters ) )
        // parameters not to be included in the traversal
        return;

    ::rtl::Reference pSubQueryParameterColumns( new OSQLColumns() );

    // get the command and the EscapeProcessing properties from the sub query
    OUString sSubQueryCommand;
    bool bEscapeProcessing = false;
    try
    {
        Reference< XPropertySet > xQueryProperties( _rQuery, UNO_QUERY_THROW );
        OSL_VERIFY( xQueryProperties->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_COMMAND ) ) >>= sSubQueryCommand );
        OSL_VERIFY( xQueryProperties->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ) ) >>= bEscapeProcessing );
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("connectivity.parse");
    }

    // parse the sub query
    do {

    if ( !bEscapeProcessing || ( sSubQueryCommand.isEmpty() ) )
        break;

    OUString sError;
    std::unique_ptr< OSQLParseNode > pSubQueryNode( const_cast< OSQLParser& >( m_rParser ).parseTree( sError, sSubQueryCommand ) );
    if (!pSubQueryNode)
        break;

    OSQLParseTreeIterator aSubQueryIterator( *this, m_rParser, pSubQueryNode.get() );
    aSubQueryIterator.impl_traverse( TraversalParts::Parameters | TraversalParts::SelectColumns );
        // SelectColumns might also contain parameters #i77635#
    pSubQueryParameterColumns = aSubQueryIterator.getParameters();
    aSubQueryIterator.dispose();

    } while ( false );

    // copy the parameters of the sub query to our own parameter array
    m_aParameters->insert( m_aParameters->end(), pSubQueryParameterColumns->begin(), pSubQueryParameterColumns->end() );
}


OSQLTable OSQLParseTreeIterator::impl_locateRecordSource( const OUString& _rComposedName )
{
    if ( _rComposedName.isEmpty() )
    {
        SAL_WARN( "connectivity.parse", "OSQLParseTreeIterator::impl_locateRecordSource: no object name at all?" );
        return OSQLTable();
    }

    OSQLTable aReturn;
    OUString sComposedName( _rComposedName );

    try
    {
        OUString sCatalog, sSchema, sName;
        qualifiedNameComponents( m_pImpl->m_xDatabaseMetaData, sComposedName, sCatalog, sSchema, sName, ::dbtools::EComposeRule::InDataManipulation );

        // check whether there is a query with the given name
        bool bQueryDoesExist = m_pImpl->m_xQueryContainer.is() && m_pImpl->m_xQueryContainer->hasByName( sComposedName );

        // check whether the table container contains an object with the given name
        if ( !bQueryDoesExist && !m_pImpl->m_xTableContainer->hasByName( sComposedName ) )
            sComposedName = lcl_findTableInMetaData( m_pImpl->m_xDatabaseMetaData, sCatalog, sSchema, sName );
        bool bTableDoesExist = m_pImpl->m_xTableContainer->hasByName( sComposedName );

        // now obtain the object

        // if we're creating a table, and there already is a table or query with the same name,
        // this is worth an error
        if ( OSQLStatementType::CreateTable == m_eStatementType )
        {
            if ( bQueryDoesExist )
                impl_appendError( IParseContext::ErrorCode::InvalidQueryExist, &sName );
            else if ( bTableDoesExist )
                impl_appendError( IParseContext::ErrorCode::InvalidTableExist, &sName );
            else
                aReturn = impl_createTableObject( sName, sCatalog, sSchema );
        }
        else
        {
            // queries win over tables, so if there's a query with this name, take this, no matter if
            // there's a table, too
            if ( bQueryDoesExist )
            {
                if  ( !m_pImpl->isQueryAllowed( sComposedName ) )
                {
                    impl_appendError( m_rParser.getErrorHelper().getSQLException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES, nullptr ) );
                    return nullptr;
                }

                m_pImpl->m_xQueryContainer->getByName( sComposedName ) >>= aReturn;

                // collect the parameters from the sub query
                ForbidQueryName aForbidName( *m_pImpl, sComposedName );
                impl_getQueryParameterColumns( aReturn );
            }
            else if ( bTableDoesExist )
                m_pImpl->m_xTableContainer->getByName( sComposedName ) >>= aReturn;
            else
            {
                if ( m_pImpl->m_xQueryContainer.is() )
                    // the connection on which we're working supports sub queries in from (else
                    // m_xQueryContainer would not have been set), so emit a better error message
                    impl_appendError( IParseContext::ErrorCode::InvalidTableOrQuery, &sName );
                else
                    impl_appendError( IParseContext::ErrorCode::InvalidTableNosuch, &sName );
            }
        }
    }
    catch(Exception&)
    {
        impl_appendError( IParseContext::ErrorCode::InvalidTableNosuch, &sComposedName );
    }

    return aReturn;
}


void OSQLParseTreeIterator::traverseOneTableName( OSQLTables& _rTables,const OSQLParseNode * pTableName, const OUString & rTableRange )
{
    if ( !( m_pImpl->m_nIncludeMask & TraversalParts::TableNames ) )
        // tables should not be included in the traversal
        return;

    OSL_ENSURE(pTableName != nullptr,"OSQLParseTreeIterator::traverseOneTableName: pTableName == NULL");

    Any aCatalog;
    OUString aSchema,aTableName,aComposedName;
    OUString aTableRange(rTableRange);

    // Get table name
    OSQLParseNode::getTableComponents(pTableName,aCatalog,aSchema,aTableName,m_pImpl->m_xDatabaseMetaData);

    // create the composed name like DOMAIN.USER.TABLE1
    aComposedName = ::dbtools::composeTableName(m_pImpl->m_xDatabaseMetaData,
                                aCatalog.hasValue() ? ::comphelper::getString(aCatalog) : OUString(),
                                aSchema,
                                aTableName,
                                false,
                                ::dbtools::EComposeRule::InDataManipulation);

    // if there is no alias for the table name assign the original name to it
    if ( aTableRange.isEmpty() )
        aTableRange = aComposedName;

    // get the object representing this table/query
    OSQLTable aTable = impl_locateRecordSource( aComposedName );
    if ( aTable.is() )
        _rTables[ aTableRange ] = aTable;
}

void OSQLParseTreeIterator::impl_fillJoinConditions(const OSQLParseNode* i_pJoinCondition)
{
    if (i_pJoinCondition->count() == 3 &&   // Expression with brackets
        SQL_ISPUNCTUATION(i_pJoinCondition->getChild(0),"(") &&
        SQL_ISPUNCTUATION(i_pJoinCondition->getChild(2),")"))
    {
        impl_fillJoinConditions(i_pJoinCondition->getChild(1));
    }
    else if (SQL_ISRULEOR2(i_pJoinCondition,search_condition,boolean_term)  &&  // AND/OR logic operation:
             i_pJoinCondition->count() == 3)
    {
        // Only allow AND logic operation
        if ( SQL_ISTOKEN(i_pJoinCondition->getChild(1),AND) )
        {
            impl_fillJoinConditions(i_pJoinCondition->getChild(0));
            impl_fillJoinConditions(i_pJoinCondition->getChild(1));
        }
    }
    else if (SQL_ISRULE(i_pJoinCondition,comparison_predicate))
    {
        // only the comparison of columns is allowed
        OSL_ENSURE(i_pJoinCondition->count() == 3,"OQueryDesignView::InsertJoinConnection: error in the parse tree");
        if (SQL_ISRULE(i_pJoinCondition->getChild(0),column_ref) &&
              SQL_ISRULE(i_pJoinCondition->getChild(2),column_ref) &&
               i_pJoinCondition->getChild(1)->getNodeType() == SQLNodeType::Equal)
        {
            m_pImpl->m_aJoinConditions.push_back( TNodePair(i_pJoinCondition->getChild(0),i_pJoinCondition->getChild(2)) );
        }
    }
}

std::vector< TNodePair >& OSQLParseTreeIterator::getJoinConditions() const
{
    return m_pImpl->m_aJoinConditions;
}

void OSQLParseTreeIterator::getQualified_join( OSQLTables& _rTables, const OSQLParseNode *pTableRef, OUString& aTableRange )
{
    OSL_PRECOND( SQL_ISRULE( pTableRef, cross_union ) || SQL_ISRULE( pTableRef, qualified_join ) ,
        "OSQLParseTreeIterator::getQualified_join: illegal node!" );

    aTableRange.clear();

    const OSQLParseNode* pNode = getTableNode(_rTables,pTableRef->getChild(0),aTableRange);
    if ( isTableNode( pNode ) )
        traverseOneTableName( _rTables, pNode, aTableRange );

    sal_uInt32 nPos = 4;
    if( SQL_ISRULE(pTableRef,cross_union) || pTableRef->getChild(1)->getTokenID() != SQL_TOKEN_NATURAL)
    {
        nPos = 3;
        // join_condition,named_columns_join
        if ( SQL_ISRULE( pTableRef, qualified_join ) )
        {
            const OSQLParseNode* pJoin_spec = pTableRef->getChild(4);
            if ( SQL_ISRULE( pJoin_spec, join_condition ) )
            {
                impl_fillJoinConditions(pJoin_spec->getChild(1));
            }
            else
            {
                const OSQLParseNode* pColumnCommalist = pJoin_spec->getChild(2);
                // All columns in the column_commalist ...
                for (size_t i = 0; i < pColumnCommalist->count(); i++)
                {
                    const OSQLParseNode * pCol = pColumnCommalist->getChild(i);
                    // add twice because the column must exists in both tables
                    m_pImpl->m_aJoinConditions.push_back( TNodePair(pCol,pCol) );
                }
            }
        }
    }

    pNode = getTableNode(_rTables,pTableRef->getChild(nPos),aTableRange);
    if ( isTableNode( pNode ) )
        traverseOneTableName( _rTables, pNode, aTableRange );
}

const OSQLParseNode* OSQLParseTreeIterator::getTableNode( OSQLTables& _rTables, const OSQLParseNode *pTableRef,OUString& rTableRange )
{
    OSL_PRECOND( SQL_ISRULE( pTableRef, table_ref ) || SQL_ISRULE( pTableRef, joined_table )
              || SQL_ISRULE( pTableRef, qualified_join ) || SQL_ISRULE( pTableRef, cross_union ),
        "OSQLParseTreeIterator::getTableNode: only to be called for table_ref nodes!" );

    const OSQLParseNode* pTableNameNode = nullptr;

    if ( SQL_ISRULE( pTableRef, joined_table ) )
    {
        getQualified_join( _rTables, pTableRef->getChild(1), rTableRange );
    }
    if ( SQL_ISRULE( pTableRef, qualified_join ) || SQL_ISRULE( pTableRef, cross_union ) )
    {
        getQualified_join( _rTables, pTableRef, rTableRange );
    }
    else
    {
        rTableRange = OSQLParseNode::getTableRange(pTableRef);
        if  (   ( pTableRef->count() == 4 ) // '{' SQL_TOKEN_OJ joined_table '}'
            ||  ( pTableRef->count() == 5 ) // '(' joined_table ')' range_variable op_column_commalist
            )
        {
            getQualified_join( _rTables, pTableRef->getChild(6 - pTableRef->count()), rTableRange );
        }
        else if ( pTableRef->count() == 3 ) // subquery range_variable op_column_commalist || '(' joined_table ')'
        {
            const OSQLParseNode* pSubQuery = pTableRef->getChild(0);
            if ( pSubQuery->isToken() )
            {
                getQualified_join( _rTables, pTableRef->getChild(1), rTableRange );
            }
            else
            {
                OSL_ENSURE( pSubQuery->count() == 3, "sub queries should have 3 children!" );
                const OSQLParseNode* pQueryExpression = pSubQuery->getChild(1);
                if ( SQL_ISRULE( pQueryExpression, select_statement ) )
                {
                    getSelect_statement( *m_pImpl->m_pSubTables, pQueryExpression );
                    // TODO: now, we need to setup an OSQLTable from pQueryExpression in some way
                    //       and stick it in _rTables[rTableRange]. Probably fake it by
                    //       setting up a full OSQLParseTreeIterator on pQueryExpression
                    //       and using its m_aSelectColumns
                    //       This is necessary in stuff like "SELECT * FROM tbl1 INNER JOIN (SELECT foo, bar FROM tbl2) AS tbl3"
                    //       so that setSelectColumnName() can expand the "*" correctly.
                    //       See e.g. R_UserAndLastSubscription query of https://bugs.libreoffice.org/attachment.cgi?id=71871
                }
                else
                {
                    SAL_WARN( "connectivity.parse", "OSQLParseTreeIterator::getTableNode: subquery which is no select_statement: not yet implemented!" );
                }
            }
        }
        else if ( pTableRef->count() == 2 ) // table_node table_primary_as_range_column
        {
            pTableNameNode = pTableRef->getChild(0);
        }
        else
            SAL_WARN( "connectivity.parse", "OSQLParseTreeIterator::getTableNode: unhandled case!" );
    }

    return pTableNameNode;
}

void OSQLParseTreeIterator::getSelect_statement(OSQLTables& _rTables,const OSQLParseNode* pSelect)
{
    if(SQL_ISRULE(pSelect,union_statement))
    {
        getSelect_statement(_rTables,pSelect->getChild(0));
        //getSelect_statement(pSelect->getChild(3));
        return;
    }
    OSQLParseNode * pTableRefCommalist = pSelect->getChild(3)->getChild(0)->getChild(1);

    OSL_ENSURE(pTableRefCommalist != nullptr,"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(SQL_ISRULE(pTableRefCommalist,table_ref_commalist),"OSQLParseTreeIterator: error in parse tree!");

    const OSQLParseNode* pTableName = nullptr;
    OUString aTableRange;
    for (size_t i = 0; i < pTableRefCommalist->count(); i++)
    {   // Process FROM clause
        aTableRange.clear();

        const OSQLParseNode* pTableListElement = pTableRefCommalist->getChild(i);
        if ( isTableNode( pTableListElement ) )
        {
            traverseOneTableName( _rTables, pTableListElement, aTableRange );
        }
        else if ( SQL_ISRULE( pTableListElement, table_ref ) )
        {
            // Table references can be made up of table names, table names (+),'('joined_table')'(+)
            pTableName = pTableListElement->getChild(0);
            if( isTableNode( pTableName ) )
            {   // Found table names
                aTableRange = OSQLParseNode::getTableRange(pTableListElement);
                traverseOneTableName( _rTables, pTableName, aTableRange );
            }
            else if(SQL_ISPUNCTUATION(pTableName,"{"))
            {   // '{' SQL_TOKEN_OJ joined_table '}'
                getQualified_join( _rTables, pTableListElement->getChild(2), aTableRange );
            }
            else
            {   // '(' joined_table ')' range_variable op_column_commalist
                getTableNode( _rTables, pTableListElement, aTableRange );
            }
        }
        else if (SQL_ISRULE( pTableListElement, qualified_join ) || SQL_ISRULE( pTableListElement, cross_union ) )
        {
            getQualified_join( _rTables, pTableListElement, aTableRange );
        }
        else if ( SQL_ISRULE( pTableListElement, joined_table ) )
        {
            getQualified_join( _rTables, pTableListElement->getChild(1), aTableRange );
        }

        //  if (! aIteratorStatus.IsSuccessful()) break;
    }
}

bool OSQLParseTreeIterator::traverseTableNames(OSQLTables& _rTables)
{
    if ( m_pParseTree == nullptr )
        return false;

    OSQLParseNode* pTableName = nullptr;

    switch ( m_eStatementType )
    {
        case OSQLStatementType::Select:
            getSelect_statement( _rTables, m_pParseTree );
            break;

        case OSQLStatementType::CreateTable:
        case OSQLStatementType::Insert:
        case OSQLStatementType::Delete:
            pTableName = m_pParseTree->getChild(2);
            break;

        case OSQLStatementType::Update:
            pTableName = m_pParseTree->getChild(1);
            break;
        default:
            break;
    }

    if ( pTableName )
    {
        traverseOneTableName( _rTables, pTableName, OUString() );
    }

    return !hasErrors();
}

OUString OSQLParseTreeIterator::getColumnAlias(const OSQLParseNode* _pDerivedColumn)
{
    OSL_ENSURE(SQL_ISRULE(_pDerivedColumn,derived_column),"No derived column!");
    OUString sColumnAlias;
    if(_pDerivedColumn->getChild(1)->count() == 2)
        sColumnAlias = _pDerivedColumn->getChild(1)->getChild(1)->getTokenValue();
    else if(!_pDerivedColumn->getChild(1)->isRule())
        sColumnAlias = _pDerivedColumn->getChild(1)->getTokenValue();
    return sColumnAlias;
}


namespace
{
    void lcl_getColumnRange( const OSQLParseNode* _pColumnRef, const Reference< XConnection >& _rxConnection,
        OUString& _out_rColumnName, OUString& _out_rTableRange,
        const OSQLColumns* _pSelectColumns, OUString& _out_rColumnAliasIfPresent )
    {
        _out_rColumnName.clear();
        _out_rTableRange.clear();
        _out_rColumnAliasIfPresent.clear();
        if ( SQL_ISRULE( _pColumnRef, column_ref ) )
        {
            if( _pColumnRef->count() > 1 )
            {
                for ( sal_Int32 i=0; i<static_cast<sal_Int32>(_pColumnRef->count())-2; ++i )
                    _pColumnRef->getChild(i)->parseNodeToStr( _out_rTableRange, _rxConnection, nullptr, false, false );
                _out_rColumnName = _pColumnRef->getChild( _pColumnRef->count()-1 )->getChild(0)->getTokenValue();
            }
            else
                _out_rColumnName = _pColumnRef->getChild(0)->getTokenValue();

            // look up the column in the select column, to find a possible alias
            if ( _pSelectColumns )
            {
                for (const Reference< XPropertySet >& xColumn : *_pSelectColumns)
                {
                    try
                    {
                        OUString sName, sTableName;
                        xColumn->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_REALNAME ) ) >>= sName;
                        xColumn->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_TABLENAME ) ) >>= sTableName;
                        if ( sName == _out_rColumnName && ( _out_rTableRange.isEmpty() || sTableName == _out_rTableRange ) )
                        {
                            xColumn->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_NAME ) ) >>= _out_rColumnAliasIfPresent;
                            break;
                        }
                    }
                    catch( const Exception& )
                    {
                        DBG_UNHANDLED_EXCEPTION("connectivity.parse");
                    }
                }
            }
        }
        else if(SQL_ISRULE(_pColumnRef,general_set_fct) || SQL_ISRULE(_pColumnRef,set_fct_spec))
        { // Function
            _pColumnRef->parseNodeToStr( _out_rColumnName, _rxConnection );
        }
        else  if(_pColumnRef->getNodeType() == SQLNodeType::Name)
            _out_rColumnName = _pColumnRef->getTokenValue();
    }
}


void OSQLParseTreeIterator::getColumnRange( const OSQLParseNode* _pColumnRef,
                        OUString& _rColumnName,
                        OUString& _rTableRange) const
{
    OUString sDummy;
    lcl_getColumnRange( _pColumnRef, m_pImpl->m_xConnection, _rColumnName, _rTableRange, nullptr, sDummy );
}


void OSQLParseTreeIterator::getColumnRange( const OSQLParseNode* _pColumnRef,
                        OUString& _rColumnName,
                        OUString& _rTableRange,
                        OUString& _out_rColumnAliasIfPresent ) const
{
    lcl_getColumnRange( _pColumnRef, m_pImpl->m_xConnection, _rColumnName, _rTableRange, &*m_aSelectColumns, _out_rColumnAliasIfPresent );
}


void OSQLParseTreeIterator::getColumnRange( const OSQLParseNode* _pColumnRef,
    const Reference< XConnection >& _rxConnection, OUString& _out_rColumnName, OUString& _out_rTableRange )
{
    OUString sDummy;
    lcl_getColumnRange( _pColumnRef, _rxConnection, _out_rColumnName, _out_rTableRange, nullptr, sDummy );
}


void OSQLParseTreeIterator::traverseCreateColumns(const OSQLParseNode* pSelectNode)
{
    //  aIteratorStatus.Clear();

    if (!pSelectNode || m_eStatementType != OSQLStatementType::CreateTable || m_pImpl->m_pTables->empty())
    {
        impl_appendError( IParseContext::ErrorCode::General );
        return;
    }
    if (!SQL_ISRULE(pSelectNode,base_table_element_commalist))
        return ;

    for (size_t i = 0; i < pSelectNode->count(); i++)
    {
        OSQLParseNode *pColumnRef = pSelectNode->getChild(i);

        if (SQL_ISRULE(pColumnRef,column_def))
        {
            OUString aColumnName;
            OUString aTypeName;
            sal_Int32 nType = DataType::VARCHAR;
            aColumnName = pColumnRef->getChild(0)->getTokenValue();

            OSQLParseNode *pDatatype = pColumnRef->getChild(1);
            if (pDatatype && SQL_ISRULE(pDatatype,character_string_type))
            {
                const OSQLParseNode *pType = pDatatype->getChild(0);
                aTypeName = pType->getTokenValue();
                if (pDatatype->count() == 2 && (pType->getTokenID() == SQL_TOKEN_CHAR || pType->getTokenID() == SQL_TOKEN_CHARACTER ))
                    nType = DataType::CHAR;
            }
            else if(pDatatype && pDatatype->getNodeType() == SQLNodeType::Keyword)
            {
                aTypeName = "VARCHAR";
            }

            if (!aTypeName.isEmpty())
            {
                //TODO:Create a new class for create statement to handle field length
                rtl::Reference<OParseColumn> pColumn = new OParseColumn(aColumnName,aTypeName,OUString(),OUString(),
                    ColumnValue::NULLABLE_UNKNOWN,0,0,nType,false,false,isCaseSensitive(),
                    OUString(),OUString(),OUString());
                pColumn->setFunction(false);
                pColumn->setRealName(aColumnName);

                m_aCreateColumns->push_back(pColumn);
            }
        }

    }
}

bool OSQLParseTreeIterator::traverseSelectColumnNames(const OSQLParseNode* pSelectNode)
{
    if ( !( m_pImpl->m_nIncludeMask & TraversalParts::SelectColumns ) )
        return true;

    if (!pSelectNode || m_eStatementType != OSQLStatementType::Select || m_pImpl->m_pTables->empty())
    {
        impl_appendError( IParseContext::ErrorCode::General );
        return false;
    }

    if(SQL_ISRULE(pSelectNode,union_statement))
    {
        return  traverseSelectColumnNames( pSelectNode->getChild( 0 ) )
            /*&&  traverseSelectColumnNames( pSelectNode->getChild( 3 ) )*/;
    }

    // nyi: more checks for correct structure!
    if (pSelectNode->getChild(2)->isRule() && SQL_ISPUNCTUATION(pSelectNode->getChild(2)->getChild(0),"*"))
    {
        // SELECT * ...
        setSelectColumnName("*", "", "");
    }
    else if (SQL_ISRULE(pSelectNode->getChild(2),scalar_exp_commalist))
    {
        // SELECT column[,column] or SELECT COUNT(*) ...
        OSQLParseNode * pSelection = pSelectNode->getChild(2);

        for (size_t i = 0; i < pSelection->count(); i++)
        {
            OSQLParseNode *pColumnRef = pSelection->getChild(i);

            //if (SQL_ISRULE(pColumnRef,select_sublist))
            if (SQL_ISRULE(pColumnRef,derived_column) &&
                SQL_ISRULE(pColumnRef->getChild(0),column_ref) &&
                pColumnRef->getChild(0)->count() == 3 &&
                SQL_ISPUNCTUATION(pColumnRef->getChild(0)->getChild(2),"*"))
            {
                // All the table's columns
                OUString aTableRange;
                pColumnRef->getChild(0)->parseNodeToStr( aTableRange, m_pImpl->m_xConnection, nullptr, false, false );
                setSelectColumnName("*", "", aTableRange);
                continue;
            }
            else if (SQL_ISRULE(pColumnRef,derived_column))
            {
                OUString aColumnAlias(getColumnAlias(pColumnRef)); // can be empty
                OUString sColumnName;
                OUString aTableRange;
                sal_Int32 nType = DataType::VARCHAR;
                bool bFkt(false);
                pColumnRef = pColumnRef->getChild(0);
                while (
                        pColumnRef->getKnownRuleID() != OSQLParseNode::subquery &&
                        pColumnRef->count() == 3 &&
                        SQL_ISPUNCTUATION(pColumnRef->getChild(0),"(") &&
                        SQL_ISPUNCTUATION(pColumnRef->getChild(2),")")
                    )
                    pColumnRef = pColumnRef->getChild(1);

                if (SQL_ISRULE(pColumnRef,column_ref))
                {
                    getColumnRange(pColumnRef,sColumnName,aTableRange);
                    OSL_ENSURE(!sColumnName.isEmpty(),"Column name must not be empty!");
                }
                else /*if (SQL_ISRULE(pColumnRef,general_set_fct) || SQL_ISRULE(pColumnRef,set_fct_spec)    ||
                         SQL_ISRULE(pColumnRef,position_exp)    || SQL_ISRULE(pColumnRef,extract_exp)   ||
                         SQL_ISRULE(pColumnRef,length_exp)      || SQL_ISRULE(pColumnRef,char_value_fct)||
                         SQL_ISRULE(pColumnRef,num_value_exp)   || SQL_ISRULE(pColumnRef,term))*/
                {
                    // Function call present
                    pColumnRef->parseNodeToStr( sColumnName, m_pImpl->m_xConnection );
                    // check if the column is also a parameter
                    traverseSearchCondition(pColumnRef); // num_value_exp

                    if ( pColumnRef->isRule() )
                    {
                        // FIXME: the if condition is not quite right
                        //        many expressions are rules, e.g. "5+3"
                        //        or even: "colName + 1"
                        bFkt = true;
                        nType = getFunctionReturnType(pColumnRef);
                    }
                }
                /*
                else
                {
                    aIteratorStatus.setStatementTooComplex();
                    return;
                }
                */
                if(aColumnAlias.isEmpty())
                    aColumnAlias = sColumnName;
                setSelectColumnName(sColumnName,aColumnAlias,aTableRange,bFkt,nType,SQL_ISRULE(pColumnRef,general_set_fct) || SQL_ISRULE(pColumnRef,set_fct_spec));
            }
        }
    }

    return !hasErrors();
}


bool OSQLParseTreeIterator::traverseOrderByColumnNames(const OSQLParseNode* pSelectNode)
{
    traverseByColumnNames( pSelectNode, true );
    return !hasErrors();
}

void OSQLParseTreeIterator::traverseByColumnNames(const OSQLParseNode* pSelectNode, bool _bOrder)
{
    //  aIteratorStatus.Clear();

    if (pSelectNode == nullptr)
    {
        //aIteratorStatus.setInvalidStatement();
        return;
    }

    if (m_eStatementType != OSQLStatementType::Select)
    {
        //aIteratorStatus.setInvalidStatement();
        return;
    }

    if(SQL_ISRULE(pSelectNode,union_statement))
    {
        traverseByColumnNames(pSelectNode->getChild(0),_bOrder);
        return;
    }

    OSL_ENSURE(pSelectNode->count() >= 4,"OSQLParseTreeIterator: error in parse tree!");

    OSQLParseNode * pTableExp = pSelectNode->getChild(3);
    OSL_ENSURE(pTableExp != nullptr,"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(SQL_ISRULE(pTableExp,table_exp),"OSQLParseTreeIterator:table_exp error in parse tree!");
    OSL_ENSURE(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT,"OSQLParseTreeIterator: error in parse tree!");

    sal_uInt32 nPos = ( _bOrder ? ORDER_BY_CHILD_POS : 2 );

    OSQLParseNode * pOptByClause = pTableExp->getChild(nPos);
    OSL_ENSURE(pOptByClause != nullptr,"OSQLParseTreeIterator: error in parse tree!");
    if ( pOptByClause->count() == 0 )
        return;

    OSL_ENSURE(pOptByClause->count() == 3,"OSQLParseTreeIterator: error in parse tree!");

    OSQLParseNode * pOrderingSpecCommalist = pOptByClause->getChild(2);
    OSL_ENSURE(pOrderingSpecCommalist != nullptr,"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(!_bOrder || SQL_ISRULE(pOrderingSpecCommalist,ordering_spec_commalist),"OSQLParseTreeIterator:ordering_spec_commalist error in parse tree!");
    OSL_ENSURE(pOrderingSpecCommalist->count() > 0,"OSQLParseTreeIterator: error in parse tree!");

    OUString sColumnName;
    OUString aTableRange;
    sal_uInt32 nCount = pOrderingSpecCommalist->count();
    for (sal_uInt32 i = 0; i < nCount; ++i)
    {
        OSQLParseNode* pColumnRef  = pOrderingSpecCommalist->getChild(i);
        OSL_ENSURE(pColumnRef  != nullptr,"OSQLParseTreeIterator: error in parse tree!");
        if ( _bOrder )
        {
            OSL_ENSURE(SQL_ISRULE(pColumnRef,ordering_spec),"OSQLParseTreeIterator:ordering_spec error in parse tree!");
            OSL_ENSURE(pColumnRef->count() == 2,"OSQLParseTreeIterator: error in parse tree!");

            pColumnRef = pColumnRef->getChild(0);
        }
        OSL_ENSURE(pColumnRef != nullptr,"OSQLParseTreeIterator: error in parse tree!");
        aTableRange.clear();
        sColumnName.clear();
        if ( SQL_ISRULE(pColumnRef,column_ref) )
        {
            // Column name (and TableRange):
            getColumnRange(pColumnRef,sColumnName,aTableRange);
        }
        else
        {   // here I found a predicate
            pColumnRef->parseNodeToStr( sColumnName, m_pImpl->m_xConnection, nullptr, false, false );
        }
        OSL_ENSURE(!sColumnName.isEmpty(),"sColumnName must not be empty!");
        if ( _bOrder )
        {
            // Ascending/Descending
            OSQLParseNode * pOptAscDesc = pColumnRef->getParent()->getChild(1);
            OSL_ENSURE(pOptAscDesc != nullptr,"OSQLParseTreeIterator: error in parse tree!");

            bool bAscending = ! (pOptAscDesc && SQL_ISTOKEN(pOptAscDesc,DESC));
            setOrderByColumnName(sColumnName, aTableRange,bAscending);
        }
        else
            setGroupByColumnName(sColumnName, aTableRange);
    }
}

bool OSQLParseTreeIterator::traverseGroupByColumnNames(const OSQLParseNode* pSelectNode)
{
    traverseByColumnNames( pSelectNode, false );
    return !hasErrors();
}


namespace
{
    OUString lcl_generateParameterName( const OSQLParseNode& _rParentNode, const OSQLParseNode& _rParamNode )
    {
        OUString sColumnName(  "param"  );
        const sal_Int32 nCount = static_cast<sal_Int32>(_rParentNode.count());
        for ( sal_Int32 i = 0; i < nCount; ++i )
        {
            if ( _rParentNode.getChild(i) == &_rParamNode )
            {
                sColumnName += OUString::number( i+1 );
                break;
            }
        }
        return sColumnName;
    }
}


void OSQLParseTreeIterator::traverseParameters(const OSQLParseNode* _pNode)
{
    if ( _pNode == nullptr )
        return;

    OUString sColumnName, sTableRange, aColumnAlias;
    const OSQLParseNode* pParent = _pNode->getParent();
    if ( pParent != nullptr )
    {
        if ( SQL_ISRULE(pParent,comparison_predicate) ) // x = X
        {
            sal_uInt32 nPos = 0;
            if ( pParent->getChild(nPos) == _pNode )
                nPos = 2;
            const OSQLParseNode* pOther = pParent->getChild(nPos);
            if ( SQL_ISRULE( pOther, column_ref ) )
                getColumnRange( pOther, sColumnName, sTableRange, aColumnAlias);
            else
                pOther->parseNodeToStr( sColumnName, m_pImpl->m_xConnection, nullptr, false, false );
        } // if ( SQL_ISRULE(pParent,comparison_predicate) ) // x = X
        else if ( SQL_ISRULE(pParent,other_like_predicate_part_2) )
        {
            const OSQLParseNode* pOther = pParent->getParent()->getChild(0);
            if ( SQL_ISRULE( pOther, column_ref ) )
                getColumnRange( pOther, sColumnName, sTableRange, aColumnAlias);
            else
                pOther->parseNodeToStr( sColumnName, m_pImpl->m_xConnection, nullptr, false, false );
        }
        else if ( SQL_ISRULE(pParent,between_predicate_part_2) )
        {
            const OSQLParseNode* pOther = pParent->getParent()->getChild(0);
            if ( SQL_ISRULE( pOther, column_ref ) )
                getColumnRange( pOther, sColumnName, sTableRange, aColumnAlias);
            else
            {
                pOther->parseNodeToStr( sColumnName, m_pImpl->m_xConnection, nullptr, false, false );
                lcl_generateParameterName( *pParent, *_pNode );
            }
        }
        else if ( pParent->getNodeType() == SQLNodeType::CommaListRule )
        {
            lcl_generateParameterName( *pParent, *_pNode );
        }
    }
    traverseParameter( _pNode, pParent, sColumnName, sTableRange, aColumnAlias );
    const sal_uInt32 nCount = _pNode->count();
    for (sal_uInt32 i = 0; i < nCount; ++i)
    {
        const OSQLParseNode* pChild  = _pNode->getChild(i);
        traverseParameters( pChild );
    }
}

bool OSQLParseTreeIterator::traverseSelectionCriteria(const OSQLParseNode* pSelectNode)
{
    if ( pSelectNode == nullptr )
        return false;


    // Analyse parse tree (depending on statement type)
    // and set pointer to WHERE clause:
    OSQLParseNode * pWhereClause = nullptr;

    if (m_eStatementType == OSQLStatementType::Select)
    {
        if(SQL_ISRULE(pSelectNode,union_statement))
        {
            return  traverseSelectionCriteria( pSelectNode->getChild( 0 ) )
                &&  traverseSelectionCriteria( pSelectNode->getChild( 3 ) );
        }
        OSL_ENSURE(pSelectNode->count() >= 4,"OSQLParseTreeIterator: error in parse tree!");

        OSQLParseNode * pTableExp = pSelectNode->getChild(3);
        OSL_ENSURE(pTableExp != nullptr,"OSQLParseTreeIterator: error in parse tree!");
        OSL_ENSURE(SQL_ISRULE(pTableExp,table_exp),"OSQLParseTreeIterator: error in parse tree!");
        OSL_ENSURE(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT,"OSQLParseTreeIterator: error in parse tree!");

        pWhereClause = pTableExp->getChild(1);
    } else if (SQL_ISRULE(pSelectNode,update_statement_searched)) {
        OSL_ENSURE(pSelectNode->count() == 5,"OSQLParseTreeIterator: error in parse tree!");
        pWhereClause = pSelectNode->getChild(4);
    } else if (SQL_ISRULE(pSelectNode,delete_statement_searched)) {
        OSL_ENSURE(pSelectNode->count() == 4,"OSQLParseTreeIterator: error in parse tree!");
        pWhereClause = pSelectNode->getChild(3);
    } else if (SQL_ISRULE(pSelectNode,delete_statement_positioned)) {
        // nyi
        SAL_WARN( "connectivity.parse","OSQLParseTreeIterator::getSelectionCriteria: positioned nyi");
    } else {
        // Other statement, no selection criteria
        return false;
    }

    if (!pWhereClause || !SQL_ISRULE(pWhereClause,where_clause))
    {
        // The WHERE clause is optional most of the time; which means it could be a "optional_where_clause".
        OSL_ENSURE(pWhereClause && SQL_ISRULE(pWhereClause,opt_where_clause),"OSQLParseTreeIterator: error in parse tree!");
        return false;
    }

    // But if it's a where_clause, then it must not be empty
    OSL_ENSURE(pWhereClause->count() == 2,"OSQLParseTreeIterator: error in parse tree!");

    OSQLParseNode * pComparisonPredicate = pWhereClause->getChild(1);
    OSL_ENSURE(pComparisonPredicate != nullptr,"OSQLParseTreeIterator: error in parse tree!");


    // Process the comparison criteria now


    traverseSearchCondition(pComparisonPredicate);

    return !hasErrors();
}


void OSQLParseTreeIterator::traverseSearchCondition(OSQLParseNode const * pSearchCondition)
{
    if (
            SQL_ISRULE(pSearchCondition,boolean_primary) &&
            pSearchCondition->count() == 3 &&
            SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
            SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")")
        )
    {
        // Round brackets
        traverseSearchCondition(pSearchCondition->getChild(1));
    }
    // The first element is an OR logical operation
    else  if ( SQL_ISRULE(pSearchCondition,search_condition) && pSearchCondition->count() == 3 )
    {
        // if this assert fails, the SQL grammar has changed!
        assert(SQL_ISTOKEN(pSearchCondition->getChild(1),OR));
        // Then process recursively (use the same row) ...
        traverseSearchCondition(pSearchCondition->getChild(0));
//      if (! aIteratorStatus.IsSuccessful())
//          return;

        // Continue with the right child
        traverseSearchCondition(pSearchCondition->getChild(2));
    }
    // The first element is an AND logical operation (again)
    else if ( SQL_ISRULE(pSearchCondition,boolean_term) && pSearchCondition->count() == 3 )
    {
        // Then process recursively (use the same row)
        traverseSearchCondition(pSearchCondition->getChild(0));
//      if (! aIteratorStatus.IsSuccessful())
//          return;

        // Continue with the right child
        traverseSearchCondition(pSearchCondition->getChild(2));
    }
    // Else, process single search criteria (like =, !=, ..., LIKE, IS NULL etc.)
    else if (SQL_ISRULE(pSearchCondition,comparison_predicate) )
    {
        OUString aValue;
        pSearchCondition->getChild(2)->parseNodeToStr( aValue, m_pImpl->m_xConnection, nullptr, false, false );
        traverseOnePredicate(pSearchCondition->getChild(0),aValue,pSearchCondition->getChild(2));
        impl_fillJoinConditions(pSearchCondition);
//      if (! aIteratorStatus.IsSuccessful())
//          return;
    }
    else if (SQL_ISRULE(pSearchCondition,like_predicate) /*&& SQL_ISRULE(pSearchCondition->getChild(0),column_ref)*/)
    {
        OSL_ENSURE(pSearchCondition->count() == 2,"OSQLParseTreeIterator: error in parse tree!");
        const OSQLParseNode* pPart2 = pSearchCondition->getChild(1);

        sal_Int32 nCurentPos = pPart2->count()-2;

        OSQLParseNode * pNum_value_exp  = pPart2->getChild(nCurentPos);
        OSQLParseNode * pOptEscape      = pPart2->getChild(nCurentPos+1);

        OSL_ENSURE(pNum_value_exp != nullptr,"OSQLParseTreeIterator: error in parse tree!");
        OSL_ENSURE(pOptEscape != nullptr,"OSQLParseTreeIterator: error in parse tree!");

        if (pOptEscape->count() != 0)
        {
            //  aIteratorStatus.setStatementTooComplex();
            return;
        }

        OUString aValue;
        OSQLParseNode * pParam = nullptr;
        if (SQL_ISRULE(pNum_value_exp,parameter))
            pParam = pNum_value_exp;
        else if(pNum_value_exp->isToken())
            // Normal value
            aValue = pNum_value_exp->getTokenValue();
        else
        {
            pNum_value_exp->parseNodeToStr( aValue, m_pImpl->m_xConnection, nullptr, false, false );
            pParam = pNum_value_exp;
        }

        traverseOnePredicate(pSearchCondition->getChild(0),aValue,pParam);
//      if (! aIteratorStatus.IsSuccessful())
//          return;
    }
    else if (SQL_ISRULE(pSearchCondition,in_predicate))
    {
        OSL_ENSURE(pSearchCondition->count() == 2,"OSQLParseTreeIterator: error in parse tree!");
        const OSQLParseNode* pPart2 = pSearchCondition->getChild(1);

        traverseSearchCondition(pSearchCondition->getChild(0));
        //  if (! aIteratorStatus.IsSuccessful()) return;

        OSQLParseNode* pChild = pPart2->getChild(2);
        if ( SQL_ISRULE(pChild->getChild(0),subquery) )
        {
            traverseTableNames( *m_pImpl->m_pSubTables );
            traverseSelectionCriteria(pChild->getChild(0)->getChild(1));
        }
        else
        { // '(' value_exp_commalist ')'
            pChild = pChild->getChild(1);
            sal_Int32 nCount = pChild->count();
            for (sal_Int32 i=0; i < nCount; ++i)
            {
                traverseSearchCondition(pChild->getChild(i));
            }
        }
    }
    else if (SQL_ISRULE(pSearchCondition,test_for_null) /*&& SQL_ISRULE(pSearchCondition->getChild(0),column_ref)*/)
    {
        OSL_ENSURE(pSearchCondition->count() == 2,"OSQLParseTreeIterator: error in parse tree!");
        const OSQLParseNode* pPart2 = pSearchCondition->getChild(1);
        OSL_ENSURE(SQL_ISTOKEN(pPart2->getChild(0),IS),"OSQLParseTreeIterator: error in parse tree!");

        OUString aString;
        traverseOnePredicate(pSearchCondition->getChild(0),aString,nullptr);
        //  if (! aIteratorStatus.IsSuccessful()) return;
    }
    else if (SQL_ISRULE(pSearchCondition,num_value_exp) || SQL_ISRULE(pSearchCondition,term))
    {
        OUString aString;
        traverseOnePredicate(pSearchCondition->getChild(0),aString,pSearchCondition->getChild(0));
        traverseOnePredicate(pSearchCondition->getChild(2),aString,pSearchCondition->getChild(2));
    }
    // Just pass on the error
}

void OSQLParseTreeIterator::traverseParameter(const OSQLParseNode* _pParseNode
                                              ,const OSQLParseNode* _pParentNode
                                              ,const OUString& _aColumnName
                                              ,OUString& _aTableRange
                                              ,const OUString& _rColumnAlias)
{
    if ( !SQL_ISRULE( _pParseNode, parameter ) )
        return;

    if ( !( m_pImpl->m_nIncludeMask & TraversalParts::Parameters ) )
        // parameters not to be included in the traversal
        return;

    OSL_ENSURE(_pParseNode->count() > 0,"OSQLParseTreeIterator: error in parse tree!");
    OSQLParseNode * pMark = _pParseNode->getChild(0);
    OUString sParameterName;

    if (SQL_ISPUNCTUATION(pMark,"?"))
    {
        sParameterName =    !_rColumnAlias.isEmpty()
                        ?   _rColumnAlias
                        :   !_aColumnName.isEmpty()
                        ?   _aColumnName
                        :   OUString("?");
    }
    else if (SQL_ISPUNCTUATION(pMark,":"))
    {
        sParameterName = _pParseNode->getChild(1)->getTokenValue();
    }
    else if (SQL_ISPUNCTUATION(pMark,"["))
    {
        sParameterName = _pParseNode->getChild(1)->getTokenValue();
    }
    else
    {
        SAL_WARN( "connectivity.parse","OSQLParseTreeIterator: error in parse tree!");
    }

    // found a parameter
    if ( _pParentNode && (SQL_ISRULE(_pParentNode,general_set_fct) || SQL_ISRULE(_pParentNode,set_fct_spec)) )
    {// found a function as column_ref
        OUString sFunctionName;
        _pParentNode->getChild(0)->parseNodeToStr( sFunctionName, m_pImpl->m_xConnection, nullptr, false, false );
        const sal_uInt32 nCount = _pParentNode->count();
        sal_uInt32 i = 0;
        for(; i < nCount;++i)
        {
            if ( _pParentNode->getChild(i) == _pParseNode )
                break;
        }
        sal_Int32 nType = ::connectivity::OSQLParser::getFunctionParameterType( _pParentNode->getChild(0)->getTokenID(), i-1);

        rtl::Reference<OParseColumn> pColumn = new OParseColumn(   sParameterName,
                                                    OUString(),
                                                    OUString(),
                                                    OUString(),
                                                    ColumnValue::NULLABLE_UNKNOWN,
                                                    0,
                                                    0,
                                                    nType,
                                                    false,
                                                    false,
                                                    isCaseSensitive(),
                                                    OUString(),
                                                    OUString(),
                                                    OUString());
        pColumn->setFunction(true);
        pColumn->setAggregateFunction(true);
        pColumn->setRealName(sFunctionName);
        m_aParameters->push_back(pColumn);
    }
    else
    {
        bool bNotFound = true;
        OSQLColumns::const_iterator aIter = ::connectivity::find(
            m_aSelectColumns->begin(),
            m_aSelectColumns->end(),
            _aColumnName,::comphelper::UStringMixEqual( isCaseSensitive() )
        );
        if(aIter != m_aSelectColumns->end())
        {
            rtl::Reference<OParseColumn> pNewColumn = new OParseColumn(*aIter,isCaseSensitive());
            pNewColumn->setName(sParameterName);
            pNewColumn->setRealName(_aColumnName);
            m_aParameters->push_back(pNewColumn);
            bNotFound = false;
        }
        else if(!_aColumnName.isEmpty())// search in the tables for the right one
        {

            Reference<XPropertySet> xColumn = findColumn( _aColumnName, _aTableRange, true );

            if ( xColumn.is() )
            {
                rtl::Reference<OParseColumn> pNewColumn = new OParseColumn(xColumn,isCaseSensitive());
                pNewColumn->setName(sParameterName);
                pNewColumn->setRealName(_aColumnName);
                m_aParameters->push_back(pNewColumn);
                bNotFound = false;
            }
        }
        if ( bNotFound )
        {
            sal_Int32 nType = DataType::VARCHAR;
            OSQLParseNode* pParent = _pParentNode ? _pParentNode->getParent() : nullptr;
            if ( pParent && (SQL_ISRULE(pParent,general_set_fct) || SQL_ISRULE(pParent,set_fct_spec)) )
            {
                const sal_uInt32 nCount = _pParentNode->count();
                sal_uInt32 i = 0;
                for(; i < nCount;++i)
                {
                    if ( _pParentNode->getChild(i) == _pParseNode )
                        break;
                }
                nType = ::connectivity::OSQLParser::getFunctionParameterType( pParent->getChild(0)->getTokenID(), i+1);
            }

            OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), sParameterName));

            rtl::Reference<OParseColumn> pColumn = new OParseColumn(aNewColName,
                                                    OUString(),
                                                    OUString(),
                                                    OUString(),
                                                    ColumnValue::NULLABLE_UNKNOWN,
                                                    0,
                                                    0,
                                                    nType,
                                                    false,
                                                    false,
                                                    isCaseSensitive(),
                                                    OUString(),
                                                    OUString(),
                                                    OUString());
            pColumn->setName(aNewColName);
            pColumn->setRealName(sParameterName);
            m_aParameters->push_back(pColumn);
        }
    }
}

void OSQLParseTreeIterator::traverseOnePredicate(
                                OSQLParseNode const * pColumnRef,
                                OUString& rValue,
                                OSQLParseNode const * pParseNode)
{
    if ( !pParseNode )
        return;

    // Column name (and TableRange):
    OUString aColumnName, aTableRange, sColumnAlias;
    getColumnRange( pColumnRef, aColumnName, aTableRange, sColumnAlias);

    OUString aName;

    /*if (SQL_ISRULE(pParseNode,parameter))
        traverseParameter( pParseNode, pColumnRef, aColumnName, aTableRange, sColumnAlias );
    else */if (SQL_ISRULE(pParseNode,column_ref))// Column-Name (and TableRange):
        getColumnRange(pParseNode,aName,rValue);
    else
    {
        traverseSearchCondition(pParseNode);
        //  if (! aIteratorStatus.IsSuccessful()) return;
    }
}


void OSQLParseTreeIterator::traverseAll()
{
    impl_traverse( TraversalParts::All );
}


void OSQLParseTreeIterator::impl_traverse( TraversalParts _nIncludeMask )
{
    // resets our errors
    m_xErrors.reset();

    m_pImpl->m_nIncludeMask = _nIncludeMask;

    if ( !traverseTableNames( *m_pImpl->m_pTables ) )
        return;

    switch ( m_eStatementType )
    {
    case OSQLStatementType::Select:
    {
        const OSQLParseNode* pSelectNode = m_pParseTree;
        traverseParameters( pSelectNode );
        if  (   !traverseSelectColumnNames( pSelectNode )
            ||  !traverseOrderByColumnNames( pSelectNode )
            ||  !traverseGroupByColumnNames( pSelectNode )
            ||  !traverseSelectionCriteria( pSelectNode )
            )
            return;
    }
    break;
    case OSQLStatementType::CreateTable:
    {
        //0     |  1  |  2   |3|        4         |5
        //create table sc.foo ( a char(20), b char )
        const OSQLParseNode* pCreateNode = m_pParseTree->getChild(4);
        traverseCreateColumns(pCreateNode);
    }
    break;
    case OSQLStatementType::Insert:
        break;
    default:
        break;
    }
}

// Dummy implementations


OSQLTable OSQLParseTreeIterator::impl_createTableObject( const OUString& rTableName,
    const OUString& rCatalogName, const OUString& rSchemaName )
{
    OSL_PRECOND( m_eStatementType == OSQLStatementType::CreateTable,
        "OSQLParseTreeIterator::impl_createTableObject: only to be called for CREATE TABLE statements!" );
        // (in all other cases, m_pTables is to contain the table objects as obtained from the tables
        // container of the connection (m_xTablesContainer)

    OSQLTable aReturnTable = new OTable(
        nullptr,
        false,
        rTableName,
        "Table",
        "New Created Table",
        rSchemaName,
        rCatalogName
    );
    return aReturnTable;
}

void OSQLParseTreeIterator::appendColumns(const OUString& _rTableAlias, const OSQLTable& _rTable)
{
    if (!_rTable.is())
        return;

    Reference<XNameAccess> xColumns = _rTable->getColumns();
    if ( !xColumns.is() )
        return;

    Sequence< OUString > aColNames =  xColumns->getElementNames();
    const OUString* pBegin = aColNames.getConstArray();
    const OUString* pEnd = pBegin + aColNames.getLength();

    ::comphelper::UStringMixLess aCompare(isCaseSensitive());
    std::vector<OUString> aSelectColumnNames = getSelectColumnNames();

    for(;pBegin != pEnd;++pBegin)
    {
        OUString aName(getUniqueColumnName(aSelectColumnNames, *pBegin));
        Reference< XPropertySet > xColumn;
        if(xColumns->hasByName(*pBegin) && (xColumns->getByName(*pBegin) >>= xColumn) && xColumn.is())
        {
            rtl::Reference<OParseColumn> pColumn = new OParseColumn(aName
                                                ,   getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
                                                ,   getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE)))
                                                ,   getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION)))
                                                ,   getINT32(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
                                                ,   getINT32(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
                                                ,   getINT32(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
                                                ,   getINT32(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
                                                ,   getBOOL(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)))
                                                ,   getBOOL(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))
                                                ,   isCaseSensitive()
                                                ,   getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CATALOGNAME)))
                                                ,   getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCHEMANAME)))
                                                ,   getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TABLENAME))));

            pColumn->setTableName(_rTableAlias);
            pColumn->setRealName(*pBegin);
            m_aSelectColumns->push_back(pColumn);
            // update aSelectColumnNames with newly insert aName
            aSelectColumnNames.insert(std::upper_bound(aSelectColumnNames.begin(), aSelectColumnNames.end(), aName, aCompare), aName);
        }
        else
            impl_appendError( IParseContext::ErrorCode::InvalidColumn, pBegin, &_rTableAlias );
    }
}

void OSQLParseTreeIterator::setSelectColumnName(const OUString & rColumnName,const OUString & rColumnAlias, const OUString & rTableRange, bool bFkt, sal_Int32 _nType, bool bAggFkt)
{
    if(rColumnName.toChar() == '*' && rTableRange.isEmpty())
    {   // SELECT * ...
        for (auto const& table : *m_pImpl->m_pTables)
            appendColumns(table.first, table.second);
    }
    else if( rColumnName.toChar() == '*' && !rTableRange.isEmpty() )
    {   // SELECT <table>.*
        OSQLTables::const_iterator aFind = m_pImpl->m_pTables->find(rTableRange);

        if(aFind != m_pImpl->m_pTables->end())
            appendColumns(rTableRange, aFind->second);
    }
    else if ( rTableRange.isEmpty() )
    {   // SELECT <something> ...
        // without table specified
        if ( !bFkt )
        {
            Reference< XPropertySet> xNewColumn;

            for (auto const& table : *m_pImpl->m_pTables)
            {
                if ( !table.second.is() )
                    continue;

                Reference<XNameAccess> xColumns = table.second->getColumns();
                Reference< XPropertySet > xColumn;
                if  (   !xColumns->hasByName( rColumnName )
                    ||  !( xColumns->getByName( rColumnName ) >>= xColumn )
                    )
                    continue;

                OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), rColumnAlias));

                rtl::Reference<OParseColumn> pColumn = new OParseColumn(xColumn,isCaseSensitive());
                xNewColumn = pColumn;
                pColumn->setTableName(table.first);
                pColumn->setName(aNewColName);
                pColumn->setRealName(rColumnName);

                break;
            }

            if ( !xNewColumn.is() )
            {
                // no function (due to the above !bFkt), no existing column
                // => assume an expression
                OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), rColumnAlias));
                // did not find a column with this name in any of the tables
                rtl::Reference<OParseColumn> pColumn = new OParseColumn(
                    aNewColName,
                    "VARCHAR",
                        // TODO: does this match with _nType?
                        // Or should be fill this from the getTypeInfo of the connection?
                    OUString(),
                    OUString(),
                    ColumnValue::NULLABLE_UNKNOWN,
                    0,
                    0,
                    _nType,
                    false,
                    false,
                    isCaseSensitive(),
                    OUString(),
                    OUString(),
                    OUString()
                );

                xNewColumn = pColumn;
                pColumn->setRealName( rColumnName );
            }

            m_aSelectColumns->push_back( xNewColumn );
        }
        else
        {
            OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), rColumnAlias));

            rtl::Reference<OParseColumn> pColumn = new OParseColumn(aNewColName,OUString(),OUString(),OUString(),
                ColumnValue::NULLABLE_UNKNOWN,0,0,_nType,false,false,isCaseSensitive(),
                OUString(),OUString(),OUString());
            pColumn->setFunction(true);
            pColumn->setAggregateFunction(bAggFkt);
            pColumn->setRealName(rColumnName);

            m_aSelectColumns->push_back(pColumn);
        }
    }
    else    // ColumnName and TableName exist
    {
        OSQLTables::const_iterator aFind = m_pImpl->m_pTables->find(rTableRange);

        bool bError = false;
        if (aFind != m_pImpl->m_pTables->end() && aFind->second.is())
        {
            if (bFkt)
            {
                OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), rColumnAlias));

                rtl::Reference<OParseColumn> pColumn = new OParseColumn(aNewColName,OUString(),OUString(),OUString(),
                    ColumnValue::NULLABLE_UNKNOWN,0,0,_nType,false,false,isCaseSensitive(),
                    OUString(),OUString(),OUString());
                pColumn->setFunction(true);
                pColumn->setAggregateFunction(bAggFkt);
                pColumn->setRealName(rColumnName);
                SAL_WARN("connectivity.parse", "Trying to construct a column with Function==true and a TableName; this makes no sense.");
                assert(false);
                pColumn->setTableName(aFind->first);

                m_aSelectColumns->push_back(pColumn);
            }
            else
            {
                Reference< XPropertySet > xColumn;
                if (aFind->second->getColumns()->hasByName(rColumnName) && (aFind->second->getColumns()->getByName(rColumnName) >>= xColumn))
                {
                    OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), rColumnAlias));

                    rtl::Reference<OParseColumn> pColumn = new OParseColumn(xColumn,isCaseSensitive());
                    pColumn->setName(aNewColName);
                    pColumn->setRealName(rColumnName);
                    pColumn->setTableName(aFind->first);

                    m_aSelectColumns->push_back(pColumn);
                }
                else
                    bError = true;
            }
        }
        else
            bError = true;

        // Table does not exist or lacking field
        if (bError)
        {
            OUString aNewColName(getUniqueColumnName(getSelectColumnNames(), rColumnAlias));

            rtl::Reference<OParseColumn> pColumn = new OParseColumn(aNewColName,OUString(),OUString(),OUString(),
                ColumnValue::NULLABLE_UNKNOWN,0,0,DataType::VARCHAR,false,false,isCaseSensitive(),
                OUString(),OUString(),OUString());
            pColumn->setFunction(true);
            pColumn->setAggregateFunction(bAggFkt);

            m_aSelectColumns->push_back(pColumn);
        }
    }
}

std::vector<OUString> OSQLParseTreeIterator::getSelectColumnNames() const
{
    ::comphelper::UStringMixLess aCompare(isCaseSensitive());

    std::vector<OUString> aColumnNames;
    OUString sPropertyName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
    for (const auto& col : *m_aSelectColumns)
        aColumnNames.push_back(getString(col->getPropertyValue(sPropertyName)));
    std::sort(aColumnNames.begin(), aColumnNames.end(), aCompare);

    return aColumnNames;
}

OUString OSQLParseTreeIterator::getUniqueColumnName(const std::vector<OUString>& rColumnNames, const OUString& rColumnName) const
{
    ::comphelper::UStringMixLess aCompare(isCaseSensitive());
    if (!std::binary_search(rColumnNames.begin(), rColumnNames.end(), rColumnName, aCompare))
        return rColumnName;

    OUString aAlias;
    sal_Int32 i=1;
    do
    {
        aAlias = rColumnName + OUString::number(i++);
    }
    while (std::binary_search(rColumnNames.begin(), rColumnNames.end(), aAlias, aCompare));
    return aAlias;
}

void OSQLParseTreeIterator::setOrderByColumnName(const OUString & rColumnName, OUString & rTableRange, bool bAscending)
{
    Reference<XPropertySet> xColumn = findSelectColumn( rColumnName );
    if ( !xColumn.is() )
        xColumn = findColumn ( rColumnName, rTableRange, false );
    if ( xColumn.is() )
        m_aOrderColumns->push_back(new OOrderColumn( xColumn, rTableRange, isCaseSensitive(), bAscending ) );
    else
    {
        sal_Int32 nId = rColumnName.toInt32();
        if ( nId > 0 && o3tl::make_unsigned(nId) < m_aSelectColumns->size() )
            m_aOrderColumns->push_back( new OOrderColumn( (*m_aSelectColumns)[nId-1], isCaseSensitive(), bAscending ) );
    }

#ifdef SQL_TEST_PARSETREEITERATOR
    cout << "OSQLParseTreeIterator::setOrderByColumnName: "
         << (const char *) rColumnName << ", "
         << (const char *) rTableRange << ", "
         << (bAscending ? "true" : "false")
         << "\n";
#endif
}

void OSQLParseTreeIterator::setGroupByColumnName(const OUString & rColumnName, OUString & rTableRange)
{
    Reference<XPropertySet> xColumn = findColumn( rColumnName, rTableRange, false );
    if ( xColumn.is() )
        m_aGroupColumns->push_back(new OParseColumn(xColumn,isCaseSensitive()));
    else
    {
        sal_Int32 nId = rColumnName.toInt32();
        if ( nId > 0 && o3tl::make_unsigned(nId) < m_aSelectColumns->size() )
            m_aGroupColumns->push_back(new OParseColumn((*m_aSelectColumns)[nId-1],isCaseSensitive()));
    }

#ifdef SQL_TEST_PARSETREEITERATOR
    cout << "OSQLParseTreeIterator::setGroupByColumnName: "
         << (const char *) rColumnName << ", "
         << (const char *) rTableRange << ", "
         << (bAscending ? "true" : "false")
         << "\n";
#endif
}


const OSQLParseNode* OSQLParseTreeIterator::getWhereTree() const
{
    if (!m_pParseTree)
        return nullptr;

    // Analyse parse tree (depending on statement type)
    // and set pointer to WHERE clause:
    OSQLParseNode * pWhereClause = nullptr;
    if(getStatementType() == OSQLStatementType::Select)
    {
        OSL_ENSURE(m_pParseTree->count() >= 4,"ParseTreeIterator: error in parse tree!");
        OSQLParseNode * pTableExp = m_pParseTree->getChild(3);
        OSL_ENSURE(pTableExp != nullptr,"OSQLParseTreeIterator: error in parse tree!");
        OSL_ENSURE(SQL_ISRULE(pTableExp,table_exp),"OSQLParseTreeIterator: error in parse tree!");
        OSL_ENSURE(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT,"OSQLParseTreeIterator: error in parse tree!");

        pWhereClause = pTableExp->getChild(1);
    }
    else if (SQL_ISRULE(m_pParseTree,update_statement_searched) ||
             SQL_ISRULE(m_pParseTree,delete_statement_searched))
    {
        pWhereClause = m_pParseTree->getChild(m_pParseTree->count()-1);
    }
    if(pWhereClause && pWhereClause->count() != 2)
        pWhereClause = nullptr;
    return pWhereClause;
}


const OSQLParseNode* OSQLParseTreeIterator::getOrderTree() const
{
    if (!m_pParseTree || getStatementType() != OSQLStatementType::Select)
        return nullptr;

    // Analyse parse tree (depending on statement type)
    // and set pointer to ORDER clause:

    assert(SQL_ISRULE(m_pParseTree, select_statement) || SQL_ISRULE(m_pParseTree, union_statement));

    auto pParseTree = m_pParseTree;
    if(SQL_ISRULE(m_pParseTree, union_statement))
    {
        assert(m_pParseTree->count() == 4);
        pParseTree = pParseTree->getChild(3);
        // since UNION is left-associative (at least in our grammar),
        // possibly the left-hand (m_pParseTree->getChild(0)) is a union_statement,
        // but the right hand cannot.
        assert(SQL_ISRULE(pParseTree, select_statement));
    }

    OSQLParseNode * pOrderClause = nullptr;
    OSL_ENSURE(pParseTree->count() == 4, "OSQLParseTreeIterator::getOrderTree: expected a SELECT, and a SELECT must have exactly four children");
    OSQLParseNode * pTableExp = pParseTree->getChild(3);
    OSL_ENSURE(pTableExp != nullptr, "OSQLParseTreeIterator::getOrderTree: got NULL table_exp");
    OSL_ENSURE(SQL_ISRULE(pTableExp, table_exp), "OSQLParseTreeIterator::getOrderTree: expected table_exp but got something else");
    OSL_ENSURE(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT,"OSQLParseTreeIterator::getOrderTree: table_exp doesn't have the expected number of children");
    // tdf#141115 upgrade the above to an assert;
    // this cannot go well if there are too few children
    assert(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT);

    pOrderClause = pTableExp->getChild(ORDER_BY_CHILD_POS);
    // If it is an order_by, it must not be empty
    if(pOrderClause->count() != 3)
        pOrderClause = nullptr;
    return pOrderClause;
}

const OSQLParseNode* OSQLParseTreeIterator::getGroupByTree() const
{
    if (!m_pParseTree || getStatementType() != OSQLStatementType::Select)
        return nullptr;

    // Analyse parse tree (depending on statement type)
    // and set pointer to ORDER clause:
    OSQLParseNode * pGroupClause = nullptr;
    OSL_ENSURE(m_pParseTree->count() >= 4,"ParseTreeIterator: error in parse tree!");
    OSQLParseNode * pTableExp = m_pParseTree->getChild(3);
    OSL_ENSURE(pTableExp != nullptr,"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(SQL_ISRULE(pTableExp,table_exp),"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT,"OSQLParseTreeIterator: error in parse tree!");

    pGroupClause = pTableExp->getChild(2);
    // If it is an order_by, it must not be empty
    if(pGroupClause->count() != 3)
        pGroupClause = nullptr;
    return pGroupClause;
}

const OSQLParseNode* OSQLParseTreeIterator::getHavingTree() const
{
    if (!m_pParseTree || getStatementType() != OSQLStatementType::Select)
        return nullptr;

    // Analyse parse tree (depending on statement type)
    // and set pointer to ORDER clause:
    OSQLParseNode * pHavingClause = nullptr;
    OSL_ENSURE(m_pParseTree->count() >= 4,"ParseTreeIterator: error in parse tree!");
    OSQLParseNode * pTableExp = m_pParseTree->getChild(3);
    OSL_ENSURE(pTableExp != nullptr,"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(SQL_ISRULE(pTableExp,table_exp),"OSQLParseTreeIterator: error in parse tree!");
    OSL_ENSURE(pTableExp->count() == TABLE_EXPRESSION_CHILD_COUNT,"OSQLParseTreeIterator: error in parse tree!");

    pHavingClause = pTableExp->getChild(3);
    // If it is an order_by, then it must not be empty
    if(pHavingClause->count() < 1)
        pHavingClause = nullptr;
    return pHavingClause;
}

bool OSQLParseTreeIterator::isTableNode(const OSQLParseNode* _pTableNode)
{
    return _pTableNode && (SQL_ISRULE(_pTableNode,catalog_name) ||
                           SQL_ISRULE(_pTableNode,schema_name)  ||
                           SQL_ISRULE(_pTableNode,table_name));
}

const OSQLParseNode* OSQLParseTreeIterator::getSimpleWhereTree() const
{
    const OSQLParseNode* pNode = getWhereTree();
    return pNode ? pNode->getChild(1) : nullptr;
}

const OSQLParseNode* OSQLParseTreeIterator::getSimpleOrderTree() const
{
    const OSQLParseNode* pNode = getOrderTree();
    return pNode ? pNode->getChild(2) : nullptr;
}

const OSQLParseNode* OSQLParseTreeIterator::getSimpleGroupByTree() const
{
    const OSQLParseNode* pNode = getGroupByTree();
    return pNode ? pNode->getChild(2) : nullptr;
}

const OSQLParseNode* OSQLParseTreeIterator::getSimpleHavingTree() const
{
    const OSQLParseNode* pNode = getHavingTree();
    return pNode ? pNode->getChild(1) : nullptr;
}


Reference< XPropertySet > OSQLParseTreeIterator::findSelectColumn( std::u16string_view rColumnName )
{
    for (auto const& lookupColumn : *m_aSelectColumns)
    {
        Reference< XPropertySet > xColumn( lookupColumn );
        try
        {
            OUString sName;
            xColumn->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_NAME ) ) >>= sName;
            if ( sName == rColumnName )
                return xColumn;
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("connectivity.parse");
        }
    }
    return nullptr;
}


Reference< XPropertySet > OSQLParseTreeIterator::findColumn( const OUString & rColumnName, OUString & rTableRange, bool _bLookInSubTables )
{
    Reference< XPropertySet > xColumn = findColumn( *m_pImpl->m_pTables, rColumnName, rTableRange );
    if ( !xColumn.is() && _bLookInSubTables )
        xColumn = findColumn( *m_pImpl->m_pSubTables, rColumnName, rTableRange );
    return xColumn;
}


Reference< XPropertySet > OSQLParseTreeIterator::findColumn(const OSQLTables& _rTables, const OUString & rColumnName, OUString & rTableRange)
{
    Reference< XPropertySet > xColumn;
    if ( !rTableRange.isEmpty() )
    {
        OSQLTables::const_iterator aFind = _rTables.find(rTableRange);

        if ( aFind != _rTables.end()
            && aFind->second.is()
            && aFind->second->getColumns().is()
            && aFind->second->getColumns()->hasByName(rColumnName) )
            aFind->second->getColumns()->getByName(rColumnName) >>= xColumn;
    }
    if ( !xColumn.is() )
    {
        for (auto const& table : _rTables)
        {
            if ( table.second.is() )
            {
                Reference<XNameAccess> xColumns = table.second->getColumns();
                if( xColumns.is() && xColumns->hasByName(rColumnName) && (xColumns->getByName(rColumnName) >>= xColumn) )
                {
                    OSL_ENSURE(xColumn.is(),"Column isn't a propertyset!");
                    // Cannot take "rTableRange = table.first" because that is the fully composed name
                    // that is, catalogName.schemaName.tableName
                    rTableRange = getString(xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TABLENAME)));
                    break; // This column must only exits once
                }
            }
        }
    }
    return xColumn;
}


void OSQLParseTreeIterator::impl_appendError( IParseContext::ErrorCode _eError, const OUString* _pReplaceToken1, const OUString* _pReplaceToken2 )
{
    OUString sErrorMessage = m_rParser.getContext().getErrorMessage( _eError );
    if ( _pReplaceToken1 )
    {
        bool bTwoTokens = ( _pReplaceToken2 != nullptr );
        const char* pPlaceHolder1 = bTwoTokens ? "#1" : "#";
        const OUString sPlaceHolder1 = OUString::createFromAscii( pPlaceHolder1 );

        sErrorMessage = sErrorMessage.replaceFirst( sPlaceHolder1, *_pReplaceToken1 );
        if ( _pReplaceToken2 )
            sErrorMessage = sErrorMessage.replaceFirst( "#2" , *_pReplaceToken2 );
    }

    impl_appendError( SQLException(
        sErrorMessage, nullptr, getStandardSQLState( StandardSQLState::GENERAL_ERROR ), 1000, Any() ) );
}


void OSQLParseTreeIterator::impl_appendError( const SQLException& _rError )
{
    SAL_WARN("connectivity.parse", "Adding error " << exceptionToString(Any(_rError)));
    if ( m_xErrors )
    {
        SQLException* pErrorChain = &*m_xErrors;
        while ( pErrorChain->NextException.hasValue() )
            pErrorChain = static_cast< SQLException* >( pErrorChain->NextException.pData );
        pErrorChain->NextException <<= _rError;
    }
    else
        m_xErrors = _rError;
}

sal_Int32 OSQLParseTreeIterator::getFunctionReturnType(const OSQLParseNode* _pNode )
{
    sal_Int32 nType = DataType::OTHER;
    OUString sFunctionName;
    if ( SQL_ISRULE(_pNode,length_exp) )
    {
        _pNode->getChild(0)->getChild(0)->parseNodeToStr(sFunctionName, m_pImpl->m_xConnection, nullptr, false, false );
        nType = ::connectivity::OSQLParser::getFunctionReturnType( sFunctionName, &m_rParser.getContext() );
    }
    else if ( SQL_ISRULE(_pNode,num_value_exp) || SQL_ISRULE(_pNode,term) || SQL_ISRULE(_pNode,factor) )
    {
        nType = DataType::DOUBLE;
    }
    else
    {
        _pNode->getChild(0)->parseNodeToStr(sFunctionName, m_pImpl->m_xConnection, nullptr, false, false );

        // MIN and MAX have another return type, we have to check the expression itself.
        // @see http://qa.openoffice.org/issues/show_bug.cgi?id=99566
        if ( SQL_ISRULE(_pNode,general_set_fct) && (SQL_ISTOKEN(_pNode->getChild(0),MIN) || SQL_ISTOKEN(_pNode->getChild(0),MAX) ))
        {
            const OSQLParseNode* pValueExp = _pNode->getChild(3);
            if (SQL_ISRULE(pValueExp,column_ref))
            {
                OUString sColumnName;
                OUString aTableRange;
                getColumnRange(pValueExp,sColumnName,aTableRange);
                OSL_ENSURE(!sColumnName.isEmpty(),"Columnname must not be empty!");
                Reference<XPropertySet> xColumn = findColumn( sColumnName, aTableRange, true );

                if ( xColumn.is() )
                {
                    xColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_TYPE)) >>= nType;
                }
            }
            else
            {
                if ( SQL_ISRULE(pValueExp,num_value_exp) || SQL_ISRULE(pValueExp,term) || SQL_ISRULE(pValueExp,factor) )
                {
                    nType = DataType::DOUBLE;
                }
                else if ( SQL_ISRULE(pValueExp,datetime_primary) )
                {
                    switch(pValueExp->getChild(0)->getTokenID() )
                    {
                        case SQL_TOKEN_CURRENT_DATE:
                            nType = DataType::DATE;
                            break;
                        case SQL_TOKEN_CURRENT_TIME:
                            nType = DataType::TIME;
                            break;
                        case SQL_TOKEN_CURRENT_TIMESTAMP:
                            nType = DataType::TIMESTAMP;
                            break;
                    }
                }
                else if ( SQL_ISRULE(pValueExp,value_exp_primary) )
                {
                    nType = getFunctionReturnType(pValueExp->getChild(1));
                }
                else if ( SQL_ISRULE(pValueExp,concatenation)
                        || SQL_ISRULE(pValueExp,char_factor)
                        || SQL_ISRULE(pValueExp,bit_value_fct)
                        || SQL_ISRULE(pValueExp,char_value_fct)
                        || SQL_ISRULE(pValueExp,char_substring_fct)
                        || SQL_ISRULE(pValueExp,fold)
                        || SQL_ISTOKEN(pValueExp,STRING) )
                {
                    nType = DataType::VARCHAR;
                }
            }
            if ( nType == DataType::OTHER )
                nType = DataType::DOUBLE;
        }
        else
            nType = ::connectivity::OSQLParser::getFunctionReturnType( sFunctionName, &m_rParser.getContext() );
    }

    return nType;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */