build fix
[LibreOffice.git] / connectivity / source / parse / sqlnode.cxx
blob52311a0ead09d7bfda6e3c25eec3704aa9df8c23
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 <comphelper/processfactory.hxx>
52 #include <connectivity/dbtools.hxx>
53 #include <connectivity/dbmetadata.hxx>
54 #include <tools/diagnose_ex.h>
55 #include <string.h>
56 #include <algorithm>
57 #include <functional>
58 #include <memory>
59 #include <rtl/ustrbuf.hxx>
61 using namespace ::com::sun::star::sdbc;
62 using namespace ::com::sun::star::util;
63 using namespace ::com::sun::star::beans;
64 using namespace ::com::sun::star::sdb;
65 using namespace ::com::sun::star::uno;
66 using namespace ::com::sun::star::lang;
67 using namespace ::com::sun::star::i18n;
68 using namespace ::com::sun::star;
69 using namespace ::osl;
70 using namespace ::dbtools;
71 using namespace ::comphelper;
73 connectivity::OSQLParser* xxx_pGLOBAL_SQLPARSER;
75 namespace
78 bool lcl_saveConvertToNumber(const Reference< XNumberFormatter > & _xFormatter,sal_Int32 _nKey,const OUString& _sValue,double& _nrValue)
80 bool bRet = false;
81 try
83 _nrValue = _xFormatter->convertStringToNumber(_nKey, _sValue);
84 bRet = true;
86 catch(Exception&)
89 return bRet;
92 void replaceAndReset(connectivity::OSQLParseNode*& _pResetNode,connectivity::OSQLParseNode* _pNewNode)
94 _pResetNode->getParent()->replace(_pResetNode, _pNewNode);
95 delete _pResetNode;
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 rQuot
103 The quote
104 @param rQuotToReplace
105 The quote to replace with
106 @return
107 The quoted string.
109 OUString SetQuotation(const OUString& rValue, const OUString& rQuot, const OUString& rQuotToReplace)
111 OUString rNewValue = rQuot;
112 rNewValue += rValue;
113 sal_Int32 nIndex = (sal_Int32)-1; // Replace quotes with double quotes or the parser gets into problems
115 if (!rQuot.isEmpty())
119 nIndex += 2;
120 nIndex = rNewValue.indexOf(rQuot,nIndex);
121 if(nIndex != -1)
122 rNewValue = rNewValue.replaceAt(nIndex,rQuot.getLength(),rQuotToReplace);
123 } while (nIndex != -1);
126 rNewValue += rQuot;
127 return rNewValue;
130 bool columnMatchP(const connectivity::OSQLParseNode* pSubTree, const connectivity::SQLParseNodeParameter& rParam)
132 using namespace connectivity;
133 assert(SQL_ISRULE(pSubTree,column_ref));
135 if(!rParam.xField.is())
136 return false;
138 // retrieve the field's name & table range
139 OUString aFieldName;
142 sal_Int32 nNamePropertyId = PROPERTY_ID_NAME;
143 if ( rParam.xField->getPropertySetInfo()->hasPropertyByName( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_REALNAME ) ) )
144 nNamePropertyId = PROPERTY_ID_REALNAME;
145 rParam.xField->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( nNamePropertyId ) ) >>= aFieldName;
147 catch ( Exception& )
151 if(pSubTree->count())
153 const OSQLParseNode* pCol = pSubTree->getChild(pSubTree->count()-1);
154 if (SQL_ISRULE(pCol,column_val))
156 assert(pCol->count() == 1);
157 pCol = pCol->getChild(0);
159 const OSQLParseNode* pTable(nullptr);
160 switch (pSubTree->count())
162 case 1:
163 break;
164 case 3:
165 pTable = pSubTree->getChild(0);
166 break;
167 case 5:
168 case 7:
169 SAL_WARN("connectivity.parse", "SQL: catalog and/or schema in column_ref in predicate");
170 break;
171 default:
172 SAL_WARN("connectivity.parse", "columnMatchP: SQL grammar changed; column_ref has " << pSubTree->count() << " children");
173 assert(false);
174 break;
176 // TODO: not all DBMS match column names case-insensitively...
177 // see XDatabaseMetaData::supportsMixedCaseIdentifiers()
178 // and XDatabaseMetaData::supportsMixedCaseQuotedIdentifiers()
179 if ( // table name matches (or no table name)?
180 ( !pTable || pTable->getTokenValue().equalsIgnoreAsciiCase(rParam.sPredicateTableAlias) )
181 && // column name matches?
182 pCol->getTokenValue().equalsIgnoreAsciiCase(aFieldName)
184 return true;
186 return false;
190 namespace connectivity
193 SQLParseNodeParameter::SQLParseNodeParameter( const Reference< XConnection >& _rxConnection,
194 const Reference< XNumberFormatter >& _xFormatter, const Reference< XPropertySet >& _xField,
195 const OUString &_sPredicateTableAlias,
196 const Locale& _rLocale, const IParseContext* _pContext,
197 bool _bIntl, bool _bQuote, sal_Char _cDecSep, bool _bPredicate, bool _bParseToSDBC )
198 :rLocale(_rLocale)
199 ,aMetaData( _rxConnection )
200 ,pParser( nullptr )
201 ,pSubQueryHistory( new QueryNameSet )
202 ,xFormatter(_xFormatter)
203 ,xField(_xField)
204 ,sPredicateTableAlias(_sPredicateTableAlias)
205 ,m_rContext( _pContext ? (const IParseContext&)(*_pContext) : (const IParseContext&)OSQLParser::s_aDefaultContext )
206 ,cDecSep(_cDecSep)
207 ,bQuote(_bQuote)
208 ,bInternational(_bIntl)
209 ,bPredicate(_bPredicate)
210 ,bParseToSDBCLevel( _bParseToSDBC )
215 SQLParseNodeParameter::~SQLParseNodeParameter()
219 OUString OSQLParseNode::convertDateString(const SQLParseNodeParameter& rParam, const OUString& rString)
221 Date aDate = DBTypeConversion::toDate(rString);
222 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
223 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
225 double fDate = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
226 sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 36; // XXX hack
227 return rParam.xFormatter->convertNumberToString(nKey, fDate);
231 OUString OSQLParseNode::convertDateTimeString(const SQLParseNodeParameter& rParam, const OUString& rString)
233 DateTime aDate = DBTypeConversion::toDateTime(rString);
234 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
235 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
237 double fDateTime = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
238 sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 51; // XXX hack
239 return rParam.xFormatter->convertNumberToString(nKey, fDateTime);
243 OUString OSQLParseNode::convertTimeString(const SQLParseNodeParameter& rParam, const OUString& rString)
245 css::util::Time aTime = DBTypeConversion::toTime(rString);
246 Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
248 Reference< XNumberFormatTypes > xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
250 double fTime = DBTypeConversion::toDouble(aTime);
251 sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 41; // XXX hack
252 return rParam.xFormatter->convertNumberToString(nKey, fTime);
256 void OSQLParseNode::parseNodeToStr(OUString& rString,
257 const Reference< XConnection >& _rxConnection,
258 const IParseContext* pContext,
259 bool _bIntl,
260 bool _bQuote) const
262 parseNodeToStr(
263 rString, _rxConnection, nullptr, nullptr, OUString(),
264 pContext ? pContext->getPreferredLocale() : OParseContext::getDefaultLocale(),
265 pContext, _bIntl, _bQuote, '.', false );
269 void OSQLParseNode::parseNodeToPredicateStr(OUString& rString,
270 const Reference< XConnection >& _rxConnection,
271 const Reference< XNumberFormatter > & xFormatter,
272 const css::lang::Locale& rIntl,
273 sal_Char _cDec,
274 const IParseContext* pContext ) const
276 OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
278 if (xFormatter.is())
279 parseNodeToStr(rString, _rxConnection, xFormatter, nullptr, OUString(), rIntl, pContext, true, true, _cDec, true);
283 void OSQLParseNode::parseNodeToPredicateStr(OUString& rString,
284 const Reference< XConnection > & _rxConnection,
285 const Reference< XNumberFormatter > & xFormatter,
286 const Reference< XPropertySet > & _xField,
287 const OUString &_sPredicateTableAlias,
288 const css::lang::Locale& rIntl,
289 sal_Char _cDec,
290 const IParseContext* pContext ) const
292 OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
294 if (xFormatter.is())
295 parseNodeToStr( rString, _rxConnection, xFormatter, _xField, _sPredicateTableAlias, rIntl, pContext, true, true, _cDec, true );
299 void OSQLParseNode::parseNodeToStr(OUString& rString,
300 const Reference< XConnection > & _rxConnection,
301 const Reference< XNumberFormatter > & xFormatter,
302 const Reference< XPropertySet > & _xField,
303 const OUString &_sPredicateTableAlias,
304 const css::lang::Locale& rIntl,
305 const IParseContext* pContext,
306 bool _bIntl,
307 bool _bQuote,
308 sal_Char _cDecSep,
309 bool _bPredicate) const
311 OSL_ENSURE( _rxConnection.is(), "OSQLParseNode::parseNodeToStr: invalid connection!" );
313 if ( _rxConnection.is() )
315 OUStringBuffer sBuffer = rString;
318 OSQLParseNode::impl_parseNodeToString_throw( sBuffer,
319 SQLParseNodeParameter(
320 _rxConnection, xFormatter, _xField, _sPredicateTableAlias, rIntl, pContext,
321 _bIntl, _bQuote, _cDecSep, _bPredicate, false
322 ) );
324 catch( const SQLException& )
326 SAL_WARN( "connectivity.parse", "OSQLParseNode::parseNodeToStr: this should not throw!" );
327 // our callers don't expect this method to throw anything. The only known situation
328 // where impl_parseNodeToString_throw can throw is when there is a cyclic reference
329 // in the sub queries, but this cannot be the case here, as we do not parse to
330 // SDBC level.
332 rString = sBuffer.makeStringAndClear();
336 bool OSQLParseNode::parseNodeToExecutableStatement( OUString& _out_rString, const Reference< XConnection >& _rxConnection,
337 OSQLParser& _rParser, css::sdbc::SQLException* _pErrorHolder ) const
339 OSL_PRECOND( _rxConnection.is(), "OSQLParseNode::parseNodeToExecutableStatement: invalid connection!" );
340 SQLParseNodeParameter aParseParam( _rxConnection,
341 nullptr, nullptr, OUString(), OParseContext::getDefaultLocale(), nullptr, false, true, '.', false, true );
343 if ( aParseParam.aMetaData.supportsSubqueriesInFrom() )
345 Reference< XQueriesSupplier > xSuppQueries( _rxConnection, UNO_QUERY );
346 OSL_ENSURE( xSuppQueries.is(), "OSQLParseNode::parseNodeToExecutableStatement: cannot substitute everything without a QueriesSupplier!" );
347 if ( xSuppQueries.is() )
348 aParseParam.xQueries = xSuppQueries->getQueries();
351 aParseParam.pParser = &_rParser;
353 _out_rString.clear();
354 OUStringBuffer sBuffer;
355 bool bSuccess = false;
358 impl_parseNodeToString_throw( sBuffer, aParseParam );
359 bSuccess = true;
361 catch( const SQLException& e )
363 if ( _pErrorHolder )
364 *_pErrorHolder = e;
366 _out_rString = sBuffer.makeStringAndClear();
367 return bSuccess;
371 namespace
373 bool lcl_isAliasNamePresent( const OSQLParseNode& _rTableNameNode )
375 return !OSQLParseNode::getTableRange(_rTableNameNode.getParent()).isEmpty();
380 void OSQLParseNode::impl_parseNodeToString_throw(OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple) const
382 if ( isToken() )
384 parseLeaf(rString,rParam);
385 return;
388 // Lets see how many nodes this subtree has
389 sal_uInt32 nCount = count();
391 bool bHandled = false;
392 switch ( getKnownRuleID() )
394 // special handling for parameters
395 case parameter:
397 bSimple=false;
398 if(!rString.isEmpty())
399 rString.append(" ");
400 if (nCount == 1) // ?
401 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
402 else if (nCount == 2) // :Name
404 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
405 rString.append(m_aChildren[1]->m_aNodeValue);
406 } // [Name]
407 else
409 m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam, false );
410 rString.append(m_aChildren[1]->m_aNodeValue);
411 rString.append(m_aChildren[2]->m_aNodeValue);
413 bHandled = true;
415 break;
417 // table refs
418 case table_ref:
419 bSimple=false;
420 if ( ( nCount == 2 ) || ( nCount == 3 ) || ( nCount == 5 ) )
422 impl_parseTableRangeNodeToString_throw( rString, rParam );
423 bHandled = true;
425 break;
427 // table name - might be a query name
428 case table_name:
429 bSimple=false;
430 bHandled = impl_parseTableNameNodeToString_throw( rString, rParam );
431 break;
433 case as_clause:
434 bSimple=false;
435 assert(nCount == 0 || nCount == 2);
436 if (nCount == 2)
438 if ( rParam.aMetaData.generateASBeforeCorrelationName() )
439 rString.append(" AS ");
440 m_aChildren[1]->impl_parseNodeToString_throw( rString, rParam, false );
442 bHandled = true;
443 break;
445 case opt_as:
446 assert(nCount == 0);
447 bHandled = true;
448 break;
450 case like_predicate:
451 // Depending on whether international is given, LIKE is treated differently
452 // international: *, ? are placeholders
453 // else SQL92 conform: %, _
454 impl_parseLikeNodeToString_throw( rString, rParam, bSimple );
455 bHandled = true;
456 break;
458 case general_set_fct:
459 case set_fct_spec:
460 case position_exp:
461 case extract_exp:
462 case length_exp:
463 case char_value_fct:
464 bSimple=false;
465 if (!addDateValue(rString, rParam))
467 // Do not quote function name
468 SQLParseNodeParameter aNewParam(rParam);
469 aNewParam.bQuote = ( SQL_ISRULE(this,length_exp) || SQL_ISRULE(this,char_value_fct) );
471 m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam, false );
472 aNewParam.bQuote = rParam.bQuote;
473 //aNewParam.bPredicate = sal_False; // disable [ ] around names // look at i73215
474 OUStringBuffer aStringPara;
475 for (sal_uInt32 i=1; i<nCount; i++)
477 const OSQLParseNode * pSubTree = m_aChildren[i];
478 if (pSubTree)
480 pSubTree->impl_parseNodeToString_throw( aStringPara, aNewParam, false );
482 // In the comma lists, put commas in-between all subtrees
483 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i < (nCount - 1)))
484 aStringPara.append(",");
486 else
487 i++;
489 rString.append(aStringPara.makeStringAndClear());
491 bHandled = true;
492 break;
493 case odbc_call_spec:
494 case subquery:
495 case term:
496 case factor:
497 case window_function:
498 case cast_spec:
499 case num_value_exp:
500 bSimple = false;
501 break;
502 default:
503 break;
504 } // switch ( getKnownRuleID() )
506 if ( !bHandled )
508 for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
509 i != m_aChildren.end();)
511 const OSQLParseNode* pSubTree = *i;
512 if ( !pSubTree )
514 ++i;
515 continue;
518 SQLParseNodeParameter aNewParam(rParam);
520 // don't replace the field for subqueries
521 if (rParam.xField.is() && SQL_ISRULE(pSubTree,subquery))
522 aNewParam.xField = nullptr;
524 // When we are building a criterion inside a query view,
525 // simplify criterion display by removing:
526 // "currentFieldName"
527 // "currentFieldName" =
528 // but only in simple expressions.
529 // This means anything that is made of:
530 // (see the rules conditionalised by inPredicateCheck() in sqlbison.y).
531 // - parentheses
532 // - logical operators (and, or, not)
533 // - comparison operators (IS, =, >, <, BETWEEN, LIKE, ...)
534 // but *not* e.g. in function arguments
535 if (bSimple && rParam.bPredicate && rParam.xField.is() && SQL_ISRULE(pSubTree,column_ref))
537 if (columnMatchP(pSubTree, rParam))
539 // skip field
540 ++i;
541 // if the following node is the comparison operator'=',
542 // we filter it as well
543 if (SQL_ISRULE(this, comparison_predicate))
545 if(i != m_aChildren.end())
547 pSubTree = *i;
548 if (pSubTree && pSubTree->getNodeType() == SQLNodeType::Equal)
549 ++i;
553 else
555 pSubTree->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
556 ++i;
558 // In the comma lists, put commas in-between all subtrees
559 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i != m_aChildren.end()))
560 rString.append(",");
563 else
565 pSubTree->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
566 ++i;
568 // In the comma lists, put commas in-between all subtrees
569 if ((m_eNodeType == SQLNodeType::CommaListRule) && (i != m_aChildren.end()))
571 if (SQL_ISRULE(this,value_exp_commalist) && rParam.bPredicate)
572 rString.append(";");
573 else
574 rString.append(",");
577 // The right hand-side of these operators is not simple
578 switch ( getKnownRuleID() )
580 case general_set_fct:
581 case set_fct_spec:
582 case position_exp:
583 case extract_exp:
584 case length_exp:
585 case char_value_fct:
586 case odbc_call_spec:
587 case subquery:
588 case comparison_predicate:
589 case between_predicate:
590 case like_predicate:
591 case test_for_null:
592 case in_predicate:
593 case existence_test:
594 case unique_test:
595 case all_or_any_predicate:
596 case join_condition:
597 case comparison_predicate_part_2:
598 case parenthesized_boolean_value_expression:
599 case other_like_predicate_part_2:
600 case between_predicate_part_2:
601 bSimple=false;
602 break;
603 default:
604 break;
611 bool OSQLParseNode::impl_parseTableNameNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const
613 // is the table_name part of a table_ref?
614 OSL_ENSURE( getParent(), "OSQLParseNode::impl_parseTableNameNodeToString_throw: table_name without parent?" );
615 if ( !getParent() || ( getParent()->getKnownRuleID() != table_ref ) )
616 return false;
618 // if it's a query, maybe we need to substitute the SQL statement ...
619 if ( !rParam.bParseToSDBCLevel )
620 return false;
622 if ( !rParam.xQueries.is() )
623 // connection does not support queries in queries, or was no query supplier
624 return false;
628 OUString sTableOrQueryName( getChild(0)->getTokenValue() );
629 bool bIsQuery = rParam.xQueries->hasByName( sTableOrQueryName );
630 if ( !bIsQuery )
631 return false;
633 // avoid recursion (e.g. "foo" defined as "SELECT * FROM bar" and "bar" defined as "SELECT * FROM foo".
634 if ( rParam.pSubQueryHistory->find( sTableOrQueryName ) != rParam.pSubQueryHistory->end() )
636 OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: no parser?" );
637 if ( rParam.pParser )
639 const SQLError& rErrors( rParam.pParser->getErrorHelper() );
640 rErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
642 else
644 SQLError aErrors( ::comphelper::getProcessComponentContext() );
645 aErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
648 rParam.pSubQueryHistory->insert( sTableOrQueryName );
650 Reference< XPropertySet > xQuery( rParam.xQueries->getByName( sTableOrQueryName ), UNO_QUERY_THROW );
652 // substitute the query name with the constituting command
653 OUString sCommand;
654 OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_COMMAND ) ) >>= sCommand );
656 bool bEscapeProcessing = false;
657 OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ) ) >>= bEscapeProcessing );
659 // the query we found here might itself be based on another query, so parse it recursively
660 OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: cannot analyze sub queries without a parser!" );
661 if ( bEscapeProcessing && rParam.pParser )
663 OUString sError;
664 std::unique_ptr< OSQLParseNode > pSubQueryNode( rParam.pParser->parseTree( sError, sCommand ) );
665 if ( pSubQueryNode.get() )
667 // parse the sub-select to SDBC level, too
668 OUStringBuffer sSubSelect;
669 pSubQueryNode->impl_parseNodeToString_throw( sSubSelect, rParam, false );
670 if ( !sSubSelect.isEmpty() )
671 sCommand = sSubSelect.makeStringAndClear();
675 rString.append( " ( " );
676 rString.append(sCommand);
677 rString.append( " )" );
679 // append the query name as table alias, since it might be referenced in other
680 // parts of the statement - but only if there's no other alias name present
681 if ( !lcl_isAliasNamePresent( *this ) )
683 rString.append( " AS " );
684 if ( rParam.bQuote )
685 rString.append(SetQuotation( sTableOrQueryName,
686 rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
689 // don't forget to remove the query name from the history, else multiple inclusions
690 // won't work
691 // #i69227# / 2006-10-10 / frank.schoenheit@sun.com
692 rParam.pSubQueryHistory->erase( sTableOrQueryName );
694 return true;
696 catch( const SQLException& )
698 throw;
700 catch( const Exception& )
702 DBG_UNHANDLED_EXCEPTION();
704 return false;
708 void OSQLParseNode::impl_parseTableRangeNodeToString_throw(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
710 OSL_PRECOND( ( count() == 2 ) || ( count() == 3 ) || ( count() == 5 ) ,"Illegal count");
712 // rString += " ";
713 ::std::for_each(m_aChildren.begin(),m_aChildren.end(),
714 [&] (OSQLParseNode *const pNode) { pNode->impl_parseNodeToString_throw(rString, rParam, false); });
718 void OSQLParseNode::impl_parseLikeNodeToString_throw( OUStringBuffer& rString, const SQLParseNodeParameter& rParam, bool bSimple ) const
720 assert(SQL_ISRULE(this,like_predicate));
721 OSL_ENSURE(count() == 2,"count != 2: Prepare for GPF");
723 const OSQLParseNode* pEscNode = nullptr;
724 const OSQLParseNode* pParaNode = nullptr;
726 SQLParseNodeParameter aNewParam(rParam);
727 //aNewParam.bQuote = sal_True; // why setting this to true? @see http://www.openoffice.org/issues/show_bug.cgi?id=75557
729 if ( !(bSimple && rParam.bPredicate && rParam.xField.is() && SQL_ISRULE(m_aChildren[0],column_ref) && columnMatchP(m_aChildren[0], rParam)) )
730 m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam, bSimple );
732 const OSQLParseNode* pPart2 = m_aChildren[1];
733 pPart2->getChild(0)->impl_parseNodeToString_throw( rString, aNewParam, false );
734 pPart2->getChild(1)->impl_parseNodeToString_throw( rString, aNewParam, false );
735 pParaNode = pPart2->getChild(2);
736 pEscNode = pPart2->getChild(3);
738 if (pParaNode->isToken())
740 OUString aStr = ConvertLikeToken(pParaNode, pEscNode, rParam.bInternational);
741 rString.append(" ");
742 rString.append(SetQuotation(aStr,"\'","\'\'"));
744 else
745 pParaNode->impl_parseNodeToString_throw( rString, aNewParam, false );
747 pEscNode->impl_parseNodeToString_throw( rString, aNewParam, false );
751 bool OSQLParseNode::getTableComponents(const OSQLParseNode* _pTableNode,
752 css::uno::Any &_rCatalog,
753 OUString &_rSchema,
754 OUString &_rTable,
755 const Reference< XDatabaseMetaData >& _xMetaData)
757 OSL_ENSURE(_pTableNode,"Wrong use of getTableComponents! _pTableNode is not allowed to be null!");
758 if(_pTableNode)
760 const bool bSupportsCatalog = _xMetaData.is() && _xMetaData->supportsCatalogsInDataManipulation();
761 const bool bSupportsSchema = _xMetaData.is() && _xMetaData->supportsSchemasInDataManipulation();
762 const OSQLParseNode* pTableNode = _pTableNode;
763 // clear the parameter given
764 _rCatalog = Any();
765 _rSchema.clear();
766 _rTable.clear();
767 // see rule catalog_name: in sqlbison.y
768 if (SQL_ISRULE(pTableNode,catalog_name))
770 OSL_ENSURE(pTableNode->getChild(0) && pTableNode->getChild(0)->isToken(),"Invalid parsenode!");
771 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
772 pTableNode = pTableNode->getChild(2);
774 // check if we have schema_name rule
775 if(SQL_ISRULE(pTableNode,schema_name))
777 if ( bSupportsCatalog && !bSupportsSchema )
778 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
779 else
780 _rSchema = pTableNode->getChild(0)->getTokenValue();
781 pTableNode = pTableNode->getChild(2);
783 // check if we have table_name rule
784 if(SQL_ISRULE(pTableNode,table_name))
786 _rTable = pTableNode->getChild(0)->getTokenValue();
788 else
790 SAL_WARN( "connectivity.parse","Error in parse tree!");
793 return !_rTable.isEmpty();
796 void OSQLParser::killThousandSeparator(OSQLParseNode* pLiteral)
798 if ( pLiteral )
800 if ( s_xLocaleData->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
802 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace('.', sal_Unicode());
803 // and replace decimal
804 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', '.');
806 else
807 pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', sal_Unicode());
811 OSQLParseNode* OSQLParser::convertNode(sal_Int32 nType, OSQLParseNode* pLiteral)
813 if ( !pLiteral )
814 return nullptr;
816 OSQLParseNode* pReturn = pLiteral;
818 if ( ( pLiteral->isRule() && !SQL_ISRULE(pLiteral,value_exp) ) || SQL_ISTOKEN(pLiteral,FALSE) || SQL_ISTOKEN(pLiteral,TRUE) )
820 switch(nType)
822 case DataType::CHAR:
823 case DataType::VARCHAR:
824 case DataType::LONGVARCHAR:
825 case DataType::CLOB:
826 if ( !SQL_ISRULE(pReturn,char_value_exp) && !buildStringNodes(pReturn) )
827 pReturn = nullptr;
828 break;
829 default:
830 break;
833 else
835 switch(pLiteral->getNodeType())
837 case SQLNodeType::String:
838 switch(nType)
840 case DataType::CHAR:
841 case DataType::VARCHAR:
842 case DataType::LONGVARCHAR:
843 case DataType::CLOB:
844 break;
845 case DataType::DATE:
846 case DataType::TIME:
847 case DataType::TIMESTAMP:
848 if (m_xFormatter.is())
849 pReturn = buildDate( nType, pReturn);
850 break;
851 default:
852 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidCompare);
853 break;
855 break;
856 case SQLNodeType::AccessDate:
857 switch(nType)
859 case DataType::DATE:
860 case DataType::TIME:
861 case DataType::TIMESTAMP:
862 if ( m_xFormatter.is() )
863 pReturn = buildDate( nType, pReturn);
864 else
865 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidDateCompare);
866 break;
867 default:
868 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidCompare);
869 break;
871 break;
872 case SQLNodeType::IntNum:
873 switch(nType)
875 case DataType::BIT:
876 case DataType::BOOLEAN:
877 case DataType::DECIMAL:
878 case DataType::NUMERIC:
879 case DataType::TINYINT:
880 case DataType::SMALLINT:
881 case DataType::INTEGER:
882 case DataType::BIGINT:
883 case DataType::FLOAT:
884 case DataType::REAL:
885 case DataType::DOUBLE:
886 // kill thousand separators if any
887 killThousandSeparator(pReturn);
888 break;
889 case DataType::CHAR:
890 case DataType::VARCHAR:
891 case DataType::LONGVARCHAR:
892 case DataType::CLOB:
893 pReturn = buildNode_STR_NUM(pReturn);
894 break;
895 default:
896 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidIntCompare);
897 break;
899 break;
900 case SQLNodeType::ApproxNum:
901 switch(nType)
903 case DataType::DECIMAL:
904 case DataType::NUMERIC:
905 case DataType::FLOAT:
906 case DataType::REAL:
907 case DataType::DOUBLE:
908 // kill thousand separators if any
909 killThousandSeparator(pReturn);
910 break;
911 case DataType::CHAR:
912 case DataType::VARCHAR:
913 case DataType::LONGVARCHAR:
914 case DataType::CLOB:
915 pReturn = buildNode_STR_NUM(pReturn);
916 break;
917 case DataType::INTEGER:
918 default:
919 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidRealCompare);
920 break;
922 break;
923 default:
927 return pReturn;
930 sal_Int16 OSQLParser::buildPredicateRule(OSQLParseNode*& pAppend, OSQLParseNode* pLiteral, OSQLParseNode* pCompare, OSQLParseNode* pLiteral2)
932 OSL_ENSURE(inPredicateCheck(),"Only in predicate check allowed!");
933 sal_Int16 nErg = 0;
934 if ( m_xField.is() )
936 sal_Int32 nType = 0;
939 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
941 catch( Exception& )
943 return nErg;
946 OSQLParseNode* pNode1 = convertNode(nType,pLiteral);
947 if ( pNode1 )
949 OSQLParseNode* pNode2 = convertNode(nType,pLiteral2);
950 if ( m_sErrorMessage.isEmpty() )
951 nErg = buildNode(pAppend,pCompare,pNode1,pNode2);
954 if (!pCompare->getParent()) // I have no parent so I was not used and I must die :-)
955 delete pCompare;
956 return nErg;
959 sal_Int16 OSQLParser::buildLikeRule(OSQLParseNode* pAppend, OSQLParseNode*& pLiteral, const OSQLParseNode* pEscape)
961 sal_Int16 nErg = 0;
962 sal_Int32 nType = 0;
964 if (!m_xField.is())
965 return nErg;
968 Any aValue;
970 aValue = m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE));
971 aValue >>= nType;
974 catch( Exception& )
976 return nErg;
979 switch (nType)
981 case DataType::CHAR:
982 case DataType::VARCHAR:
983 case DataType::LONGVARCHAR:
984 case DataType::CLOB:
985 if(pLiteral->isRule())
987 pAppend->append(pLiteral);
988 nErg = 1;
990 else
992 switch(pLiteral->getNodeType())
994 case SQLNodeType::String:
995 pLiteral->m_aNodeValue = ConvertLikeToken(pLiteral, pEscape, false);
996 pAppend->append(pLiteral);
997 nErg = 1;
998 break;
999 case SQLNodeType::ApproxNum:
1000 if (m_xFormatter.is() && m_nFormatKey)
1002 sal_Int16 nScale = 0;
1005 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, "Decimals" );
1006 aValue >>= nScale;
1008 catch( Exception& )
1012 pAppend->append(new OSQLInternalNode(stringToDouble(pLiteral->getTokenValue(),nScale),SQLNodeType::String));
1014 else
1015 pAppend->append(new OSQLInternalNode(pLiteral->getTokenValue(),SQLNodeType::String));
1017 delete pLiteral;
1018 nErg = 1;
1019 break;
1020 default:
1021 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::ValueNoLike);
1022 m_sErrorMessage = m_sErrorMessage.replaceAt(m_sErrorMessage.indexOf("#1"),2,pLiteral->getTokenValue());
1023 break;
1026 break;
1027 default:
1028 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::FieldNoLike);
1029 break;
1031 return nErg;
1034 OSQLParseNode* OSQLParser::buildNode_Date(const double& fValue, sal_Int32 nType)
1036 OUString aEmptyString;
1037 OSQLParseNode* pNewNode = new OSQLInternalNode(aEmptyString, SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::set_fct_spec));
1038 pNewNode->append(new OSQLInternalNode(OUString("{"), SQLNodeType::Punctuation));
1039 OSQLParseNode* pDateNode = new OSQLInternalNode(aEmptyString, SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::odbc_fct_spec));
1040 pNewNode->append(pDateNode);
1041 pNewNode->append(new OSQLInternalNode(OUString("}"), SQLNodeType::Punctuation));
1043 switch (nType)
1045 case DataType::DATE:
1047 Date aDate = DBTypeConversion::toDate(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1048 OUString aString = DBTypeConversion::toDateString(aDate);
1049 pDateNode->append(new OSQLInternalNode(aEmptyString, SQLNodeType::Keyword, SQL_TOKEN_D));
1050 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1051 break;
1053 case DataType::TIME:
1055 css::util::Time aTime = DBTypeConversion::toTime(fValue);
1056 OUString aString = DBTypeConversion::toTimeString(aTime);
1057 pDateNode->append(new OSQLInternalNode(aEmptyString, SQLNodeType::Keyword, SQL_TOKEN_T));
1058 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1059 break;
1061 case DataType::TIMESTAMP:
1063 DateTime aDateTime = DBTypeConversion::toDateTime(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1064 if (aDateTime.Seconds || aDateTime.Minutes || aDateTime.Hours)
1066 OUString aString = DBTypeConversion::toDateTimeString(aDateTime);
1067 pDateNode->append(new OSQLInternalNode(aEmptyString, SQLNodeType::Keyword, SQL_TOKEN_TS));
1068 pDateNode->append(new OSQLInternalNode(aString, SQLNodeType::String));
1070 else
1072 Date aDate(aDateTime.Day,aDateTime.Month,aDateTime.Year);
1073 pDateNode->append(new OSQLInternalNode(aEmptyString, SQLNodeType::Keyword, SQL_TOKEN_D));
1074 pDateNode->append(new OSQLInternalNode(DBTypeConversion::toDateString(aDate), SQLNodeType::String));
1076 break;
1080 return pNewNode;
1083 OSQLParseNode* OSQLParser::buildNode_STR_NUM(OSQLParseNode*& _pLiteral)
1085 OSQLParseNode* pReturn = nullptr;
1086 if ( _pLiteral )
1088 if (m_nFormatKey)
1090 sal_Int16 nScale = 0;
1093 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, "Decimals" );
1094 aValue >>= nScale;
1096 catch( Exception& )
1100 pReturn = new OSQLInternalNode(stringToDouble(_pLiteral->getTokenValue(),nScale),SQLNodeType::String);
1102 else
1103 pReturn = new OSQLInternalNode(_pLiteral->getTokenValue(),SQLNodeType::String);
1105 delete _pLiteral;
1106 _pLiteral = nullptr;
1108 return pReturn;
1111 OUString OSQLParser::stringToDouble(const OUString& _rValue,sal_Int16 _nScale)
1113 OUString aValue;
1114 if(!m_xCharClass.is())
1115 m_xCharClass = CharacterClassification::create( m_xContext );
1116 if( s_xLocaleData.is() )
1120 ParseResult aResult = m_xCharClass->parsePredefinedToken(KParseType::ANY_NUMBER,_rValue,0,m_pData->aLocale,0,OUString(),KParseType::ANY_NUMBER,OUString());
1121 if((aResult.TokenType & KParseType::IDENTNAME) && aResult.EndPos == _rValue.getLength())
1123 aValue = OUString::number(aResult.Value);
1124 sal_Int32 nPos = aValue.lastIndexOf('.');
1125 if((nPos+_nScale) < aValue.getLength())
1126 aValue = aValue.replaceAt(nPos+_nScale,aValue.getLength()-nPos-_nScale,OUString());
1127 aValue = aValue.replaceAt(aValue.lastIndexOf('.'),1,s_xLocaleData->getLocaleItem(m_pData->aLocale).decimalSeparator);
1128 return aValue;
1131 catch(Exception&)
1135 return aValue;
1139 ::osl::Mutex& OSQLParser::getMutex()
1141 static ::osl::Mutex aMutex;
1142 return aMutex;
1146 OSQLParseNode* OSQLParser::predicateTree(OUString& rErrorMessage, const OUString& rStatement,
1147 const Reference< css::util::XNumberFormatter > & xFormatter,
1148 const Reference< XPropertySet > & xField,
1149 bool bUseRealName)
1151 // Guard the parsing
1152 ::osl::MutexGuard aGuard(getMutex());
1153 // must be reset
1154 setParser(this);
1157 // reset the parser
1158 m_xField = xField;
1159 m_xFormatter = xFormatter;
1161 if (m_xField.is())
1163 sal_Int32 nType=0;
1166 // get the field name
1167 OUString aString;
1169 // retrieve the fields name
1170 // #75243# use the RealName of the column if there is any otherwise the name which could be the alias
1171 // of the field
1172 Reference< XPropertySetInfo> xInfo = m_xField->getPropertySetInfo();
1173 if ( bUseRealName && xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)))
1174 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)) >>= aString;
1175 else
1176 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aString;
1178 m_sFieldName = aString;
1180 // get the field format key
1181 if ( xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)))
1182 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) >>= m_nFormatKey;
1183 else
1184 m_nFormatKey = 0;
1186 // get the field type
1187 m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
1189 catch ( Exception& )
1191 OSL_ASSERT(false);
1194 if (m_nFormatKey && m_xFormatter.is())
1196 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_LOCALE) );
1197 OSL_ENSURE(aValue.getValueType() == cppu::UnoType<css::lang::Locale>::get(), "OSQLParser::PredicateTree : invalid language property !");
1199 if (aValue.getValueType() == cppu::UnoType<css::lang::Locale>::get())
1200 aValue >>= m_pData->aLocale;
1202 else
1203 m_pData->aLocale = m_pContext->getPreferredLocale();
1205 if ( m_xFormatter.is() )
1209 Reference< css::util::XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1210 if ( xFormatSup.is() )
1212 Reference< css::util::XNumberFormats > xFormats = xFormatSup->getNumberFormats();
1213 if ( xFormats.is() )
1215 css::lang::Locale aLocale;
1216 aLocale.Language = "en";
1217 aLocale.Country = "US";
1218 OUString sFormat("YYYY-MM-DD");
1219 m_nDateFormatKey = xFormats->queryKey(sFormat,aLocale,false);
1220 if ( m_nDateFormatKey == sal_Int32(-1) )
1221 m_nDateFormatKey = xFormats->addNew(sFormat, aLocale);
1225 catch ( Exception& )
1227 SAL_WARN( "connectivity.parse","DateFormatKey");
1231 switch (nType)
1233 case DataType::DATE:
1234 case DataType::TIME:
1235 case DataType::TIMESTAMP:
1236 s_pScanner->SetRule(OSQLScanner::GetDATERule());
1237 break;
1238 case DataType::CHAR:
1239 case DataType::VARCHAR:
1240 case DataType::LONGVARCHAR:
1241 case DataType::CLOB:
1242 s_pScanner->SetRule(OSQLScanner::GetSTRINGRule());
1243 break;
1244 default:
1245 if ( s_xLocaleData->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
1246 s_pScanner->SetRule(OSQLScanner::GetGERRule());
1247 else
1248 s_pScanner->SetRule(OSQLScanner::GetENGRule());
1252 else
1253 s_pScanner->SetRule(OSQLScanner::GetSQLRule());
1255 s_pScanner->prepareScan(rStatement, m_pContext, true);
1257 SQLyylval.pParseNode = nullptr;
1258 // SQLyypvt = NULL;
1259 m_pParseTree = nullptr;
1260 m_sErrorMessage.clear();
1262 // Start the parser
1263 if (SQLyyparse() != 0)
1265 m_sFieldName.clear();
1266 m_xField.clear();
1267 m_xFormatter.clear();
1268 m_nFormatKey = 0;
1269 m_nDateFormatKey = 0;
1271 if (m_sErrorMessage.isEmpty())
1272 m_sErrorMessage = s_pScanner->getErrorMessage();
1273 if (m_sErrorMessage.isEmpty())
1274 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::General);
1276 rErrorMessage = m_sErrorMessage;
1278 // clear the garbage collector
1279 (*s_pGarbageCollector)->clearAndDelete();
1280 return nullptr;
1282 else
1284 (*s_pGarbageCollector)->clear();
1286 m_sFieldName.clear();
1287 m_xField.clear();
1288 m_xFormatter.clear();
1289 m_nFormatKey = 0;
1290 m_nDateFormatKey = 0;
1292 // Return the result (the root parse node):
1294 // Instead, the parse method sets the member pParseTree and simply returns that
1295 OSL_ENSURE(m_pParseTree != nullptr,"OSQLParser: Parser did not return a ParseTree!");
1296 return m_pParseTree;
1301 OSQLParser::OSQLParser(const css::uno::Reference< css::uno::XComponentContext >& rxContext, const IParseContext* _pContext)
1302 :m_pContext(_pContext)
1303 ,m_pParseTree(nullptr)
1304 ,m_pData( new OSQLParser_Data( rxContext ) )
1305 ,m_nFormatKey(0)
1306 ,m_nDateFormatKey(0)
1307 ,m_xContext(rxContext)
1311 setParser(this);
1313 #ifdef SQLYYDEBUG
1314 #ifdef SQLYYDEBUG_ON
1315 SQLyydebug = 1;
1316 #endif
1317 #endif
1319 ::osl::MutexGuard aGuard(getMutex());
1320 // Do we have to initialize the data?
1321 if (s_nRefCount == 0)
1323 s_pScanner = new OSQLScanner();
1324 s_pScanner->setScanner();
1325 s_pGarbageCollector = new OSQLParseNodesGarbageCollector();
1327 if(!s_xLocaleData.is())
1328 s_xLocaleData = LocaleData::create(m_xContext);
1330 // reset to UNKNOWN_RULE
1331 static_assert(OSQLParseNode::UNKNOWN_RULE==0, "UNKNOWN_RULE must be 0 for memset to 0 to work");
1332 memset(OSQLParser::s_nRuleIDs,0,sizeof(OSQLParser::s_nRuleIDs));
1334 const struct
1336 OSQLParseNode::Rule eRule; // the parse node's ID for the rule
1337 OString sRuleName; // the name of the rule ("select_statement")
1338 } aRuleDescriptions[] =
1340 { OSQLParseNode::select_statement, "select_statement" },
1341 { OSQLParseNode::table_exp, "table_exp" },
1342 { OSQLParseNode::table_ref_commalist, "table_ref_commalist" },
1343 { OSQLParseNode::table_ref, "table_ref" },
1344 { OSQLParseNode::catalog_name, "catalog_name" },
1345 { OSQLParseNode::schema_name, "schema_name" },
1346 { OSQLParseNode::table_name, "table_name" },
1347 { OSQLParseNode::opt_column_commalist, "opt_column_commalist" },
1348 { OSQLParseNode::column_commalist, "column_commalist" },
1349 { OSQLParseNode::column_ref_commalist, "column_ref_commalist" },
1350 { OSQLParseNode::column_ref, "column_ref" },
1351 { OSQLParseNode::opt_order_by_clause, "opt_order_by_clause" },
1352 { OSQLParseNode::ordering_spec_commalist, "ordering_spec_commalist" },
1353 { OSQLParseNode::ordering_spec, "ordering_spec" },
1354 { OSQLParseNode::opt_asc_desc, "opt_asc_desc" },
1355 { OSQLParseNode::where_clause, "where_clause" },
1356 { OSQLParseNode::opt_where_clause, "opt_where_clause" },
1357 { OSQLParseNode::search_condition, "search_condition" },
1358 { OSQLParseNode::comparison, "comparison" },
1359 { OSQLParseNode::comparison_predicate, "comparison_predicate" },
1360 { OSQLParseNode::between_predicate, "between_predicate" },
1361 { OSQLParseNode::like_predicate, "like_predicate" },
1362 { OSQLParseNode::opt_escape, "opt_escape" },
1363 { OSQLParseNode::test_for_null, "test_for_null" },
1364 { OSQLParseNode::scalar_exp_commalist, "scalar_exp_commalist" },
1365 { OSQLParseNode::scalar_exp, "scalar_exp" },
1366 { OSQLParseNode::parameter_ref, "parameter_ref" },
1367 { OSQLParseNode::parameter, "parameter" },
1368 { OSQLParseNode::general_set_fct, "general_set_fct" },
1369 { OSQLParseNode::range_variable, "range_variable" },
1370 { OSQLParseNode::column, "column" },
1371 { OSQLParseNode::delete_statement_positioned, "delete_statement_positioned" },
1372 { OSQLParseNode::delete_statement_searched, "delete_statement_searched" },
1373 { OSQLParseNode::update_statement_positioned, "update_statement_positioned" },
1374 { OSQLParseNode::update_statement_searched, "update_statement_searched" },
1375 { OSQLParseNode::assignment_commalist, "assignment_commalist" },
1376 { OSQLParseNode::assignment, "assignment" },
1377 { OSQLParseNode::values_or_query_spec, "values_or_query_spec" },
1378 { OSQLParseNode::insert_statement, "insert_statement" },
1379 { OSQLParseNode::insert_atom_commalist, "insert_atom_commalist" },
1380 { OSQLParseNode::insert_atom, "insert_atom" },
1381 { OSQLParseNode::from_clause, "from_clause" },
1382 { OSQLParseNode::qualified_join, "qualified_join" },
1383 { OSQLParseNode::cross_union, "cross_union" },
1384 { OSQLParseNode::select_sublist, "select_sublist" },
1385 { OSQLParseNode::derived_column, "derived_column" },
1386 { OSQLParseNode::column_val, "column_val" },
1387 { OSQLParseNode::set_fct_spec, "set_fct_spec" },
1388 { OSQLParseNode::boolean_term, "boolean_term" },
1389 { OSQLParseNode::boolean_primary, "boolean_primary" },
1390 { OSQLParseNode::num_value_exp, "num_value_exp" },
1391 { OSQLParseNode::join_type, "join_type" },
1392 { OSQLParseNode::position_exp, "position_exp" },
1393 { OSQLParseNode::extract_exp, "extract_exp" },
1394 { OSQLParseNode::length_exp, "length_exp" },
1395 { OSQLParseNode::char_value_fct, "char_value_fct" },
1396 { OSQLParseNode::odbc_call_spec, "odbc_call_spec" },
1397 { OSQLParseNode::in_predicate, "in_predicate" },
1398 { OSQLParseNode::existence_test, "existence_test" },
1399 { OSQLParseNode::unique_test, "unique_test" },
1400 { OSQLParseNode::all_or_any_predicate, "all_or_any_predicate" },
1401 { OSQLParseNode::named_columns_join, "named_columns_join" },
1402 { OSQLParseNode::join_condition, "join_condition" },
1403 { OSQLParseNode::joined_table, "joined_table" },
1404 { OSQLParseNode::boolean_factor, "boolean_factor" },
1405 { OSQLParseNode::sql_not, "sql_not" },
1406 { OSQLParseNode::manipulative_statement, "manipulative_statement" },
1407 { OSQLParseNode::subquery, "subquery" },
1408 { OSQLParseNode::value_exp_commalist, "value_exp_commalist" },
1409 { OSQLParseNode::odbc_fct_spec, "odbc_fct_spec" },
1410 { OSQLParseNode::union_statement, "union_statement" },
1411 { OSQLParseNode::outer_join_type, "outer_join_type" },
1412 { OSQLParseNode::char_value_exp, "char_value_exp" },
1413 { OSQLParseNode::term, "term" },
1414 { OSQLParseNode::value_exp_primary, "value_exp_primary" },
1415 { OSQLParseNode::value_exp, "value_exp" },
1416 { OSQLParseNode::selection, "selection" },
1417 { OSQLParseNode::fold, "fold" },
1418 { OSQLParseNode::char_substring_fct, "char_substring_fct" },
1419 { OSQLParseNode::factor, "factor" },
1420 { OSQLParseNode::base_table_def, "base_table_def" },
1421 { OSQLParseNode::base_table_element_commalist, "base_table_element_commalist" },
1422 { OSQLParseNode::data_type, "data_type" },
1423 { OSQLParseNode::column_def, "column_def" },
1424 { OSQLParseNode::table_node, "table_node" },
1425 { OSQLParseNode::as_clause, "as_clause" },
1426 { OSQLParseNode::opt_as, "opt_as" },
1427 { OSQLParseNode::op_column_commalist, "op_column_commalist" },
1428 { OSQLParseNode::table_primary_as_range_column, "table_primary_as_range_column" },
1429 { OSQLParseNode::datetime_primary, "datetime_primary" },
1430 { OSQLParseNode::concatenation, "concatenation" },
1431 { OSQLParseNode::char_factor, "char_factor" },
1432 { OSQLParseNode::bit_value_fct, "bit_value_fct" },
1433 { OSQLParseNode::comparison_predicate_part_2, "comparison_predicate_part_2" },
1434 { OSQLParseNode::parenthesized_boolean_value_expression, "parenthesized_boolean_value_expression" },
1435 { OSQLParseNode::character_string_type, "character_string_type" },
1436 { OSQLParseNode::other_like_predicate_part_2, "other_like_predicate_part_2" },
1437 { OSQLParseNode::between_predicate_part_2, "between_predicate_part_2" },
1438 { OSQLParseNode::null_predicate_part_2, "null_predicate_part_2" },
1439 { OSQLParseNode::cast_spec, "cast_spec" },
1440 { OSQLParseNode::window_function, "window_function" }
1442 const size_t nRuleMapCount = SAL_N_ELEMENTS( aRuleDescriptions );
1443 // added a new rule? Adjust this map!
1444 // +1 for UNKNOWN_RULE
1445 static_assert(nRuleMapCount + 1 == static_cast<size_t>(OSQLParseNode::rule_count), "must be equal");
1447 for (const auto & aRuleDescription : aRuleDescriptions)
1449 // look up the rule description in the our identifier map
1450 sal_uInt32 nParserRuleID = StrToRuleID( aRuleDescription.sRuleName );
1451 // map the parser's rule ID to the OSQLParseNode::Rule
1452 s_aReverseRuleIDLookup[ nParserRuleID ] = aRuleDescription.eRule;
1453 // and map the OSQLParseNode::Rule to the parser's rule ID
1454 s_nRuleIDs[ aRuleDescription.eRule ] = nParserRuleID;
1457 ++s_nRefCount;
1459 if (m_pContext == nullptr)
1460 // take the default context
1461 m_pContext = &s_aDefaultContext;
1463 m_pData->aLocale = m_pContext->getPreferredLocale();
1467 OSQLParser::~OSQLParser()
1470 ::osl::MutexGuard aGuard(getMutex());
1471 OSL_ENSURE(s_nRefCount > 0, "OSQLParser::~OSQLParser() : suspicious call : has a refcount of 0 !");
1472 if (!--s_nRefCount)
1474 s_pScanner->setScanner(true);
1475 delete s_pScanner;
1476 s_pScanner = nullptr;
1478 delete s_pGarbageCollector;
1479 s_pGarbageCollector = nullptr;
1480 // Is only set the first time, so we should delete it only when there are no more instances
1481 s_xLocaleData = nullptr;
1483 RuleIDMap aEmpty;
1484 s_aReverseRuleIDLookup.swap( aEmpty );
1486 m_pParseTree = nullptr;
1490 void OSQLParseNode::substituteParameterNames(OSQLParseNode* _pNode)
1492 sal_Int32 nCount = _pNode->count();
1493 for(sal_Int32 i=0;i < nCount;++i)
1495 OSQLParseNode* pChildNode = _pNode->getChild(i);
1496 if(SQL_ISRULE(pChildNode,parameter) && pChildNode->count() > 1)
1498 OSQLParseNode* pNewNode = new OSQLParseNode(OUString("?") ,SQLNodeType::Punctuation,0);
1499 delete pChildNode->replace(pChildNode->getChild(0),pNewNode);
1500 sal_Int32 nChildCount = pChildNode->count();
1501 for(sal_Int32 j=1;j < nChildCount;++j)
1502 delete pChildNode->removeAt(1);
1504 else
1505 substituteParameterNames(pChildNode);
1510 bool OSQLParser::extractDate(OSQLParseNode* pLiteral,double& _rfValue)
1512 Reference< XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1513 Reference< XNumberFormatTypes > xFormatTypes;
1514 if ( xFormatSup.is() )
1515 xFormatTypes.set(xFormatSup->getNumberFormats(), css::uno::UNO_QUERY);
1517 // if there is no format key, yet, make sure we have a feasible one for our locale
1520 if ( !m_nFormatKey && xFormatTypes.is() )
1521 m_nFormatKey = ::dbtools::getDefaultNumberFormat( m_xField, xFormatTypes, m_pData->aLocale );
1523 catch( Exception& ) { }
1524 OUString sValue = pLiteral->getTokenValue();
1525 sal_Int32 nTryFormat = m_nFormatKey;
1526 bool bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1528 // If our format key didn't do, try the default date format for our locale.
1529 if ( !bSuccess && xFormatTypes.is() )
1533 nTryFormat = xFormatTypes->getStandardFormat( NumberFormat::DATE, m_pData->aLocale );
1535 catch( Exception& ) { }
1536 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1539 // if this also didn't do, try ISO format
1540 if ( !bSuccess && xFormatTypes.is() )
1544 nTryFormat = xFormatTypes->getFormatIndex( NumberFormatIndex::DATE_DIN_YYYYMMDD, m_pData->aLocale );
1546 catch( Exception& ) { }
1547 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1550 // if this also didn't do, try fallback date format (en-US)
1551 if ( !bSuccess )
1553 nTryFormat = m_nDateFormatKey;
1554 bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1556 return bSuccess;
1559 OSQLParseNode* OSQLParser::buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral)
1561 // try converting the string into a date, according to our format key
1562 double fValue = 0.0;
1563 OSQLParseNode* pFCTNode = nullptr;
1565 if ( extractDate(pLiteral,fValue) )
1566 pFCTNode = buildNode_Date( fValue, _nType);
1568 delete pLiteral;
1569 pLiteral = nullptr;
1571 if ( !pFCTNode )
1572 m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ErrorCode::InvalidDateCompare);
1574 return pFCTNode;
1578 OSQLParseNode::OSQLParseNode(const sal_Char * pNewValue,
1579 SQLNodeType eNewNodeType,
1580 sal_uInt32 nNewNodeID)
1581 :m_pParent(nullptr)
1582 ,m_aNodeValue(pNewValue,strlen(pNewValue),RTL_TEXTENCODING_UTF8)
1583 ,m_eNodeType(eNewNodeType)
1584 ,m_nNodeID(nNewNodeID)
1586 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1589 OSQLParseNode::OSQLParseNode(const OString &_rNewValue,
1590 SQLNodeType eNewNodeType,
1591 sal_uInt32 nNewNodeID)
1592 :m_pParent(nullptr)
1593 ,m_aNodeValue(OStringToOUString(_rNewValue,RTL_TEXTENCODING_UTF8))
1594 ,m_eNodeType(eNewNodeType)
1595 ,m_nNodeID(nNewNodeID)
1597 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1600 OSQLParseNode::OSQLParseNode(const OUString &_rNewValue,
1601 SQLNodeType eNewNodeType,
1602 sal_uInt32 nNewNodeID)
1603 :m_pParent(nullptr)
1604 ,m_aNodeValue(_rNewValue)
1605 ,m_eNodeType(eNewNodeType)
1606 ,m_nNodeID(nNewNodeID)
1608 OSL_ENSURE(m_eNodeType >= SQLNodeType::Rule && m_eNodeType <= SQLNodeType::Concat,"OSQLParseNode: created with invalid NodeType");
1611 OSQLParseNode::OSQLParseNode(const OSQLParseNode& rParseNode)
1613 // Set the getParent to NULL
1614 m_pParent = nullptr;
1616 // Copy the members
1617 m_aNodeValue = rParseNode.m_aNodeValue;
1618 m_eNodeType = rParseNode.m_eNodeType;
1619 m_nNodeID = rParseNode.m_nNodeID;
1622 // Remember that we derived from Container. According to SV-Help the Container's
1623 // copy ctor creates a new Container with the same pointers for content.
1624 // This means after copying the Container, for all non-NULL pointers a copy is
1625 // created and reattached instead of the old pointer.
1627 // If not a leaf, then process SubTrees
1628 for (OSQLParseNodes::const_iterator i = rParseNode.m_aChildren.begin();
1629 i != rParseNode.m_aChildren.end(); ++i)
1630 append(new OSQLParseNode(**i));
1634 OSQLParseNode& OSQLParseNode::operator=(const OSQLParseNode& rParseNode)
1636 if (this != &rParseNode)
1638 // Copy the members - pParent remains the same
1639 m_aNodeValue = rParseNode.m_aNodeValue;
1640 m_eNodeType = rParseNode.m_eNodeType;
1641 m_nNodeID = rParseNode.m_nNodeID;
1643 for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
1644 i != m_aChildren.end(); ++i)
1645 delete *i;
1647 m_aChildren.clear();
1649 for (OSQLParseNodes::const_iterator j = rParseNode.m_aChildren.begin();
1650 j != rParseNode.m_aChildren.end(); ++j)
1651 append(new OSQLParseNode(**j));
1653 return *this;
1657 bool OSQLParseNode::operator==(OSQLParseNode& rParseNode) const
1659 // The members must be equal
1660 bool bResult = (m_nNodeID == rParseNode.m_nNodeID) &&
1661 (m_eNodeType == rParseNode.m_eNodeType) &&
1662 (m_aNodeValue == rParseNode.m_aNodeValue) &&
1663 count() == rParseNode.count();
1665 // Parameters are not equal!
1666 bResult = bResult && !SQL_ISRULE(this, parameter);
1668 // compare children
1669 for (sal_uInt32 i=0; bResult && i < count(); i++)
1670 bResult = *getChild(i) == *rParseNode.getChild(i);
1672 return bResult;
1676 OSQLParseNode::~OSQLParseNode()
1678 for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
1679 i != m_aChildren.end(); ++i)
1680 delete *i;
1681 m_aChildren.clear();
1685 void OSQLParseNode::append(OSQLParseNode* pNewNode)
1687 OSL_ENSURE(pNewNode != nullptr, "OSQLParseNode: invalid NewSubTree");
1688 OSL_ENSURE(pNewNode->getParent() == nullptr, "OSQLParseNode: Node is not an orphan");
1689 OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pNewNode) == m_aChildren.end(),
1690 "OSQLParseNode::append() Node already element of parent");
1692 // Create connection to getParent
1693 pNewNode->setParent( this );
1694 // and attach the SubTree at the end
1695 m_aChildren.push_back(pNewNode);
1698 bool OSQLParseNode::addDateValue(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
1700 // special display for date/time values
1701 if (SQL_ISRULE(this,set_fct_spec) && SQL_ISPUNCTUATION(m_aChildren[0],"{"))
1703 const OSQLParseNode* pODBCNode = m_aChildren[1];
1704 const OSQLParseNode* pODBCNodeChild = pODBCNode->m_aChildren[0];
1706 if (pODBCNodeChild->getNodeType() == SQLNodeType::Keyword && (
1707 SQL_ISTOKEN(pODBCNodeChild, D) ||
1708 SQL_ISTOKEN(pODBCNodeChild, T) ||
1709 SQL_ISTOKEN(pODBCNodeChild, TS) ))
1711 OUString suQuote("'");
1712 if (rParam.bPredicate)
1714 if (rParam.aMetaData.shouldEscapeDateTime())
1716 suQuote = "#";
1719 else
1721 if (rParam.aMetaData.shouldEscapeDateTime())
1723 // suQuote = "'";
1724 return false;
1728 if (!rString.isEmpty())
1729 rString.append(" ");
1730 rString.append(suQuote);
1731 const OUString sTokenValue = pODBCNode->m_aChildren[1]->getTokenValue();
1732 if (SQL_ISTOKEN(pODBCNodeChild, D))
1734 rString.append(rParam.bPredicate ? convertDateString(rParam, sTokenValue) : sTokenValue);
1736 else if (SQL_ISTOKEN(pODBCNodeChild, T))
1738 rString.append(rParam.bPredicate ? convertTimeString(rParam, sTokenValue) : sTokenValue);
1740 else
1742 rString.append(rParam.bPredicate ? convertDateTimeString(rParam, sTokenValue) : sTokenValue);
1744 rString.append(suQuote);
1745 return true;
1748 return false;
1751 void OSQLParseNode::replaceNodeValue(const OUString& rTableAlias, const OUString& rColumnName)
1753 for (size_t i=0;i<count();++i)
1755 if (SQL_ISRULE(this,column_ref) && count() == 1 && getChild(0)->getTokenValue() == rColumnName)
1757 OSQLParseNode * pCol = removeAt((sal_uInt32)0);
1758 append(new OSQLParseNode(rTableAlias,SQLNodeType::Name));
1759 append(new OSQLParseNode(OUString("."),SQLNodeType::Punctuation));
1760 append(pCol);
1762 else
1763 getChild(i)->replaceNodeValue(rTableAlias,rColumnName);
1767 OSQLParseNode* OSQLParseNode::getByRule(OSQLParseNode::Rule eRule) const
1769 OSQLParseNode* pRetNode = nullptr;
1770 if (isRule() && OSQLParser::RuleID(eRule) == getRuleID())
1771 pRetNode = const_cast<OSQLParseNode*>(this);
1772 else
1774 for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
1775 !pRetNode && i != m_aChildren.end(); ++i)
1776 pRetNode = (*i)->getByRule(eRule);
1778 return pRetNode;
1781 OSQLParseNode* MakeANDNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1783 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1784 pNewNode->append(pLeftLeaf);
1785 pNewNode->append(new OSQLParseNode(OUString("AND"),SQLNodeType::Keyword,SQL_TOKEN_AND));
1786 pNewNode->append(pRightLeaf);
1787 return pNewNode;
1790 OSQLParseNode* MakeORNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1792 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::search_condition));
1793 pNewNode->append(pLeftLeaf);
1794 pNewNode->append(new OSQLParseNode(OUString("OR"),SQLNodeType::Keyword,SQL_TOKEN_OR));
1795 pNewNode->append(pRightLeaf);
1796 return pNewNode;
1799 void OSQLParseNode::disjunctiveNormalForm(OSQLParseNode*& pSearchCondition)
1801 if(!pSearchCondition) // no where condition at entry point
1802 return;
1804 OSQLParseNode::absorptions(pSearchCondition);
1805 // '(' search_condition ')'
1806 if (SQL_ISRULE(pSearchCondition,boolean_primary))
1808 OSQLParseNode* pLeft = pSearchCondition->getChild(1);
1809 disjunctiveNormalForm(pLeft);
1811 // search_condition SQL_TOKEN_OR boolean_term
1812 else if (SQL_ISRULE(pSearchCondition,search_condition))
1814 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1815 disjunctiveNormalForm(pLeft);
1817 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1818 disjunctiveNormalForm(pRight);
1820 // boolean_term SQL_TOKEN_AND boolean_factor
1821 else if (SQL_ISRULE(pSearchCondition,boolean_term))
1823 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1824 disjunctiveNormalForm(pLeft);
1826 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1827 disjunctiveNormalForm(pRight);
1829 OSQLParseNode* pNewNode = nullptr;
1830 // '(' search_condition ')' on left side
1831 if(pLeft->count() == 3 && SQL_ISRULE(pLeft,boolean_primary) && SQL_ISRULE(pLeft->getChild(1),search_condition))
1833 // and-or tree on left side
1834 OSQLParseNode* pOr = pLeft->getChild(1);
1835 OSQLParseNode* pNewLeft = nullptr;
1836 OSQLParseNode* pNewRight = nullptr;
1838 // cut right from parent
1839 pSearchCondition->removeAt(2);
1841 pNewRight = MakeANDNode(pOr->removeAt(2) ,pRight);
1842 pNewLeft = MakeANDNode(pOr->removeAt((sal_uInt32)0) ,new OSQLParseNode(*pRight));
1843 pNewNode = MakeORNode(pNewLeft,pNewRight);
1844 // and append new Node
1845 replaceAndReset(pSearchCondition,pNewNode);
1847 disjunctiveNormalForm(pSearchCondition);
1849 else if(pRight->count() == 3 && SQL_ISRULE(pRight,boolean_primary) && SQL_ISRULE(pRight->getChild(1),search_condition))
1850 { // '(' search_condition ')' on right side
1851 // and-or tree on right side
1852 // a and (b or c)
1853 OSQLParseNode* pOr = pRight->getChild(1);
1854 OSQLParseNode* pNewLeft = nullptr;
1855 OSQLParseNode* pNewRight = nullptr;
1857 // cut left from parent
1858 pSearchCondition->removeAt((sal_uInt32)0);
1860 pNewRight = MakeANDNode(pLeft,pOr->removeAt(2));
1861 pNewLeft = MakeANDNode(new OSQLParseNode(*pLeft),pOr->removeAt((sal_uInt32)0));
1862 pNewNode = MakeORNode(pNewLeft,pNewRight);
1864 // and append new Node
1865 replaceAndReset(pSearchCondition,pNewNode);
1866 disjunctiveNormalForm(pSearchCondition);
1868 else if(SQL_ISRULE(pLeft,boolean_primary) && (!SQL_ISRULE(pLeft->getChild(1),search_condition) || !SQL_ISRULE(pLeft->getChild(1),boolean_term)))
1869 pSearchCondition->replace(pLeft, pLeft->removeAt(1));
1870 else if(SQL_ISRULE(pRight,boolean_primary) && (!SQL_ISRULE(pRight->getChild(1),search_condition) || !SQL_ISRULE(pRight->getChild(1),boolean_term)))
1871 pSearchCondition->replace(pRight, pRight->removeAt(1));
1875 void OSQLParseNode::negateSearchCondition(OSQLParseNode*& pSearchCondition, bool bNegate)
1877 if(!pSearchCondition) // no where condition at entry point
1878 return;
1879 // '(' search_condition ')'
1880 if (pSearchCondition->count() == 3 && SQL_ISRULE(pSearchCondition,boolean_primary))
1882 OSQLParseNode* pRight = pSearchCondition->getChild(1);
1883 negateSearchCondition(pRight,bNegate);
1885 // search_condition SQL_TOKEN_OR boolean_term
1886 else if (SQL_ISRULE(pSearchCondition,search_condition))
1888 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1889 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1890 if(bNegate)
1892 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1893 pNewNode->append(pSearchCondition->removeAt((sal_uInt32)0));
1894 pNewNode->append(new OSQLParseNode(OUString("AND"),SQLNodeType::Keyword,SQL_TOKEN_AND));
1895 pNewNode->append(pSearchCondition->removeAt((sal_uInt32)1));
1896 replaceAndReset(pSearchCondition,pNewNode);
1898 pLeft = pNewNode->getChild(0);
1899 pRight = pNewNode->getChild(2);
1902 negateSearchCondition(pLeft,bNegate);
1903 negateSearchCondition(pRight,bNegate);
1905 // boolean_term SQL_TOKEN_AND boolean_factor
1906 else if (SQL_ISRULE(pSearchCondition,boolean_term))
1908 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
1909 OSQLParseNode* pRight = pSearchCondition->getChild(2);
1910 if(bNegate)
1912 OSQLParseNode* pNewNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::search_condition));
1913 pNewNode->append(pSearchCondition->removeAt((sal_uInt32)0));
1914 pNewNode->append(new OSQLParseNode(OUString("OR"),SQLNodeType::Keyword,SQL_TOKEN_OR));
1915 pNewNode->append(pSearchCondition->removeAt((sal_uInt32)1));
1916 replaceAndReset(pSearchCondition,pNewNode);
1918 pLeft = pNewNode->getChild(0);
1919 pRight = pNewNode->getChild(2);
1922 negateSearchCondition(pLeft,bNegate);
1923 negateSearchCondition(pRight,bNegate);
1925 // SQL_TOKEN_NOT ( boolean_primary )
1926 else if (SQL_ISRULE(pSearchCondition,boolean_factor))
1928 OSQLParseNode *pNot = pSearchCondition->removeAt((sal_uInt32)0);
1929 delete pNot;
1930 OSQLParseNode *pBooleanTest = pSearchCondition->removeAt((sal_uInt32)0);
1931 // TODO is this needed // pBooleanTest->setParent(NULL);
1932 replaceAndReset(pSearchCondition,pBooleanTest);
1934 if (!bNegate)
1935 negateSearchCondition(pSearchCondition, true); // negate all deeper values
1937 // row_value_constructor comparison row_value_constructor
1938 // row_value_constructor comparison any_all_some subquery
1939 else if(bNegate && (SQL_ISRULE(pSearchCondition,comparison_predicate) || SQL_ISRULE(pSearchCondition,all_or_any_predicate)))
1941 assert(pSearchCondition->count() == 3);
1942 OSQLParseNode* pComparison = pSearchCondition->getChild(1);
1943 if(SQL_ISRULE(pComparison, comparison))
1945 assert(pComparison->count() == 2 ||
1946 pComparison->count() == 4);
1947 assert(SQL_ISTOKEN(pComparison->getChild(0), IS));
1949 OSQLParseNode* pNot = pComparison->getChild(1);
1950 OSQLParseNode* pNotNot = nullptr;
1951 if(pNot->isRule()) // no NOT token (empty rule)
1952 pNotNot = new OSQLParseNode(OUString("NOT"),SQLNodeType::Keyword,SQL_TOKEN_NOT);
1953 else
1955 assert(SQL_ISTOKEN(pNot,NOT));
1956 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
1958 pComparison->replace(pNot, pNotNot);
1959 delete pNot;
1961 else
1963 OSQLParseNode* pNewComparison;
1964 switch(pComparison->getNodeType())
1966 default:
1967 case SQLNodeType::Equal:
1968 assert(pComparison->getNodeType() == SQLNodeType::Equal &&
1969 "OSQLParseNode::negateSearchCondition: unexpected node type!");
1970 pNewComparison = new OSQLParseNode(OUString("<>"),SQLNodeType::NotEqual,SQL_NOTEQUAL);
1971 break;
1972 case SQLNodeType::Less:
1973 pNewComparison = new OSQLParseNode(OUString(">="),SQLNodeType::GreatEq,SQL_GREATEQ);
1974 break;
1975 case SQLNodeType::Great:
1976 pNewComparison = new OSQLParseNode(OUString("<="),SQLNodeType::LessEq,SQL_LESSEQ);
1977 break;
1978 case SQLNodeType::LessEq:
1979 pNewComparison = new OSQLParseNode(OUString(">"),SQLNodeType::Great,SQL_GREAT);
1980 break;
1981 case SQLNodeType::GreatEq:
1982 pNewComparison = new OSQLParseNode(OUString("<"),SQLNodeType::Less,SQL_LESS);
1983 break;
1984 case SQLNodeType::NotEqual:
1985 pNewComparison = new OSQLParseNode(OUString("="),SQLNodeType::Equal,SQL_EQUAL);
1986 break;
1988 pSearchCondition->replace(pComparison, pNewComparison);
1989 delete pComparison;
1993 else if(bNegate && (SQL_ISRULE(pSearchCondition,test_for_null) ||
1994 SQL_ISRULE(pSearchCondition,in_predicate) ||
1995 SQL_ISRULE(pSearchCondition,between_predicate) ))
1997 OSQLParseNode* pPart2 = pSearchCondition->getChild(1);
1998 sal_uInt32 nNotPos = 0;
1999 if ( SQL_ISRULE( pSearchCondition, test_for_null ) )
2000 nNotPos = 1;
2002 OSQLParseNode* pNot = pPart2->getChild(nNotPos);
2003 OSQLParseNode* pNotNot = nullptr;
2004 if(pNot->isRule()) // no NOT token (empty rule)
2005 pNotNot = new OSQLParseNode(OUString("NOT"),SQLNodeType::Keyword,SQL_TOKEN_NOT);
2006 else
2008 assert(SQL_ISTOKEN(pNot,NOT));
2009 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
2011 pPart2->replace(pNot, pNotNot);
2012 delete pNot;
2014 else if(bNegate && (SQL_ISRULE(pSearchCondition,like_predicate)))
2016 OSQLParseNode* pNot = pSearchCondition->getChild( 1 )->getChild( 0 );
2017 OSQLParseNode* pNotNot = nullptr;
2018 if(pNot->isRule())
2019 pNotNot = new OSQLParseNode(OUString("NOT"),SQLNodeType::Keyword,SQL_TOKEN_NOT);
2020 else
2021 pNotNot = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::sql_not));
2022 pSearchCondition->getChild( 1 )->replace(pNot, pNotNot);
2023 delete pNot;
2027 void OSQLParseNode::eraseBraces(OSQLParseNode*& pSearchCondition)
2029 if (pSearchCondition && (SQL_ISRULE(pSearchCondition,boolean_primary) || (pSearchCondition->count() == 3 && SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
2030 SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")"))))
2032 OSQLParseNode* pRight = pSearchCondition->getChild(1);
2033 absorptions(pRight);
2034 // if child is not an or and tree then delete () around child
2035 if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2036 SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || // and can always stand without ()
2037 (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2039 OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2040 replaceAndReset(pSearchCondition,pNode);
2045 void OSQLParseNode::absorptions(OSQLParseNode*& pSearchCondition)
2047 if(!pSearchCondition) // no where condition at entry point
2048 return;
2050 eraseBraces(pSearchCondition);
2052 if(SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2054 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
2055 absorptions(pLeft);
2056 OSQLParseNode* pRight = pSearchCondition->getChild(2);
2057 absorptions(pRight);
2060 sal_uInt32 nPos = 0;
2061 // a and a || a or a
2062 OSQLParseNode* pNewNode = nullptr;
2063 if(( SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2064 && *pSearchCondition->getChild(0) == *pSearchCondition->getChild(2))
2066 pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2067 replaceAndReset(pSearchCondition,pNewNode);
2069 // (a or b) and a || ( b or c ) and a
2070 // a and ( a or b) || a and ( b or c )
2071 else if ( SQL_ISRULE(pSearchCondition,boolean_term)
2072 && (
2073 ( SQL_ISRULE(pSearchCondition->getChild(nPos = 0),boolean_primary)
2074 || SQL_ISRULE(pSearchCondition->getChild(nPos),search_condition)
2076 || ( SQL_ISRULE(pSearchCondition->getChild(nPos = 2),boolean_primary)
2077 || SQL_ISRULE(pSearchCondition->getChild(nPos),search_condition)
2082 OSQLParseNode* p2ndSearch = pSearchCondition->getChild(nPos);
2083 if ( SQL_ISRULE(p2ndSearch,boolean_primary) )
2084 p2ndSearch = p2ndSearch->getChild(1);
2086 if ( *p2ndSearch->getChild(0) == *pSearchCondition->getChild(2-nPos) ) // a and ( a or b) -> a or b
2088 pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2089 replaceAndReset(pSearchCondition,pNewNode);
2092 else if ( *p2ndSearch->getChild(2) == *pSearchCondition->getChild(2-nPos) ) // a and ( b or a) -> a or b
2094 pNewNode = pSearchCondition->removeAt((sal_uInt32)2);
2095 replaceAndReset(pSearchCondition,pNewNode);
2097 else if ( p2ndSearch->getByRule(OSQLParseNode::search_condition) )
2099 // a and ( b or c ) -> ( a and b ) or ( a and c )
2100 // ( b or c ) and a -> ( a and b ) or ( a and c )
2101 OSQLParseNode* pC = p2ndSearch->removeAt((sal_uInt32)2);
2102 OSQLParseNode* pB = p2ndSearch->removeAt((sal_uInt32)0);
2103 OSQLParseNode* pA = pSearchCondition->removeAt((sal_uInt32)2-nPos);
2105 OSQLParseNode* p1stAnd = MakeANDNode(pA,pB);
2106 OSQLParseNode* p2ndAnd = MakeANDNode(new OSQLParseNode(*pA),pC);
2107 pNewNode = MakeORNode(p1stAnd,p2ndAnd);
2108 OSQLParseNode* pNode = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2109 pNode->append(new OSQLParseNode(OUString("("),SQLNodeType::Punctuation));
2110 pNode->append(pNewNode);
2111 pNode->append(new OSQLParseNode(OUString(")"),SQLNodeType::Punctuation));
2112 OSQLParseNode::eraseBraces(p1stAnd);
2113 OSQLParseNode::eraseBraces(p2ndAnd);
2114 replaceAndReset(pSearchCondition,pNode);
2117 // a or a and b || a or b and a
2118 else if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(2),boolean_term))
2120 if(*pSearchCondition->getChild(2)->getChild(0) == *pSearchCondition->getChild(0))
2122 pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2123 replaceAndReset(pSearchCondition,pNewNode);
2125 else if(*pSearchCondition->getChild(2)->getChild(2) == *pSearchCondition->getChild(0))
2127 pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2128 replaceAndReset(pSearchCondition,pNewNode);
2131 // a and b or a || b and a or a
2132 else if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(0),boolean_term))
2134 if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2))
2136 pNewNode = pSearchCondition->removeAt((sal_uInt32)2);
2137 replaceAndReset(pSearchCondition,pNewNode);
2139 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2))
2141 pNewNode = pSearchCondition->removeAt((sal_uInt32)2);
2142 replaceAndReset(pSearchCondition,pNewNode);
2145 eraseBraces(pSearchCondition);
2148 void OSQLParseNode::compress(OSQLParseNode *&pSearchCondition)
2150 if(!pSearchCondition) // no WHERE condition at entry point
2151 return;
2153 OSQLParseNode::eraseBraces(pSearchCondition);
2155 if(SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2157 OSQLParseNode* pLeft = pSearchCondition->getChild(0);
2158 compress(pLeft);
2160 OSQLParseNode* pRight = pSearchCondition->getChild(2);
2161 compress(pRight);
2163 else if( SQL_ISRULE(pSearchCondition,boolean_primary) || (pSearchCondition->count() == 3 && SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
2164 SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")")))
2166 OSQLParseNode* pRight = pSearchCondition->getChild(1);
2167 compress(pRight);
2168 // if child is not an or and tree then delete () around child
2169 if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2170 (SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) && SQL_ISRULE(pSearchCondition->getParent(),boolean_term)) ||
2171 (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2173 OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2174 replaceAndReset(pSearchCondition,pNode);
2178 // or with two and trees where one element of the and trees are equal
2179 if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(0),boolean_term) && SQL_ISRULE(pSearchCondition->getChild(2),boolean_term))
2181 if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(0))
2183 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(2);
2184 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2185 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2187 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2188 pNewRule->append(new OSQLParseNode(OUString("("),SQLNodeType::Punctuation));
2189 pNewRule->append(pNode);
2190 pNewRule->append(new OSQLParseNode(OUString(")"),SQLNodeType::Punctuation));
2192 OSQLParseNode::eraseBraces(pLeft);
2193 OSQLParseNode::eraseBraces(pRight);
2195 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt((sal_uInt32)0),pNewRule);
2196 replaceAndReset(pSearchCondition,pNode);
2198 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(0))
2200 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt((sal_uInt32)0);
2201 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2202 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2204 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2205 pNewRule->append(new OSQLParseNode(OUString("("),SQLNodeType::Punctuation));
2206 pNewRule->append(pNode);
2207 pNewRule->append(new OSQLParseNode(OUString(")"),SQLNodeType::Punctuation));
2209 OSQLParseNode::eraseBraces(pLeft);
2210 OSQLParseNode::eraseBraces(pRight);
2212 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2213 replaceAndReset(pSearchCondition,pNode);
2215 else if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(2))
2217 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt(2);
2218 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt((sal_uInt32)0);
2219 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2221 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2222 pNewRule->append(new OSQLParseNode(OUString("("),SQLNodeType::Punctuation));
2223 pNewRule->append(pNode);
2224 pNewRule->append(new OSQLParseNode(OUString(")"),SQLNodeType::Punctuation));
2226 OSQLParseNode::eraseBraces(pLeft);
2227 OSQLParseNode::eraseBraces(pRight);
2229 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt((sal_uInt32)0),pNewRule);
2230 replaceAndReset(pSearchCondition,pNode);
2232 else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(2))
2234 OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt((sal_uInt32)0);
2235 OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt((sal_uInt32)0);
2236 OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2238 OSQLParseNode* pNewRule = new OSQLParseNode(OUString(),SQLNodeType::Rule,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2239 pNewRule->append(new OSQLParseNode(OUString("("),SQLNodeType::Punctuation));
2240 pNewRule->append(pNode);
2241 pNewRule->append(new OSQLParseNode(OUString(")"),SQLNodeType::Punctuation));
2243 OSQLParseNode::eraseBraces(pLeft);
2244 OSQLParseNode::eraseBraces(pRight);
2246 pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2247 replaceAndReset(pSearchCondition,pNode);
2251 #if OSL_DEBUG_LEVEL > 1
2253 void OSQLParseNode::showParseTree( OUString& rString ) const
2255 OUStringBuffer aBuf;
2256 showParseTree( aBuf, 0 );
2257 rString = aBuf.makeStringAndClear();
2261 void OSQLParseNode::showParseTree( OUStringBuffer& _inout_rBuffer, sal_uInt32 nLevel ) const
2263 for ( sal_uInt32 j=0; j<nLevel; ++j)
2264 _inout_rBuffer.appendAscii( " " );
2266 if ( !isToken() )
2268 // Rule name as rule
2269 _inout_rBuffer.appendAscii( "RULE_ID: " );
2270 _inout_rBuffer.append( (sal_Int32)getRuleID() );
2271 _inout_rBuffer.append( '(' );
2272 _inout_rBuffer.append( OSQLParser::RuleIDToStr( getRuleID() ) );
2273 _inout_rBuffer.append( ')' );
2274 _inout_rBuffer.append( '\n' );
2276 // Get the first sub tree
2277 for ( OSQLParseNodes::const_iterator i = m_aChildren.begin();
2278 i != m_aChildren.end();
2281 (*i)->showParseTree( _inout_rBuffer, nLevel+1 );
2283 else
2285 // Found a token
2286 switch (m_eNodeType)
2289 case SQLNodeType::Keyword:
2290 _inout_rBuffer.appendAscii( "SQL_KEYWORD: " );
2291 _inout_rBuffer.append( OStringToOUString( OSQLParser::TokenIDToStr( getTokenID() ), RTL_TEXTENCODING_UTF8 ) );
2292 _inout_rBuffer.append( '\n' );
2293 break;
2295 case SQLNodeType::Comparison:
2296 _inout_rBuffer.appendAscii( "SQL_COMPARISON: " );
2297 _inout_rBuffer.append( m_aNodeValue );
2298 _inout_rBuffer.append( '\n' );
2299 break;
2301 case SQLNodeType::Name:
2302 _inout_rBuffer.appendAscii( "SQL_NAME: " );
2303 _inout_rBuffer.append( '"' );
2304 _inout_rBuffer.append( m_aNodeValue );
2305 _inout_rBuffer.append( '"' );
2306 _inout_rBuffer.append( '\n' );
2307 break;
2309 case SQLNodeType::String:
2310 _inout_rBuffer.appendAscii( "SQL_STRING: " );
2311 _inout_rBuffer.append( '\'' );
2312 _inout_rBuffer.append( m_aNodeValue );
2313 _inout_rBuffer.append( '\'' );
2314 _inout_rBuffer.append( '\n' );
2315 break;
2317 case SQLNodeType::IntNum:
2318 _inout_rBuffer.appendAscii( "SQL_INTNUM: " );
2319 _inout_rBuffer.append( m_aNodeValue );
2320 _inout_rBuffer.append( '\n' );
2321 break;
2323 case SQLNodeType::ApproxNum:
2324 _inout_rBuffer.appendAscii( "SQL_APPROXNUM: " );
2325 _inout_rBuffer.append( m_aNodeValue );
2326 _inout_rBuffer.append( '\n' );
2327 break;
2329 case SQLNodeType::Punctuation:
2330 _inout_rBuffer.appendAscii( "SQL_PUNCTUATION: " );
2331 _inout_rBuffer.append( m_aNodeValue );
2332 _inout_rBuffer.append( '\n' );
2333 break;
2335 case SQLNodeType::AMMSC:
2336 _inout_rBuffer.appendAscii( "SQL_AMMSC: " );
2337 _inout_rBuffer.append( m_aNodeValue );
2338 _inout_rBuffer.append( '\n' );
2339 break;
2341 case SQLNodeType::Equal:
2342 case SQLNodeType::Less:
2343 case SQLNodeType::Great:
2344 case SQLNodeType::LessEq:
2345 case SQLNodeType::GreatEq:
2346 case SQLNodeType::NotEqual:
2347 _inout_rBuffer.append( m_aNodeValue );
2348 _inout_rBuffer.append( '\n' );
2349 break;
2351 case SQLNodeType::AccessDate:
2352 _inout_rBuffer.appendAscii( "SQL_ACCESS_DATE: " );
2353 _inout_rBuffer.append( m_aNodeValue );
2354 _inout_rBuffer.append( '\n' );
2355 break;
2357 case SQLNodeType::Date:
2358 _inout_rBuffer.appendAscii( "SQL_DATE: " );
2359 _inout_rBuffer.append( m_aNodeValue );
2360 _inout_rBuffer.append( '\n' );
2361 break;
2363 case SQLNodeType::Concat:
2364 _inout_rBuffer.appendAscii( "||" );
2365 _inout_rBuffer.append( '\n' );
2366 break;
2368 default:
2369 SAL_INFO( "connectivity.parse", "-- " << int( m_eNodeType ) );
2370 SAL_WARN( "connectivity.parse", "OSQLParser::ShowParseTree: unzulaessiger NodeType" );
2374 #endif // OSL_DEBUG_LEVEL > 0
2376 // Insert methods
2378 void OSQLParseNode::insert(sal_uInt32 nPos, OSQLParseNode* pNewSubTree)
2380 OSL_ENSURE(pNewSubTree != nullptr, "OSQLParseNode: invalid NewSubTree");
2381 OSL_ENSURE(pNewSubTree->getParent() == nullptr, "OSQLParseNode: Node is not an orphan");
2383 // Create connection to getParent
2384 pNewSubTree->setParent( this );
2385 m_aChildren.insert(m_aChildren.begin() + nPos, pNewSubTree);
2388 // removeAt methods
2390 OSQLParseNode* OSQLParseNode::removeAt(sal_uInt32 nPos)
2392 OSL_ENSURE(nPos < m_aChildren.size(),"Illegal position for removeAt");
2393 OSQLParseNodes::iterator aPos(m_aChildren.begin() + nPos);
2394 OSQLParseNode* pNode = *aPos;
2396 // Set the getParent of the removed node to NULL
2397 pNode->setParent( nullptr );
2399 m_aChildren.erase(aPos);
2400 return pNode;
2403 // Replace methods
2405 OSQLParseNode* OSQLParseNode::replace (OSQLParseNode* pOldSubNode, OSQLParseNode* pNewSubNode )
2407 OSL_ENSURE(pOldSubNode != nullptr && pNewSubNode != nullptr, "OSQLParseNode: invalid nodes");
2408 OSL_ENSURE(pNewSubNode->getParent() == nullptr, "OSQLParseNode: node already has getParent");
2409 OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pOldSubNode) != m_aChildren.end(),
2410 "OSQLParseNode::Replace() Node not element of parent");
2411 OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pNewSubNode) == m_aChildren.end(),
2412 "OSQLParseNode::Replace() Node already element of parent");
2414 pOldSubNode->setParent( nullptr );
2415 pNewSubNode->setParent( this );
2416 ::std::replace(m_aChildren.begin(), m_aChildren.end(), pOldSubNode, pNewSubNode);
2417 return pOldSubNode;
2420 void OSQLParseNode::parseLeaf(OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
2422 // Found a leaf
2423 // Append content to the output string
2424 switch (m_eNodeType)
2426 case SQLNodeType::Keyword:
2428 if (!rString.isEmpty())
2429 rString.append(" ");
2431 const OString sT = OSQLParser::TokenIDToStr(m_nNodeID, rParam.bInternational ? &rParam.m_rContext : nullptr);
2432 rString.append(OStringToOUString(sT,RTL_TEXTENCODING_UTF8));
2433 } break;
2434 case SQLNodeType::String:
2435 if (!rString.isEmpty())
2436 rString.append(" ");
2437 rString.append(SetQuotation(m_aNodeValue,"\'","\'\'"));
2438 break;
2439 case SQLNodeType::Name:
2440 if (!rString.isEmpty())
2442 switch(rString[rString.getLength()-1])
2444 case ' ' :
2445 case '.' : break;
2446 default :
2447 if ( rParam.aMetaData.getCatalogSeparator().isEmpty()
2448 || rString[rString.getLength() - 1] != rParam.aMetaData.getCatalogSeparator().toChar()
2450 rString.append(" ");
2451 break;
2454 if (rParam.bQuote)
2456 if (rParam.bPredicate)
2458 rString.append("[");
2459 rString.append(m_aNodeValue);
2460 rString.append("]");
2462 else
2463 rString.append(SetQuotation(m_aNodeValue,
2464 rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
2466 else
2467 rString.append(m_aNodeValue);
2468 break;
2469 case SQLNodeType::AccessDate:
2470 if (!rString.isEmpty())
2471 rString.append(" ");
2472 rString.append("#");
2473 rString.append(m_aNodeValue);
2474 rString.append("#");
2475 break;
2477 case SQLNodeType::IntNum:
2478 case SQLNodeType::ApproxNum:
2480 OUString aTmp = m_aNodeValue;
2481 if (rParam.bInternational && rParam.bPredicate && rParam.cDecSep != '.')
2482 aTmp = aTmp.replace('.', rParam.cDecSep);
2484 if (!rString.isEmpty())
2485 rString.append(" ");
2486 rString.append(aTmp);
2488 } break;
2489 case SQLNodeType::Punctuation:
2490 if ( getParent() && SQL_ISRULE(getParent(),cast_spec) && m_aNodeValue.toChar() == '(' ) // no spaces in front of '('
2492 rString.append(m_aNodeValue);
2493 break;
2495 SAL_FALLTHROUGH;
2496 default:
2497 if (!rString.isEmpty() && m_aNodeValue.toChar() != '.' && m_aNodeValue.toChar() != ':' )
2499 switch( rString[rString.getLength() - 1] )
2501 case ' ' :
2502 case '.' : break;
2503 default :
2504 if ( rParam.aMetaData.getCatalogSeparator().isEmpty()
2505 || rString[rString.getLength() - 1] != rParam.aMetaData.getCatalogSeparator().toChar()
2507 rString.append(" ");
2508 break;
2511 rString.append(m_aNodeValue);
2516 sal_Int32 OSQLParser::getFunctionReturnType(const OUString& _sFunctionName, const IParseContext* pContext)
2518 sal_Int32 nType = DataType::VARCHAR;
2519 OString sFunctionName(OUStringToOString(_sFunctionName,RTL_TEXTENCODING_UTF8));
2521 if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASCII,pContext))) nType = DataType::INTEGER;
2522 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_BIT_LENGTH,pContext))) nType = DataType::INTEGER;
2523 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR,pContext))) nType = DataType::VARCHAR;
2524 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR_LENGTH,pContext))) nType = DataType::INTEGER;
2525 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CONCAT,pContext))) nType = DataType::VARCHAR;
2526 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DIFFERENCE,pContext))) nType = DataType::VARCHAR;
2527 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_INSERT,pContext))) nType = DataType::VARCHAR;
2528 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LCASE,pContext))) nType = DataType::VARCHAR;
2529 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LEFT,pContext))) nType = DataType::VARCHAR;
2530 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LENGTH,pContext))) nType = DataType::INTEGER;
2531 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE,pContext))) nType = DataType::VARCHAR;
2532 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE_2,pContext))) nType = DataType::VARCHAR;
2533 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LTRIM,pContext))) nType = DataType::VARCHAR;
2534 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_OCTET_LENGTH,pContext))) nType = DataType::INTEGER;
2535 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POSITION,pContext))) nType = DataType::INTEGER;
2536 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPEAT,pContext))) nType = DataType::VARCHAR;
2537 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPLACE,pContext))) nType = DataType::VARCHAR;
2538 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RIGHT,pContext))) nType = DataType::VARCHAR;
2539 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RTRIM,pContext))) nType = DataType::VARCHAR;
2540 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SOUNDEX,pContext))) nType = DataType::VARCHAR;
2541 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SPACE,pContext))) nType = DataType::VARCHAR;
2542 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUBSTRING,pContext))) nType = DataType::VARCHAR;
2543 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UCASE,pContext))) nType = DataType::VARCHAR;
2544 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_DATE,pContext))) nType = DataType::DATE;
2545 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIME,pContext))) nType = DataType::TIME;
2546 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIMESTAMP,pContext))) nType = DataType::TIMESTAMP;
2547 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURDATE,pContext))) nType = DataType::DATE;
2548 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEDIFF,pContext))) nType = DataType::INTEGER;
2549 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEVALUE,pContext))) nType = DataType::DATE;
2550 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURTIME,pContext))) nType = DataType::TIME;
2551 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYNAME,pContext))) nType = DataType::VARCHAR;
2552 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFMONTH,pContext))) nType = DataType::INTEGER;
2553 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFWEEK,pContext))) nType = DataType::INTEGER;
2554 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFYEAR,pContext))) nType = DataType::INTEGER;
2555 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXTRACT,pContext))) nType = DataType::VARCHAR;
2556 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_HOUR,pContext))) nType = DataType::INTEGER;
2557 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MINUTE,pContext))) nType = DataType::INTEGER;
2558 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTH,pContext))) nType = DataType::INTEGER;
2559 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTHNAME,pContext))) nType = DataType::VARCHAR;
2560 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_NOW,pContext))) nType = DataType::TIMESTAMP;
2561 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_QUARTER,pContext))) nType = DataType::INTEGER;
2562 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SECOND,pContext))) nType = DataType::INTEGER;
2563 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPADD,pContext))) nType = DataType::TIMESTAMP;
2564 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPDIFF,pContext))) nType = DataType::TIMESTAMP;
2565 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMEVALUE,pContext))) nType = DataType::TIMESTAMP;
2566 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_WEEK,pContext))) nType = DataType::INTEGER;
2567 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_YEAR,pContext))) nType = DataType::INTEGER;
2568 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ABS,pContext))) nType = DataType::DOUBLE;
2569 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ACOS,pContext))) nType = DataType::DOUBLE;
2570 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASIN,pContext))) nType = DataType::DOUBLE;
2571 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN,pContext))) nType = DataType::DOUBLE;
2572 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN2,pContext))) nType = DataType::DOUBLE;
2573 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CEILING,pContext))) nType = DataType::DOUBLE;
2574 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COS,pContext))) nType = DataType::DOUBLE;
2575 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COT,pContext))) nType = DataType::DOUBLE;
2576 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DEGREES,pContext))) nType = DataType::DOUBLE;
2577 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXP,pContext))) nType = DataType::DOUBLE;
2578 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_FLOOR,pContext))) nType = DataType::DOUBLE;
2579 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOGF,pContext))) nType = DataType::DOUBLE;
2580 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG,pContext))) nType = DataType::DOUBLE;
2581 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG10,pContext))) nType = DataType::DOUBLE;
2582 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LN,pContext))) nType = DataType::DOUBLE;
2583 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MOD,pContext))) nType = DataType::DOUBLE;
2584 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_PI,pContext))) nType = DataType::DOUBLE;
2585 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POWER,pContext))) nType = DataType::DOUBLE;
2586 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RADIANS,pContext))) nType = DataType::DOUBLE;
2587 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RAND,pContext))) nType = DataType::DOUBLE;
2588 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUND,pContext))) nType = DataType::DOUBLE;
2589 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUNDMAGIC,pContext))) nType = DataType::DOUBLE;
2590 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIGN,pContext))) nType = DataType::DOUBLE;
2591 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIN,pContext))) nType = DataType::DOUBLE;
2592 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SQRT,pContext))) nType = DataType::DOUBLE;
2593 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TAN,pContext))) nType = DataType::DOUBLE;
2594 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TRUNCATE,pContext))) nType = DataType::DOUBLE;
2595 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COUNT,pContext))) nType = DataType::INTEGER;
2596 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MAX,pContext))) nType = DataType::DOUBLE;
2597 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MIN,pContext))) nType = DataType::DOUBLE;
2598 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_AVG,pContext))) nType = DataType::DOUBLE;
2599 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUM,pContext))) nType = DataType::DOUBLE;
2600 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOWER,pContext))) nType = DataType::VARCHAR;
2601 else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UPPER,pContext))) nType = DataType::VARCHAR;
2603 return nType;
2606 sal_Int32 OSQLParser::getFunctionParameterType(sal_uInt32 _nTokenId, sal_uInt32 _nPos)
2608 sal_Int32 nType = DataType::VARCHAR;
2610 if(_nTokenId == SQL_TOKEN_CHAR) nType = DataType::INTEGER;
2611 else if(_nTokenId == SQL_TOKEN_INSERT)
2613 if ( _nPos == 2 || _nPos == 3 )
2614 nType = DataType::INTEGER;
2616 else if(_nTokenId == SQL_TOKEN_LEFT)
2618 if ( _nPos == 2 )
2619 nType = DataType::INTEGER;
2621 else if(_nTokenId == SQL_TOKEN_LOCATE)
2623 if ( _nPos == 3 )
2624 nType = DataType::INTEGER;
2626 else if(_nTokenId == SQL_TOKEN_LOCATE_2)
2628 if ( _nPos == 3 )
2629 nType = DataType::INTEGER;
2631 else if( _nTokenId == SQL_TOKEN_REPEAT || _nTokenId == SQL_TOKEN_RIGHT )
2633 if ( _nPos == 2 )
2634 nType = DataType::INTEGER;
2636 else if(_nTokenId == SQL_TOKEN_SPACE )
2638 nType = DataType::INTEGER;
2640 else if(_nTokenId == SQL_TOKEN_SUBSTRING)
2642 if ( _nPos != 1 )
2643 nType = DataType::INTEGER;
2645 else if(_nTokenId == SQL_TOKEN_DATEDIFF)
2647 if ( _nPos != 1 )
2648 nType = DataType::TIMESTAMP;
2650 else if(_nTokenId == SQL_TOKEN_DATEVALUE)
2651 nType = DataType::DATE;
2652 else if(_nTokenId == SQL_TOKEN_DAYNAME)
2653 nType = DataType::DATE;
2654 else if(_nTokenId == SQL_TOKEN_DAYOFMONTH)
2655 nType = DataType::DATE;
2656 else if(_nTokenId == SQL_TOKEN_DAYOFWEEK)
2657 nType = DataType::DATE;
2658 else if(_nTokenId == SQL_TOKEN_DAYOFYEAR)
2659 nType = DataType::DATE;
2660 else if(_nTokenId == SQL_TOKEN_EXTRACT) nType = DataType::VARCHAR;
2661 else if(_nTokenId == SQL_TOKEN_HOUR) nType = DataType::TIME;
2662 else if(_nTokenId == SQL_TOKEN_MINUTE) nType = DataType::TIME;
2663 else if(_nTokenId == SQL_TOKEN_MONTH) nType = DataType::DATE;
2664 else if(_nTokenId == SQL_TOKEN_MONTHNAME) nType = DataType::DATE;
2665 else if(_nTokenId == SQL_TOKEN_NOW) nType = DataType::TIMESTAMP;
2666 else if(_nTokenId == SQL_TOKEN_QUARTER) nType = DataType::DATE;
2667 else if(_nTokenId == SQL_TOKEN_SECOND) nType = DataType::TIME;
2668 else if(_nTokenId == SQL_TOKEN_TIMESTAMPADD) nType = DataType::TIMESTAMP;
2669 else if(_nTokenId == SQL_TOKEN_TIMESTAMPDIFF) nType = DataType::TIMESTAMP;
2670 else if(_nTokenId == SQL_TOKEN_TIMEVALUE) nType = DataType::TIMESTAMP;
2671 else if(_nTokenId == SQL_TOKEN_WEEK) nType = DataType::DATE;
2672 else if(_nTokenId == SQL_TOKEN_YEAR) nType = DataType::DATE;
2674 else if(_nTokenId == SQL_TOKEN_ABS) nType = DataType::DOUBLE;
2675 else if(_nTokenId == SQL_TOKEN_ACOS) nType = DataType::DOUBLE;
2676 else if(_nTokenId == SQL_TOKEN_ASIN) nType = DataType::DOUBLE;
2677 else if(_nTokenId == SQL_TOKEN_ATAN) nType = DataType::DOUBLE;
2678 else if(_nTokenId == SQL_TOKEN_ATAN2) nType = DataType::DOUBLE;
2679 else if(_nTokenId == SQL_TOKEN_CEILING) nType = DataType::DOUBLE;
2680 else if(_nTokenId == SQL_TOKEN_COS) nType = DataType::DOUBLE;
2681 else if(_nTokenId == SQL_TOKEN_COT) nType = DataType::DOUBLE;
2682 else if(_nTokenId == SQL_TOKEN_DEGREES) nType = DataType::DOUBLE;
2683 else if(_nTokenId == SQL_TOKEN_EXP) nType = DataType::DOUBLE;
2684 else if(_nTokenId == SQL_TOKEN_FLOOR) nType = DataType::DOUBLE;
2685 else if(_nTokenId == SQL_TOKEN_LOGF) nType = DataType::DOUBLE;
2686 else if(_nTokenId == SQL_TOKEN_LOG) nType = DataType::DOUBLE;
2687 else if(_nTokenId == SQL_TOKEN_LOG10) nType = DataType::DOUBLE;
2688 else if(_nTokenId == SQL_TOKEN_LN) nType = DataType::DOUBLE;
2689 else if(_nTokenId == SQL_TOKEN_MOD) nType = DataType::DOUBLE;
2690 else if(_nTokenId == SQL_TOKEN_PI) nType = DataType::DOUBLE;
2691 else if(_nTokenId == SQL_TOKEN_POWER) nType = DataType::DOUBLE;
2692 else if(_nTokenId == SQL_TOKEN_RADIANS) nType = DataType::DOUBLE;
2693 else if(_nTokenId == SQL_TOKEN_RAND) nType = DataType::DOUBLE;
2694 else if(_nTokenId == SQL_TOKEN_ROUND) nType = DataType::DOUBLE;
2695 else if(_nTokenId == SQL_TOKEN_ROUNDMAGIC) nType = DataType::DOUBLE;
2696 else if(_nTokenId == SQL_TOKEN_SIGN) nType = DataType::DOUBLE;
2697 else if(_nTokenId == SQL_TOKEN_SIN) nType = DataType::DOUBLE;
2698 else if(_nTokenId == SQL_TOKEN_SQRT) nType = DataType::DOUBLE;
2699 else if(_nTokenId == SQL_TOKEN_TAN) nType = DataType::DOUBLE;
2700 else if(_nTokenId == SQL_TOKEN_TRUNCATE) nType = DataType::DOUBLE;
2701 else if(_nTokenId == SQL_TOKEN_COUNT) nType = DataType::INTEGER;
2702 else if(_nTokenId == SQL_TOKEN_MAX) nType = DataType::DOUBLE;
2703 else if(_nTokenId == SQL_TOKEN_MIN) nType = DataType::DOUBLE;
2704 else if(_nTokenId == SQL_TOKEN_AVG) nType = DataType::DOUBLE;
2705 else if(_nTokenId == SQL_TOKEN_SUM) nType = DataType::DOUBLE;
2707 else if(_nTokenId == SQL_TOKEN_LOWER) nType = DataType::VARCHAR;
2708 else if(_nTokenId == SQL_TOKEN_UPPER) nType = DataType::VARCHAR;
2710 return nType;
2714 const SQLError& OSQLParser::getErrorHelper() const
2716 return m_pData->aErrors;
2720 OSQLParseNode::Rule OSQLParseNode::getKnownRuleID() const
2722 if ( !isRule() )
2723 return UNKNOWN_RULE;
2724 return OSQLParser::RuleIDToRule( getRuleID() );
2727 OUString OSQLParseNode::getTableRange(const OSQLParseNode* _pTableRef)
2729 OSL_ENSURE(_pTableRef && _pTableRef->count() > 1 && _pTableRef->getKnownRuleID() == OSQLParseNode::table_ref,"Invalid node give, only table ref is allowed!");
2730 const sal_uInt32 nCount = _pTableRef->count();
2731 OUString sTableRange;
2732 if ( nCount == 2 || (nCount == 3 && !_pTableRef->getChild(0)->isToken()) )
2734 const OSQLParseNode* pNode = _pTableRef->getChild(nCount - (nCount == 2 ? 1 : 2));
2735 OSL_ENSURE(pNode && (pNode->getKnownRuleID() == OSQLParseNode::table_primary_as_range_column
2736 || pNode->getKnownRuleID() == OSQLParseNode::range_variable)
2737 ,"SQL grammar changed!");
2738 if ( !pNode->isLeaf() )
2739 sTableRange = pNode->getChild(1)->getTokenValue();
2740 } // if ( nCount == 2 || nCount == 3 )
2742 return sTableRange;
2745 OSQLParseNodesContainer::OSQLParseNodesContainer()
2749 OSQLParseNodesContainer::~OSQLParseNodesContainer()
2753 void OSQLParseNodesContainer::push_back(OSQLParseNode* _pNode)
2755 ::osl::MutexGuard aGuard(m_aMutex);
2756 m_aNodes.push_back(_pNode);
2759 void OSQLParseNodesContainer::erase(OSQLParseNode* _pNode)
2761 ::osl::MutexGuard aGuard(m_aMutex);
2762 if ( !m_aNodes.empty() )
2764 ::std::vector< OSQLParseNode* >::iterator aFind = ::std::find(m_aNodes.begin(), m_aNodes.end(),_pNode);
2765 if ( aFind != m_aNodes.end() )
2766 m_aNodes.erase(aFind);
2770 void OSQLParseNodesContainer::clear()
2772 ::osl::MutexGuard aGuard(m_aMutex);
2773 m_aNodes.clear();
2776 void OSQLParseNodesContainer::clearAndDelete()
2778 ::osl::MutexGuard aGuard(m_aMutex);
2779 // clear the garbage collector
2780 while ( !m_aNodes.empty() )
2782 OSQLParseNode* pNode = m_aNodes[0];
2783 while ( pNode->getParent() )
2785 pNode = pNode->getParent();
2787 delete pNode;
2790 } // namespace connectivity
2792 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */