bump product version to 6.3.0.0.beta1
[LibreOffice.git] / connectivity / source / parse / sqlnode.cxx
blob82b8c75b60e7152c215fe6c759b9c3305da51db3
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/macros.h>
21 #include <connectivity/sqlnode.hxx>
22 #include <connectivity/sqlerror.hxx>
23 #include <connectivity/sqlbison_exports.hxx>
24 #include <connectivity/internalnode.hxx>
25 #define YYBISON 1
26 #include <sqlbison.hxx>
27 #include <connectivity/sqlparse.hxx>
28 #include <connectivity/sqlscan.hxx>
29 #include <com/sun/star/lang/Locale.hpp>
30 #include <com/sun/star/util/XNumberFormatter.hpp>
31 #include <com/sun/star/util/XNumberFormatTypes.hpp>
32 #include <com/sun/star/i18n/LocaleData.hpp>
33 #include <com/sun/star/i18n/NumberFormatIndex.hpp>
34 #include <com/sun/star/beans/XPropertySet.hpp>
35 #include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
36 #include <com/sun/star/sdbc/DataType.hpp>
37 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
38 #include <com/sun/star/sdb/ErrorCondition.hpp>
39 #include <com/sun/star/util/XNumberFormatsSupplier.hpp>
40 #include <com/sun/star/util/XNumberFormats.hpp>
41 #include <com/sun/star/util/NumberFormat.hpp>
42 #include <com/sun/star/i18n/KParseType.hpp>
43 #include <com/sun/star/i18n/KParseTokens.hpp>
44 #include <com/sun/star/i18n/CharacterClassification.hpp>
45 #include <connectivity/dbconversion.hxx>
46 #include <com/sun/star/util/DateTime.hpp>
47 #include <com/sun/star/util/Time.hpp>
48 #include <com/sun/star/util/Date.hpp>
49 #include <TConnection.hxx>
50 #include <comphelper/numbers.hxx>
51 #include <connectivity/dbtools.hxx>
52 #include <connectivity/dbmetadata.hxx>
53 #include <tools/diagnose_ex.h>
54 #include <string.h>
55 #include <algorithm>
56 #include <functional>
57 #include <memory>
58 #include <rtl/ustrbuf.hxx>
59 #include <sal/log.hxx>
61 using namespace ::com::sun::star::sdbc;
62 using namespace ::com::sun::star::util;
63 using namespace ::com::sun::star::beans;
64 using namespace ::com::sun::star::sdb;
65 using namespace ::com::sun::star::uno;
66 using namespace ::com::sun::star::lang;
67 using namespace ::com::sun::star::i18n;
68 using namespace ::com::sun::star;
69 using namespace ::osl;
70 using namespace ::dbtools;
71 using namespace ::comphelper;
73 namespace
76 bool lcl_saveConvertToNumber(const Reference< XNumberFormatter > & _xFormatter,sal_Int32 _nKey,const OUString& _sValue,double& _nrValue)
78 bool bRet = false;
79 try
81 _nrValue = _xFormatter->convertStringToNumber(_nKey, _sValue);
82 bRet = true;
84 catch(Exception&)
87 return bRet;
90 void replaceAndReset(connectivity::OSQLParseNode*& _pResetNode,connectivity::OSQLParseNode* _pNewNode)
92 _pResetNode->getParent()->replace(_pResetNode, _pNewNode);
93 delete _pResetNode;
94 _pResetNode = _pNewNode;
97 /** quotes a string and search for quotes inside the string and replace them with the new quote
98 @param rValue
99 The value to be quoted.
100 @param rQuot
101 The quote
102 @param rQuotToReplace
103 The quote to replace with
104 @return
105 The quoted string.
107 OUString SetQuotation(const OUString& rValue, const OUString& rQuot, const OUString& rQuotToReplace)
109 OUString rNewValue = rQuot;
110 rNewValue += rValue;
111 sal_Int32 nIndex = sal_Int32(-1); // Replace quotes with double quotes or the parser gets into problems
113 if (!rQuot.isEmpty())
117 nIndex += 2;
118 nIndex = rNewValue.indexOf(rQuot,nIndex);
119 if(nIndex != -1)
120 rNewValue = rNewValue.replaceAt(nIndex,rQuot.getLength(),rQuotToReplace);
121 } while (nIndex != -1);
124 rNewValue += rQuot;
125 return rNewValue;
128 bool columnMatchP(const connectivity::OSQLParseNode* pSubTree, const connectivity::SQLParseNodeParameter& rParam)
130 using namespace connectivity;
131 assert(SQL_ISRULE(pSubTree,column_ref));
133 if(!rParam.xField.is())
134 return false;
136 // retrieve the field's name & table range
137 OUString aFieldName;
140 sal_Int32 nNamePropertyId = PROPERTY_ID_NAME;
141 if ( rParam.xField->getPropertySetInfo()->hasPropertyByName( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_REALNAME ) ) )
142 nNamePropertyId = PROPERTY_ID_REALNAME;
143 rParam.xField->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( nNamePropertyId ) ) >>= aFieldName;
145 catch ( Exception& )
149 if(pSubTree->count())
151 const OSQLParseNode* pCol = pSubTree->getChild(pSubTree->count()-1);
152 if (SQL_ISRULE(pCol,column_val))
154 assert(pCol->count() == 1);
155 pCol = pCol->getChild(0);
157 const OSQLParseNode* pTable(nullptr);
158 switch (pSubTree->count())
160 case 1:
161 break;
162 case 3:
163 pTable = pSubTree->getChild(0);
164 break;
165 case 5:
166 case 7:
167 SAL_WARN("connectivity.parse", "SQL: catalog and/or schema in column_ref in predicate");
168 break;
169 default:
170 SAL_WARN("connectivity.parse", "columnMatchP: SQL grammar changed; column_ref has " << pSubTree->count() << " children");
171 assert(false);
172 break;
174 // TODO: not all DBMS match column names case-insensitively...
175 // see XDatabaseMetaData::supportsMixedCaseIdentifiers()
176 // and XDatabaseMetaData::supportsMixedCaseQuotedIdentifiers()
177 if ( // table name matches (or no table name)?
178 ( !pTable || pTable->getTokenValue().equalsIgnoreAsciiCase(rParam.sPredicateTableAlias) )
179 && // column name matches?
180 pCol->getTokenValue().equalsIgnoreAsciiCase(aFieldName)
182 return true;
184 return false;
188 namespace connectivity
191 SQLParseNodeParameter::SQLParseNodeParameter( const Reference< XConnection >& _rxConnection,
192 const Reference< XNumberFormatter >& _xFormatter, const Reference< XPropertySet >& _xField,
193 const OUString &_sPredicateTableAlias,
194 const Locale& _rLocale, const IParseContext* _pContext,
195 bool _bIntl, bool _bQuote, sal_Char _cDecSep, bool _bPredicate, bool _bParseToSDBC )
196 :rLocale(_rLocale)
197 ,aMetaData( _rxConnection )
198 ,pParser( nullptr )
199 ,pSubQueryHistory( new QueryNameSet )
200 ,xFormatter(_xFormatter)
201 ,xField(_xField)
202 ,sPredicateTableAlias(_sPredicateTableAlias)
203 ,m_rContext( _pContext ? *_pContext : OSQLParser::s_aDefaultContext )
204 ,cDecSep(_cDecSep)
205 ,bQuote(_bQuote)
206 ,bInternational(_bIntl)
207 ,bPredicate(_bPredicate)
208 ,bParseToSDBCLevel( _bParseToSDBC )
212 OUString OSQLParseNode::convertDateString(const SQLParseNodeParameter& rParam, const OUString& rString)
214 Date aDate = DBTypeConversion::toDate(rString);
215 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
216 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
218 double fDate = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
219 sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 36; // XXX hack
220 return rParam.xFormatter->convertNumberToString(nKey, fDate);
224 OUString OSQLParseNode::convertDateTimeString(const SQLParseNodeParameter& rParam, const OUString& rString)
226 DateTime aDate = DBTypeConversion::toDateTime(rString);
227 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
228 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
230 double fDateTime = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
231 sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 51; // XXX hack
232 return rParam.xFormatter->convertNumberToString(nKey, fDateTime);
236 OUString OSQLParseNode::convertTimeString(const SQLParseNodeParameter& rParam, const OUString& rString)
238 css::util::Time aTime = DBTypeConversion::toTime(rString);
239 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
241 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
243 double fTime = DBTypeConversion::toDouble(aTime);
244 sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 41; // XXX hack
245 return rParam.xFormatter->convertNumberToString(nKey, fTime);
249 void OSQLParseNode::parseNodeToStr(OUString& rString,
250 const Reference< XConnection >& _rxConnection,
251 const IParseContext* pContext,
252 bool _bIntl,
253 bool _bQuote) const
255 parseNodeToStr(
256 rString, _rxConnection, nullptr, nullptr, OUString(),
257 pContext ? pContext->getPreferredLocale() : OParseContext::getDefaultLocale(),
258 pContext, _bIntl, _bQuote, '.', false );
262 void OSQLParseNode::parseNodeToPredicateStr(OUString& rString,
263 const Reference< XConnection >& _rxConnection,
264 const Reference< XNumberFormatter > & xFormatter,
265 const css::lang::Locale& rIntl,
266 sal_Char _cDec,
267 const IParseContext* pContext ) const
269 OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
271 if (xFormatter.is())
272 parseNodeToStr(rString, _rxConnection, xFormatter, nullptr, OUString(), rIntl, pContext, true, true, _cDec, true);
276 void OSQLParseNode::parseNodeToPredicateStr(OUString& rString,
277 const Reference< XConnection > & _rxConnection,
278 const Reference< XNumberFormatter > & xFormatter,
279 const Reference< XPropertySet > & _xField,
280 const OUString &_sPredicateTableAlias,
281 const css::lang::Locale& rIntl,
282 sal_Char _cDec,
283 const IParseContext* pContext ) const
285 OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
287 if (xFormatter.is())
288 parseNodeToStr( rString, _rxConnection, xFormatter, _xField, _sPredicateTableAlias, rIntl, pContext, true, true, _cDec, true );
292 void OSQLParseNode::parseNodeToStr(OUString& rString,
293 const Reference< XConnection > & _rxConnection,
294 const Reference< XNumberFormatter > & xFormatter,
295 const Reference< XPropertySet > & _xField,
296 const OUString &_sPredicateTableAlias,
297 const css::lang::Locale& rIntl,
298 const IParseContext* pContext,
299 bool _bIntl,
300 bool _bQuote,
301 sal_Char _cDecSep,
302 bool _bPredicate) const
304 OSL_ENSURE( _rxConnection.is(), "OSQLParseNode::parseNodeToStr: invalid connection!" );
306 if ( _rxConnection.is() )
308 OUStringBuffer sBuffer = rString;
311 OSQLParseNode::impl_parseNodeToString_throw( sBuffer,
312 SQLParseNodeParameter(
313 _rxConnection, xFormatter, _xField, _sPredicateTableAlias, rIntl, pContext,
314 _bIntl, _bQuote, _cDecSep, _bPredicate, false
315 ) );
317 catch( const SQLException& )
319 SAL_WARN( "connectivity.parse", "OSQLParseNode::parseNodeToStr: this should not throw!" );
320 // our callers don't expect this method to throw anything. The only known situation
321 // where impl_parseNodeToString_throw can throw is when there is a cyclic reference
322 // in the sub queries, but this cannot be the case here, as we do not parse to
323 // SDBC level.
325 rString = sBuffer.makeStringAndClear();
329 bool OSQLParseNode::parseNodeToExecutableStatement( OUString& _out_rString, const Reference< XConnection >& _rxConnection,
330 OSQLParser& _rParser, css::sdbc::SQLException* _pErrorHolder ) const
332 OSL_PRECOND( _rxConnection.is(), "OSQLParseNode::parseNodeToExecutableStatement: invalid connection!" );
333 SQLParseNodeParameter aParseParam( _rxConnection,
334 nullptr, nullptr, OUString(), OParseContext::getDefaultLocale(), nullptr, false, true, '.', false, true );
336 if ( aParseParam.aMetaData.supportsSubqueriesInFrom() )
338 Reference< XQueriesSupplier > xSuppQueries( _rxConnection, UNO_QUERY );
339 OSL_ENSURE( xSuppQueries.is(), "OSQLParseNode::parseNodeToExecutableStatement: cannot substitute everything without a QueriesSupplier!" );
340 if ( xSuppQueries.is() )
341 aParseParam.xQueries = xSuppQueries->getQueries();
344 aParseParam.pParser = &_rParser;
346 // LIMIT keyword differs in Firebird
347 OSQLParseNode* pTableExp = getChild(3);
348 Reference< XDatabaseMetaData > xMeta( _rxConnection->getMetaData() );
349 OUString sLimitValue;
350 if( pTableExp->getChild(6)->count() >= 2 && pTableExp->getChild(6)->getChild(1)
351 && (xMeta->getURL().equalsIgnoreAsciiCase("sdbc:embedded:firebird")
352 || xMeta->getURL().startsWithIgnoreAsciiCase("sdbc:firebird:")))
354 sLimitValue = pTableExp->getChild(6)->getChild(1)->getTokenValue();
355 pTableExp->removeAt(6);
358 _out_rString.clear();
359 OUStringBuffer sBuffer;
360 bool bSuccess = false;
363 impl_parseNodeToString_throw( sBuffer, aParseParam );
364 bSuccess = true;
366 catch( const SQLException& e )
368 if ( _pErrorHolder )
369 *_pErrorHolder = e;
372 if(sLimitValue.getLength() > 0)
374 constexpr char SELECT_KEYWORD[] = "SELECT";
375 sBuffer.insert(sBuffer.indexOf(SELECT_KEYWORD) + strlen(SELECT_KEYWORD),
376 " FIRST " + sLimitValue);
379 _out_rString = sBuffer.makeStringAndClear();
380 return bSuccess;
384 namespace
386 bool lcl_isAliasNamePresent( const OSQLParseNode& _rTableNameNode )
388 return !OSQLParseNode::getTableRange(_rTableNameNode.getParent()).isEmpty();
393 void OSQLParseNode::impl_parseNodeToString_throw(OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple) const
395 if ( isToken() )
397 parseLeaf(rString,rParam);
398 return;
401 // Lets see how many nodes this subtree has
402 sal_uInt32 nCount = count();
404 bool bHandled = false;
405 switch ( getKnownRuleID() )
407 // special handling for parameters
408 case parameter:
410 bSimple=false;
411 if(!rString.isEmpty())
412 rString.append(" ");
413 if (nCount == 1) // ?
414 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
415 else if (rParam.bParseToSDBCLevel && rParam.aMetaData.shouldSubstituteParameterNames())
417 rString.append("?");
419 else if (nCount == 2) // :Name
421 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
422 rString.append(m_aChildren[1]->m_aNodeValue);
423 } // [Name]
424 else
426 assert (nCount == 3);
427 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
428 rString.append(m_aChildren[1]->m_aNodeValue);
429 rString.append(m_aChildren[2]->m_aNodeValue);
431 bHandled = true;
433 break;
435 // table refs
436 case table_ref:
437 bSimple=false;
438 if ( ( nCount == 2 ) || ( nCount == 3 ) || ( nCount == 5 ) )
440 impl_parseTableRangeNodeToString_throw( rString, rParam );
441 bHandled = true;
443 break;
445 // table name - might be a query name
446 case table_name:
447 bSimple=false;
448 bHandled = impl_parseTableNameNodeToString_throw( rString, rParam );
449 break;
451 case as_clause:
452 bSimple=false;
453 assert(nCount == 0 || nCount == 2);
454 if (nCount == 2)
456 if ( rParam.aMetaData.generateASBeforeCorrelationName() )
457 rString.append(" AS ");
458 m_aChildren[1]->impl_parseNodeToString_throw( rString, rParam, false );
460 bHandled = true;
461 break;
463 case opt_as:
464 assert(nCount == 0);
465 bHandled = true;
466 break;
468 case like_predicate:
469 // Depending on whether international is given, LIKE is treated differently
470 // international: *, ? are placeholders
471 // else SQL92 conform: %, _
472 impl_parseLikeNodeToString_throw( rString, rParam, bSimple );
473 bHandled = true;
474 break;
476 case general_set_fct:
477 case set_fct_spec:
478 case position_exp:
479 case extract_exp:
480 case length_exp:
481 case char_value_fct:
482 bSimple=false;
483 if (!addDateValue(rString, rParam))
485 // Do not quote function name
486 SQLParseNodeParameter aNewParam(rParam);
487 aNewParam.bQuote = ( SQL_ISRULE(this,length_exp) || SQL_ISRULE(this,char_value_fct) );
489 m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam, false );
490 aNewParam.bQuote = rParam.bQuote;
491 //aNewParam.bPredicate = sal_False; // disable [ ] around names // look at i73215
492 OUStringBuffer aStringPara;
493 for (sal_uInt32 i=1; i<nCount; i++)
495 const OSQLParseNode * pSubTree = m_aChildren[i].get();
496 if (pSubTree)
498 pSubTree->impl_parseNodeToString_throw( aStringPara, aNewParam, false );
500 // In the comma lists, put commas in-between all subtrees
501 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i < (nCount - 1)))
502 aStringPara.append(",");
504 else
505 i++;
507 rString.append(aStringPara.makeStringAndClear());
509 bHandled = true;
510 break;
511 case odbc_call_spec:
512 case subquery:
513 case term:
514 case factor:
515 case window_function:
516 case cast_spec:
517 case num_value_exp:
518 bSimple = false;
519 break;
520 default:
521 break;
522 } // switch ( getKnownRuleID() )
524 if ( !bHandled )
526 for (auto i = m_aChildren.begin(); i != m_aChildren.end();)
528 const OSQLParseNode* pSubTree = i->get();
529 if ( !pSubTree )
531 ++i;
532 continue;
535 SQLParseNodeParameter aNewParam(rParam);
537 // don't replace the field for subqueries
538 if (rParam.xField.is() && SQL_ISRULE(pSubTree,subquery))
539 aNewParam.xField = nullptr;
541 // When we are building a criterion inside a query view,
542 // simplify criterion display by removing:
543 // "currentFieldName"
544 // "currentFieldName" =
545 // but only in simple expressions.
546 // This means anything that is made of:
547 // (see the rules conditionalised by inPredicateCheck() in sqlbison.y).
548 // - parentheses
549 // - logical operators (and, or, not)
550 // - comparison operators (IS, =, >, <, BETWEEN, LIKE, ...)
551 // but *not* e.g. in function arguments
552 if (bSimple && rParam.bPredicate && rParam.xField.is() && SQL_ISRULE(pSubTree,column_ref))
554 if (columnMatchP(pSubTree, rParam))
556 // skip field
557 ++i;
558 // if the following node is the comparison operator'=',
559 // we filter it as well
560 if (SQL_ISRULE(this, comparison_predicate))
562 if(i != m_aChildren.end())
564 pSubTree = i->get();
565 if (pSubTree && pSubTree->getNodeType() == SQLNodeType::Equal)
566 ++i;
570 else
572 pSubTree->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
573 ++i;
575 // In the comma lists, put commas in-between all subtrees
576 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i != m_aChildren.end()))
577 rString.append(",");
580 else
582 pSubTree->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
583 ++i;
585 // In the comma lists, put commas in-between all subtrees
586 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i != m_aChildren.end()))
588 if (SQL_ISRULE(this,value_exp_commalist) && rParam.bPredicate)
589 rString.append(";");
590 else
591 rString.append(",");
594 // The right hand-side of these operators is not simple
595 switch ( getKnownRuleID() )
597 case general_set_fct:
598 case set_fct_spec:
599 case position_exp:
600 case extract_exp:
601 case length_exp:
602 case char_value_fct:
603 case odbc_call_spec:
604 case subquery:
605 case comparison_predicate:
606 case between_predicate:
607 case like_predicate:
608 case test_for_null:
609 case in_predicate:
610 case existence_test:
611 case unique_test:
612 case all_or_any_predicate:
613 case join_condition:
614 case comparison_predicate_part_2:
615 case parenthesized_boolean_value_expression:
616 case other_like_predicate_part_2:
617 case between_predicate_part_2:
618 bSimple=false;
619 break;
620 default:
621 break;
628 bool OSQLParseNode::impl_parseTableNameNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const
630 // is the table_name part of a table_ref?
631 OSL_ENSURE( getParent(), "OSQLParseNode::impl_parseTableNameNodeToString_throw: table_name without parent?" );
632 if ( !getParent() || ( getParent()->getKnownRuleID() != table_ref ) )
633 return false;
635 // if it's a query, maybe we need to substitute the SQL statement ...
636 if ( !rParam.bParseToSDBCLevel )
637 return false;
639 if ( !rParam.xQueries.is() )
640 // connection does not support queries in queries, or was no query supplier
641 return false;
645 OUString sTableOrQueryName( getChild(0)->getTokenValue() );
646 bool bIsQuery = rParam.xQueries->hasByName( sTableOrQueryName );
647 if ( !bIsQuery )
648 return false;
650 // avoid recursion (e.g. "foo" defined as "SELECT * FROM bar" and "bar" defined as "SELECT * FROM foo".
651 if ( rParam.pSubQueryHistory->find( sTableOrQueryName ) != rParam.pSubQueryHistory->end() )
653 OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: no parser?" );
654 if ( rParam.pParser )
656 const SQLError& rErrors( rParam.pParser->getErrorHelper() );
657 rErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
659 else
661 SQLError aErrors;
662 aErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
665 rParam.pSubQueryHistory->insert( sTableOrQueryName );
667 Reference< XPropertySet > xQuery( rParam.xQueries->getByName( sTableOrQueryName ), UNO_QUERY_THROW );
669 // substitute the query name with the constituting command
670 OUString sCommand;
671 OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_COMMAND ) ) >>= sCommand );
673 bool bEscapeProcessing = false;
674 OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ) ) >>= bEscapeProcessing );
676 // the query we found here might itself be based on another query, so parse it recursively
677 OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: cannot analyze sub queries without a parser!" );
678 if ( bEscapeProcessing && rParam.pParser )
680 OUString sError;
681 std::unique_ptr< OSQLParseNode > pSubQueryNode( rParam.pParser->parseTree( sError, sCommand ) );
682 if (pSubQueryNode)
684 // parse the sub-select to SDBC level, too
685 OUStringBuffer sSubSelect;
686 pSubQueryNode->impl_parseNodeToString_throw( sSubSelect, rParam, false );
687 if ( !sSubSelect.isEmpty() )
688 sCommand = sSubSelect.makeStringAndClear();
692 rString.append( " ( " );
693 rString.append(sCommand);
694 rString.append( " )" );
696 // append the query name as table alias, since it might be referenced in other
697 // parts of the statement - but only if there's no other alias name present
698 if ( !lcl_isAliasNamePresent( *this ) )
700 rString.append( " AS " );
701 if ( rParam.bQuote )
702 rString.append(SetQuotation( sTableOrQueryName,
703 rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
706 // don't forget to remove the query name from the history, else multiple inclusions
707 // won't work
708 // #i69227# / 2006-10-10 / frank.schoenheit@sun.com
709 rParam.pSubQueryHistory->erase( sTableOrQueryName );
711 return true;
713 catch( const SQLException& )
715 throw;
717 catch( const Exception& )
719 DBG_UNHANDLED_EXCEPTION("connectivity.parse");
721 return false;
725 void OSQLParseNode::impl_parseTableRangeNodeToString_throw(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
727 OSL_PRECOND( ( count() == 2 ) || ( count() == 3 ) || ( count() == 5 ) ,"Illegal count");
729 // rString += " ";
730 std::for_each(m_aChildren.begin(),m_aChildren.end(),
731 [&] (std::unique_ptr<OSQLParseNode> const & pNode) { pNode->impl_parseNodeToString_throw(rString, rParam, false); });
735 void OSQLParseNode::impl_parseLikeNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple ) const
737 assert(SQL_ISRULE(this,like_predicate));
738 OSL_ENSURE(count() == 2,"count != 2: Prepare for GPF");
740 const OSQLParseNode* pEscNode = nullptr;
741 const OSQLParseNode* pParaNode = nullptr;
743 SQLParseNodeParameter aNewParam(rParam);
744 //aNewParam.bQuote = sal_True; // why setting this to true? @see https://bz.apache.org/ooo/show_bug.cgi?id=75557
746 if ( !(bSimple && rParam.bPredicate && rParam.xField.is() && SQL_ISRULE(m_aChildren[0],column_ref) && columnMatchP(m_aChildren[0].get(), rParam)) )
747 m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
749 const OSQLParseNode* pPart2 = m_aChildren[1].get();
750 pPart2->getChild(0)->impl_parseNodeToString_throw( rString, aNewParam, false );
751 pPart2->getChild(1)->impl_parseNodeToString_throw( rString, aNewParam, false );
752 pParaNode = pPart2->getChild(2);
753 pEscNode = pPart2->getChild(3);
755 if (pParaNode->isToken())
757 OUString aStr = ConvertLikeToken(pParaNode, pEscNode, rParam.bInternational);
758 rString.append(" ");
759 rString.append(SetQuotation(aStr,"\'","\'\'"));
761 else
762 pParaNode->impl_parseNodeToString_throw( rString, aNewParam, false );
764 pEscNode->impl_parseNodeToString_throw( rString, aNewParam, false );
768 bool OSQLParseNode::getTableComponents(const OSQLParseNode* _pTableNode,
769 css::uno::Any &_rCatalog,
770 OUString &_rSchema,
771 OUString &_rTable,
772 const Reference< XDatabaseMetaData >& _xMetaData)
774 OSL_ENSURE(_pTableNode,"Wrong use of getTableComponents! _pTableNode is not allowed to be null!");
775 if(_pTableNode)
777 const bool bSupportsCatalog = _xMetaData.is() && _xMetaData->supportsCatalogsInDataManipulation();
778 const bool bSupportsSchema = _xMetaData.is() && _xMetaData->supportsSchemasInDataManipulation();
779 const OSQLParseNode* pTableNode = _pTableNode;
780 // clear the parameter given
781 _rCatalog = Any();
782 _rSchema.clear();
783 _rTable.clear();
784 // see rule catalog_name: in sqlbison.y
785 if (SQL_ISRULE(pTableNode,catalog_name))
787 OSL_ENSURE(pTableNode->getChild(0) && pTableNode->getChild(0)->isToken(),"Invalid parsenode!");
788 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
789 pTableNode = pTableNode->getChild(2);
791 // check if we have schema_name rule
792 if(SQL_ISRULE(pTableNode,schema_name))
794 if ( bSupportsCatalog && !bSupportsSchema )
795 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
796 else
797 _rSchema = pTableNode->getChild(0)->getTokenValue();
798 pTableNode = pTableNode->getChild(2);
800 // check if we have table_name rule
801 if(SQL_ISRULE(pTableNode,table_name))
803 _rTable = pTableNode->getChild(0)->getTokenValue();
805 else
807 SAL_WARN( "connectivity.parse","Error in parse tree!");
810 return !_rTable.isEmpty();
813 void OSQLParser::killThousandSeparator(OSQLParseNode* pLiteral)
815 if ( pLiteral )
817 if ( s_xLocaleData->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
819 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace('.', sal_Unicode());
820 // and replace decimal
821 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', '.');
823 else
824 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', sal_Unicode());
828 OSQLParseNode* OSQLParser::convertNode(sal_Int32 nType, OSQLParseNode* pLiteral)
830 if ( !pLiteral )
831 return nullptr;
833 OSQLParseNode* pReturn = pLiteral;
835 if ( ( pLiteral->isRule() && !SQL_ISRULE(pLiteral,value_exp) ) || SQL_ISTOKEN(pLiteral,FALSE) || SQL_ISTOKEN(pLiteral,TRUE) )
837 switch(nType)
839 case DataType::CHAR:
840 case DataType::VARCHAR:
841 case DataType::LONGVARCHAR:
842 case DataType::CLOB:
843 if ( !SQL_ISRULE(pReturn,char_value_exp) && !buildStringNodes(pReturn) )
844 pReturn = nullptr;
845 break;
846 default:
847 break;
850 else
852 switch(pLiteral->getNodeType())
854 case SQLNodeType::String:
855 switch(nType)
857 case DataType::CHAR:
858 case DataType::VARCHAR:
859 case DataType::LONGVARCHAR:
860 case DataType::CLOB:
861 break;
862 case DataType::DATE:
863 case DataType::TIME:
864 case DataType::TIMESTAMP:
865 if (m_xFormatter.is())
866 pReturn = buildDate( nType, pReturn);
867 break;
868 default:
869 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidCompare);
870 break;
872 break;
873 case SQLNodeType::AccessDate:
874 switch(nType)
876 case DataType::DATE:
877 case DataType::TIME:
878 case DataType::TIMESTAMP:
879 if ( m_xFormatter.is() )
880 pReturn = buildDate( nType, pReturn);
881 else
882 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidDateCompare);
883 break;
884 default:
885 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidCompare);
886 break;
888 break;
889 case SQLNodeType::IntNum:
890 switch(nType)
892 case DataType::BIT:
893 case DataType::BOOLEAN:
894 case DataType::DECIMAL:
895 case DataType::NUMERIC:
896 case DataType::TINYINT:
897 case DataType::SMALLINT:
898 case DataType::INTEGER:
899 case DataType::BIGINT:
900 case DataType::FLOAT:
901 case DataType::REAL:
902 case DataType::DOUBLE:
903 // kill thousand separators if any
904 killThousandSeparator(pReturn);
905 break;
906 case DataType::CHAR:
907 case DataType::VARCHAR:
908 case DataType::LONGVARCHAR:
909 case DataType::CLOB:
910 pReturn = buildNode_STR_NUM(pReturn);
911 break;
912 default:
913 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidIntCompare);
914 break;
916 break;
917 case SQLNodeType::ApproxNum:
918 switch(nType)
920 case DataType::DECIMAL:
921 case DataType::NUMERIC:
922 case DataType::FLOAT:
923 case DataType::REAL:
924 case DataType::DOUBLE:
925 // kill thousand separators if any
926 killThousandSeparator(pReturn);
927 break;
928 case DataType::CHAR:
929 case DataType::VARCHAR:
930 case DataType::LONGVARCHAR:
931 case DataType::CLOB:
932 pReturn = buildNode_STR_NUM(pReturn);
933 break;
934 case DataType::INTEGER:
935 default:
936 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidRealCompare);
937 break;
939 break;
940 default:
944 return pReturn;
947 sal_Int16 OSQLParser::buildPredicateRule(OSQLParseNode*& pAppend, OSQLParseNode* pLiteral, OSQLParseNode* pCompare, OSQLParseNode* pLiteral2)
949 OSL_ENSURE(inPredicateCheck(),"Only in predicate check allowed!");
950 sal_Int16 nErg = 0;
951 if ( m_xField.is() )
953 sal_Int32 nType = 0;
956 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
958 catch( Exception& )
960 return nErg;
963 OSQLParseNode* pNode1 = convertNode(nType,pLiteral);
964 if ( pNode1 )
966 OSQLParseNode* pNode2 = convertNode(nType,pLiteral2);
967 if ( m_sErrorMessage.isEmpty() )
968 nErg = buildNode(pAppend,pCompare,pNode1,pNode2);
971 if (!pCompare->getParent()) // I have no parent so I was not used and I must die :-)
972 delete pCompare;
973 return nErg;
976 sal_Int16 OSQLParser::buildLikeRule(OSQLParseNode* pAppend, OSQLParseNode*& pLiteral, const OSQLParseNode* pEscape)
978 sal_Int16 nErg = 0;
979 sal_Int32 nType = 0;
981 if (!m_xField.is())
982 return nErg;
985 Any aValue;
987 aValue = m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE));
988 aValue >>= nType;
991 catch( Exception& )
993 return nErg;
996 switch (nType)
998 case DataType::CHAR:
999 case DataType::VARCHAR:
1000 case DataType::LONGVARCHAR:
1001 case DataType::CLOB:
1002 if(pLiteral->isRule())
1004 pAppend->append(pLiteral);
1005 nErg = 1;
1007 else
1009 switch(pLiteral->getNodeType())
1011 case SQLNodeType::String:
1012 pLiteral->m_aNodeValue = ConvertLikeToken(pLiteral, pEscape, false);
1013 pAppend->append(pLiteral);
1014 nErg = 1;
1015 break;
1016 case SQLNodeType::ApproxNum:
1017 if (m_xFormatter.is() && m_nFormatKey)
1019 sal_Int16 nScale = 0;
1022 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, "Decimals" );
1023 aValue >>= nScale;
1025 catch( Exception& )
1029 pAppend->append(new OSQLInternalNode(stringToDouble(pLiteral->getTokenValue(),nScale),SQLNodeType::String));
1031 else
1032 pAppend->append(new OSQLInternalNode(pLiteral->getTokenValue(),SQLNodeType::String));
1034 delete pLiteral;
1035 nErg = 1;
1036 break;
1037 default:
1038 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::ValueNoLike);
1039 m_sErrorMessage = m_sErrorMessage.replaceAt(m_sErrorMessage.indexOf("#1"),2,pLiteral->getTokenValue());
1040 break;
1043 break;
1044 default:
1045 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::FieldNoLike);
1046 break;
1048 return nErg;
1051 OSQLParseNode* OSQLParser::buildNode_Date(const double& fValue, sal_Int32 nType)
1053 OSQLParseNode* pNewNode = new OSQLInternalNode("", SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::set_fct_spec));
1054 pNewNode->append(new OSQLInternalNode("{", SQLNodeType::Punctuation));
1055 OSQLParseNode* pDateNode = new OSQLInternalNode("", SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::odbc_fct_spec));
1056 pNewNode->append(pDateNode);
1057 pNewNode->append(new OSQLInternalNode("}", SQLNodeType::Punctuation));
1059 switch (nType)
1061 case DataType::DATE:
1063 Date aDate = DBTypeConversion::toDate(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1064 OUString aString = DBTypeConversion::toDateString(aDate);
1065 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_D));
1066 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1067 break;
1069 case DataType::TIME:
1071 css::util::Time aTime = DBTypeConversion::toTime(fValue);
1072 OUString aString = DBTypeConversion::toTimeString(aTime);
1073 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_T));
1074 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1075 break;
1077 case DataType::TIMESTAMP:
1079 DateTime aDateTime = DBTypeConversion::toDateTime(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1080 if (aDateTime.Seconds || aDateTime.Minutes || aDateTime.Hours)
1082 OUString aString = DBTypeConversion::toDateTimeString(aDateTime);
1083 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_TS));
1084 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1086 else
1088 Date aDate(aDateTime.Day,aDateTime.Month,aDateTime.Year);
1089 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_D));
1090 pDateNode->append(new OSQLInternalNode(DBTypeConversion::toDateString(aDate), SQLNodeType::String));
1092 break;
1096 return pNewNode;
1099 OSQLParseNode* OSQLParser::buildNode_STR_NUM(OSQLParseNode*& _pLiteral)
1101 OSQLParseNode* pReturn = nullptr;
1102 if ( _pLiteral )
1104 if (m_nFormatKey)
1106 sal_Int16 nScale = 0;
1109 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, "Decimals" );
1110 aValue >>= nScale;
1112 catch( Exception& )
1116 pReturn = new OSQLInternalNode(stringToDouble(_pLiteral->getTokenValue(),nScale),SQLNodeType::String);
1118 else
1119 pReturn = new OSQLInternalNode(_pLiteral->getTokenValue(),SQLNodeType::String);
1121 delete _pLiteral;
1122 _pLiteral = nullptr;
1124 return pReturn;
1127 OUString OSQLParser::stringToDouble(const OUString& _rValue,sal_Int16 _nScale)
1129 OUString aValue;
1130 if(!m_xCharClass.is())
1131 m_xCharClass = CharacterClassification::create( m_xContext );
1132 if( s_xLocaleData.is() )
1136 ParseResult aResult = m_xCharClass->parsePredefinedToken(KParseType::ANY_NUMBER,_rValue,0,m_pData->aLocale,0,OUString(),KParseType::ANY_NUMBER,OUString());
1137 if((aResult.TokenType & KParseType::IDENTNAME) && aResult.EndPos == _rValue.getLength())
1139 aValue = OUString::number(aResult.Value);
1140 sal_Int32 nPos = aValue.lastIndexOf('.');
1141 if((nPos+_nScale) < aValue.getLength())
1142 aValue = aValue.replaceAt(nPos+_nScale,aValue.getLength()-nPos-_nScale,OUString());
1143 aValue = aValue.replaceAt(aValue.lastIndexOf('.'),1,s_xLocaleData->getLocaleItem(m_pData->aLocale).decimalSeparator);
1144 return aValue;
1147 catch(Exception&)
1151 return aValue;
1155 ::osl::Mutex& OSQLParser::getMutex()
1157 static ::osl::Mutex aMutex;
1158 return aMutex;
1162 std::unique_ptr<OSQLParseNode> OSQLParser::predicateTree(OUString& rErrorMessage, const OUString& rStatement,
1163 const Reference< css::util::XNumberFormatter > & xFormatter,
1164 const Reference< XPropertySet > & xField,
1165 bool bUseRealName)
1167 // Guard the parsing
1168 ::osl::MutexGuard aGuard(getMutex());
1169 // must be reset
1170 setParser(this);
1173 // reset the parser
1174 m_xField = xField;
1175 m_xFormatter = xFormatter;
1177 if (m_xField.is())
1179 sal_Int32 nType=0;
1182 // get the field name
1183 OUString aString;
1185 // retrieve the fields name
1186 // #75243# use the RealName of the column if there is any otherwise the name which could be the alias
1187 // of the field
1188 Reference< XPropertySetInfo> xInfo = m_xField->getPropertySetInfo();
1189 if ( bUseRealName && xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)))
1190 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)) >>= aString;
1191 else
1192 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aString;
1194 m_sFieldName = aString;
1196 // get the field format key
1197 if ( xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)))
1198 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) >>= m_nFormatKey;
1199 else
1200 m_nFormatKey = 0;
1202 // get the field type
1203 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
1205 catch ( Exception& )
1207 OSL_ASSERT(false);
1210 if (m_nFormatKey && m_xFormatter.is())
1212 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_LOCALE) );
1213 OSL_ENSURE(aValue.getValueType() == cppu::UnoType<css::lang::Locale>::get(), "OSQLParser::PredicateTree : invalid language property !");
1215 if (aValue.getValueType() == cppu::UnoType<css::lang::Locale>::get())
1216 aValue >>= m_pData->aLocale;
1218 else
1219 m_pData->aLocale = m_pContext->getPreferredLocale();
1221 if ( m_xFormatter.is() )
1225 Reference< css::util::XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1226 if ( xFormatSup.is() )
1228 Reference< css::util::XNumberFormats > xFormats = xFormatSup->getNumberFormats();
1229 if ( xFormats.is() )
1231 css::lang::Locale aLocale;
1232 aLocale.Language = "en";
1233 aLocale.Country = "US";
1234 OUString sFormat("YYYY-MM-DD");
1235 m_nDateFormatKey = xFormats->queryKey(sFormat,aLocale,false);
1236 if ( m_nDateFormatKey == sal_Int32(-1) )
1237 m_nDateFormatKey = xFormats->addNew(sFormat, aLocale);
1241 catch ( Exception& )
1243 SAL_WARN( "connectivity.parse","DateFormatKey");
1247 switch (nType)
1249 case DataType::DATE:
1250 case DataType::TIME:
1251 case DataType::TIMESTAMP:
1252 s_pScanner->SetRule(OSQLScanner::GetDATERule());
1253 break;
1254 case DataType::CHAR:
1255 case DataType::VARCHAR:
1256 case DataType::LONGVARCHAR:
1257 case DataType::CLOB:
1258 s_pScanner->SetRule(OSQLScanner::GetSTRINGRule());
1259 break;
1260 default:
1261 if ( s_xLocaleData->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
1262 s_pScanner->SetRule(OSQLScanner::GetGERRule());
1263 else
1264 s_pScanner->SetRule(OSQLScanner::GetENGRule());
1268 else
1269 s_pScanner->SetRule(OSQLScanner::GetSQLRule());
1271 s_pScanner->prepareScan(rStatement, m_pContext, true);
1273 SQLyylval.pParseNode = nullptr;
1274 // SQLyypvt = NULL;
1275 m_pParseTree = nullptr;
1276 m_sErrorMessage.clear();
1278 // Start the parser
1279 if (SQLyyparse() != 0)
1281 m_sFieldName.clear();
1282 m_xField.clear();
1283 m_xFormatter.clear();
1284 m_nFormatKey = 0;
1285 m_nDateFormatKey = 0;
1287 if (m_sErrorMessage.isEmpty())
1288 m_sErrorMessage = s_pScanner->getErrorMessage();
1289 if (m_sErrorMessage.isEmpty())
1290 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::General);
1292 rErrorMessage = m_sErrorMessage;
1294 // clear the garbage collector
1295 (*s_pGarbageCollector)->clearAndDelete();
1296 return nullptr;
1298 else
1300 (*s_pGarbageCollector)->clear();
1302 m_sFieldName.clear();
1303 m_xField.clear();
1304 m_xFormatter.clear();
1305 m_nFormatKey = 0;
1306 m_nDateFormatKey = 0;
1308 // Return the result (the root parse node):
1310 // Instead, the parse method sets the member pParseTree and simply returns that
1311 OSL_ENSURE(m_pParseTree != nullptr,"OSQLParser: Parser did not return a ParseTree!");
1312 return std::move(m_pParseTree);
1317 OSQLParser::OSQLParser(const css::uno::Reference< css::uno::XComponentContext >& rxContext, const IParseContext* _pContext)
1318 :m_pContext(_pContext)
1319 ,m_pData( new OSQLParser_Data )
1320 ,m_nFormatKey(0)
1321 ,m_nDateFormatKey(0)
1322 ,m_xContext(rxContext)
1326 setParser(this);
1328 #ifdef SQLYYDEBUG
1329 #ifdef SQLYYDEBUG_ON
1330 SQLyydebug = 1;
1331 #endif
1332 #endif
1334 ::osl::MutexGuard aGuard(getMutex());
1335 // Do we have to initialize the data?
1336 if (s_nRefCount == 0)
1338 s_pScanner = new OSQLScanner();
1339 s_pScanner->setScanner();
1340 s_pGarbageCollector = new OSQLParseNodesGarbageCollector();
1342 if(!s_xLocaleData.is())
1343 s_xLocaleData = LocaleData::create(m_xContext);
1345 // reset to UNKNOWN_RULE
1346 static_assert(OSQLParseNode::UNKNOWN_RULE==0, "UNKNOWN_RULE must be 0 for memset to 0 to work");
1347 memset(OSQLParser::s_nRuleIDs,0,sizeof(OSQLParser::s_nRuleIDs));
1349 const struct
1351 OSQLParseNode::Rule eRule; // the parse node's ID for the rule
1352 OString sRuleName; // the name of the rule ("select_statement")
1353 } aRuleDescriptions[] =
1355 { OSQLParseNode::select_statement, "select_statement" },
1356 { OSQLParseNode::table_exp, "table_exp" },
1357 { OSQLParseNode::table_ref_commalist, "table_ref_commalist" },
1358 { OSQLParseNode::table_ref, "table_ref" },
1359 { OSQLParseNode::catalog_name, "catalog_name" },
1360 { OSQLParseNode::schema_name, "schema_name" },
1361 { OSQLParseNode::table_name, "table_name" },
1362 { OSQLParseNode::opt_column_commalist, "opt_column_commalist" },
1363 { OSQLParseNode::column_commalist, "column_commalist" },
1364 { OSQLParseNode::column_ref_commalist, "column_ref_commalist" },
1365 { OSQLParseNode::column_ref, "column_ref" },
1366 { OSQLParseNode::opt_order_by_clause, "opt_order_by_clause" },
1367 { OSQLParseNode::ordering_spec_commalist, "ordering_spec_commalist" },
1368 { OSQLParseNode::ordering_spec, "ordering_spec" },
1369 { OSQLParseNode::opt_asc_desc, "opt_asc_desc" },
1370 { OSQLParseNode::where_clause, "where_clause" },
1371 { OSQLParseNode::opt_where_clause, "opt_where_clause" },
1372 { OSQLParseNode::search_condition, "search_condition" },
1373 { OSQLParseNode::comparison, "comparison" },
1374 { OSQLParseNode::comparison_predicate, "comparison_predicate" },
1375 { OSQLParseNode::between_predicate, "between_predicate" },
1376 { OSQLParseNode::like_predicate, "like_predicate" },
1377 { OSQLParseNode::opt_escape, "opt_escape" },
1378 { OSQLParseNode::test_for_null, "test_for_null" },
1379 { OSQLParseNode::scalar_exp_commalist, "scalar_exp_commalist" },
1380 { OSQLParseNode::scalar_exp, "scalar_exp" },
1381 { OSQLParseNode::parameter_ref, "parameter_ref" },
1382 { OSQLParseNode::parameter, "parameter" },
1383 { OSQLParseNode::general_set_fct, "general_set_fct" },
1384 { OSQLParseNode::range_variable, "range_variable" },
1385 { OSQLParseNode::column, "column" },
1386 { OSQLParseNode::delete_statement_positioned, "delete_statement_positioned" },
1387 { OSQLParseNode::delete_statement_searched, "delete_statement_searched" },
1388 { OSQLParseNode::update_statement_positioned, "update_statement_positioned" },
1389 { OSQLParseNode::update_statement_searched, "update_statement_searched" },
1390 { OSQLParseNode::assignment_commalist, "assignment_commalist" },
1391 { OSQLParseNode::assignment, "assignment" },
1392 { OSQLParseNode::values_or_query_spec, "values_or_query_spec" },
1393 { OSQLParseNode::insert_statement, "insert_statement" },
1394 { OSQLParseNode::insert_atom_commalist, "insert_atom_commalist" },
1395 { OSQLParseNode::insert_atom, "insert_atom" },
1396 { OSQLParseNode::from_clause, "from_clause" },
1397 { OSQLParseNode::qualified_join, "qualified_join" },
1398 { OSQLParseNode::cross_union, "cross_union" },
1399 { OSQLParseNode::select_sublist, "select_sublist" },
1400 { OSQLParseNode::derived_column, "derived_column" },
1401 { OSQLParseNode::column_val, "column_val" },
1402 { OSQLParseNode::set_fct_spec, "set_fct_spec" },
1403 { OSQLParseNode::boolean_term, "boolean_term" },
1404 { OSQLParseNode::boolean_primary, "boolean_primary" },
1405 { OSQLParseNode::num_value_exp, "num_value_exp" },
1406 { OSQLParseNode::join_type, "join_type" },
1407 { OSQLParseNode::position_exp, "position_exp" },
1408 { OSQLParseNode::extract_exp, "extract_exp" },
1409 { OSQLParseNode::length_exp, "length_exp" },
1410 { OSQLParseNode::char_value_fct, "char_value_fct" },
1411 { OSQLParseNode::odbc_call_spec, "odbc_call_spec" },
1412 { OSQLParseNode::in_predicate, "in_predicate" },
1413 { OSQLParseNode::existence_test, "existence_test" },
1414 { OSQLParseNode::unique_test, "unique_test" },
1415 { OSQLParseNode::all_or_any_predicate, "all_or_any_predicate" },
1416 { OSQLParseNode::named_columns_join, "named_columns_join" },
1417 { OSQLParseNode::join_condition, "join_condition" },
1418 { OSQLParseNode::joined_table, "joined_table" },
1419 { OSQLParseNode::boolean_factor, "boolean_factor" },
1420 { OSQLParseNode::sql_not, "sql_not" },
1421 { OSQLParseNode::manipulative_statement, "manipulative_statement" },
1422 { OSQLParseNode::subquery, "subquery" },
1423 { OSQLParseNode::value_exp_commalist, "value_exp_commalist" },
1424 { OSQLParseNode::odbc_fct_spec, "odbc_fct_spec" },
1425 { OSQLParseNode::union_statement, "union_statement" },
1426 { OSQLParseNode::outer_join_type, "outer_join_type" },
1427 { OSQLParseNode::char_value_exp, "char_value_exp" },
1428 { OSQLParseNode::term, "term" },
1429 { OSQLParseNode::value_exp_primary, "value_exp_primary" },
1430 { OSQLParseNode::value_exp, "value_exp" },
1431 { OSQLParseNode::selection, "selection" },
1432 { OSQLParseNode::fold, "fold" },
1433 { OSQLParseNode::char_substring_fct, "char_substring_fct" },
1434 { OSQLParseNode::factor, "factor" },
1435 { OSQLParseNode::base_table_def, "base_table_def" },
1436 { OSQLParseNode::base_table_element_commalist, "base_table_element_commalist" },
1437 { OSQLParseNode::data_type, "data_type" },
1438 { OSQLParseNode::column_def, "column_def" },
1439 { OSQLParseNode::table_node, "table_node" },
1440 { OSQLParseNode::as_clause, "as_clause" },
1441 { OSQLParseNode::opt_as, "opt_as" },
1442 { OSQLParseNode::op_column_commalist, "op_column_commalist" },
1443 { OSQLParseNode::table_primary_as_range_column, "table_primary_as_range_column" },
1444 { OSQLParseNode::datetime_primary, "datetime_primary" },
1445 { OSQLParseNode::concatenation, "concatenation" },
1446 { OSQLParseNode::char_factor, "char_factor" },
1447 { OSQLParseNode::bit_value_fct, "bit_value_fct" },
1448 { OSQLParseNode::comparison_predicate_part_2, "comparison_predicate_part_2" },
1449 { OSQLParseNode::parenthesized_boolean_value_expression, "parenthesized_boolean_value_expression" },
1450 { OSQLParseNode::character_string_type, "character_string_type" },
1451 { OSQLParseNode::other_like_predicate_part_2, "other_like_predicate_part_2" },
1452 { OSQLParseNode::between_predicate_part_2, "between_predicate_part_2" },
1453 { OSQLParseNode::null_predicate_part_2, "null_predicate_part_2" },
1454 { OSQLParseNode::cast_spec, "cast_spec" },
1455 { OSQLParseNode::window_function, "window_function" }
1457 const size_t nRuleMapCount = SAL_N_ELEMENTS( aRuleDescriptions );
1458 // added a new rule? Adjust this map!
1459 // +1 for UNKNOWN_RULE
1460 static_assert(nRuleMapCount + 1 == static_cast<size_t>(OSQLParseNode::rule_count), "must be equal");
1462 for (const auto & aRuleDescription : aRuleDescriptions)
1464 // look up the rule description in the our identifier map
1465 sal_uInt32 nParserRuleID = StrToRuleID( aRuleDescription.sRuleName );
1466 // map the parser's rule ID to the OSQLParseNode::Rule
1467 s_aReverseRuleIDLookup[ nParserRuleID ] = aRuleDescription.eRule;
1468 // and map the OSQLParseNode::Rule to the parser's rule ID
1469 s_nRuleIDs[ aRuleDescription.eRule ] = nParserRuleID;
1472 ++s_nRefCount;
1474 if (m_pContext == nullptr)
1475 // take the default context
1476 m_pContext = &s_aDefaultContext;
1478 m_pData->aLocale = m_pContext->getPreferredLocale();
1482 OSQLParser::~OSQLParser()
1484 ::osl::MutexGuard aGuard(getMutex());
1485 OSL_ENSURE(s_nRefCount > 0, "OSQLParser::~OSQLParser() : suspicious call : has a refcount of 0 !");
1486 if (!--s_nRefCount)
1488 s_pScanner->setScanner(true);
1489 delete s_pScanner;
1490 s_pScanner = nullptr;
1492 delete s_pGarbageCollector;
1493 s_pGarbageCollector = nullptr;
1494 // Is only set the first time, so we should delete it only when there are no more instances
1495 s_xLocaleData = nullptr;
1497 RuleIDMap aEmpty;
1498 s_aReverseRuleIDLookup.swap( aEmpty );
1500 m_pParseTree = nullptr;
1503 void OSQLParseNode::substituteParameterNames(OSQLParseNode const * _pNode)
1505 sal_Int32 nCount = _pNode->count();
1506 for(sal_Int32 i=0;i < nCount;++i)
1508 OSQLParseNode* pChildNode = _pNode->getChild(i);
1509 if(SQL_ISRULE(pChildNode,parameter) && pChildNode->count() > 1)
1511 OSQLParseNode* pNewNode = new OSQLParseNode("?" ,SQLNodeType::Punctuation,0);
1512 delete pChildNode->replace(pChildNode->getChild(0),pNewNode);
1513 sal_Int32 nChildCount = pChildNode->count();
1514 for(sal_Int32 j=1;j < nChildCount;++j)
1515 delete pChildNode->removeAt(1);
1517 else
1518 substituteParameterNames(pChildNode);
1523 bool OSQLParser::extractDate(OSQLParseNode const * pLiteral,double& _rfValue)
1525 Reference< XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1526 Reference< XNumberFormatTypes > xFormatTypes;
1527 if ( xFormatSup.is() )
1528 xFormatTypes.set(xFormatSup->getNumberFormats(), css::uno::UNO_QUERY);
1530 // if there is no format key, yet, make sure we have a feasible one for our locale
1533 if ( !m_nFormatKey && xFormatTypes.is() )
1534 m_nFormatKey = ::dbtools::getDefaultNumberFormat( m_xField, xFormatTypes, m_pData->aLocale );
1536 catch( Exception& ) { }
1537 const OUString& sValue = pLiteral->getTokenValue();
1538 sal_Int32 nTryFormat = m_nFormatKey;
1539 bool bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1541 // If our format key didn't do, try the default date format for our locale.
1542 if ( !bSuccess && xFormatTypes.is() )
1546 nTryFormat = xFormatTypes->getStandardFormat( NumberFormat::DATE, m_pData->aLocale );
1548 catch( Exception& ) { }
1549 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1552 // if this also didn't do, try ISO format
1553 if ( !bSuccess && xFormatTypes.is() )
1557 nTryFormat = xFormatTypes->getFormatIndex( NumberFormatIndex::DATE_DIN_YYYYMMDD, m_pData->aLocale );
1559 catch( Exception& ) { }
1560 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1563 // if this also didn't do, try fallback date format (en-US)
1564 if ( !bSuccess )
1566 nTryFormat = m_nDateFormatKey;
1567 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1569 return bSuccess;
1572 OSQLParseNode* OSQLParser::buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral)
1574 // try converting the string into a date, according to our format key
1575 double fValue = 0.0;
1576 OSQLParseNode* pFCTNode = nullptr;
1578 if ( extractDate(pLiteral,fValue) )
1579 pFCTNode = buildNode_Date( fValue, _nType);
1581 delete pLiteral;
1582 pLiteral = nullptr;
1584 if ( !pFCTNode )
1585 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidDateCompare);
1587 return pFCTNode;
1591 OSQLParseNode::OSQLParseNode(const sal_Char * pNewValue,
1592 SQLNodeType eNewNodeType,
1593 sal_uInt32 nNewNodeID)
1594 :m_pParent(nullptr)
1595 ,m_aNodeValue(pNewValue,strlen(pNewValue),RTL_TEXTENCODING_UTF8)
1596 ,m_eNodeType(eNewNodeType)
1597 ,m_nNodeID(nNewNodeID)
1599 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1602 OSQLParseNode::OSQLParseNode(const OString &_rNewValue,
1603 SQLNodeType eNewNodeType,
1604 sal_uInt32 nNewNodeID)
1605 :m_pParent(nullptr)
1606 ,m_aNodeValue(OStringToOUString(_rNewValue,RTL_TEXTENCODING_UTF8))
1607 ,m_eNodeType(eNewNodeType)
1608 ,m_nNodeID(nNewNodeID)
1610 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1613 OSQLParseNode::OSQLParseNode(const OUString &_rNewValue,
1614 SQLNodeType eNewNodeType,
1615 sal_uInt32 nNewNodeID)
1616 :m_pParent(nullptr)
1617 ,m_aNodeValue(_rNewValue)
1618 ,m_eNodeType(eNewNodeType)
1619 ,m_nNodeID(nNewNodeID)
1621 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1624 OSQLParseNode::OSQLParseNode(const OSQLParseNode& rParseNode)
1626 // Set the getParent to NULL
1627 m_pParent = nullptr;
1629 // Copy the members
1630 m_aNodeValue = rParseNode.m_aNodeValue;
1631 m_eNodeType = rParseNode.m_eNodeType;
1632 m_nNodeID = rParseNode.m_nNodeID;
1635 // Remember that we derived from Container. According to SV-Help the Container's
1636 // copy ctor creates a new Container with the same pointers for content.
1637 // This means after copying the Container, for all non-NULL pointers a copy is
1638 // created and reattached instead of the old pointer.
1640 // If not a leaf, then process SubTrees
1641 for (auto const& child : rParseNode.m_aChildren)
1642 append(new OSQLParseNode(*child));
1646 OSQLParseNode& OSQLParseNode::operator=(const OSQLParseNode& rParseNode)
1648 if (this != &rParseNode)
1650 // Copy the members - pParent remains the same
1651 m_aNodeValue = rParseNode.m_aNodeValue;
1652 m_eNodeType = rParseNode.m_eNodeType;
1653 m_nNodeID = rParseNode.m_nNodeID;
1655 m_aChildren.clear();
1657 for (auto const& child : rParseNode.m_aChildren)
1658 append(new OSQLParseNode(*child));
1660 return *this;
1664 bool OSQLParseNode::operator==(OSQLParseNode const & rParseNode) const
1666 // The members must be equal
1667 bool bResult = (m_nNodeID == rParseNode.m_nNodeID) &&
1668 (m_eNodeType == rParseNode.m_eNodeType) &&
1669 (m_aNodeValue == rParseNode.m_aNodeValue) &&
1670 count() == rParseNode.count();
1672 // Parameters are not equal!
1673 bResult = bResult && !SQL_ISRULE(this, parameter);
1675 // compare children
1676 for (size_t i=0; bResult && i < count(); i++)
1677 bResult = *getChild(i) == *rParseNode.getChild(i);
1679 return bResult;
1683 OSQLParseNode::~OSQLParseNode()
1688 void OSQLParseNode::append(OSQLParseNode* pNewNode)
1690 OSL_ENSURE(pNewNode != nullptr, "OSQLParseNode: invalid NewSubTree");
1691 OSL_ENSURE(pNewNode->getParent() == nullptr, "OSQLParseNode: Node is not an orphan");
1692 OSL_ENSURE(std::none_of(m_aChildren.begin(), m_aChildren.end(),
1693 [&] (std::unique_ptr<OSQLParseNode> const & r) { return r.get() == pNewNode; }),
1694 "OSQLParseNode::append() Node already element of parent");
1696 // Create connection to getParent
1697 pNewNode->setParent( this );
1698 // and attach the SubTree at the end
1699 m_aChildren.emplace_back(pNewNode);
1702 bool OSQLParseNode::addDateValue(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
1704 // special display for date/time values
1705 if (SQL_ISRULE(this,set_fct_spec) && SQL_ISPUNCTUATION(m_aChildren[0],"{"))
1707 const OSQLParseNode* pODBCNode = m_aChildren[1].get();
1708 const OSQLParseNode* pODBCNodeChild = pODBCNode->m_aChildren[0].get();
1710 if (pODBCNodeChild->getNodeType() == SQLNodeType::Keyword && (
1711 SQL_ISTOKEN(pODBCNodeChild, D) ||
1712 SQL_ISTOKEN(pODBCNodeChild, T) ||
1713 SQL_ISTOKEN(pODBCNodeChild, TS) ))
1715 OUString suQuote("'");
1716 if (rParam.bPredicate)
1718 if (rParam.aMetaData.shouldEscapeDateTime())
1720 suQuote = "#";
1723 else
1725 if (rParam.aMetaData.shouldEscapeDateTime())
1727 // suQuote = "'";
1728 return false;
1732 if (!rString.isEmpty())
1733 rString.append(" ");
1734 rString.append(suQuote);
1735 const OUString sTokenValue = pODBCNode->m_aChildren[1]->getTokenValue();
1736 if (SQL_ISTOKEN(pODBCNodeChild, D))
1738 rString.append(rParam.bPredicate ? convertDateString(rParam, sTokenValue) : sTokenValue);
1740 else if (SQL_ISTOKEN(pODBCNodeChild, T))
1742 rString.append(rParam.bPredicate ? convertTimeString(rParam, sTokenValue) : sTokenValue);
1744 else
1746 rString.append(rParam.bPredicate ? convertDateTimeString(rParam, sTokenValue) : sTokenValue);
1748 rString.append(suQuote);
1749 return true;
1752 return false;
1755 void OSQLParseNode::replaceNodeValue(const OUString& rTableAlias, const OUString& rColumnName)
1757 for (size_t i=0;i<count();++i)
1759 if (SQL_ISRULE(this,column_ref) && count() == 1 && getChild(0)->getTokenValue() == rColumnName)
1761 OSQLParseNode * pCol = removeAt(sal_uInt32(0));
1762 append(new OSQLParseNode(rTableAlias,SQLNodeType::Name));
1763 append(new OSQLParseNode(".",SQLNodeType::Punctuation));
1764 append(pCol);
1766 else
1767 getChild(i)->replaceNodeValue(rTableAlias,rColumnName);
1771 OSQLParseNode* OSQLParseNode::getByRule(OSQLParseNode::Rule eRule) const
1773 OSQLParseNode* pRetNode = nullptr;
1774 if (isRule() && OSQLParser::RuleID(eRule) == getRuleID())
1775 pRetNode = const_cast<OSQLParseNode*>(this);
1776 else
1778 for (auto const& child : m_aChildren)
1780 pRetNode = child->getByRule(eRule);
1781 if (pRetNode)
1782 break;
1785 return pRetNode;
1788 static OSQLParseNode* MakeANDNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1790 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1791 pNewNode->append(pLeftLeaf);
1792 pNewNode->append(new OSQLParseNode("AND",SQLNodeType::Keyword,SQL_TOKEN_AND));
1793 pNewNode->append(pRightLeaf);
1794 return pNewNode;
1797 static OSQLParseNode* MakeORNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1799 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::search_condition));
1800 pNewNode->append(pLeftLeaf);
1801 pNewNode->append(new OSQLParseNode("OR",SQLNodeType::Keyword,SQL_TOKEN_OR));
1802 pNewNode->append(pRightLeaf);
1803 return pNewNode;
1806 void OSQLParseNode::disjunctiveNormalForm(OSQLParseNode*& pSearchCondition)
1808 if(!pSearchCondition) // no where condition at entry point
1809 return;
1811 OSQLParseNode::absorptions(pSearchCondition);
1812 // '(' search_condition ')'
1813 if (SQL_ISRULE(pSearchCondition,boolean_primary))
1815 OSQLParseNode* pLeft = pSearchCondition->getChild(1);
1816 disjunctiveNormalForm(pLeft);
1818 // search_condition SQL_TOKEN_OR boolean_term
1819 else if (SQL_ISRULE(pSearchCondition,search_condition))
1821 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1822 disjunctiveNormalForm(pLeft);
1824 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1825 disjunctiveNormalForm(pRight);
1827 // boolean_term SQL_TOKEN_AND boolean_factor
1828 else if (SQL_ISRULE(pSearchCondition,boolean_term))
1830 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1831 disjunctiveNormalForm(pLeft);
1833 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1834 disjunctiveNormalForm(pRight);
1836 OSQLParseNode* pNewNode = nullptr;
1837 // '(' search_condition ')' on left side
1838 if(pLeft->count() == 3 && SQL_ISRULE(pLeft,boolean_primary) && SQL_ISRULE(pLeft->getChild(1),search_condition))
1840 // and-or tree on left side
1841 OSQLParseNode* pOr = pLeft->getChild(1);
1842 OSQLParseNode* pNewLeft = nullptr;
1843 OSQLParseNode* pNewRight = nullptr;
1845 // cut right from parent
1846 pSearchCondition->removeAt(2);
1848 pNewRight = MakeANDNode(pOr->removeAt(2) ,pRight);
1849 pNewLeft = MakeANDNode(pOr->removeAt(sal_uInt32(0)) ,new OSQLParseNode(*pRight));
1850 pNewNode = MakeORNode(pNewLeft,pNewRight);
1851 // and append new Node
1852 replaceAndReset(pSearchCondition,pNewNode);
1854 disjunctiveNormalForm(pSearchCondition);
1856 else if(pRight->count() == 3 && SQL_ISRULE(pRight,boolean_primary) && SQL_ISRULE(pRight->getChild(1),search_condition))
1857 { // '(' search_condition ')' on right side
1858 // and-or tree on right side
1859 // a and (b or c)
1860 OSQLParseNode* pOr = pRight->getChild(1);
1861 OSQLParseNode* pNewLeft = nullptr;
1862 OSQLParseNode* pNewRight = nullptr;
1864 // cut left from parent
1865 pSearchCondition->removeAt(sal_uInt32(0));
1867 pNewRight = MakeANDNode(pLeft,pOr->removeAt(2));
1868 pNewLeft = MakeANDNode(new OSQLParseNode(*pLeft),pOr->removeAt(sal_uInt32(0)));
1869 pNewNode = MakeORNode(pNewLeft,pNewRight);
1871 // and append new Node
1872 replaceAndReset(pSearchCondition,pNewNode);
1873 disjunctiveNormalForm(pSearchCondition);
1875 else if(SQL_ISRULE(pLeft,boolean_primary) && (!SQL_ISRULE(pLeft->getChild(1),search_condition) || !SQL_ISRULE(pLeft->getChild(1),boolean_term)))
1876 pSearchCondition->replace(pLeft, pLeft->removeAt(1));
1877 else if(SQL_ISRULE(pRight,boolean_primary) && (!SQL_ISRULE(pRight->getChild(1),search_condition) || !SQL_ISRULE(pRight->getChild(1),boolean_term)))
1878 pSearchCondition->replace(pRight, pRight->removeAt(1));
1882 void OSQLParseNode::negateSearchCondition(OSQLParseNode*& pSearchCondition, bool bNegate)
1884 if(!pSearchCondition) // no where condition at entry point
1885 return;
1886 // '(' search_condition ')'
1887 if (pSearchCondition->count() == 3 && SQL_ISRULE(pSearchCondition,boolean_primary))
1889 OSQLParseNode* pRight = pSearchCondition->getChild(1);
1890 negateSearchCondition(pRight,bNegate);
1892 // search_condition SQL_TOKEN_OR boolean_term
1893 else if (SQL_ISRULE(pSearchCondition,search_condition))
1895 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1896 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1897 if(bNegate)
1899 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1900 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(0)));
1901 pNewNode->append(new OSQLParseNode("AND",SQLNodeType::Keyword,SQL_TOKEN_AND));
1902 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(1)));
1903 replaceAndReset(pSearchCondition,pNewNode);
1905 pLeft = pNewNode->getChild(0);
1906 pRight = pNewNode->getChild(2);
1909 negateSearchCondition(pLeft,bNegate);
1910 negateSearchCondition(pRight,bNegate);
1912 // boolean_term SQL_TOKEN_AND boolean_factor
1913 else if (SQL_ISRULE(pSearchCondition,boolean_term))
1915 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1916 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1917 if(bNegate)
1919 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::search_condition));
1920 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(0)));
1921 pNewNode->append(new OSQLParseNode("OR",SQLNodeType::Keyword,SQL_TOKEN_OR));
1922 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(1)));
1923 replaceAndReset(pSearchCondition,pNewNode);
1925 pLeft = pNewNode->getChild(0);
1926 pRight = pNewNode->getChild(2);
1929 negateSearchCondition(pLeft,bNegate);
1930 negateSearchCondition(pRight,bNegate);
1932 // SQL_TOKEN_NOT ( boolean_primary )
1933 else if (SQL_ISRULE(pSearchCondition,boolean_factor))
1935 OSQLParseNode *pNot = pSearchCondition->removeAt(sal_uInt32(0));
1936 delete pNot;
1937 OSQLParseNode *pBooleanTest = pSearchCondition->removeAt(sal_uInt32(0));
1938 // TODO is this needed // pBooleanTest->setParent(NULL);
1939 replaceAndReset(pSearchCondition,pBooleanTest);
1941 if (!bNegate)
1942 negateSearchCondition(pSearchCondition, true); // negate all deeper values
1944 // row_value_constructor comparison row_value_constructor
1945 // row_value_constructor comparison any_all_some subquery
1946 else if(bNegate && (SQL_ISRULE(pSearchCondition,comparison_predicate) || SQL_ISRULE(pSearchCondition,all_or_any_predicate)))
1948 assert(pSearchCondition->count() == 3);
1949 OSQLParseNode* pComparison = pSearchCondition->getChild(1);
1950 if(SQL_ISRULE(pComparison, comparison))
1952 assert(pComparison->count() == 2 ||
1953 pComparison->count() == 4);
1954 assert(SQL_ISTOKEN(pComparison->getChild(0), IS));
1956 OSQLParseNode* pNot = pComparison->getChild(1);
1957 OSQLParseNode* pNotNot = nullptr;
1958 if(pNot->isRule()) // no NOT token (empty rule)
1959 pNotNot = new OSQLParseNode("NOT",SQLNodeType::Keyword,SQL_TOKEN_NOT);
1960 else
1962 assert(SQL_ISTOKEN(pNot,NOT));
1963 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
1965 pComparison->replace(pNot, pNotNot);
1966 delete pNot;
1968 else
1970 OSQLParseNode* pNewComparison;
1971 switch(pComparison->getNodeType())
1973 default:
1974 case SQLNodeType::Equal:
1975 assert(pComparison->getNodeType() == SQLNodeType::Equal &&
1976 "OSQLParseNode::negateSearchCondition: unexpected node type!");
1977 pNewComparison = new OSQLParseNode("<>",SQLNodeType::NotEqual,SQL_NOTEQUAL);
1978 break;
1979 case SQLNodeType::Less:
1980 pNewComparison = new OSQLParseNode(">=",SQLNodeType::GreatEq,SQL_GREATEQ);
1981 break;
1982 case SQLNodeType::Great:
1983 pNewComparison = new OSQLParseNode("<=",SQLNodeType::LessEq,SQL_LESSEQ);
1984 break;
1985 case SQLNodeType::LessEq:
1986 pNewComparison = new OSQLParseNode(">",SQLNodeType::Great,SQL_GREAT);
1987 break;
1988 case SQLNodeType::GreatEq:
1989 pNewComparison = new OSQLParseNode("<",SQLNodeType::Less,SQL_LESS);
1990 break;
1991 case SQLNodeType::NotEqual:
1992 pNewComparison = new OSQLParseNode("=",SQLNodeType::Equal,SQL_EQUAL);
1993 break;
1995 pSearchCondition->replace(pComparison, pNewComparison);
1996 delete pComparison;
2000 else if(bNegate && (SQL_ISRULE(pSearchCondition,test_for_null) ||
2001 SQL_ISRULE(pSearchCondition,in_predicate) ||
2002 SQL_ISRULE(pSearchCondition,between_predicate) ))
2004 OSQLParseNode* pPart2 = pSearchCondition->getChild(1);
2005 sal_uInt32 nNotPos = 0;
2006 if ( SQL_ISRULE( pSearchCondition, test_for_null ) )
2007 nNotPos = 1;
2009 OSQLParseNode* pNot = pPart2->getChild(nNotPos);
2010 OSQLParseNode* pNotNot = nullptr;
2011 if(pNot->isRule()) // no NOT token (empty rule)
2012 pNotNot = new OSQLParseNode("NOT",SQLNodeType::Keyword,SQL_TOKEN_NOT);
2013 else
2015 assert(SQL_ISTOKEN(pNot,NOT));
2016 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
2018 pPart2->replace(pNot, pNotNot);
2019 delete pNot;
2021 else if(bNegate && SQL_ISRULE(pSearchCondition,like_predicate))
2023 OSQLParseNode* pNot = pSearchCondition->getChild( 1 )->getChild( 0 );
2024 OSQLParseNode* pNotNot = nullptr;
2025 if(pNot->isRule())
2026 pNotNot = new OSQLParseNode("NOT",SQLNodeType::Keyword,SQL_TOKEN_NOT);
2027 else
2028 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
2029 pSearchCondition->getChild( 1 )->replace(pNot, pNotNot);
2030 delete pNot;
2034 void OSQLParseNode::eraseBraces(OSQLParseNode*& pSearchCondition)
2036 if (pSearchCondition && (SQL_ISRULE(pSearchCondition,boolean_primary) || (pSearchCondition->count() == 3 && SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
2037 SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")"))))
2039 OSQLParseNode* pRight = pSearchCondition->getChild(1);
2040 absorptions(pRight);
2041 // if child is not an or and tree then delete () around child
2042 if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2043 SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || // and can always stand without ()
2044 (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2046 OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2047 replaceAndReset(pSearchCondition,pNode);
2052 void OSQLParseNode::absorptions(OSQLParseNode*& pSearchCondition)
2054 if(!pSearchCondition) // no where condition at entry point
2055 return;
2057 eraseBraces(pSearchCondition);
2059 if(SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2061 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
2062 absorptions(pLeft);
2063 OSQLParseNode* pRight = pSearchCondition->getChild(2);
2064 absorptions(pRight);
2067 sal_uInt32 nPos = 0;
2068 // a and a || a or a
2069 OSQLParseNode* pNewNode = nullptr;
2070 if(( SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2071 && *pSearchCondition->getChild(0) == *pSearchCondition->getChild(2))
2073 pNewNode = pSearchCondition->removeAt(sal_uInt32(0));
2074 replaceAndReset(pSearchCondition,pNewNode);
2076 // (a or b) and a || ( b or c ) and a
2077 // a and ( a or b) || a and ( b or c )
2078 else if ( SQL_ISRULE(pSearchCondition,boolean_term)
2079 && (
2080 ( SQL_ISRULE(pSearchCondition->getChild(nPos = 0),boolean_primary)
2081 || SQL_ISRULE(pSearchCondition->getChild(nPos),search_condition)
2083 || ( SQL_ISRULE(pSearchCondition->getChild(nPos = 2),boolean_primary)
2084 || SQL_ISRULE(pSearchCondition->getChild(nPos),search_condition)
2089 OSQLParseNode* p2ndSearch = pSearchCondition->getChild(nPos);
2090 if ( SQL_ISRULE(p2ndSearch,boolean_primary) )
2091 p2ndSearch = p2ndSearch->getChild(1);
2093 if ( *p2ndSearch->getChild(0) == *pSearchCondition->getChild(2-nPos) ) // a and ( a or b) -> a or b
2095 pNewNode = pSearchCondition->removeAt(sal_uInt32(0));
2096 replaceAndReset(pSearchCondition,pNewNode);
2099 else if ( *p2ndSearch->getChild(2) == *pSearchCondition->getChild(2-nPos) ) // a and ( b or a) -> a or b
2101 pNewNode = pSearchCondition->removeAt(sal_uInt32(2));
2102 replaceAndReset(pSearchCondition,pNewNode);
2104 else if ( p2ndSearch->getByRule(OSQLParseNode::search_condition) )
2106 // a and ( b or c ) -> ( a and b ) or ( a and c )
2107 // ( b or c ) and a -> ( a and b ) or ( a and c )
2108 OSQLParseNode* pC = p2ndSearch->removeAt(sal_uInt32(2));
2109 OSQLParseNode* pB = p2ndSearch->removeAt(sal_uInt32(0));
2110 OSQLParseNode* pA = pSearchCondition->removeAt(sal_uInt32(2)-nPos);
2112 OSQLParseNode* p1stAnd = MakeANDNode(pA,pB);
2113 OSQLParseNode* p2ndAnd = MakeANDNode(new OSQLParseNode(*pA),pC);
2114 pNewNode = MakeORNode(p1stAnd,p2ndAnd);
2115 OSQLParseNode* pNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2116 pNode->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2117 pNode->append(pNewNode);
2118 pNode->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2119 OSQLParseNode::eraseBraces(p1stAnd);
2120 OSQLParseNode::eraseBraces(p2ndAnd);
2121 replaceAndReset(pSearchCondition,pNode);
2124 // a or a and b || a or b and a
2125 else if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(2),boolean_term))
2127 if(*pSearchCondition->getChild(2)->getChild(0) == *pSearchCondition->getChild(0))
2129 pNewNode = pSearchCondition->removeAt(sal_uInt32(0));
2130 replaceAndReset(pSearchCondition,pNewNode);
2132 else if(*pSearchCondition->getChild(2)->getChild(2) == *pSearchCondition->getChild(0))
2134 pNewNode = pSearchCondition->removeAt(sal_uInt32(0));
2135 replaceAndReset(pSearchCondition,pNewNode);
2138 // a and b or a || b and a or a
2139 else if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(0),boolean_term))
2141 if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2))
2143 pNewNode = pSearchCondition->removeAt(sal_uInt32(2));
2144 replaceAndReset(pSearchCondition,pNewNode);
2146 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2))
2148 pNewNode = pSearchCondition->removeAt(sal_uInt32(2));
2149 replaceAndReset(pSearchCondition,pNewNode);
2152 eraseBraces(pSearchCondition);
2155 void OSQLParseNode::compress(OSQLParseNode *&pSearchCondition)
2157 if(!pSearchCondition) // no WHERE condition at entry point
2158 return;
2160 OSQLParseNode::eraseBraces(pSearchCondition);
2162 if(SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2164 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
2165 compress(pLeft);
2167 OSQLParseNode* pRight = pSearchCondition->getChild(2);
2168 compress(pRight);
2170 else if( SQL_ISRULE(pSearchCondition,boolean_primary) || (pSearchCondition->count() == 3 && SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
2171 SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")")))
2173 OSQLParseNode* pRight = pSearchCondition->getChild(1);
2174 compress(pRight);
2175 // if child is not an or and tree then delete () around child
2176 if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2177 (SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) && SQL_ISRULE(pSearchCondition->getParent(),boolean_term)) ||
2178 (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2180 OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2181 replaceAndReset(pSearchCondition,pNode);
2185 // or with two and trees where one element of the and trees are equal
2186 if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(0),boolean_term) && SQL_ISRULE(pSearchCondition->getChild(2),boolean_term))
2188 if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(0))
2190 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(2);
2191 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2192 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2194 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2195 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2196 pNewRule->append(pNode);
2197 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2199 OSQLParseNode::eraseBraces(pLeft);
2200 OSQLParseNode::eraseBraces(pRight);
2202 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(sal_uInt32(0)),pNewRule);
2203 replaceAndReset(pSearchCondition,pNode);
2205 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(0))
2207 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(sal_uInt32(0));
2208 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2209 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2211 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2212 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2213 pNewRule->append(pNode);
2214 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2216 OSQLParseNode::eraseBraces(pLeft);
2217 OSQLParseNode::eraseBraces(pRight);
2219 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2220 replaceAndReset(pSearchCondition,pNode);
2222 else if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(2))
2224 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(2);
2225 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(sal_uInt32(0));
2226 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2228 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2229 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2230 pNewRule->append(pNode);
2231 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2233 OSQLParseNode::eraseBraces(pLeft);
2234 OSQLParseNode::eraseBraces(pRight);
2236 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(sal_uInt32(0)),pNewRule);
2237 replaceAndReset(pSearchCondition,pNode);
2239 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(2))
2241 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(sal_uInt32(0));
2242 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(sal_uInt32(0));
2243 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2245 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2246 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2247 pNewRule->append(pNode);
2248 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2250 OSQLParseNode::eraseBraces(pLeft);
2251 OSQLParseNode::eraseBraces(pRight);
2253 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2254 replaceAndReset(pSearchCondition,pNode);
2258 #if OSL_DEBUG_LEVEL > 1
2260 void OSQLParseNode::showParseTree( OUString& rString ) const
2262 OUStringBuffer aBuf;
2263 showParseTree( aBuf, 0 );
2264 rString = aBuf.makeStringAndClear();
2268 void OSQLParseNode::showParseTree( OUStringBuffer& _inout_rBuffer, sal_uInt32 nLevel ) const
2270 for ( sal_uInt32 j=0; j<nLevel; ++j)
2271 _inout_rBuffer.appendAscii( " " );
2273 if ( !isToken() )
2275 // Rule name as rule
2276 _inout_rBuffer.appendAscii( "RULE_ID: " );
2277 _inout_rBuffer.append( (sal_Int32)getRuleID() );
2278 _inout_rBuffer.append( '(' );
2279 _inout_rBuffer.append( OSQLParser::RuleIDToStr( getRuleID() ) );
2280 _inout_rBuffer.append( ')' );
2281 _inout_rBuffer.append( '\n' );
2283 // Get the first sub tree
2284 for (auto const& child : m_aChildren)
2285 child->showParseTree( _inout_rBuffer, nLevel+1 );
2287 else
2289 // Found a token
2290 switch (m_eNodeType)
2293 case SQLNodeType::Keyword:
2294 _inout_rBuffer.appendAscii( "SQL_KEYWORD: " );
2295 _inout_rBuffer.append( OStringToOUString( OSQLParser::TokenIDToStr( getTokenID() ), RTL_TEXTENCODING_UTF8 ) );
2296 _inout_rBuffer.append( '\n' );
2297 break;
2299 case SQLNodeType::Name:
2300 _inout_rBuffer.appendAscii( "SQL_NAME: " );
2301 _inout_rBuffer.append( '"' );
2302 _inout_rBuffer.append( m_aNodeValue );
2303 _inout_rBuffer.append( '"' );
2304 _inout_rBuffer.append( '\n' );
2305 break;
2307 case SQLNodeType::String:
2308 _inout_rBuffer.appendAscii( "SQL_STRING: " );
2309 _inout_rBuffer.append( '\'' );
2310 _inout_rBuffer.append( m_aNodeValue );
2311 _inout_rBuffer.append( '\'' );
2312 _inout_rBuffer.append( '\n' );
2313 break;
2315 case SQLNodeType::IntNum:
2316 _inout_rBuffer.appendAscii( "SQL_INTNUM: " );
2317 _inout_rBuffer.append( m_aNodeValue );
2318 _inout_rBuffer.append( '\n' );
2319 break;
2321 case SQLNodeType::ApproxNum:
2322 _inout_rBuffer.appendAscii( "SQL_APPROXNUM: " );
2323 _inout_rBuffer.append( m_aNodeValue );
2324 _inout_rBuffer.append( '\n' );
2325 break;
2327 case SQLNodeType::Punctuation:
2328 _inout_rBuffer.appendAscii( "SQL_PUNCTUATION: " );
2329 _inout_rBuffer.append( m_aNodeValue );
2330 _inout_rBuffer.append( '\n' );
2331 break;
2333 case SQLNodeType::Equal:
2334 case SQLNodeType::Less:
2335 case SQLNodeType::Great:
2336 case SQLNodeType::LessEq:
2337 case SQLNodeType::GreatEq:
2338 case SQLNodeType::NotEqual:
2339 _inout_rBuffer.append( m_aNodeValue );
2340 _inout_rBuffer.append( '\n' );
2341 break;
2343 case SQLNodeType::AccessDate:
2344 _inout_rBuffer.appendAscii( "SQL_ACCESS_DATE: " );
2345 _inout_rBuffer.append( m_aNodeValue );
2346 _inout_rBuffer.append( '\n' );
2347 break;
2349 case SQLNodeType::Concat:
2350 _inout_rBuffer.appendAscii( "||" );
2351 _inout_rBuffer.append( '\n' );
2352 break;
2354 default:
2355 SAL_INFO( "connectivity.parse", "-- " << int( m_eNodeType ) );
2356 SAL_WARN( "connectivity.parse", "OSQLParser::ShowParseTree: unzulaessiger NodeType" );
2360 #endif // OSL_DEBUG_LEVEL > 0
2362 // Insert methods
2364 void OSQLParseNode::insert(sal_uInt32 nPos, OSQLParseNode* pNewSubTree)
2366 OSL_ENSURE(pNewSubTree != nullptr, "OSQLParseNode: invalid NewSubTree");
2367 OSL_ENSURE(pNewSubTree->getParent() == nullptr, "OSQLParseNode: Node is not an orphan");
2369 // Create connection to getParent
2370 pNewSubTree->setParent( this );
2371 m_aChildren.emplace(m_aChildren.begin() + nPos, pNewSubTree);
2374 // removeAt methods
2376 OSQLParseNode* OSQLParseNode::removeAt(sal_uInt32 nPos)
2378 OSL_ENSURE(nPos < m_aChildren.size(),"Illegal position for removeAt");
2379 auto aPos(m_aChildren.begin() + nPos);
2380 auto pNode = std::move(*aPos);
2382 // Set the getParent of the removed node to NULL
2383 pNode->setParent( nullptr );
2385 m_aChildren.erase(aPos);
2386 return pNode.release();
2389 // Replace methods
2391 OSQLParseNode* OSQLParseNode::replace(OSQLParseNode* pOldSubNode, OSQLParseNode* pNewSubNode )
2393 OSL_ENSURE(pOldSubNode != nullptr && pNewSubNode != nullptr, "OSQLParseNode: invalid nodes");
2394 OSL_ENSURE(pNewSubNode->getParent() == nullptr, "OSQLParseNode: node already has getParent");
2395 OSL_ENSURE(std::any_of(m_aChildren.begin(), m_aChildren.end(),
2396 [&] (std::unique_ptr<OSQLParseNode> const & r) { return r.get() == pOldSubNode; }),
2397 "OSQLParseNode::Replace() Node not element of parent");
2398 OSL_ENSURE(std::none_of(m_aChildren.begin(), m_aChildren.end(),
2399 [&] (std::unique_ptr<OSQLParseNode> const & r) { return r.get() == pNewSubNode; }),
2400 "OSQLParseNode::Replace() Node already element of parent");
2402 pOldSubNode->setParent( nullptr );
2403 pNewSubNode->setParent( this );
2404 auto it = std::find_if(m_aChildren.begin(), m_aChildren.end(),
2405 [&pOldSubNode](const std::unique_ptr<OSQLParseNode>& rxChild) { return rxChild.get() == pOldSubNode; });
2406 if (it != m_aChildren.end())
2408 it->release();
2409 it->reset(pNewSubNode);
2411 return pOldSubNode;
2414 void OSQLParseNode::parseLeaf(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
2416 // Found a leaf
2417 // Append content to the output string
2418 switch (m_eNodeType)
2420 case SQLNodeType::Keyword:
2422 if (!rString.isEmpty())
2423 rString.append(" ");
2425 const OString sT = OSQLParser::TokenIDToStr(m_nNodeID, rParam.bInternational ? &rParam.m_rContext : nullptr);
2426 rString.append(OStringToOUString(sT,RTL_TEXTENCODING_UTF8));
2427 } break;
2428 case SQLNodeType::String:
2429 if (!rString.isEmpty())
2430 rString.append(" ");
2431 rString.append(SetQuotation(m_aNodeValue,"\'","\'\'"));
2432 break;
2433 case SQLNodeType::Name:
2434 if (!rString.isEmpty())
2436 switch(rString[rString.getLength()-1])
2438 case ' ' :
2439 case '.' : break;
2440 default :
2441 if ( rParam.aMetaData.getCatalogSeparator().isEmpty()
2442 || rString[rString.getLength() - 1] != rParam.aMetaData.getCatalogSeparator().toChar()
2444 rString.append(" ");
2445 break;
2448 if (rParam.bQuote)
2450 if (rParam.bPredicate)
2452 rString.append("[");
2453 rString.append(m_aNodeValue);
2454 rString.append("]");
2456 else
2457 rString.append(SetQuotation(m_aNodeValue,
2458 rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
2460 else
2461 rString.append(m_aNodeValue);
2462 break;
2463 case SQLNodeType::AccessDate:
2464 if (!rString.isEmpty())
2465 rString.append(" ");
2466 rString.append("#");
2467 rString.append(m_aNodeValue);
2468 rString.append("#");
2469 break;
2471 case SQLNodeType::IntNum:
2472 case SQLNodeType::ApproxNum:
2474 OUString aTmp = m_aNodeValue;
2475 if (rParam.bInternational && rParam.bPredicate && rParam.cDecSep != '.')
2476 aTmp = aTmp.replace('.', rParam.cDecSep);
2478 if (!rString.isEmpty())
2479 rString.append(" ");
2480 rString.append(aTmp);
2482 } break;
2483 case SQLNodeType::Punctuation:
2484 if ( getParent() && SQL_ISRULE(getParent(),cast_spec) && m_aNodeValue.toChar() == '(' ) // no spaces in front of '('
2486 rString.append(m_aNodeValue);
2487 break;
2489 [[fallthrough]];
2490 default:
2491 if (!rString.isEmpty() && m_aNodeValue.toChar() != '.' && m_aNodeValue.toChar() != ':' )
2493 switch( rString[rString.getLength() - 1] )
2495 case ' ' :
2496 case '.' : break;
2497 default :
2498 if ( rParam.aMetaData.getCatalogSeparator().isEmpty()
2499 || rString[rString.getLength() - 1] != rParam.aMetaData.getCatalogSeparator().toChar()
2501 rString.append(" ");
2502 break;
2505 rString.append(m_aNodeValue);
2510 sal_Int32 OSQLParser::getFunctionReturnType(const OUString& _sFunctionName, const IParseContext* pContext)
2512 sal_Int32 nType = DataType::VARCHAR;
2513 OString sFunctionName(OUStringToOString(_sFunctionName,RTL_TEXTENCODING_UTF8));
2515 if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASCII,pContext))) nType = DataType::INTEGER;
2516 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_BIT_LENGTH,pContext))) nType = DataType::INTEGER;
2517 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR,pContext))) nType = DataType::VARCHAR;
2518 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR_LENGTH,pContext))) nType = DataType::INTEGER;
2519 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CONCAT,pContext))) nType = DataType::VARCHAR;
2520 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DIFFERENCE,pContext))) nType = DataType::VARCHAR;
2521 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_INSERT,pContext))) nType = DataType::VARCHAR;
2522 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LCASE,pContext))) nType = DataType::VARCHAR;
2523 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LEFT,pContext))) nType = DataType::VARCHAR;
2524 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LENGTH,pContext))) nType = DataType::INTEGER;
2525 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE,pContext))) nType = DataType::VARCHAR;
2526 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE_2,pContext))) nType = DataType::VARCHAR;
2527 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LTRIM,pContext))) nType = DataType::VARCHAR;
2528 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_OCTET_LENGTH,pContext))) nType = DataType::INTEGER;
2529 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POSITION,pContext))) nType = DataType::INTEGER;
2530 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPEAT,pContext))) nType = DataType::VARCHAR;
2531 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPLACE,pContext))) nType = DataType::VARCHAR;
2532 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RIGHT,pContext))) nType = DataType::VARCHAR;
2533 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RTRIM,pContext))) nType = DataType::VARCHAR;
2534 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SOUNDEX,pContext))) nType = DataType::VARCHAR;
2535 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SPACE,pContext))) nType = DataType::VARCHAR;
2536 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUBSTRING,pContext))) nType = DataType::VARCHAR;
2537 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UCASE,pContext))) nType = DataType::VARCHAR;
2538 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_DATE,pContext))) nType = DataType::DATE;
2539 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIME,pContext))) nType = DataType::TIME;
2540 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIMESTAMP,pContext))) nType = DataType::TIMESTAMP;
2541 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURDATE,pContext))) nType = DataType::DATE;
2542 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEDIFF,pContext))) nType = DataType::INTEGER;
2543 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEVALUE,pContext))) nType = DataType::DATE;
2544 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURTIME,pContext))) nType = DataType::TIME;
2545 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYNAME,pContext))) nType = DataType::VARCHAR;
2546 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFMONTH,pContext))) nType = DataType::INTEGER;
2547 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFWEEK,pContext))) nType = DataType::INTEGER;
2548 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFYEAR,pContext))) nType = DataType::INTEGER;
2549 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXTRACT,pContext))) nType = DataType::VARCHAR;
2550 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_HOUR,pContext))) nType = DataType::INTEGER;
2551 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MINUTE,pContext))) nType = DataType::INTEGER;
2552 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTH,pContext))) nType = DataType::INTEGER;
2553 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTHNAME,pContext))) nType = DataType::VARCHAR;
2554 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_NOW,pContext))) nType = DataType::TIMESTAMP;
2555 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_QUARTER,pContext))) nType = DataType::INTEGER;
2556 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SECOND,pContext))) nType = DataType::INTEGER;
2557 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPADD,pContext))) nType = DataType::TIMESTAMP;
2558 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPDIFF,pContext))) nType = DataType::TIMESTAMP;
2559 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMEVALUE,pContext))) nType = DataType::TIMESTAMP;
2560 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_WEEK,pContext))) nType = DataType::INTEGER;
2561 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_YEAR,pContext))) nType = DataType::INTEGER;
2562 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ABS,pContext))) nType = DataType::DOUBLE;
2563 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ACOS,pContext))) nType = DataType::DOUBLE;
2564 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASIN,pContext))) nType = DataType::DOUBLE;
2565 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN,pContext))) nType = DataType::DOUBLE;
2566 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN2,pContext))) nType = DataType::DOUBLE;
2567 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CEILING,pContext))) nType = DataType::DOUBLE;
2568 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COS,pContext))) nType = DataType::DOUBLE;
2569 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COT,pContext))) nType = DataType::DOUBLE;
2570 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DEGREES,pContext))) nType = DataType::DOUBLE;
2571 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXP,pContext))) nType = DataType::DOUBLE;
2572 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_FLOOR,pContext))) nType = DataType::DOUBLE;
2573 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOGF,pContext))) nType = DataType::DOUBLE;
2574 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG,pContext))) nType = DataType::DOUBLE;
2575 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG10,pContext))) nType = DataType::DOUBLE;
2576 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LN,pContext))) nType = DataType::DOUBLE;
2577 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MOD,pContext))) nType = DataType::DOUBLE;
2578 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_PI,pContext))) nType = DataType::DOUBLE;
2579 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POWER,pContext))) nType = DataType::DOUBLE;
2580 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RADIANS,pContext))) nType = DataType::DOUBLE;
2581 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RAND,pContext))) nType = DataType::DOUBLE;
2582 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUND,pContext))) nType = DataType::DOUBLE;
2583 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUNDMAGIC,pContext))) nType = DataType::DOUBLE;
2584 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIGN,pContext))) nType = DataType::DOUBLE;
2585 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIN,pContext))) nType = DataType::DOUBLE;
2586 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SQRT,pContext))) nType = DataType::DOUBLE;
2587 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TAN,pContext))) nType = DataType::DOUBLE;
2588 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TRUNCATE,pContext))) nType = DataType::DOUBLE;
2589 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COUNT,pContext))) nType = DataType::INTEGER;
2590 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MAX,pContext))) nType = DataType::DOUBLE;
2591 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MIN,pContext))) nType = DataType::DOUBLE;
2592 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_AVG,pContext))) nType = DataType::DOUBLE;
2593 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUM,pContext))) nType = DataType::DOUBLE;
2594 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOWER,pContext))) nType = DataType::VARCHAR;
2595 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UPPER,pContext))) nType = DataType::VARCHAR;
2597 return nType;
2600 sal_Int32 OSQLParser::getFunctionParameterType(sal_uInt32 _nTokenId, sal_uInt32 _nPos)
2602 sal_Int32 nType = DataType::VARCHAR;
2604 if(_nTokenId == SQL_TOKEN_CHAR) nType = DataType::INTEGER;
2605 else if(_nTokenId == SQL_TOKEN_INSERT)
2607 if ( _nPos == 2 || _nPos == 3 )
2608 nType = DataType::INTEGER;
2610 else if(_nTokenId == SQL_TOKEN_LEFT)
2612 if ( _nPos == 2 )
2613 nType = DataType::INTEGER;
2615 else if(_nTokenId == SQL_TOKEN_LOCATE)
2617 if ( _nPos == 3 )
2618 nType = DataType::INTEGER;
2620 else if(_nTokenId == SQL_TOKEN_LOCATE_2)
2622 if ( _nPos == 3 )
2623 nType = DataType::INTEGER;
2625 else if( _nTokenId == SQL_TOKEN_REPEAT || _nTokenId == SQL_TOKEN_RIGHT )
2627 if ( _nPos == 2 )
2628 nType = DataType::INTEGER;
2630 else if(_nTokenId == SQL_TOKEN_SPACE )
2632 nType = DataType::INTEGER;
2634 else if(_nTokenId == SQL_TOKEN_SUBSTRING)
2636 if ( _nPos != 1 )
2637 nType = DataType::INTEGER;
2639 else if(_nTokenId == SQL_TOKEN_DATEDIFF)
2641 if ( _nPos != 1 )
2642 nType = DataType::TIMESTAMP;
2644 else if(_nTokenId == SQL_TOKEN_DATEVALUE)
2645 nType = DataType::DATE;
2646 else if(_nTokenId == SQL_TOKEN_DAYNAME)
2647 nType = DataType::DATE;
2648 else if(_nTokenId == SQL_TOKEN_DAYOFMONTH)
2649 nType = DataType::DATE;
2650 else if(_nTokenId == SQL_TOKEN_DAYOFWEEK)
2651 nType = DataType::DATE;
2652 else if(_nTokenId == SQL_TOKEN_DAYOFYEAR)
2653 nType = DataType::DATE;
2654 else if(_nTokenId == SQL_TOKEN_EXTRACT) nType = DataType::VARCHAR;
2655 else if(_nTokenId == SQL_TOKEN_HOUR) nType = DataType::TIME;
2656 else if(_nTokenId == SQL_TOKEN_MINUTE) nType = DataType::TIME;
2657 else if(_nTokenId == SQL_TOKEN_MONTH) nType = DataType::DATE;
2658 else if(_nTokenId == SQL_TOKEN_MONTHNAME) nType = DataType::DATE;
2659 else if(_nTokenId == SQL_TOKEN_NOW) nType = DataType::TIMESTAMP;
2660 else if(_nTokenId == SQL_TOKEN_QUARTER) nType = DataType::DATE;
2661 else if(_nTokenId == SQL_TOKEN_SECOND) nType = DataType::TIME;
2662 else if(_nTokenId == SQL_TOKEN_TIMESTAMPADD) nType = DataType::TIMESTAMP;
2663 else if(_nTokenId == SQL_TOKEN_TIMESTAMPDIFF) nType = DataType::TIMESTAMP;
2664 else if(_nTokenId == SQL_TOKEN_TIMEVALUE) nType = DataType::TIMESTAMP;
2665 else if(_nTokenId == SQL_TOKEN_WEEK) nType = DataType::DATE;
2666 else if(_nTokenId == SQL_TOKEN_YEAR) nType = DataType::DATE;
2668 else if(_nTokenId == SQL_TOKEN_ABS) nType = DataType::DOUBLE;
2669 else if(_nTokenId == SQL_TOKEN_ACOS) nType = DataType::DOUBLE;
2670 else if(_nTokenId == SQL_TOKEN_ASIN) nType = DataType::DOUBLE;
2671 else if(_nTokenId == SQL_TOKEN_ATAN) nType = DataType::DOUBLE;
2672 else if(_nTokenId == SQL_TOKEN_ATAN2) nType = DataType::DOUBLE;
2673 else if(_nTokenId == SQL_TOKEN_CEILING) nType = DataType::DOUBLE;
2674 else if(_nTokenId == SQL_TOKEN_COS) nType = DataType::DOUBLE;
2675 else if(_nTokenId == SQL_TOKEN_COT) nType = DataType::DOUBLE;
2676 else if(_nTokenId == SQL_TOKEN_DEGREES) nType = DataType::DOUBLE;
2677 else if(_nTokenId == SQL_TOKEN_EXP) nType = DataType::DOUBLE;
2678 else if(_nTokenId == SQL_TOKEN_FLOOR) nType = DataType::DOUBLE;
2679 else if(_nTokenId == SQL_TOKEN_LOGF) nType = DataType::DOUBLE;
2680 else if(_nTokenId == SQL_TOKEN_LOG) nType = DataType::DOUBLE;
2681 else if(_nTokenId == SQL_TOKEN_LOG10) nType = DataType::DOUBLE;
2682 else if(_nTokenId == SQL_TOKEN_LN) nType = DataType::DOUBLE;
2683 else if(_nTokenId == SQL_TOKEN_MOD) nType = DataType::DOUBLE;
2684 else if(_nTokenId == SQL_TOKEN_PI) nType = DataType::DOUBLE;
2685 else if(_nTokenId == SQL_TOKEN_POWER) nType = DataType::DOUBLE;
2686 else if(_nTokenId == SQL_TOKEN_RADIANS) nType = DataType::DOUBLE;
2687 else if(_nTokenId == SQL_TOKEN_RAND) nType = DataType::DOUBLE;
2688 else if(_nTokenId == SQL_TOKEN_ROUND) nType = DataType::DOUBLE;
2689 else if(_nTokenId == SQL_TOKEN_ROUNDMAGIC) nType = DataType::DOUBLE;
2690 else if(_nTokenId == SQL_TOKEN_SIGN) nType = DataType::DOUBLE;
2691 else if(_nTokenId == SQL_TOKEN_SIN) nType = DataType::DOUBLE;
2692 else if(_nTokenId == SQL_TOKEN_SQRT) nType = DataType::DOUBLE;
2693 else if(_nTokenId == SQL_TOKEN_TAN) nType = DataType::DOUBLE;
2694 else if(_nTokenId == SQL_TOKEN_TRUNCATE) nType = DataType::DOUBLE;
2695 else if(_nTokenId == SQL_TOKEN_COUNT) nType = DataType::INTEGER;
2696 else if(_nTokenId == SQL_TOKEN_MAX) nType = DataType::DOUBLE;
2697 else if(_nTokenId == SQL_TOKEN_MIN) nType = DataType::DOUBLE;
2698 else if(_nTokenId == SQL_TOKEN_AVG) nType = DataType::DOUBLE;
2699 else if(_nTokenId == SQL_TOKEN_SUM) nType = DataType::DOUBLE;
2701 else if(_nTokenId == SQL_TOKEN_LOWER) nType = DataType::VARCHAR;
2702 else if(_nTokenId == SQL_TOKEN_UPPER) nType = DataType::VARCHAR;
2704 return nType;
2708 const SQLError& OSQLParser::getErrorHelper() const
2710 return m_pData->aErrors;
2714 OSQLParseNode::Rule OSQLParseNode::getKnownRuleID() const
2716 if ( !isRule() )
2717 return UNKNOWN_RULE;
2718 return OSQLParser::RuleIDToRule( getRuleID() );
2721 OUString OSQLParseNode::getTableRange(const OSQLParseNode* _pTableRef)
2723 OSL_ENSURE(_pTableRef && _pTableRef->count() > 1 && _pTableRef->getKnownRuleID() == OSQLParseNode::table_ref,"Invalid node give, only table ref is allowed!");
2724 const sal_uInt32 nCount = _pTableRef->count();
2725 OUString sTableRange;
2726 if ( nCount == 2 || (nCount == 3 && !_pTableRef->getChild(0)->isToken()) )
2728 const OSQLParseNode* pNode = _pTableRef->getChild(nCount - (nCount == 2 ? 1 : 2));
2729 OSL_ENSURE(pNode && (pNode->getKnownRuleID() == OSQLParseNode::table_primary_as_range_column
2730 || pNode->getKnownRuleID() == OSQLParseNode::range_variable)
2731 ,"SQL grammar changed!");
2732 if ( !pNode->isLeaf() )
2733 sTableRange = pNode->getChild(1)->getTokenValue();
2734 } // if ( nCount == 2 || nCount == 3 )
2736 return sTableRange;
2739 OSQLParseNodesContainer::OSQLParseNodesContainer()
2743 OSQLParseNodesContainer::~OSQLParseNodesContainer()
2747 void OSQLParseNodesContainer::push_back(OSQLParseNode* _pNode)
2749 ::osl::MutexGuard aGuard(m_aMutex);
2750 m_aNodes.push_back(_pNode);
2753 void OSQLParseNodesContainer::erase(OSQLParseNode* _pNode)
2755 ::osl::MutexGuard aGuard(m_aMutex);
2756 if ( !m_aNodes.empty() )
2758 std::vector< OSQLParseNode* >::iterator aFind = std::find(m_aNodes.begin(), m_aNodes.end(),_pNode);
2759 if ( aFind != m_aNodes.end() )
2760 m_aNodes.erase(aFind);
2764 void OSQLParseNodesContainer::clear()
2766 ::osl::MutexGuard aGuard(m_aMutex);
2767 m_aNodes.clear();
2770 void OSQLParseNodesContainer::clearAndDelete()
2772 ::osl::MutexGuard aGuard(m_aMutex);
2773 // clear the garbage collector
2774 while ( !m_aNodes.empty() )
2776 OSQLParseNode* pNode = m_aNodes[0];
2777 while ( pNode->getParent() )
2779 pNode = pNode->getParent();
2781 delete pNode;
2784 } // namespace connectivity
2786 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */