tdf#130857 qt weld: Implement QtInstanceWidget::strip_mnemonic
[LibreOffice.git] / connectivity / source / parse / sqlnode.cxx
blob95d6e88c2215d4017bffc4bb3c3a14f47263b2e5
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 <comphelper/diagnose_ex.hxx>
54 #include <string.h>
55 #include <algorithm>
56 #include <functional>
57 #include <memory>
58 #include <string_view>
60 #include <rtl/ustrbuf.hxx>
61 #include <sal/log.hxx>
62 #include <utility>
64 using namespace ::com::sun::star::sdbc;
65 using namespace ::com::sun::star::util;
66 using namespace ::com::sun::star::beans;
67 using namespace ::com::sun::star::sdb;
68 using namespace ::com::sun::star::uno;
69 using namespace ::com::sun::star::lang;
70 using namespace ::com::sun::star::i18n;
71 using namespace ::com::sun::star;
72 using namespace ::osl;
73 using namespace ::dbtools;
74 using namespace ::comphelper;
76 namespace
79 bool lcl_saveConvertToNumber(const Reference< XNumberFormatter > & _xFormatter,sal_Int32 _nKey,const OUString& _sValue,double& _nrValue)
81 bool bRet = false;
82 try
84 _nrValue = _xFormatter->convertStringToNumber(_nKey, _sValue);
85 bRet = true;
87 catch(Exception&)
90 return bRet;
93 void replaceAndReset(connectivity::OSQLParseNode*& _pResetNode,connectivity::OSQLParseNode* _pNewNode)
95 _pResetNode->getParent()->replaceAndDelete(_pResetNode, _pNewNode);
96 _pResetNode = _pNewNode;
99 /** quotes a string and search for quotes inside the string and replace them with the new quote
100 @param rValue
101 The value to be quoted.
102 @param rQuote
103 The quote
104 @param rQuoteToReplace
105 The quote to replace with
106 @return
107 The quoted string.
109 OUString SetQuotation(const OUString& rValue, std::u16string_view rQuote, std::u16string_view rQuoteToReplace)
111 // Replace quotes with double quotes or the parser gets into problems
112 if (!rQuote.empty())
113 return rQuote + rValue.replaceAll(rQuote, rQuoteToReplace) + rQuote;
114 return rValue;
117 bool columnMatchP(const connectivity::OSQLParseNode* pSubTree, const connectivity::SQLParseNodeParameter& rParam)
119 using namespace connectivity;
120 assert(SQL_ISRULE(pSubTree,column_ref));
122 if(!rParam.xField.is())
123 return false;
125 // retrieve the field's name & table range
126 OUString aFieldName;
129 sal_Int32 nNamePropertyId = PROPERTY_ID_NAME;
130 if ( rParam.xField->getPropertySetInfo()->hasPropertyByName( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_REALNAME ) ) )
131 nNamePropertyId = PROPERTY_ID_REALNAME;
132 rParam.xField->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( nNamePropertyId ) ) >>= aFieldName;
134 catch ( Exception& )
138 if(!pSubTree->count())
139 return false;
141 const OSQLParseNode* pCol = pSubTree->getChild(pSubTree->count()-1);
142 if (SQL_ISRULE(pCol,column_val))
144 assert(pCol->count() == 1);
145 pCol = pCol->getChild(0);
147 const OSQLParseNode* pTable(nullptr);
148 switch (pSubTree->count())
150 case 1:
151 break;
152 case 3:
153 pTable = pSubTree->getChild(0);
154 break;
155 case 5:
156 case 7:
157 SAL_WARN("connectivity.parse", "SQL: catalog and/or schema in column_ref in predicate");
158 break;
159 default:
160 SAL_WARN("connectivity.parse", "columnMatchP: SQL grammar changed; column_ref has " << pSubTree->count() << " children");
161 assert(false);
162 break;
164 // TODO: not all DBMS match column names case-insensitively...
165 // see XDatabaseMetaData::supportsMixedCaseIdentifiers()
166 // and XDatabaseMetaData::supportsMixedCaseQuotedIdentifiers()
167 if ( // table name matches (or no table name)?
168 ( !pTable || pTable->getTokenValue().equalsIgnoreAsciiCase(rParam.sPredicateTableAlias) )
169 && // column name matches?
170 pCol->getTokenValue().equalsIgnoreAsciiCase(aFieldName)
172 return true;
173 return false;
177 namespace connectivity
180 SQLParseNodeParameter::SQLParseNodeParameter( const Reference< XConnection >& _rxConnection,
181 const Reference< XNumberFormatter >& _xFormatter, const Reference< XPropertySet >& _xField,
182 OUString _sPredicateTableAlias,
183 const Locale& _rLocale, const IParseContext* _pContext,
184 bool _bIntl, bool _bQuote, OUString _sDecSep, bool _bPredicate, bool _bParseToSDBC )
185 :rLocale(_rLocale)
186 ,aMetaData( _rxConnection )
187 ,pParser( nullptr )
188 ,pSubQueryHistory( std::make_shared<QueryNameSet>() )
189 ,xFormatter(_xFormatter)
190 ,xField(_xField)
191 ,sPredicateTableAlias(std::move(_sPredicateTableAlias))
192 ,m_rContext( _pContext ? *_pContext : OSQLParser::s_aDefaultContext )
193 ,sDecSep(std::move(_sDecSep))
194 ,bQuote(_bQuote)
195 ,bInternational(_bIntl)
196 ,bPredicate(_bPredicate)
197 ,bParseToSDBCLevel( _bParseToSDBC )
201 OUString OSQLParseNode::convertDateString(const SQLParseNodeParameter& rParam, std::u16string_view rString)
203 Date aDate = DBTypeConversion::toDate(rString);
204 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
205 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
207 double fDate = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
208 sal_Int32 nKey = xTypes->getFormatIndex(NumberFormatIndex::DATE_SYS_DDMMYYYY, rParam.rLocale);
209 return rParam.xFormatter->convertNumberToString(nKey, fDate);
213 OUString OSQLParseNode::convertDateTimeString(const SQLParseNodeParameter& rParam, const OUString& rString)
215 DateTime aDate = DBTypeConversion::toDateTime(rString);
216 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
217 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
219 double fDateTime = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
220 sal_Int32 nKey = xTypes->getFormatIndex(NumberFormatIndex::DATETIME_SYS_DDMMYYYY_HHMMSS, rParam.rLocale);
221 return rParam.xFormatter->convertNumberToString(nKey, fDateTime);
225 OUString OSQLParseNode::convertTimeString(const SQLParseNodeParameter& rParam, std::u16string_view rString)
227 css::util::Time aTime = DBTypeConversion::toTime(rString);
228 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
230 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
232 double fTime = DBTypeConversion::toDouble(aTime);
233 sal_Int32 nKey = xTypes->getFormatIndex(NumberFormatIndex::TIME_HHMMSS, rParam.rLocale);
234 return rParam.xFormatter->convertNumberToString(nKey, fTime);
238 void OSQLParseNode::parseNodeToStr(OUString& rString,
239 const Reference< XConnection >& _rxConnection,
240 const IParseContext* pContext,
241 bool _bIntl,
242 bool _bQuote) const
244 parseNodeToStr(
245 rString, _rxConnection, nullptr, nullptr, OUString(),
246 pContext ? pContext->getPreferredLocale() : OParseContext::getDefaultLocale(),
247 pContext, _bIntl, _bQuote, u"."_ustr, false );
251 void OSQLParseNode::parseNodeToPredicateStr(OUString& rString,
252 const Reference< XConnection >& _rxConnection,
253 const Reference< XNumberFormatter > & xFormatter,
254 const css::lang::Locale& rIntl,
255 const OUString& rDec,
256 const IParseContext* pContext ) const
258 OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
260 if (xFormatter.is())
261 parseNodeToStr(rString, _rxConnection, xFormatter, nullptr, OUString(), rIntl, pContext, true, true, rDec, true);
265 void OSQLParseNode::parseNodeToPredicateStr(OUString& rString,
266 const Reference< XConnection > & _rxConnection,
267 const Reference< XNumberFormatter > & xFormatter,
268 const Reference< XPropertySet > & _xField,
269 const OUString &_sPredicateTableAlias,
270 const css::lang::Locale& rIntl,
271 const OUString& rDec,
272 const IParseContext* pContext ) const
274 OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
276 if (xFormatter.is())
277 parseNodeToStr( rString, _rxConnection, xFormatter, _xField, _sPredicateTableAlias, rIntl, pContext, true, true, rDec, true );
281 void OSQLParseNode::parseNodeToStr(OUString& rString,
282 const Reference< XConnection > & _rxConnection,
283 const Reference< XNumberFormatter > & xFormatter,
284 const Reference< XPropertySet > & _xField,
285 const OUString &_sPredicateTableAlias,
286 const css::lang::Locale& rIntl,
287 const IParseContext* pContext,
288 bool _bIntl,
289 bool _bQuote,
290 const OUString& _rDecSep,
291 bool _bPredicate) const
293 OSL_ENSURE( _rxConnection.is(), "OSQLParseNode::parseNodeToStr: invalid connection!" );
295 if ( !_rxConnection.is() )
296 return;
298 OUStringBuffer sBuffer(rString);
301 OSQLParseNode::impl_parseNodeToString_throw( sBuffer,
302 SQLParseNodeParameter(
303 _rxConnection, xFormatter, _xField, _sPredicateTableAlias, rIntl, pContext,
304 _bIntl, _bQuote, _rDecSep, _bPredicate, false
305 ) );
307 catch( const SQLException& )
309 SAL_WARN( "connectivity.parse", "OSQLParseNode::parseNodeToStr: this should not throw!" );
310 // our callers don't expect this method to throw anything. The only known situation
311 // where impl_parseNodeToString_throw can throw is when there is a cyclic reference
312 // in the sub queries, but this cannot be the case here, as we do not parse to
313 // SDBC level.
315 rString = sBuffer.makeStringAndClear();
318 bool OSQLParseNode::parseNodeToExecutableStatement( OUString& _out_rString, const Reference< XConnection >& _rxConnection,
319 OSQLParser& _rParser, css::sdbc::SQLException* _pErrorHolder ) const
321 OSL_PRECOND( _rxConnection.is(), "OSQLParseNode::parseNodeToExecutableStatement: invalid connection!" );
322 SQLParseNodeParameter aParseParam( _rxConnection,
323 nullptr, nullptr, OUString(), OParseContext::getDefaultLocale(), nullptr, false, true, u"."_ustr, false, true );
325 if ( aParseParam.aMetaData.supportsSubqueriesInFrom() )
327 Reference< XQueriesSupplier > xSuppQueries( _rxConnection, UNO_QUERY );
328 OSL_ENSURE( xSuppQueries.is(), "OSQLParseNode::parseNodeToExecutableStatement: cannot substitute everything without a QueriesSupplier!" );
329 if ( xSuppQueries.is() )
330 aParseParam.xQueries = xSuppQueries->getQueries();
333 aParseParam.pParser = &_rParser;
335 // LIMIT keyword differs in Firebird
336 OSQLParseNode* pTableExp = getChild(3);
337 Reference< XDatabaseMetaData > xMeta( _rxConnection->getMetaData() );
338 OUString sLimitValue;
339 if( pTableExp->getChild(6)->count() >= 2 && pTableExp->getChild(6)->getChild(1)
340 && (xMeta->getURL().equalsIgnoreAsciiCase("sdbc:embedded:firebird")
341 || xMeta->getURL().startsWithIgnoreAsciiCase("sdbc:firebird:")))
343 sLimitValue = pTableExp->getChild(6)->getChild(1)->getTokenValue();
344 delete pTableExp->removeAt(6);
347 _out_rString.clear();
348 OUStringBuffer sBuffer;
349 bool bSuccess = false;
352 impl_parseNodeToString_throw( sBuffer, aParseParam );
353 bSuccess = true;
355 catch( const SQLException& e )
357 if ( _pErrorHolder )
358 *_pErrorHolder = e;
361 if(sLimitValue.getLength() > 0)
363 static constexpr char SELECT_KEYWORD[] = "SELECT";
364 sBuffer.insert(sBuffer.indexOf(SELECT_KEYWORD) + strlen(SELECT_KEYWORD),
365 Concat2View(" FIRST " + sLimitValue));
368 _out_rString = sBuffer.makeStringAndClear();
369 return bSuccess;
373 namespace
375 bool lcl_isAliasNamePresent( const OSQLParseNode& _rTableNameNode )
377 return !OSQLParseNode::getTableRange(_rTableNameNode.getParent()).isEmpty();
382 void OSQLParseNode::impl_parseNodeToString_throw(OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple) const
384 if ( isToken() )
386 parseLeaf(rString,rParam);
387 return;
390 // Let's see how many nodes this subtree has
391 sal_uInt32 nCount = count();
393 bool bHandled = false;
394 switch ( getKnownRuleID() )
396 // special handling for parameters
397 case parameter:
399 bSimple=false;
400 if(!rString.isEmpty())
401 rString.append(" ");
402 if (nCount == 1) // ?
403 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
404 else if (rParam.bParseToSDBCLevel && rParam.aMetaData.shouldSubstituteParameterNames())
406 rString.append("?");
408 else if (nCount == 2) // :Name
410 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
411 rString.append(m_aChildren[1]->m_aNodeValue);
412 } // [Name]
413 else
415 assert (nCount == 3);
416 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
417 rString.append(m_aChildren[1]->m_aNodeValue);
418 rString.append(m_aChildren[2]->m_aNodeValue);
420 bHandled = true;
422 break;
424 // table refs
425 case table_ref:
426 bSimple=false;
427 if ( ( nCount == 2 ) || ( nCount == 3 ) || ( nCount == 5 ) )
429 impl_parseTableRangeNodeToString_throw( rString, rParam );
430 bHandled = true;
432 break;
434 // table name - might be a query name
435 case table_name:
436 bSimple=false;
437 bHandled = impl_parseTableNameNodeToString_throw( rString, rParam );
438 break;
440 case as_clause:
441 bSimple=false;
442 assert(nCount == 0 || nCount == 2);
443 if (nCount == 2)
445 if ( rParam.aMetaData.generateASBeforeCorrelationName() )
446 rString.append(" AS ");
447 m_aChildren[1]->impl_parseNodeToString_throw( rString, rParam, false );
449 bHandled = true;
450 break;
452 case opt_as:
453 assert(nCount == 0);
454 bHandled = true;
455 break;
457 case like_predicate:
458 // Depending on whether international is given, LIKE is treated differently
459 // international: *, ? are placeholders
460 // else SQL92 conform: %, _
461 impl_parseLikeNodeToString_throw( rString, rParam, bSimple );
462 bHandled = true;
463 break;
465 case general_set_fct:
466 case set_fct_spec:
467 case position_exp:
468 case extract_exp:
469 case length_exp:
470 case char_value_fct:
471 bSimple=false;
472 if (!addDateValue(rString, rParam))
474 // Do not quote function name
475 SQLParseNodeParameter aNewParam(rParam);
476 aNewParam.bQuote = ( SQL_ISRULE(this,length_exp) || SQL_ISRULE(this,char_value_fct) );
478 m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam, false );
479 aNewParam.bQuote = rParam.bQuote;
480 //aNewParam.bPredicate = sal_False; // disable [ ] around names // look at i73215
481 OUStringBuffer aStringPara;
482 for (sal_uInt32 i=1; i<nCount; i++)
484 const OSQLParseNode * pSubTree = m_aChildren[i].get();
485 if (pSubTree)
487 pSubTree->impl_parseNodeToString_throw( aStringPara, aNewParam, false );
489 // In the comma lists, put commas in-between all subtrees
490 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i < (nCount - 1)))
491 aStringPara.append(",");
493 else
494 i++;
496 rString.append(aStringPara);
498 bHandled = true;
499 break;
500 case odbc_call_spec:
501 case subquery:
502 case term:
503 case factor:
504 case window_function:
505 case cast_spec:
506 case num_value_exp:
507 bSimple = false;
508 break;
509 default:
510 break;
511 } // switch ( getKnownRuleID() )
513 if ( bHandled )
514 return;
516 for (auto i = m_aChildren.begin(); i != m_aChildren.end();)
518 const OSQLParseNode* pSubTree = i->get();
519 if ( !pSubTree )
521 ++i;
522 continue;
525 SQLParseNodeParameter aNewParam(rParam);
527 // don't replace the field for subqueries
528 if (rParam.xField.is() && SQL_ISRULE(pSubTree,subquery))
529 aNewParam.xField = nullptr;
531 // When we are building a criterion inside a query view,
532 // simplify criterion display by removing:
533 // "currentFieldName"
534 // "currentFieldName" =
535 // but only in simple expressions.
536 // This means anything that is made of:
537 // (see the rules conditionalised by inPredicateCheck() in sqlbison.y).
538 // - parentheses
539 // - logical operators (and, or, not)
540 // - comparison operators (IS, =, >, <, BETWEEN, LIKE, ...)
541 // but *not* e.g. in function arguments
542 if (bSimple && rParam.bPredicate && rParam.xField.is() && SQL_ISRULE(pSubTree,column_ref))
544 if (columnMatchP(pSubTree, rParam))
546 // skip field
547 ++i;
548 // if the following node is the comparison operator'=',
549 // we filter it as well
550 if (SQL_ISRULE(this, comparison_predicate))
552 if(i != m_aChildren.end())
554 pSubTree = i->get();
555 if (pSubTree && pSubTree->getNodeType() == SQLNodeType::Equal)
556 ++i;
560 else
562 pSubTree->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
563 ++i;
565 // In the comma lists, put commas in-between all subtrees
566 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i != m_aChildren.end()))
567 rString.append(",");
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()))
578 if (SQL_ISRULE(this,value_exp_commalist) && rParam.bPredicate)
579 rString.append(";");
580 else
581 rString.append(",");
584 // The right hand-side of these operators is not simple
585 switch ( getKnownRuleID() )
587 case general_set_fct:
588 case set_fct_spec:
589 case position_exp:
590 case extract_exp:
591 case length_exp:
592 case char_value_fct:
593 case odbc_call_spec:
594 case subquery:
595 case comparison_predicate:
596 case between_predicate:
597 case like_predicate:
598 case test_for_null:
599 case in_predicate:
600 case existence_test:
601 case unique_test:
602 case all_or_any_predicate:
603 case join_condition:
604 case comparison_predicate_part_2:
605 case parenthesized_boolean_value_expression:
606 case other_like_predicate_part_2:
607 case between_predicate_part_2:
608 bSimple=false;
609 break;
610 default:
611 break;
617 bool OSQLParseNode::impl_parseTableNameNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const
619 // is the table_name part of a table_ref?
620 OSL_ENSURE( getParent(), "OSQLParseNode::impl_parseTableNameNodeToString_throw: table_name without parent?" );
621 if ( !getParent() || ( getParent()->getKnownRuleID() != table_ref ) )
622 return false;
624 // if it's a query, maybe we need to substitute the SQL statement ...
625 if ( !rParam.bParseToSDBCLevel )
626 return false;
628 if ( !rParam.xQueries.is() )
629 // connection does not support queries in queries, or was no query supplier
630 return false;
634 OUString sTableOrQueryName( getChild(0)->getTokenValue() );
635 bool bIsQuery = rParam.xQueries->hasByName( sTableOrQueryName );
636 if ( !bIsQuery )
637 return false;
639 // avoid recursion (e.g. "foo" defined as "SELECT * FROM bar" and "bar" defined as "SELECT * FROM foo".
640 if ( rParam.pSubQueryHistory->find( sTableOrQueryName ) != rParam.pSubQueryHistory->end() )
642 OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: no parser?" );
643 if ( rParam.pParser )
645 const SQLError& rErrors( rParam.pParser->getErrorHelper() );
646 rErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
648 else
650 SQLError aErrors;
651 aErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
654 rParam.pSubQueryHistory->insert( sTableOrQueryName );
656 Reference< XPropertySet > xQuery( rParam.xQueries->getByName( sTableOrQueryName ), UNO_QUERY_THROW );
658 // substitute the query name with the constituting command
659 OUString sCommand;
660 OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_COMMAND ) ) >>= sCommand );
662 bool bEscapeProcessing = false;
663 OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ) ) >>= bEscapeProcessing );
665 // the query we found here might itself be based on another query, so parse it recursively
666 OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: cannot analyze sub queries without a parser!" );
667 if ( bEscapeProcessing && rParam.pParser )
669 OUString sError;
670 std::unique_ptr< OSQLParseNode > pSubQueryNode( rParam.pParser->parseTree( sError, sCommand ) );
671 if (pSubQueryNode)
673 // parse the sub-select to SDBC level, too
674 OUStringBuffer sSubSelect;
675 pSubQueryNode->impl_parseNodeToString_throw( sSubSelect, rParam, false );
676 if ( !sSubSelect.isEmpty() )
677 sCommand = sSubSelect.makeStringAndClear();
681 rString.append( " ( " );
682 rString.append(sCommand);
683 rString.append( " )" );
685 // append the query name as table alias, since it might be referenced in other
686 // parts of the statement - but only if there's no other alias name present
687 if ( !lcl_isAliasNamePresent( *this ) )
689 rString.append( " AS " );
690 if ( rParam.bQuote )
691 rString.append(SetQuotation( sTableOrQueryName,
692 rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
695 // don't forget to remove the query name from the history, else multiple inclusions
696 // won't work
697 // #i69227# / 2006-10-10 / frank.schoenheit@sun.com
698 rParam.pSubQueryHistory->erase( sTableOrQueryName );
700 return true;
702 catch( const SQLException& )
704 throw;
706 catch( const Exception& )
708 DBG_UNHANDLED_EXCEPTION("connectivity.parse");
710 return false;
714 void OSQLParseNode::impl_parseTableRangeNodeToString_throw(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
716 OSL_PRECOND( ( count() == 2 ) || ( count() == 3 ) || ( count() == 5 ) ,"Illegal count");
718 // rString += " ";
719 std::for_each(m_aChildren.begin(),m_aChildren.end(),
720 [&] (std::unique_ptr<OSQLParseNode> const & pNode) { pNode->impl_parseNodeToString_throw(rString, rParam, false); });
724 void OSQLParseNode::impl_parseLikeNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple ) const
726 assert(SQL_ISRULE(this,like_predicate));
727 OSL_ENSURE(count() == 2,"count != 2: Prepare for GPF");
729 const OSQLParseNode* pEscNode = nullptr;
730 const OSQLParseNode* pParaNode = nullptr;
732 const SQLParseNodeParameter& aNewParam(rParam);
733 //aNewParam.bQuote = sal_True; // why setting this to true? @see https://bz.apache.org/ooo/show_bug.cgi?id=75557
735 if ( !(bSimple && rParam.bPredicate && rParam.xField.is() && SQL_ISRULE(m_aChildren[0],column_ref) && columnMatchP(m_aChildren[0].get(), rParam)) )
736 m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
738 const OSQLParseNode* pPart2 = m_aChildren[1].get();
739 pPart2->getChild(0)->impl_parseNodeToString_throw( rString, aNewParam, false );
740 pPart2->getChild(1)->impl_parseNodeToString_throw( rString, aNewParam, false );
741 pParaNode = pPart2->getChild(2);
742 pEscNode = pPart2->getChild(3);
744 if (pParaNode->isToken())
746 OUString aStr = ConvertLikeToken(pParaNode, pEscNode, rParam.bInternational);
747 rString.append(" ");
748 rString.append(SetQuotation(aStr, u"\'", u"\'\'"));
750 else
751 pParaNode->impl_parseNodeToString_throw( rString, aNewParam, false );
753 pEscNode->impl_parseNodeToString_throw( rString, aNewParam, false );
757 bool OSQLParseNode::getTableComponents(const OSQLParseNode* _pTableNode,
758 css::uno::Any &_rCatalog,
759 OUString &_rSchema,
760 OUString &_rTable,
761 const Reference< XDatabaseMetaData >& _xMetaData)
763 OSL_ENSURE(_pTableNode,"Wrong use of getTableComponents! _pTableNode is not allowed to be null!");
764 if(_pTableNode)
766 const bool bSupportsCatalog = _xMetaData.is() && _xMetaData->supportsCatalogsInDataManipulation();
767 const bool bSupportsSchema = _xMetaData.is() && _xMetaData->supportsSchemasInDataManipulation();
768 const OSQLParseNode* pTableNode = _pTableNode;
769 // clear the parameter given
770 _rCatalog = Any();
771 _rSchema.clear();
772 _rTable.clear();
773 // see rule catalog_name: in sqlbison.y
774 if (SQL_ISRULE(pTableNode,catalog_name))
776 OSL_ENSURE(pTableNode->getChild(0) && pTableNode->getChild(0)->isToken(),"Invalid parsenode!");
777 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
778 pTableNode = pTableNode->getChild(2);
780 // check if we have schema_name rule
781 if(SQL_ISRULE(pTableNode,schema_name))
783 if ( bSupportsCatalog && !bSupportsSchema )
784 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
785 else
786 _rSchema = pTableNode->getChild(0)->getTokenValue();
787 pTableNode = pTableNode->getChild(2);
789 // check if we have table_name rule
790 if(SQL_ISRULE(pTableNode,table_name))
792 _rTable = pTableNode->getChild(0)->getTokenValue();
794 else
796 SAL_WARN( "connectivity.parse","Error in parse tree!");
799 return !_rTable.isEmpty();
802 void OSQLParser::killThousandSeparator(OSQLParseNode* pLiteral)
804 if ( pLiteral )
806 auto& s_xLocaleData = getLocaleData();
807 if ( s_xLocaleData.get()->get()->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
809 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace('.', sal_Unicode());
810 // and replace decimal
811 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', '.');
813 else
814 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', sal_Unicode());
818 OSQLParseNode* OSQLParser::convertNode(sal_Int32 nType, OSQLParseNode* pLiteral)
820 if ( !pLiteral )
821 return nullptr;
823 OSQLParseNode* pReturn = pLiteral;
825 if ( ( pLiteral->isRule() && !SQL_ISRULE(pLiteral,value_exp) ) || SQL_ISTOKEN(pLiteral,FALSE) || SQL_ISTOKEN(pLiteral,TRUE) )
827 switch(nType)
829 case DataType::CHAR:
830 case DataType::VARCHAR:
831 case DataType::LONGVARCHAR:
832 case DataType::CLOB:
833 if ( !SQL_ISRULE(pReturn,char_value_exp) && !buildStringNodes(pReturn) )
834 pReturn = nullptr;
835 break;
836 default:
837 break;
840 else
842 switch(pLiteral->getNodeType())
844 case SQLNodeType::String:
845 switch(nType)
847 case DataType::CHAR:
848 case DataType::VARCHAR:
849 case DataType::LONGVARCHAR:
850 case DataType::CLOB:
851 break;
852 case DataType::DATE:
853 case DataType::TIME:
854 case DataType::TIMESTAMP:
855 if (m_xFormatter.is())
856 pReturn = buildDate( nType, pReturn);
857 break;
858 default:
859 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidCompare);
860 break;
862 break;
863 case SQLNodeType::AccessDate:
864 switch(nType)
866 case DataType::DATE:
867 case DataType::TIME:
868 case DataType::TIMESTAMP:
869 if ( m_xFormatter.is() )
870 pReturn = buildDate( nType, pReturn);
871 else
872 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidDateCompare);
873 break;
874 default:
875 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidCompare);
876 break;
878 break;
879 case SQLNodeType::IntNum:
880 switch(nType)
882 case DataType::BIT:
883 case DataType::BOOLEAN:
884 case DataType::DECIMAL:
885 case DataType::NUMERIC:
886 case DataType::TINYINT:
887 case DataType::SMALLINT:
888 case DataType::INTEGER:
889 case DataType::BIGINT:
890 case DataType::FLOAT:
891 case DataType::REAL:
892 case DataType::DOUBLE:
893 // kill thousand separators if any
894 killThousandSeparator(pReturn);
895 break;
896 case DataType::CHAR:
897 case DataType::VARCHAR:
898 case DataType::LONGVARCHAR:
899 case DataType::CLOB:
900 pReturn = buildNode_STR_NUM(pReturn);
901 break;
902 default:
903 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidIntCompare);
904 break;
906 break;
907 case SQLNodeType::ApproxNum:
908 switch(nType)
910 case DataType::DECIMAL:
911 case DataType::NUMERIC:
912 case DataType::FLOAT:
913 case DataType::REAL:
914 case DataType::DOUBLE:
915 // kill thousand separators if any
916 killThousandSeparator(pReturn);
917 break;
918 case DataType::CHAR:
919 case DataType::VARCHAR:
920 case DataType::LONGVARCHAR:
921 case DataType::CLOB:
922 pReturn = buildNode_STR_NUM(pReturn);
923 break;
924 case DataType::INTEGER:
925 default:
926 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidRealCompare);
927 break;
929 break;
930 default:
934 return pReturn;
937 sal_Int16 OSQLParser::buildPredicateRule(OSQLParseNode*& pAppend, OSQLParseNode* pLiteral, OSQLParseNode* pCompare, OSQLParseNode* pLiteral2)
939 OSL_ENSURE(inPredicateCheck(),"Only in predicate check allowed!");
940 sal_Int16 nErg = 0;
941 if ( m_xField.is() )
943 sal_Int32 nType = 0;
946 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
948 catch( Exception& )
950 return nErg;
953 OSQLParseNode* pNode1 = convertNode(nType,pLiteral);
954 if ( pNode1 )
956 OSQLParseNode* pNode2 = convertNode(nType,pLiteral2);
957 if ( m_sErrorMessage.isEmpty() )
958 nErg = buildNode(pAppend,pCompare,pNode1,pNode2);
961 if (!pCompare->getParent()) // I have no parent so I was not used and I must die :-)
962 delete pCompare;
963 return nErg;
966 sal_Int16 OSQLParser::buildLikeRule(OSQLParseNode* pAppend, OSQLParseNode*& pLiteral, const OSQLParseNode* pEscape)
968 sal_Int16 nErg = 0;
969 sal_Int32 nType = 0;
971 if (!m_xField.is())
972 return nErg;
975 Any aValue;
977 aValue = m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE));
978 aValue >>= nType;
981 catch( Exception& )
983 return nErg;
986 switch (nType)
988 case DataType::CHAR:
989 case DataType::VARCHAR:
990 case DataType::LONGVARCHAR:
991 case DataType::CLOB:
992 if(pLiteral->isRule())
994 pAppend->append(pLiteral);
995 nErg = 1;
997 else
999 switch(pLiteral->getNodeType())
1001 case SQLNodeType::String:
1002 pLiteral->m_aNodeValue = ConvertLikeToken(pLiteral, pEscape, false);
1003 pAppend->append(pLiteral);
1004 nErg = 1;
1005 break;
1006 case SQLNodeType::ApproxNum:
1007 if (m_xFormatter.is() && m_nFormatKey)
1009 sal_Int16 nScale = 0;
1012 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, u"Decimals"_ustr );
1013 aValue >>= nScale;
1015 catch( Exception& )
1019 pAppend->append(new OSQLInternalNode(stringToDouble(pLiteral->getTokenValue(),nScale),SQLNodeType::String));
1021 else
1022 pAppend->append(new OSQLInternalNode(pLiteral->getTokenValue(),SQLNodeType::String));
1024 delete pLiteral;
1025 nErg = 1;
1026 break;
1027 default:
1028 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::ValueNoLike);
1029 m_sErrorMessage = m_sErrorMessage.replaceAt(m_sErrorMessage.indexOf("#1"),2,pLiteral->getTokenValue());
1030 break;
1033 break;
1034 default:
1035 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::FieldNoLike);
1036 break;
1038 return nErg;
1041 OSQLParseNode* OSQLParser::buildNode_Date(const double& fValue, sal_Int32 nType)
1043 OSQLParseNode* pNewNode = new OSQLInternalNode("", SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::set_fct_spec));
1044 pNewNode->append(new OSQLInternalNode("{", SQLNodeType::Punctuation));
1045 OSQLParseNode* pDateNode = new OSQLInternalNode("", SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::odbc_fct_spec));
1046 pNewNode->append(pDateNode);
1047 pNewNode->append(new OSQLInternalNode("}", SQLNodeType::Punctuation));
1049 switch (nType)
1051 case DataType::DATE:
1053 Date aDate = DBTypeConversion::toDate(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1054 OUString aString = DBTypeConversion::toDateString(aDate);
1055 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_D));
1056 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1057 break;
1059 case DataType::TIME:
1061 css::util::Time aTime = DBTypeConversion::toTime(fValue);
1062 OUString aString = DBTypeConversion::toTimeString(aTime);
1063 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_T));
1064 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1065 break;
1067 case DataType::TIMESTAMP:
1069 DateTime aDateTime = DBTypeConversion::toDateTime(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1070 if (aDateTime.Seconds || aDateTime.Minutes || aDateTime.Hours)
1072 OUString aString = DBTypeConversion::toDateTimeString(aDateTime);
1073 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_TS));
1074 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1076 else
1078 Date aDate(aDateTime.Day,aDateTime.Month,aDateTime.Year);
1079 pDateNode->append(new OSQLInternalNode("", SQLNodeType::Keyword, SQL_TOKEN_D));
1080 pDateNode->append(new OSQLInternalNode(DBTypeConversion::toDateString(aDate), SQLNodeType::String));
1082 break;
1086 return pNewNode;
1089 OSQLParseNode* OSQLParser::buildNode_STR_NUM(OSQLParseNode*& _pLiteral)
1091 OSQLParseNode* pReturn = nullptr;
1092 if ( _pLiteral )
1094 if (m_nFormatKey)
1096 sal_Int16 nScale = 0;
1099 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, u"Decimals"_ustr );
1100 aValue >>= nScale;
1102 catch( Exception& )
1106 pReturn = new OSQLInternalNode(stringToDouble(_pLiteral->getTokenValue(),nScale),SQLNodeType::String);
1108 else
1109 pReturn = new OSQLInternalNode(_pLiteral->getTokenValue(),SQLNodeType::String);
1111 delete _pLiteral;
1112 _pLiteral = nullptr;
1114 return pReturn;
1117 OUString OSQLParser::stringToDouble(const OUString& _rValue,sal_Int16 _nScale)
1119 OUString aValue;
1120 if(!m_xCharClass.is())
1121 m_xCharClass = CharacterClassification::create( m_xContext );
1122 auto& s_xLocaleData = getLocaleData();
1123 if( s_xLocaleData.get() )
1127 ParseResult aResult = m_xCharClass->parsePredefinedToken(KParseType::ANY_NUMBER,_rValue,0,m_pData->aLocale,0,OUString(),KParseType::ANY_NUMBER,OUString());
1128 if((aResult.TokenType & KParseType::IDENTNAME) && aResult.EndPos == _rValue.getLength())
1130 aValue = OUString::number(aResult.Value);
1131 sal_Int32 nPos = aValue.lastIndexOf('.');
1132 if((nPos+_nScale) < aValue.getLength())
1133 aValue = aValue.replaceAt(nPos+_nScale,aValue.getLength()-nPos-_nScale, u"");
1134 OUString sDecimalSeparator = s_xLocaleData.get()->get()->getLocaleItem(m_pData->aLocale).decimalSeparator;
1135 aValue = aValue.replaceAt(aValue.lastIndexOf('.'), 1, sDecimalSeparator);
1136 return aValue;
1139 catch(Exception&)
1143 return aValue;
1147 std::mutex& OSQLParser::getMutex()
1149 static std::mutex aMutex;
1150 return aMutex;
1154 std::unique_ptr<OSQLParseNode> OSQLParser::predicateTree(OUString& rErrorMessage, const OUString& rStatement,
1155 const Reference< css::util::XNumberFormatter > & xFormatter,
1156 const Reference< XPropertySet > & xField,
1157 bool bUseRealName)
1159 // Guard the parsing
1160 std::unique_lock aGuard(getMutex());
1161 // must be reset
1162 setParser(this);
1165 // reset the parser
1166 m_xField = xField;
1167 m_xFormatter = xFormatter;
1169 if (m_xField.is())
1171 sal_Int32 nType=0;
1174 // get the field name
1175 OUString aString;
1177 // retrieve the fields name
1178 // #75243# use the RealName of the column if there is any otherwise the name which could be the alias
1179 // of the field
1180 Reference< XPropertySetInfo> xInfo = m_xField->getPropertySetInfo();
1181 if ( bUseRealName && xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)))
1182 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)) >>= aString;
1183 else
1184 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aString;
1186 m_sFieldName = aString;
1188 // get the field format key
1189 if ( xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)))
1190 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) >>= m_nFormatKey;
1191 else
1192 m_nFormatKey = 0;
1194 // get the field type
1195 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
1197 catch ( Exception& )
1199 OSL_ASSERT(false);
1202 if (m_nFormatKey && m_xFormatter.is())
1204 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_LOCALE) );
1205 OSL_ENSURE(aValue.getValueType() == cppu::UnoType<css::lang::Locale>::get(), "OSQLParser::PredicateTree : invalid language property !");
1207 if (aValue.getValueType() == cppu::UnoType<css::lang::Locale>::get())
1208 aValue >>= m_pData->aLocale;
1210 else
1211 m_pData->aLocale = m_pContext->getPreferredLocale();
1213 if ( m_xFormatter.is() )
1217 Reference< css::util::XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1218 if ( xFormatSup.is() )
1220 Reference< css::util::XNumberFormats > xFormats = xFormatSup->getNumberFormats();
1221 if ( xFormats.is() )
1223 css::lang::Locale aLocale;
1224 aLocale.Language = "en";
1225 aLocale.Country = "US";
1226 OUString sFormat(u"YYYY-MM-DD"_ustr);
1227 m_nDateFormatKey = xFormats->queryKey(sFormat,aLocale,false);
1228 if ( m_nDateFormatKey == sal_Int32(-1) )
1229 m_nDateFormatKey = xFormats->addNew(sFormat, aLocale);
1233 catch ( Exception& )
1235 SAL_WARN( "connectivity.parse","DateFormatKey");
1239 switch (nType)
1241 case DataType::DATE:
1242 case DataType::TIME:
1243 case DataType::TIMESTAMP:
1244 s_pScanner->SetRule(OSQLScanner::GetDATERule());
1245 break;
1246 case DataType::CHAR:
1247 case DataType::VARCHAR:
1248 case DataType::LONGVARCHAR:
1249 case DataType::CLOB:
1250 s_pScanner->SetRule(OSQLScanner::GetSTRINGRule());
1251 break;
1252 default:
1254 auto& s_xLocaleData = getLocaleData();
1255 if ( s_xLocaleData.get()->get()->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
1256 s_pScanner->SetRule(OSQLScanner::GetGERRule());
1257 else
1258 s_pScanner->SetRule(OSQLScanner::GetENGRule());
1263 else
1264 s_pScanner->SetRule(OSQLScanner::GetSQLRule());
1266 s_pScanner->prepareScan(rStatement, m_pContext, true);
1268 SQLyylval.pParseNode = nullptr;
1269 // SQLyypvt = NULL;
1270 m_pParseTree = nullptr;
1271 m_sErrorMessage.clear();
1273 // Start the parser
1274 if (SQLyyparse() != 0)
1276 m_sFieldName.clear();
1277 m_xField.clear();
1278 m_xFormatter.clear();
1279 m_nFormatKey = 0;
1280 m_nDateFormatKey = 0;
1282 if (m_sErrorMessage.isEmpty())
1283 m_sErrorMessage = s_pScanner->getErrorMessage();
1284 if (m_sErrorMessage.isEmpty())
1285 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::General);
1287 rErrorMessage = m_sErrorMessage;
1289 // clear the garbage collector
1290 (*s_pGarbageCollector)->clearAndDelete();
1291 // coverity[leaked_storage : FALSE] - because the garbage collector deleted it
1292 m_pParseTree.release();
1293 return nullptr;
1295 else
1297 (*s_pGarbageCollector)->clear();
1299 m_sFieldName.clear();
1300 m_xField.clear();
1301 m_xFormatter.clear();
1302 m_nFormatKey = 0;
1303 m_nDateFormatKey = 0;
1305 // Return the result (the root parse node):
1307 // Instead, the parse method sets the member pParseTree and simply returns that
1308 OSL_ENSURE(m_pParseTree != nullptr,"OSQLParser: Parser did not return a ParseTree!");
1309 return std::move(m_pParseTree);
1314 OSQLParser::OSQLParser(css::uno::Reference< css::uno::XComponentContext > xContext,
1315 const IParseContext* _pContext,
1316 const IParseContext* _pNeutral)
1317 :m_pContext(_pContext)
1318 ,m_pNeutral(_pNeutral)
1319 ,m_pData( new OSQLParser_Data )
1320 ,m_nFormatKey(0)
1321 ,m_nDateFormatKey(0)
1322 ,m_xContext(std::move(xContext))
1326 setParser(this);
1328 #ifdef SQLYYDEBUG
1329 #ifdef SQLYYDEBUG_ON
1330 SQLyydebug = 1;
1331 #endif
1332 #endif
1334 std::unique_lock 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 auto& s_xLocaleData = getLocaleData();
1343 if(!s_xLocaleData.get())
1344 s_xLocaleData.set(LocaleData::create(m_xContext));
1346 // reset to UNKNOWN_RULE
1347 static_assert(OSQLParseNode::UNKNOWN_RULE==0, "UNKNOWN_RULE must be 0 for memset to 0 to work");
1348 memset(OSQLParser::s_nRuleIDs,0,sizeof(OSQLParser::s_nRuleIDs));
1350 const struct
1352 OSQLParseNode::Rule eRule; // the parse node's ID for the rule
1353 OString sRuleName; // the name of the rule ("select_statement")
1354 } aRuleDescriptions[] =
1356 { OSQLParseNode::select_statement, "select_statement"_ostr },
1357 { OSQLParseNode::table_exp, "table_exp"_ostr },
1358 { OSQLParseNode::table_ref_commalist, "table_ref_commalist"_ostr },
1359 { OSQLParseNode::table_ref, "table_ref"_ostr },
1360 { OSQLParseNode::catalog_name, "catalog_name"_ostr },
1361 { OSQLParseNode::schema_name, "schema_name"_ostr },
1362 { OSQLParseNode::table_name, "table_name"_ostr },
1363 { OSQLParseNode::opt_column_commalist, "opt_column_commalist"_ostr },
1364 { OSQLParseNode::column_commalist, "column_commalist"_ostr },
1365 { OSQLParseNode::column_ref_commalist, "column_ref_commalist"_ostr },
1366 { OSQLParseNode::column_ref, "column_ref"_ostr },
1367 { OSQLParseNode::opt_order_by_clause, "opt_order_by_clause"_ostr },
1368 { OSQLParseNode::ordering_spec_commalist, "ordering_spec_commalist"_ostr },
1369 { OSQLParseNode::ordering_spec, "ordering_spec"_ostr },
1370 { OSQLParseNode::opt_asc_desc, "opt_asc_desc"_ostr },
1371 { OSQLParseNode::where_clause, "where_clause"_ostr },
1372 { OSQLParseNode::opt_where_clause, "opt_where_clause"_ostr },
1373 { OSQLParseNode::search_condition, "search_condition"_ostr },
1374 { OSQLParseNode::comparison, "comparison"_ostr },
1375 { OSQLParseNode::comparison_predicate, "comparison_predicate"_ostr },
1376 { OSQLParseNode::between_predicate, "between_predicate"_ostr },
1377 { OSQLParseNode::like_predicate, "like_predicate"_ostr },
1378 { OSQLParseNode::opt_escape, "opt_escape"_ostr },
1379 { OSQLParseNode::test_for_null, "test_for_null"_ostr },
1380 { OSQLParseNode::scalar_exp_commalist, "scalar_exp_commalist"_ostr },
1381 { OSQLParseNode::scalar_exp, "scalar_exp"_ostr },
1382 { OSQLParseNode::parameter_ref, "parameter_ref"_ostr },
1383 { OSQLParseNode::parameter, "parameter"_ostr },
1384 { OSQLParseNode::general_set_fct, "general_set_fct"_ostr },
1385 { OSQLParseNode::range_variable, "range_variable"_ostr },
1386 { OSQLParseNode::column, "column"_ostr },
1387 { OSQLParseNode::delete_statement_positioned, "delete_statement_positioned"_ostr },
1388 { OSQLParseNode::delete_statement_searched, "delete_statement_searched"_ostr },
1389 { OSQLParseNode::update_statement_positioned, "update_statement_positioned"_ostr },
1390 { OSQLParseNode::update_statement_searched, "update_statement_searched"_ostr },
1391 { OSQLParseNode::assignment_commalist, "assignment_commalist"_ostr },
1392 { OSQLParseNode::assignment, "assignment"_ostr },
1393 { OSQLParseNode::values_or_query_spec, "values_or_query_spec"_ostr },
1394 { OSQLParseNode::insert_statement, "insert_statement"_ostr },
1395 { OSQLParseNode::insert_atom_commalist, "insert_atom_commalist"_ostr },
1396 { OSQLParseNode::insert_atom, "insert_atom"_ostr },
1397 { OSQLParseNode::from_clause, "from_clause"_ostr },
1398 { OSQLParseNode::qualified_join, "qualified_join"_ostr },
1399 { OSQLParseNode::cross_union, "cross_union"_ostr },
1400 { OSQLParseNode::select_sublist, "select_sublist"_ostr },
1401 { OSQLParseNode::derived_column, "derived_column"_ostr },
1402 { OSQLParseNode::column_val, "column_val"_ostr },
1403 { OSQLParseNode::set_fct_spec, "set_fct_spec"_ostr },
1404 { OSQLParseNode::boolean_term, "boolean_term"_ostr },
1405 { OSQLParseNode::boolean_primary, "boolean_primary"_ostr },
1406 { OSQLParseNode::num_value_exp, "num_value_exp"_ostr },
1407 { OSQLParseNode::join_type, "join_type"_ostr },
1408 { OSQLParseNode::position_exp, "position_exp"_ostr },
1409 { OSQLParseNode::extract_exp, "extract_exp"_ostr },
1410 { OSQLParseNode::length_exp, "length_exp"_ostr },
1411 { OSQLParseNode::char_value_fct, "char_value_fct"_ostr },
1412 { OSQLParseNode::odbc_call_spec, "odbc_call_spec"_ostr },
1413 { OSQLParseNode::in_predicate, "in_predicate"_ostr },
1414 { OSQLParseNode::existence_test, "existence_test"_ostr },
1415 { OSQLParseNode::unique_test, "unique_test"_ostr },
1416 { OSQLParseNode::all_or_any_predicate, "all_or_any_predicate"_ostr },
1417 { OSQLParseNode::named_columns_join, "named_columns_join"_ostr },
1418 { OSQLParseNode::join_condition, "join_condition"_ostr },
1419 { OSQLParseNode::joined_table, "joined_table"_ostr },
1420 { OSQLParseNode::boolean_factor, "boolean_factor"_ostr },
1421 { OSQLParseNode::sql_not, "sql_not"_ostr },
1422 { OSQLParseNode::manipulative_statement, "manipulative_statement"_ostr },
1423 { OSQLParseNode::subquery, "subquery"_ostr },
1424 { OSQLParseNode::value_exp_commalist, "value_exp_commalist"_ostr },
1425 { OSQLParseNode::odbc_fct_spec, "odbc_fct_spec"_ostr },
1426 { OSQLParseNode::union_statement, "union_statement"_ostr },
1427 { OSQLParseNode::outer_join_type, "outer_join_type"_ostr },
1428 { OSQLParseNode::char_value_exp, "char_value_exp"_ostr },
1429 { OSQLParseNode::term, "term"_ostr },
1430 { OSQLParseNode::value_exp_primary, "value_exp_primary"_ostr },
1431 { OSQLParseNode::value_exp, "value_exp"_ostr },
1432 { OSQLParseNode::selection, "selection"_ostr },
1433 { OSQLParseNode::fold, "fold"_ostr },
1434 { OSQLParseNode::char_substring_fct, "char_substring_fct"_ostr },
1435 { OSQLParseNode::factor, "factor"_ostr },
1436 { OSQLParseNode::base_table_def, "base_table_def"_ostr },
1437 { OSQLParseNode::base_table_element_commalist, "base_table_element_commalist"_ostr },
1438 { OSQLParseNode::data_type, "data_type"_ostr },
1439 { OSQLParseNode::column_def, "column_def"_ostr },
1440 { OSQLParseNode::table_node, "table_node"_ostr },
1441 { OSQLParseNode::as_clause, "as_clause"_ostr },
1442 { OSQLParseNode::opt_as, "opt_as"_ostr },
1443 { OSQLParseNode::op_column_commalist, "op_column_commalist"_ostr },
1444 { OSQLParseNode::table_primary_as_range_column, "table_primary_as_range_column"_ostr },
1445 { OSQLParseNode::datetime_primary, "datetime_primary"_ostr },
1446 { OSQLParseNode::concatenation, "concatenation"_ostr },
1447 { OSQLParseNode::char_factor, "char_factor"_ostr },
1448 { OSQLParseNode::bit_value_fct, "bit_value_fct"_ostr },
1449 { OSQLParseNode::comparison_predicate_part_2, "comparison_predicate_part_2"_ostr },
1450 { OSQLParseNode::parenthesized_boolean_value_expression, "parenthesized_boolean_value_expression"_ostr },
1451 { OSQLParseNode::character_string_type, "character_string_type"_ostr },
1452 { OSQLParseNode::other_like_predicate_part_2, "other_like_predicate_part_2"_ostr },
1453 { OSQLParseNode::between_predicate_part_2, "between_predicate_part_2"_ostr },
1454 { OSQLParseNode::null_predicate_part_2, "null_predicate_part_2"_ostr },
1455 { OSQLParseNode::cast_spec, "cast_spec"_ostr },
1456 { OSQLParseNode::window_function, "window_function"_ostr }
1458 const size_t nRuleMapCount = std::size( aRuleDescriptions );
1459 // added a new rule? Adjust this map!
1460 // +1 for UNKNOWN_RULE
1461 static_assert(nRuleMapCount + 1 == static_cast<size_t>(OSQLParseNode::rule_count), "must be equal");
1463 for (const auto & aRuleDescription : aRuleDescriptions)
1465 // look up the rule description in the our identifier map
1466 sal_uInt32 nParserRuleID = StrToRuleID( aRuleDescription.sRuleName );
1467 // map the parser's rule ID to the OSQLParseNode::Rule
1468 s_aReverseRuleIDLookup[ nParserRuleID ] = aRuleDescription.eRule;
1469 // and map the OSQLParseNode::Rule to the parser's rule ID
1470 s_nRuleIDs[ aRuleDescription.eRule ] = nParserRuleID;
1473 ++s_nRefCount;
1475 if (m_pContext == nullptr)
1476 // take the default context
1477 m_pContext = &s_aDefaultContext;
1479 m_pData->aLocale = m_pContext->getPreferredLocale();
1482 //static
1483 tools::DeleteOnDeinit<css::uno::Reference< css::i18n::XLocaleData4>>& OSQLParser::getLocaleData()
1485 static tools::DeleteOnDeinit<css::uno::Reference< css::i18n::XLocaleData4>> s_xLocaleData(tools::DeleteOnDeinitFlag::Empty);
1486 return s_xLocaleData;
1489 OSQLParser::~OSQLParser()
1491 std::unique_lock aGuard(getMutex());
1492 OSL_ENSURE(s_nRefCount > 0, "OSQLParser::~OSQLParser() : suspicious call : has a refcount of 0 !");
1493 if (!--s_nRefCount)
1495 s_pScanner->setScanner(true);
1496 delete s_pScanner;
1497 s_pScanner = nullptr;
1499 delete s_pGarbageCollector;
1500 s_pGarbageCollector = nullptr;
1502 RuleIDMap().swap(s_aReverseRuleIDLookup);
1504 m_pParseTree = nullptr;
1507 void OSQLParseNode::substituteParameterNames(OSQLParseNode const * _pNode)
1509 sal_Int32 nCount = _pNode->count();
1510 for(sal_Int32 i=0;i < nCount;++i)
1512 OSQLParseNode* pChildNode = _pNode->getChild(i);
1513 if(SQL_ISRULE(pChildNode,parameter) && pChildNode->count() > 1)
1515 OSQLParseNode* pNewNode = new OSQLParseNode("?" ,SQLNodeType::Punctuation,0);
1516 pChildNode->replaceAndDelete(pChildNode->getChild(0), pNewNode);
1517 sal_Int32 nChildCount = pChildNode->count();
1518 for(sal_Int32 j=1;j < nChildCount;++j)
1519 delete pChildNode->removeAt(1);
1521 else
1522 substituteParameterNames(pChildNode);
1527 bool OSQLParser::extractDate(OSQLParseNode const * pLiteral,double& _rfValue)
1529 Reference< XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1530 Reference< XNumberFormatTypes > xFormatTypes;
1531 if ( xFormatSup.is() )
1532 xFormatTypes.set(xFormatSup->getNumberFormats(), css::uno::UNO_QUERY);
1534 // if there is no format key, yet, make sure we have a feasible one for our locale
1537 if ( !m_nFormatKey && xFormatTypes.is() )
1538 m_nFormatKey = ::dbtools::getDefaultNumberFormat( m_xField, xFormatTypes, m_pData->aLocale );
1540 catch( Exception& ) { }
1541 const OUString& sValue = pLiteral->getTokenValue();
1542 sal_Int32 nTryFormat = m_nFormatKey;
1543 bool bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1545 // If our format key didn't do, try the default date format for our locale.
1546 if ( !bSuccess && xFormatTypes.is() )
1550 nTryFormat = xFormatTypes->getStandardFormat( NumberFormat::DATE, m_pData->aLocale );
1552 catch( Exception& ) { }
1553 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1556 // if this also didn't do, try ISO format
1557 if ( !bSuccess && xFormatTypes.is() )
1561 nTryFormat = xFormatTypes->getFormatIndex( NumberFormatIndex::DATE_DIN_YYYYMMDD, m_pData->aLocale );
1563 catch( Exception& ) { }
1564 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1567 // if this also didn't do, try fallback date format (en-US)
1568 if ( !bSuccess )
1570 nTryFormat = m_nDateFormatKey;
1571 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1573 return bSuccess;
1576 OSQLParseNode* OSQLParser::buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral)
1578 // try converting the string into a date, according to our format key
1579 double fValue = 0.0;
1580 OSQLParseNode* pFCTNode = nullptr;
1582 if ( extractDate(pLiteral,fValue) )
1583 pFCTNode = buildNode_Date( fValue, _nType);
1585 delete pLiteral;
1586 pLiteral = nullptr;
1588 if ( !pFCTNode )
1589 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidDateCompare);
1591 return pFCTNode;
1595 OSQLParseNode::OSQLParseNode(const char * pNewValue,
1596 SQLNodeType eNewNodeType,
1597 sal_uInt32 nNewNodeID)
1598 :m_pParent(nullptr)
1599 ,m_aNodeValue(pNewValue,strlen(pNewValue),RTL_TEXTENCODING_UTF8)
1600 ,m_eNodeType(eNewNodeType)
1601 ,m_nNodeID(nNewNodeID)
1603 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1606 OSQLParseNode::OSQLParseNode(std::string_view _rNewValue,
1607 SQLNodeType eNewNodeType,
1608 sal_uInt32 nNewNodeID)
1609 :m_pParent(nullptr)
1610 ,m_aNodeValue(OStringToOUString(_rNewValue,RTL_TEXTENCODING_UTF8))
1611 ,m_eNodeType(eNewNodeType)
1612 ,m_nNodeID(nNewNodeID)
1614 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1617 OSQLParseNode::OSQLParseNode(OUString _aNewValue,
1618 SQLNodeType eNewNodeType,
1619 sal_uInt32 nNewNodeID)
1620 :m_pParent(nullptr)
1621 ,m_aNodeValue(std::move(_aNewValue))
1622 ,m_eNodeType(eNewNodeType)
1623 ,m_nNodeID(nNewNodeID)
1625 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1628 OSQLParseNode::OSQLParseNode(const OSQLParseNode& rParseNode)
1630 // Set the getParent to NULL
1631 m_pParent = nullptr;
1633 // Copy the members
1634 m_aNodeValue = rParseNode.m_aNodeValue;
1635 m_eNodeType = rParseNode.m_eNodeType;
1636 m_nNodeID = rParseNode.m_nNodeID;
1639 // Remember that we derived from Container. According to SV-Help the Container's
1640 // copy ctor creates a new Container with the same pointers for content.
1641 // This means after copying the Container, for all non-NULL pointers a copy is
1642 // created and reattached instead of the old pointer.
1644 // If not a leaf, then process SubTrees
1645 for (auto const& child : rParseNode.m_aChildren)
1646 append(new OSQLParseNode(*child));
1650 OSQLParseNode& OSQLParseNode::operator=(const OSQLParseNode& rParseNode)
1652 if (this != &rParseNode)
1654 // Copy the members - pParent remains the same
1655 m_aNodeValue = rParseNode.m_aNodeValue;
1656 m_eNodeType = rParseNode.m_eNodeType;
1657 m_nNodeID = rParseNode.m_nNodeID;
1659 m_aChildren.clear();
1661 for (auto const& child : rParseNode.m_aChildren)
1662 append(new OSQLParseNode(*child));
1664 return *this;
1668 bool OSQLParseNode::operator==(OSQLParseNode const & rParseNode) const
1670 // The members must be equal
1671 bool bResult = (m_nNodeID == rParseNode.m_nNodeID) &&
1672 (m_eNodeType == rParseNode.m_eNodeType) &&
1673 (m_aNodeValue == rParseNode.m_aNodeValue) &&
1674 count() == rParseNode.count();
1676 // Parameters are not equal!
1677 bResult = bResult && !SQL_ISRULE(this, parameter);
1679 // compare children
1680 for (size_t i=0; bResult && i < count(); i++)
1681 bResult = *getChild(i) == *rParseNode.getChild(i);
1683 return bResult;
1687 OSQLParseNode::~OSQLParseNode()
1691 void OSQLParseNode::append(OSQLParseNode* pNewNode)
1693 assert(pNewNode != nullptr && "OSQLParseNode: invalid NewSubTree");
1694 OSL_ENSURE(pNewNode->getParent() == nullptr, "OSQLParseNode: Node is not an orphan");
1695 OSL_ENSURE(std::none_of(m_aChildren.begin(), m_aChildren.end(),
1696 [&] (std::unique_ptr<OSQLParseNode> const & r) { return r.get() == pNewNode; }),
1697 "OSQLParseNode::append() Node already element of parent");
1699 // Create connection to getParent
1700 pNewNode->setParent( this );
1701 // and attach the SubTree at the end
1702 m_aChildren.emplace_back(pNewNode);
1705 bool OSQLParseNode::addDateValue(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
1707 // special display for date/time values
1708 if (!SQL_ISRULE(this,set_fct_spec) || !SQL_ISPUNCTUATION(m_aChildren[0],"{"))
1709 return false;
1711 const OSQLParseNode* pODBCNode = m_aChildren[1].get();
1712 const OSQLParseNode* pODBCNodeChild = pODBCNode->m_aChildren[0].get();
1714 if (pODBCNodeChild->getNodeType() != SQLNodeType::Keyword || !(
1715 SQL_ISTOKEN(pODBCNodeChild, D) ||
1716 SQL_ISTOKEN(pODBCNodeChild, T) ||
1717 SQL_ISTOKEN(pODBCNodeChild, TS) ))
1718 return false;
1720 OUString suQuote(u"'"_ustr);
1721 if (rParam.bPredicate)
1723 if (rParam.aMetaData.shouldEscapeDateTime())
1725 suQuote = "#";
1728 else
1730 if (rParam.aMetaData.shouldEscapeDateTime())
1732 // suQuote = "'";
1733 return false;
1737 if (!rString.isEmpty())
1738 rString.append(" ");
1739 rString.append(suQuote);
1740 const OUString sTokenValue = pODBCNode->m_aChildren[1]->getTokenValue();
1741 if (SQL_ISTOKEN(pODBCNodeChild, D))
1743 rString.append(rParam.bPredicate ? convertDateString(rParam, sTokenValue) : sTokenValue);
1745 else if (SQL_ISTOKEN(pODBCNodeChild, T))
1747 rString.append(rParam.bPredicate ? convertTimeString(rParam, sTokenValue) : sTokenValue);
1749 else
1751 rString.append(rParam.bPredicate ? convertDateTimeString(rParam, sTokenValue) : sTokenValue);
1753 rString.append(suQuote);
1754 return true;
1757 void OSQLParseNode::replaceNodeValue(const OUString& rTableAlias, const OUString& rColumnName)
1759 for (size_t i=0;i<count();++i)
1761 if (SQL_ISRULE(this,column_ref) && count() == 1 && getChild(0)->getTokenValue() == rColumnName)
1763 OSQLParseNode * pCol = removeAt(sal_uInt32(0));
1764 append(new OSQLParseNode(rTableAlias,SQLNodeType::Name));
1765 append(new OSQLParseNode(".",SQLNodeType::Punctuation));
1766 append(pCol);
1768 else
1769 getChild(i)->replaceNodeValue(rTableAlias,rColumnName);
1773 OSQLParseNode* OSQLParseNode::getByRule(OSQLParseNode::Rule eRule) const
1775 OSQLParseNode* pRetNode = nullptr;
1776 if (isRule() && OSQLParser::RuleID(eRule) == getRuleID())
1777 pRetNode = const_cast<OSQLParseNode*>(this);
1778 else
1780 for (auto const& child : m_aChildren)
1782 pRetNode = child->getByRule(eRule);
1783 if (pRetNode)
1784 break;
1787 return pRetNode;
1790 static OSQLParseNode* MakeANDNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1792 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1793 pNewNode->append(pLeftLeaf);
1794 pNewNode->append(new OSQLParseNode("AND",SQLNodeType::Keyword,SQL_TOKEN_AND));
1795 pNewNode->append(pRightLeaf);
1796 return pNewNode;
1799 static OSQLParseNode* MakeORNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1801 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::search_condition));
1802 pNewNode->append(pLeftLeaf);
1803 pNewNode->append(new OSQLParseNode("OR",SQLNodeType::Keyword,SQL_TOKEN_OR));
1804 pNewNode->append(pRightLeaf);
1805 return pNewNode;
1808 void OSQLParseNode::disjunctiveNormalForm(OSQLParseNode*& pSearchCondition)
1810 if(!pSearchCondition) // no where condition at entry point
1811 return;
1813 OSQLParseNode::absorptions(pSearchCondition);
1814 // '(' search_condition ')'
1815 if (SQL_ISRULE(pSearchCondition,boolean_primary))
1817 OSQLParseNode* pLeft = pSearchCondition->getChild(1);
1818 disjunctiveNormalForm(pLeft);
1820 // search_condition SQL_TOKEN_OR boolean_term
1821 else if (SQL_ISRULE(pSearchCondition,search_condition))
1823 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1824 disjunctiveNormalForm(pLeft);
1826 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1827 disjunctiveNormalForm(pRight);
1829 // boolean_term SQL_TOKEN_AND boolean_factor
1830 else if (SQL_ISRULE(pSearchCondition,boolean_term))
1832 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1833 disjunctiveNormalForm(pLeft);
1835 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1836 disjunctiveNormalForm(pRight);
1838 OSQLParseNode* pNewNode = nullptr;
1839 // '(' search_condition ')' on left side
1840 if(pLeft->count() == 3 && SQL_ISRULE(pLeft,boolean_primary) && SQL_ISRULE(pLeft->getChild(1),search_condition))
1842 // and-or tree on left side
1843 OSQLParseNode* pOr = pLeft->getChild(1);
1844 OSQLParseNode* pNewLeft = nullptr;
1845 OSQLParseNode* pNewRight = nullptr;
1847 // cut right from parent
1848 OSQLParseNode* pOldRight = pSearchCondition->removeAt(2);
1849 assert(pOldRight == pRight);
1851 pNewRight = MakeANDNode(pOr->removeAt(2), pOldRight);
1852 pNewLeft = MakeANDNode(pOr->removeAt(sal_uInt32(0)), new OSQLParseNode(*pOldRight));
1853 pNewNode = MakeORNode(pNewLeft,pNewRight);
1854 // and append new Node
1855 replaceAndReset(pSearchCondition,pNewNode);
1857 disjunctiveNormalForm(pSearchCondition);
1859 else if(pRight->count() == 3 && SQL_ISRULE(pRight,boolean_primary) && SQL_ISRULE(pRight->getChild(1),search_condition))
1860 { // '(' search_condition ')' on right side
1861 // and-or tree on right side
1862 // a and (b or c)
1863 OSQLParseNode* pOr = pRight->getChild(1);
1864 OSQLParseNode* pNewLeft = nullptr;
1865 OSQLParseNode* pNewRight = nullptr;
1867 // cut left from parent
1868 OSQLParseNode* pOldLeft = pSearchCondition->removeAt(sal_uInt32(0));
1869 assert(pOldLeft == pLeft);
1871 pNewRight = MakeANDNode(pOldLeft, pOr->removeAt(2));
1872 pNewLeft = MakeANDNode(new OSQLParseNode(*pOldLeft), pOr->removeAt(sal_uInt32(0)));
1873 pNewNode = MakeORNode(pNewLeft,pNewRight);
1875 // and append new Node
1876 replaceAndReset(pSearchCondition,pNewNode);
1877 disjunctiveNormalForm(pSearchCondition);
1879 else if(SQL_ISRULE(pLeft,boolean_primary) && (!SQL_ISRULE(pLeft->getChild(1),search_condition) || !SQL_ISRULE(pLeft->getChild(1),boolean_term)))
1880 pSearchCondition->replaceAndDelete(pLeft, pLeft->removeAt(1));
1881 else if(SQL_ISRULE(pRight,boolean_primary) && (!SQL_ISRULE(pRight->getChild(1),search_condition) || !SQL_ISRULE(pRight->getChild(1),boolean_term)))
1882 pSearchCondition->replaceAndDelete(pRight, pRight->removeAt(1));
1886 void OSQLParseNode::negateSearchCondition(OSQLParseNode*& pSearchCondition, bool bNegate)
1888 if(!pSearchCondition) // no where condition at entry point
1889 return;
1890 // '(' search_condition ')'
1891 if (pSearchCondition->count() == 3 && SQL_ISRULE(pSearchCondition,boolean_primary))
1893 OSQLParseNode* pRight = pSearchCondition->getChild(1);
1894 negateSearchCondition(pRight,bNegate);
1896 // search_condition SQL_TOKEN_OR boolean_term
1897 else if (SQL_ISRULE(pSearchCondition,search_condition))
1899 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1900 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1901 if(bNegate)
1903 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1904 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(0)));
1905 pNewNode->append(new OSQLParseNode("AND",SQLNodeType::Keyword,SQL_TOKEN_AND));
1906 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(1)));
1907 replaceAndReset(pSearchCondition,pNewNode);
1909 pLeft = pNewNode->getChild(0);
1910 pRight = pNewNode->getChild(2);
1913 negateSearchCondition(pLeft,bNegate);
1914 negateSearchCondition(pRight,bNegate);
1916 // boolean_term SQL_TOKEN_AND boolean_factor
1917 else if (SQL_ISRULE(pSearchCondition,boolean_term))
1919 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1920 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1921 if(bNegate)
1923 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::search_condition));
1924 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(0)));
1925 pNewNode->append(new OSQLParseNode("OR",SQLNodeType::Keyword,SQL_TOKEN_OR));
1926 pNewNode->append(pSearchCondition->removeAt(sal_uInt32(1)));
1927 replaceAndReset(pSearchCondition,pNewNode);
1929 pLeft = pNewNode->getChild(0);
1930 pRight = pNewNode->getChild(2);
1933 negateSearchCondition(pLeft,bNegate);
1934 negateSearchCondition(pRight,bNegate);
1936 // SQL_TOKEN_NOT ( boolean_primary )
1937 else if (SQL_ISRULE(pSearchCondition,boolean_factor))
1939 OSQLParseNode *pNot = pSearchCondition->removeAt(sal_uInt32(0));
1940 delete pNot;
1941 OSQLParseNode *pBooleanTest = pSearchCondition->removeAt(sal_uInt32(0));
1942 // TODO is this needed // pBooleanTest->setParent(NULL);
1943 replaceAndReset(pSearchCondition,pBooleanTest);
1945 if (!bNegate)
1946 negateSearchCondition(pSearchCondition, true); // negate all deeper values
1948 // row_value_constructor comparison row_value_constructor
1949 // row_value_constructor comparison any_all_some subquery
1950 else if(bNegate && (SQL_ISRULE(pSearchCondition,comparison_predicate) || SQL_ISRULE(pSearchCondition,all_or_any_predicate)))
1952 assert(pSearchCondition->count() == 3);
1953 OSQLParseNode* pComparison = pSearchCondition->getChild(1);
1954 if(SQL_ISRULE(pComparison, comparison))
1956 assert(pComparison->count() == 2 ||
1957 pComparison->count() == 4);
1958 assert(SQL_ISTOKEN(pComparison->getChild(0), IS));
1960 OSQLParseNode* pNot = pComparison->getChild(1);
1961 OSQLParseNode* pNotNot = nullptr;
1962 if(pNot->isRule()) // no NOT token (empty rule)
1963 pNotNot = new OSQLParseNode("NOT",SQLNodeType::Keyword,SQL_TOKEN_NOT);
1964 else
1966 assert(SQL_ISTOKEN(pNot,NOT));
1967 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
1969 pComparison->replaceAndDelete(pNot, pNotNot);
1971 else
1973 OSQLParseNode* pNewComparison;
1974 switch(pComparison->getNodeType())
1976 default:
1977 case SQLNodeType::Equal:
1978 assert(pComparison->getNodeType() == SQLNodeType::Equal &&
1979 "OSQLParseNode::negateSearchCondition: unexpected node type!");
1980 pNewComparison = new OSQLParseNode("<>",SQLNodeType::NotEqual,SQL_NOTEQUAL);
1981 break;
1982 case SQLNodeType::Less:
1983 pNewComparison = new OSQLParseNode(">=",SQLNodeType::GreatEq,SQL_GREATEQ);
1984 break;
1985 case SQLNodeType::Great:
1986 pNewComparison = new OSQLParseNode("<=",SQLNodeType::LessEq,SQL_LESSEQ);
1987 break;
1988 case SQLNodeType::LessEq:
1989 pNewComparison = new OSQLParseNode(">",SQLNodeType::Great,SQL_GREAT);
1990 break;
1991 case SQLNodeType::GreatEq:
1992 pNewComparison = new OSQLParseNode("<",SQLNodeType::Less,SQL_LESS);
1993 break;
1994 case SQLNodeType::NotEqual:
1995 pNewComparison = new OSQLParseNode("=",SQLNodeType::Equal,SQL_EQUAL);
1996 break;
1998 pSearchCondition->replaceAndDelete(pComparison, pNewComparison);
2002 else if(bNegate && (SQL_ISRULE(pSearchCondition,test_for_null) ||
2003 SQL_ISRULE(pSearchCondition,in_predicate) ||
2004 SQL_ISRULE(pSearchCondition,between_predicate) ))
2006 OSQLParseNode* pPart2 = pSearchCondition->getChild(1);
2007 sal_uInt32 nNotPos = 0;
2008 if ( SQL_ISRULE( pSearchCondition, test_for_null ) )
2009 nNotPos = 1;
2011 OSQLParseNode* pNot = pPart2->getChild(nNotPos);
2012 OSQLParseNode* pNotNot = nullptr;
2013 if(pNot->isRule()) // no NOT token (empty rule)
2014 pNotNot = new OSQLParseNode("NOT",SQLNodeType::Keyword,SQL_TOKEN_NOT);
2015 else
2017 assert(SQL_ISTOKEN(pNot,NOT));
2018 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
2020 pPart2->replaceAndDelete(pNot, pNotNot);
2022 else if(bNegate && SQL_ISRULE(pSearchCondition,like_predicate))
2024 OSQLParseNode* pNot = pSearchCondition->getChild( 1 )->getChild( 0 );
2025 OSQLParseNode* pNotNot = nullptr;
2026 if(pNot->isRule())
2027 pNotNot = new OSQLParseNode("NOT",SQLNodeType::Keyword,SQL_TOKEN_NOT);
2028 else
2029 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
2030 pSearchCondition->getChild( 1 )->replaceAndDelete(pNot, pNotNot);
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),")")))))
2038 return;
2040 OSQLParseNode* pRight = pSearchCondition->getChild(1);
2041 absorptions(pRight);
2042 // if child is not an or and tree then delete () around child
2043 if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2044 SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || // and can always stand without ()
2045 (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2047 OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2048 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)))
2187 return;
2189 if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(0))
2191 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(2);
2192 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2193 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2195 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2196 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2197 pNewRule->append(pNode);
2198 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2200 OSQLParseNode::eraseBraces(pLeft);
2201 OSQLParseNode::eraseBraces(pRight);
2203 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(sal_uInt32(0)),pNewRule);
2204 replaceAndReset(pSearchCondition,pNode);
2206 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(0))
2208 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(sal_uInt32(0));
2209 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2210 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2212 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2213 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2214 pNewRule->append(pNode);
2215 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2217 OSQLParseNode::eraseBraces(pLeft);
2218 OSQLParseNode::eraseBraces(pRight);
2220 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2221 replaceAndReset(pSearchCondition,pNode);
2223 else if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(2))
2225 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(2);
2226 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(sal_uInt32(0));
2227 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2229 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2230 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2231 pNewRule->append(pNode);
2232 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2234 OSQLParseNode::eraseBraces(pLeft);
2235 OSQLParseNode::eraseBraces(pRight);
2237 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(sal_uInt32(0)),pNewRule);
2238 replaceAndReset(pSearchCondition,pNode);
2240 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(2))
2242 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(sal_uInt32(0));
2243 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(sal_uInt32(0));
2244 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2246 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2247 pNewRule->append(new OSQLParseNode("(",SQLNodeType::Punctuation));
2248 pNewRule->append(pNode);
2249 pNewRule->append(new OSQLParseNode(")",SQLNodeType::Punctuation));
2251 OSQLParseNode::eraseBraces(pLeft);
2252 OSQLParseNode::eraseBraces(pRight);
2254 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2255 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 assert(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 assert(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 void OSQLParseNode::replaceAndDelete(OSQLParseNode* pOldSubNode, OSQLParseNode* pNewSubNode )
2393 assert(pOldSubNode != nullptr && pNewSubNode != nullptr && "OSQLParseNode: invalid nodes");
2394 assert(pOldSubNode != pNewSubNode && "OSQLParseNode: same node");
2395 assert(pNewSubNode->getParent() == nullptr && "OSQLParseNode: node already has getParent");
2396 assert(std::any_of(m_aChildren.begin(), m_aChildren.end(),
2397 [&] (std::unique_ptr<OSQLParseNode> const & r) { return r.get() == pOldSubNode; })
2398 && "OSQLParseNode::Replace() Node not element of parent");
2399 assert(std::none_of(m_aChildren.begin(), m_aChildren.end(),
2400 [&] (std::unique_ptr<OSQLParseNode> const & r) { return r.get() == pNewSubNode; })
2401 && "OSQLParseNode::Replace() Node already element of parent");
2403 pOldSubNode->setParent( nullptr );
2404 pNewSubNode->setParent( this );
2405 auto it = std::find_if(m_aChildren.begin(), m_aChildren.end(),
2406 [&pOldSubNode](const std::unique_ptr<OSQLParseNode>& rxChild) { return rxChild.get() == pOldSubNode; });
2407 assert(it != m_aChildren.end());
2408 it->reset(pNewSubNode);
2411 void OSQLParseNode::parseLeaf(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
2413 // Found a leaf
2414 // Append content to the output string
2415 switch (m_eNodeType)
2417 case SQLNodeType::Keyword:
2419 if (!rString.isEmpty())
2420 rString.append(" ");
2422 const OString sT = OSQLParser::TokenIDToStr(m_nNodeID, rParam.bInternational ? &rParam.m_rContext : nullptr);
2423 rString.append(OStringToOUString(sT,RTL_TEXTENCODING_UTF8));
2424 } break;
2425 case SQLNodeType::String:
2426 if (!rString.isEmpty())
2427 rString.append(" ");
2428 rString.append(SetQuotation(m_aNodeValue, u"\'", u"\'\'"));
2429 break;
2430 case SQLNodeType::Name:
2431 if (!rString.isEmpty())
2433 switch(rString[rString.getLength()-1])
2435 case ' ' :
2436 case '.' : break;
2437 default :
2438 if ( rParam.aMetaData.getCatalogSeparator().isEmpty()
2439 || rString[rString.getLength() - 1] != rParam.aMetaData.getCatalogSeparator().toChar()
2441 rString.append(" ");
2442 break;
2445 if (rParam.bQuote)
2447 if (rParam.bPredicate)
2449 rString.append("[");
2450 rString.append(m_aNodeValue);
2451 rString.append("]");
2453 else
2454 rString.append(SetQuotation(m_aNodeValue,
2455 rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
2457 else
2458 rString.append(m_aNodeValue);
2459 break;
2460 case SQLNodeType::AccessDate:
2461 if (!rString.isEmpty())
2462 rString.append(" ");
2463 rString.append("#");
2464 rString.append(m_aNodeValue);
2465 rString.append("#");
2466 break;
2468 case SQLNodeType::IntNum:
2469 case SQLNodeType::ApproxNum:
2471 OUString aTmp = m_aNodeValue;
2472 static constexpr OUString strPoint(u"."_ustr);
2473 if (rParam.bInternational && rParam.bPredicate && rParam.sDecSep != strPoint)
2474 aTmp = aTmp.replaceAll(strPoint, rParam.sDecSep);
2476 if (!rString.isEmpty())
2477 rString.append(" ");
2478 rString.append(aTmp);
2480 } break;
2481 case SQLNodeType::Punctuation:
2482 if ( getParent() && SQL_ISRULE(getParent(),cast_spec) && m_aNodeValue.toChar() == '(' ) // no spaces in front of '('
2484 rString.append(m_aNodeValue);
2485 break;
2487 [[fallthrough]];
2488 default:
2489 if (!rString.isEmpty() && m_aNodeValue.toChar() != '.' && m_aNodeValue.toChar() != ':' )
2491 switch( rString[rString.getLength() - 1] )
2493 case ' ' :
2494 case '.' : break;
2495 default :
2496 if ( rParam.aMetaData.getCatalogSeparator().isEmpty()
2497 || rString[rString.getLength() - 1] != rParam.aMetaData.getCatalogSeparator().toChar()
2499 rString.append(" ");
2500 break;
2503 rString.append(m_aNodeValue);
2508 sal_Int32 OSQLParser::getFunctionReturnType(std::u16string_view _sFunctionName, const IParseContext* pContext)
2510 sal_Int32 nType = DataType::SQLNULL;
2511 OString sFunctionName(OUStringToOString(_sFunctionName,RTL_TEXTENCODING_UTF8));
2513 if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASCII,pContext))) nType = DataType::INTEGER;
2514 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_BIT_LENGTH,pContext))) nType = DataType::INTEGER;
2515 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR,pContext))) nType = DataType::VARCHAR;
2516 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR_LENGTH,pContext))) nType = DataType::INTEGER;
2517 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CONCAT,pContext))) nType = DataType::VARCHAR;
2518 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DIFFERENCE,pContext))) nType = DataType::VARCHAR;
2519 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_INSERT,pContext))) nType = DataType::VARCHAR;
2520 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LCASE,pContext))) nType = DataType::VARCHAR;
2521 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LEFT,pContext))) nType = DataType::VARCHAR;
2522 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LENGTH,pContext))) nType = DataType::INTEGER;
2523 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE,pContext))) nType = DataType::VARCHAR;
2524 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE_2,pContext))) nType = DataType::VARCHAR;
2525 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LTRIM,pContext))) nType = DataType::VARCHAR;
2526 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_OCTET_LENGTH,pContext))) nType = DataType::INTEGER;
2527 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POSITION,pContext))) nType = DataType::INTEGER;
2528 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPEAT,pContext))) nType = DataType::VARCHAR;
2529 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPLACE,pContext))) nType = DataType::VARCHAR;
2530 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RIGHT,pContext))) nType = DataType::VARCHAR;
2531 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RTRIM,pContext))) nType = DataType::VARCHAR;
2532 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SOUNDEX,pContext))) nType = DataType::VARCHAR;
2533 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SPACE,pContext))) nType = DataType::VARCHAR;
2534 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUBSTRING,pContext))) nType = DataType::VARCHAR;
2535 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UCASE,pContext))) nType = DataType::VARCHAR;
2536 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_DATE,pContext))) nType = DataType::DATE;
2537 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIME,pContext))) nType = DataType::TIME;
2538 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIMESTAMP,pContext))) nType = DataType::TIMESTAMP;
2539 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURDATE,pContext))) nType = DataType::DATE;
2540 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEDIFF,pContext))) nType = DataType::INTEGER;
2541 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEVALUE,pContext))) nType = DataType::DATE;
2542 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURTIME,pContext))) nType = DataType::TIME;
2543 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYNAME,pContext))) nType = DataType::VARCHAR;
2544 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFMONTH,pContext))) nType = DataType::INTEGER;
2545 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFWEEK,pContext))) nType = DataType::INTEGER;
2546 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFYEAR,pContext))) nType = DataType::INTEGER;
2547 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXTRACT,pContext))) nType = DataType::VARCHAR;
2548 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_HOUR,pContext))) nType = DataType::INTEGER;
2549 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MINUTE,pContext))) nType = DataType::INTEGER;
2550 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTH,pContext))) nType = DataType::INTEGER;
2551 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTHNAME,pContext))) nType = DataType::VARCHAR;
2552 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_NOW,pContext))) nType = DataType::TIMESTAMP;
2553 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_QUARTER,pContext))) nType = DataType::INTEGER;
2554 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SECOND,pContext))) nType = DataType::INTEGER;
2555 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPADD,pContext))) nType = DataType::TIMESTAMP;
2556 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPDIFF,pContext))) nType = DataType::TIMESTAMP;
2557 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMEVALUE,pContext))) nType = DataType::TIMESTAMP;
2558 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_WEEK,pContext))) nType = DataType::INTEGER;
2559 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_YEAR,pContext))) nType = DataType::INTEGER;
2560 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ABS,pContext))) nType = DataType::DOUBLE;
2561 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ACOS,pContext))) nType = DataType::DOUBLE;
2562 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASIN,pContext))) nType = DataType::DOUBLE;
2563 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN,pContext))) nType = DataType::DOUBLE;
2564 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN2,pContext))) nType = DataType::DOUBLE;
2565 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CEILING,pContext))) nType = DataType::DOUBLE;
2566 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COS,pContext))) nType = DataType::DOUBLE;
2567 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COT,pContext))) nType = DataType::DOUBLE;
2568 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DEGREES,pContext))) nType = DataType::DOUBLE;
2569 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXP,pContext))) nType = DataType::DOUBLE;
2570 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_FLOOR,pContext))) nType = DataType::DOUBLE;
2571 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOGF,pContext))) nType = DataType::DOUBLE;
2572 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG,pContext))) nType = DataType::DOUBLE;
2573 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG10,pContext))) nType = DataType::DOUBLE;
2574 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LN,pContext))) nType = DataType::DOUBLE;
2575 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MOD,pContext))) nType = DataType::DOUBLE;
2576 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_PI,pContext))) nType = DataType::DOUBLE;
2577 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POWER,pContext))) nType = DataType::DOUBLE;
2578 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RADIANS,pContext))) nType = DataType::DOUBLE;
2579 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RAND,pContext))) nType = DataType::DOUBLE;
2580 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUND,pContext))) nType = DataType::DOUBLE;
2581 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUNDMAGIC,pContext))) nType = DataType::DOUBLE;
2582 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIGN,pContext))) nType = DataType::DOUBLE;
2583 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIN,pContext))) nType = DataType::DOUBLE;
2584 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SQRT,pContext))) nType = DataType::DOUBLE;
2585 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TAN,pContext))) nType = DataType::DOUBLE;
2586 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TRUNCATE,pContext))) nType = DataType::DOUBLE;
2587 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COUNT,pContext))) nType = DataType::INTEGER;
2588 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MAX,pContext))) nType = DataType::DOUBLE;
2589 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MIN,pContext))) nType = DataType::DOUBLE;
2590 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_AVG,pContext))) nType = DataType::DOUBLE;
2591 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUM,pContext))) nType = DataType::DOUBLE;
2592 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOWER,pContext))) nType = DataType::VARCHAR;
2593 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UPPER,pContext))) nType = DataType::VARCHAR;
2595 return nType;
2598 sal_Int32 OSQLParser::getFunctionParameterType(sal_uInt32 _nTokenId, sal_uInt32 _nPos)
2600 sal_Int32 nType = DataType::VARCHAR;
2602 if(_nTokenId == SQL_TOKEN_CHAR) nType = DataType::INTEGER;
2603 else if(_nTokenId == SQL_TOKEN_INSERT)
2605 if ( _nPos == 2 || _nPos == 3 )
2606 nType = DataType::INTEGER;
2608 else if(_nTokenId == SQL_TOKEN_LEFT)
2610 if ( _nPos == 2 )
2611 nType = DataType::INTEGER;
2613 else if(_nTokenId == SQL_TOKEN_LOCATE)
2615 if ( _nPos == 3 )
2616 nType = DataType::INTEGER;
2618 else if(_nTokenId == SQL_TOKEN_LOCATE_2)
2620 if ( _nPos == 3 )
2621 nType = DataType::INTEGER;
2623 else if( _nTokenId == SQL_TOKEN_REPEAT || _nTokenId == SQL_TOKEN_RIGHT )
2625 if ( _nPos == 2 )
2626 nType = DataType::INTEGER;
2628 else if(_nTokenId == SQL_TOKEN_SPACE )
2630 nType = DataType::INTEGER;
2632 else if(_nTokenId == SQL_TOKEN_SUBSTRING)
2634 if ( _nPos != 1 )
2635 nType = DataType::INTEGER;
2637 else if(_nTokenId == SQL_TOKEN_DATEDIFF)
2639 if ( _nPos != 1 )
2640 nType = DataType::TIMESTAMP;
2642 else if(_nTokenId == SQL_TOKEN_DATEVALUE)
2643 nType = DataType::DATE;
2644 else if(_nTokenId == SQL_TOKEN_DAYNAME)
2645 nType = DataType::DATE;
2646 else if(_nTokenId == SQL_TOKEN_DAYOFMONTH)
2647 nType = DataType::DATE;
2648 else if(_nTokenId == SQL_TOKEN_DAYOFWEEK)
2649 nType = DataType::DATE;
2650 else if(_nTokenId == SQL_TOKEN_DAYOFYEAR)
2651 nType = DataType::DATE;
2652 else if(_nTokenId == SQL_TOKEN_EXTRACT) nType = DataType::VARCHAR;
2653 else if(_nTokenId == SQL_TOKEN_HOUR) nType = DataType::TIME;
2654 else if(_nTokenId == SQL_TOKEN_MINUTE) nType = DataType::TIME;
2655 else if(_nTokenId == SQL_TOKEN_MONTH) nType = DataType::DATE;
2656 else if(_nTokenId == SQL_TOKEN_MONTHNAME) nType = DataType::DATE;
2657 else if(_nTokenId == SQL_TOKEN_NOW) nType = DataType::TIMESTAMP;
2658 else if(_nTokenId == SQL_TOKEN_QUARTER) nType = DataType::DATE;
2659 else if(_nTokenId == SQL_TOKEN_SECOND) nType = DataType::TIME;
2660 else if(_nTokenId == SQL_TOKEN_TIMESTAMPADD) nType = DataType::TIMESTAMP;
2661 else if(_nTokenId == SQL_TOKEN_TIMESTAMPDIFF) nType = DataType::TIMESTAMP;
2662 else if(_nTokenId == SQL_TOKEN_TIMEVALUE) nType = DataType::TIMESTAMP;
2663 else if(_nTokenId == SQL_TOKEN_WEEK) nType = DataType::DATE;
2664 else if(_nTokenId == SQL_TOKEN_YEAR) nType = DataType::DATE;
2666 else if(_nTokenId == SQL_TOKEN_ABS) nType = DataType::DOUBLE;
2667 else if(_nTokenId == SQL_TOKEN_ACOS) nType = DataType::DOUBLE;
2668 else if(_nTokenId == SQL_TOKEN_ASIN) nType = DataType::DOUBLE;
2669 else if(_nTokenId == SQL_TOKEN_ATAN) nType = DataType::DOUBLE;
2670 else if(_nTokenId == SQL_TOKEN_ATAN2) nType = DataType::DOUBLE;
2671 else if(_nTokenId == SQL_TOKEN_CEILING) nType = DataType::DOUBLE;
2672 else if(_nTokenId == SQL_TOKEN_COS) nType = DataType::DOUBLE;
2673 else if(_nTokenId == SQL_TOKEN_COT) nType = DataType::DOUBLE;
2674 else if(_nTokenId == SQL_TOKEN_DEGREES) nType = DataType::DOUBLE;
2675 else if(_nTokenId == SQL_TOKEN_EXP) nType = DataType::DOUBLE;
2676 else if(_nTokenId == SQL_TOKEN_FLOOR) nType = DataType::DOUBLE;
2677 else if(_nTokenId == SQL_TOKEN_LOGF) nType = DataType::DOUBLE;
2678 else if(_nTokenId == SQL_TOKEN_LOG) nType = DataType::DOUBLE;
2679 else if(_nTokenId == SQL_TOKEN_LOG10) nType = DataType::DOUBLE;
2680 else if(_nTokenId == SQL_TOKEN_LN) nType = DataType::DOUBLE;
2681 else if(_nTokenId == SQL_TOKEN_MOD) nType = DataType::DOUBLE;
2682 else if(_nTokenId == SQL_TOKEN_PI) nType = DataType::DOUBLE;
2683 else if(_nTokenId == SQL_TOKEN_POWER) nType = DataType::DOUBLE;
2684 else if(_nTokenId == SQL_TOKEN_RADIANS) nType = DataType::DOUBLE;
2685 else if(_nTokenId == SQL_TOKEN_RAND) nType = DataType::DOUBLE;
2686 else if(_nTokenId == SQL_TOKEN_ROUND) nType = DataType::DOUBLE;
2687 else if(_nTokenId == SQL_TOKEN_ROUNDMAGIC) nType = DataType::DOUBLE;
2688 else if(_nTokenId == SQL_TOKEN_SIGN) nType = DataType::DOUBLE;
2689 else if(_nTokenId == SQL_TOKEN_SIN) nType = DataType::DOUBLE;
2690 else if(_nTokenId == SQL_TOKEN_SQRT) nType = DataType::DOUBLE;
2691 else if(_nTokenId == SQL_TOKEN_TAN) nType = DataType::DOUBLE;
2692 else if(_nTokenId == SQL_TOKEN_TRUNCATE) nType = DataType::DOUBLE;
2693 else if(_nTokenId == SQL_TOKEN_COUNT) nType = DataType::INTEGER;
2694 else if(_nTokenId == SQL_TOKEN_MAX) nType = DataType::DOUBLE;
2695 else if(_nTokenId == SQL_TOKEN_MIN) nType = DataType::DOUBLE;
2696 else if(_nTokenId == SQL_TOKEN_AVG) nType = DataType::DOUBLE;
2697 else if(_nTokenId == SQL_TOKEN_SUM) nType = DataType::DOUBLE;
2699 else if(_nTokenId == SQL_TOKEN_LOWER) nType = DataType::VARCHAR;
2700 else if(_nTokenId == SQL_TOKEN_UPPER) nType = DataType::VARCHAR;
2702 return nType;
2706 const SQLError& OSQLParser::getErrorHelper() const
2708 return m_pData->aErrors;
2712 OSQLParseNode::Rule OSQLParseNode::getKnownRuleID() const
2714 if ( !isRule() )
2715 return UNKNOWN_RULE;
2716 return OSQLParser::RuleIDToRule( getRuleID() );
2719 OUString OSQLParseNode::getTableRange(const OSQLParseNode* _pTableRef)
2721 assert(_pTableRef);
2722 OSL_ENSURE(_pTableRef->count() > 1 && _pTableRef->getKnownRuleID() == OSQLParseNode::table_ref,"Invalid node give, only table ref is allowed!");
2723 const sal_uInt32 nCount = _pTableRef->count();
2724 OUString sTableRange;
2725 if ( nCount == 2 || (nCount == 3 && !_pTableRef->getChild(0)->isToken()) )
2727 const OSQLParseNode* pNode = _pTableRef->getChild(nCount - (nCount == 2 ? 1 : 2));
2728 assert(pNode);
2729 OSL_ENSURE(pNode->getKnownRuleID() == OSQLParseNode::table_primary_as_range_column ||
2730 pNode->getKnownRuleID() == OSQLParseNode::range_variable, "SQL grammar changed!");
2731 if ( !pNode->isLeaf() )
2732 sTableRange = pNode->getChild(1)->getTokenValue();
2733 } // if ( nCount == 2 || nCount == 3 )
2735 return sTableRange;
2738 OSQLParseNodesContainer::OSQLParseNodesContainer()
2742 OSQLParseNodesContainer::~OSQLParseNodesContainer()
2746 void OSQLParseNodesContainer::push_back(OSQLParseNode* _pNode)
2748 std::unique_lock aGuard(m_aMutex);
2749 m_aNodes.push_back(_pNode);
2752 void OSQLParseNodesContainer::erase(OSQLParseNode* _pNode)
2754 std::unique_lock aGuard(m_aMutex);
2755 if ( !m_aNodes.empty() )
2757 std::vector< OSQLParseNode* >::iterator aFind = std::find(m_aNodes.begin(), m_aNodes.end(),_pNode);
2758 if ( aFind != m_aNodes.end() )
2759 m_aNodes.erase(aFind);
2763 void OSQLParseNodesContainer::clear()
2765 std::unique_lock aGuard(m_aMutex);
2766 m_aNodes.clear();
2769 void OSQLParseNodesContainer::clearAndDelete()
2771 std::unique_lock aGuard(m_aMutex);
2772 // clear the garbage collector
2773 while ( !m_aNodes.empty() )
2775 OSQLParseNode* pNode = m_aNodes[0];
2776 while ( pNode->getParent() )
2778 pNode = pNode->getParent();
2780 aGuard.unlock(); // can call back into this object during destruction
2781 delete pNode;
2782 aGuard.lock();
2785 } // namespace connectivity
2787 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */