1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_connectivity.hxx"
26 
27 
28 #include <connectivity/sqlnode.hxx>
29 #include <connectivity/sqlerror.hxx>
30 #include <internalnode.hxx>
31 #define YYBISON	  1
32 #ifndef BISON_INCLUDED
33 #define BISON_INCLUDED
34 #include <sqlbison.hxx>
35 #endif
36 #include <connectivity/sqlparse.hxx>
37 #include <com/sun/star/lang/Locale.hpp>
38 #include <com/sun/star/util/XNumberFormatter.hpp>
39 #include <com/sun/star/util/XNumberFormatTypes.hpp>
40 #include <com/sun/star/i18n/NumberFormatIndex.hpp>
41 #include <com/sun/star/beans/XPropertySet.hpp>
42 #include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
43 #include <com/sun/star/sdbc/DataType.hpp>
44 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
45 #include <com/sun/star/sdb/ErrorCondition.hpp>
46 #include <com/sun/star/util/XNumberFormatter.hpp>
47 #include <com/sun/star/util/XNumberFormatsSupplier.hpp>
48 #include <com/sun/star/util/XNumberFormats.hpp>
49 #include <com/sun/star/util/NumberFormat.hpp>
50 #include <com/sun/star/util/XNumberFormatTypes.hpp>
51 #include <com/sun/star/lang/Locale.hpp>
52 #include <com/sun/star/i18n/KParseType.hpp>
53 #include <com/sun/star/i18n/KParseTokens.hpp>
54 #include "connectivity/dbconversion.hxx"
55 #include <com/sun/star/util/DateTime.hpp>
56 #include <com/sun/star/util/Time.hpp>
57 #include <com/sun/star/util/Date.hpp>
58 #include "TConnection.hxx"
59 #include "sqlscan.hxx"
60 #include <comphelper/numbers.hxx>
61 #include <comphelper/processfactory.hxx>
62 #include <comphelper/stl_types.hxx>
63 #include "connectivity/dbtools.hxx"
64 #include "connectivity/dbmetadata.hxx"
65 #include "connectivity/sqlerror.hxx"
66 #include <tools/diagnose_ex.h>
67 #include <string.h>
68 #include <boost/bind.hpp>
69 #include <algorithm>
70 #include <functional>
71 #include <rtl/logfile.hxx>
72 #include <rtl/ustrbuf.hxx>
73 
74 using namespace ::com::sun::star::sdbc;
75 using namespace ::com::sun::star::util;
76 using namespace ::com::sun::star::beans;
77 using namespace ::com::sun::star::sdb;
78 using namespace ::com::sun::star::uno;
79 using namespace ::com::sun::star::lang;
80 using namespace ::com::sun::star::i18n;
81 using namespace ::com::sun::star;
82 using namespace ::osl;
83 using namespace ::dbtools;
84 using namespace ::comphelper;
85 
86 
87 extern int SQLyyparse (void);
88 extern ::rtl::OUString ConvertLikeToken(const ::connectivity::OSQLParseNode* pTokenNode, const ::connectivity::OSQLParseNode* pEscapeNode, sal_Bool bInternational);
89 extern void setParser( ::connectivity::OSQLParser* );
90 
91 namespace
92 {
93     // -----------------------------------------------------------------------------
lcl_saveConvertToNumber(const Reference<XNumberFormatter> & _xFormatter,sal_Int32 _nKey,const::rtl::OUString & _sValue,double & _nrValue)94 	sal_Bool lcl_saveConvertToNumber(const Reference< XNumberFormatter > & _xFormatter,sal_Int32 _nKey,const ::rtl::OUString& _sValue,double& _nrValue)
95 	{
96 		sal_Bool bRet = sal_False;
97 		try
98 		{
99 			_nrValue = _xFormatter->convertStringToNumber(_nKey, _sValue);
100 			bRet = sal_True;
101 		}
102 		catch(Exception&)
103 		{
104 		}
105 		return bRet;
106 	}
107     // -----------------------------------------------------------------------------
replaceAndReset(connectivity::OSQLParseNode * & _pResetNode,connectivity::OSQLParseNode * _pNewNode)108     void replaceAndReset(connectivity::OSQLParseNode*& _pResetNode,connectivity::OSQLParseNode* _pNewNode)
109     {
110         _pResetNode->getParent()->replace(_pResetNode, _pNewNode);
111         delete _pResetNode;
112         _pResetNode = _pNewNode;
113     }
114     // -----------------------------------------------------------------------------
115     /** quotes a string and search for quotes inside the string and replace them with the new quote
116         @param  rValue
117             The value to be quoted.
118         @param  rQuot
119             The quote
120         @param  rQuotToReplace
121             The quote to replace with
122         @return
123             The quoted string.
124     */
SetQuotation(const::rtl::OUString & rValue,const::rtl::OUString & rQuot,const::rtl::OUString & rQuotToReplace)125     ::rtl::OUString SetQuotation(const ::rtl::OUString& rValue, const ::rtl::OUString& rQuot, const ::rtl::OUString& rQuotToReplace)
126     {
127         ::rtl::OUString rNewValue = rQuot;
128         rNewValue += rValue;
129         sal_Int32 nIndex = (sal_Int32)-1;   // Quotes durch zweifache Quotes ersetzen, sonst kriegt der Parser Probleme
130 
131         if (rQuot.getLength())
132         {
133             do
134             {
135                 nIndex += 2;
136                 nIndex = rNewValue.indexOf(rQuot,nIndex);
137                 if(nIndex != -1)
138                     rNewValue = rNewValue.replaceAt(nIndex,rQuot.getLength(),rQuotToReplace);
139             } while (nIndex != -1);
140         }
141 
142         rNewValue += rQuot;
143         return rNewValue;
144     }
145 }
146 
147 namespace connectivity
148 {
149 
150 //=============================================================================
151 struct OSQLParser_Data
152 {
153     ::com::sun::star::lang::Locale  aLocale;
154     ::connectivity::SQLError        aErrors;
155 
OSQLParser_Dataconnectivity::OSQLParser_Data156     OSQLParser_Data( const Reference< XMultiServiceFactory >& _xServiceFactory )
157         :aErrors( _xServiceFactory )
158     {
159     }
160 };
161 
162 //=============================================================================
163 //= SQLParseNodeParameter
164 //=============================================================================
165 //-----------------------------------------------------------------------------
SQLParseNodeParameter(const Reference<XConnection> & _rxConnection,const Reference<XNumberFormatter> & _xFormatter,const Reference<XPropertySet> & _xField,const Locale & _rLocale,const IParseContext * _pContext,bool _bIntl,bool _bQuote,sal_Char _cDecSep,bool _bPredicate,bool _bParseToSDBC)166 SQLParseNodeParameter::SQLParseNodeParameter( const Reference< XConnection >& _rxConnection,
167 		const Reference< XNumberFormatter >& _xFormatter, const Reference< XPropertySet >& _xField,
168 		const Locale& _rLocale, const IParseContext* _pContext,
169         bool _bIntl, bool _bQuote, sal_Char _cDecSep, bool _bPredicate, bool _bParseToSDBC )
170     :rLocale(_rLocale)
171     ,aMetaData( _rxConnection )
172     ,pParser( NULL )
173     ,pSubQueryHistory( new QueryNameSet )
174     ,xFormatter(_xFormatter)
175     ,xField(_xField)
176     ,m_rContext( _pContext ? (const IParseContext&)(*_pContext) : (const IParseContext&)OSQLParser::s_aDefaultContext )
177     ,cDecSep(_cDecSep)
178     ,bQuote(_bQuote)
179 	,bInternational(_bIntl)
180 	,bPredicate(_bPredicate)
181     ,bParseToSDBCLevel( _bParseToSDBC )
182 {
183 }
184 
185 //-----------------------------------------------------------------------------
~SQLParseNodeParameter()186 SQLParseNodeParameter::~SQLParseNodeParameter()
187 {
188 }
189 
190 //=============================================================================
191 //= OSQLParseNode
192 //=============================================================================
193 //-----------------------------------------------------------------------------
convertDateString(const SQLParseNodeParameter & rParam,const::rtl::OUString & rString) const194 ::rtl::OUString OSQLParseNode::convertDateString(const SQLParseNodeParameter& rParam, const ::rtl::OUString& rString) const
195 {
196     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::convertDateString" );
197 	Date aDate = DBTypeConversion::toDate(rString);
198 	Reference< XNumberFormatsSupplier > xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
199 	Reference< XNumberFormatTypes >		xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
200 
201 	double fDate = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
202 	sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 36; // XXX hack
203 	return rParam.xFormatter->convertNumberToString(nKey, fDate);
204 }
205 
206 //-----------------------------------------------------------------------------
convertDateTimeString(const SQLParseNodeParameter & rParam,const::rtl::OUString & rString) const207 ::rtl::OUString OSQLParseNode::convertDateTimeString(const SQLParseNodeParameter& rParam, const ::rtl::OUString& rString) const
208 {
209     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::convertDateTimeString" );
210 	DateTime aDate = DBTypeConversion::toDateTime(rString);
211 	Reference< XNumberFormatsSupplier >  xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
212 	Reference< XNumberFormatTypes >  xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
213 
214 	double fDateTime = DBTypeConversion::toDouble(aDate,DBTypeConversion::getNULLDate(xSupplier));
215 	sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 51; // XXX hack
216 	return rParam.xFormatter->convertNumberToString(nKey, fDateTime);
217 }
218 
219 //-----------------------------------------------------------------------------
convertTimeString(const SQLParseNodeParameter & rParam,const::rtl::OUString & rString) const220 ::rtl::OUString OSQLParseNode::convertTimeString(const SQLParseNodeParameter& rParam, const ::rtl::OUString& rString) const
221 {
222     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::convertTimeString" );
223 	Time aTime = DBTypeConversion::toTime(rString);
224 	Reference< XNumberFormatsSupplier >  xSupplier(rParam.xFormatter->getNumberFormatsSupplier());
225 
226 	Reference< XNumberFormatTypes >  xTypes(xSupplier->getNumberFormats(), UNO_QUERY);
227 
228 	double fTime = DBTypeConversion::toDouble(aTime);
229 	sal_Int32 nKey = xTypes->getStandardIndex(rParam.rLocale) + 41; // XXX hack
230 	return rParam.xFormatter->convertNumberToString(nKey, fTime);
231 }
232 
233 //-----------------------------------------------------------------------------
parseNodeToStr(::rtl::OUString & rString,const Reference<XConnection> & _rxConnection,const IParseContext * pContext,sal_Bool _bIntl,sal_Bool _bQuote) const234 void OSQLParseNode::parseNodeToStr(::rtl::OUString& rString,
235 								   const Reference< XConnection >& _rxConnection,
236 								   const IParseContext* pContext,
237 								   sal_Bool _bIntl,
238 								   sal_Bool _bQuote) const
239 {
240     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::parseNodeToStr" );
241 
242 	parseNodeToStr(
243 		rString, _rxConnection, NULL, NULL,
244 		pContext ? pContext->getPreferredLocale() : OParseContext::getDefaultLocale(),
245 		pContext, _bIntl, _bQuote, '.', false, false );
246 }
247 
248 //-----------------------------------------------------------------------------
parseNodeToPredicateStr(::rtl::OUString & rString,const Reference<XConnection> & _rxConnection,const Reference<XNumberFormatter> & xFormatter,const::com::sun::star::lang::Locale & rIntl,sal_Char _cDec,const IParseContext * pContext) const249 void OSQLParseNode::parseNodeToPredicateStr(::rtl::OUString& rString,
250 											  const Reference< XConnection >& _rxConnection,
251 											  const Reference< XNumberFormatter > & xFormatter,
252 											  const ::com::sun::star::lang::Locale& rIntl,
253 											  sal_Char _cDec,
254 											  const IParseContext* pContext ) const
255 {
256     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::parseNodeToPredicateStr" );
257 
258 	OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
259 
260 	if (xFormatter.is())
261 		parseNodeToStr(rString, _rxConnection, xFormatter, NULL, rIntl, pContext, sal_True, sal_True, _cDec, true, false);
262 }
263 
264 //-----------------------------------------------------------------------------
parseNodeToPredicateStr(::rtl::OUString & rString,const Reference<XConnection> & _rxConnection,const Reference<XNumberFormatter> & xFormatter,const Reference<XPropertySet> & _xField,const::com::sun::star::lang::Locale & rIntl,sal_Char _cDec,const IParseContext * pContext) const265 void OSQLParseNode::parseNodeToPredicateStr(::rtl::OUString& rString,
266 											  const Reference< XConnection > & _rxConnection,
267 											  const Reference< XNumberFormatter > & xFormatter,
268 											  const Reference< XPropertySet > & _xField,
269 											  const ::com::sun::star::lang::Locale& rIntl,
270 											  sal_Char _cDec,
271 											  const IParseContext* pContext ) const
272 {
273     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::parseNodeToPredicateStr" );
274 
275 	OSL_ENSURE(xFormatter.is(), "OSQLParseNode::parseNodeToPredicateStr:: no formatter!");
276 
277 	if (xFormatter.is())
278 		parseNodeToStr( rString, _rxConnection, xFormatter, _xField, rIntl, pContext, true, true, _cDec, true, false );
279 }
280 
281 //-----------------------------------------------------------------------------
parseNodeToStr(::rtl::OUString & rString,const Reference<XConnection> & _rxConnection,const Reference<XNumberFormatter> & xFormatter,const Reference<XPropertySet> & _xField,const::com::sun::star::lang::Locale & rIntl,const IParseContext * pContext,bool _bIntl,bool _bQuote,sal_Char _cDecSep,bool _bPredicate,bool _bSubstitute) const282 void OSQLParseNode::parseNodeToStr(::rtl::OUString& rString,
283 					  const Reference< XConnection > & _rxConnection,
284 					  const Reference< XNumberFormatter > & xFormatter,
285 					  const Reference< XPropertySet > & _xField,
286 					  const ::com::sun::star::lang::Locale& rIntl,
287 					  const IParseContext* pContext,
288 					  bool _bIntl,
289 					  bool _bQuote,
290 					  sal_Char _cDecSep,
291 					  bool _bPredicate,
292                       bool _bSubstitute) const
293 {
294     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::parseNodeToStr" );
295 
296 	OSL_ENSURE( _rxConnection.is(), "OSQLParseNode::parseNodeToStr: invalid connection!" );
297 
298 	if ( _rxConnection.is() )
299 	{
300         ::rtl::OUStringBuffer sBuffer = rString;
301         try
302         {
303 		    OSQLParseNode::impl_parseNodeToString_throw( sBuffer,
304 			    SQLParseNodeParameter(
305                     _rxConnection, xFormatter, _xField, rIntl, pContext,
306                     _bIntl, _bQuote, _cDecSep, _bPredicate, _bSubstitute
307                 ) );
308         }
309         catch( const SQLException& )
310         {
311             OSL_ENSURE( false, "OSQLParseNode::parseNodeToStr: this should not throw!" );
312             // our callers don't expect this method to throw anything. The only known situation
313             // where impl_parseNodeToString_throw can throw is when there is a cyclic reference
314             // in the sub queries, but this cannot be the case here, as we do not parse to
315             // SDBC level.
316         }
317         rString = sBuffer.makeStringAndClear();
318 	}
319 }
320 //-----------------------------------------------------------------------------
parseNodeToExecutableStatement(::rtl::OUString & _out_rString,const Reference<XConnection> & _rxConnection,OSQLParser & _rParser,::com::sun::star::sdbc::SQLException * _pErrorHolder) const321 bool OSQLParseNode::parseNodeToExecutableStatement( ::rtl::OUString& _out_rString, const Reference< XConnection >& _rxConnection,
322     OSQLParser& _rParser, ::com::sun::star::sdbc::SQLException* _pErrorHolder ) const
323 {
324     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::parseNodeToExecutableStatement" );
325     OSL_PRECOND( _rxConnection.is(), "OSQLParseNode::parseNodeToExecutableStatement: invalid connection!" );
326     SQLParseNodeParameter aParseParam( _rxConnection,
327         NULL, NULL, OParseContext::getDefaultLocale(), NULL, false, true, '.', false, true );
328 
329     if ( aParseParam.aMetaData.supportsSubqueriesInFrom() )
330     {
331         Reference< XQueriesSupplier > xSuppQueries( _rxConnection, UNO_QUERY );
332         OSL_ENSURE( xSuppQueries.is(), "OSQLParseNode::parseNodeToExecutableStatement: cannot substitute everything without a QueriesSupplier!" );
333         if ( xSuppQueries.is() )
334             aParseParam.xQueries = xSuppQueries->getQueries();
335     }
336 
337     aParseParam.pParser = &_rParser;
338 
339     _out_rString = ::rtl::OUString();
340     ::rtl::OUStringBuffer sBuffer;
341     bool bSuccess = false;
342     try
343     {
344         impl_parseNodeToString_throw( sBuffer, aParseParam );
345         bSuccess = true;
346     }
347     catch( const SQLException& e )
348     {
349         if ( _pErrorHolder )
350             *_pErrorHolder = e;
351     }
352     _out_rString = sBuffer.makeStringAndClear();
353     return bSuccess;
354 }
355 
356 //-----------------------------------------------------------------------------
357 namespace
358 {
lcl_isAliasNamePresent(const OSQLParseNode & _rTableNameNode)359     bool lcl_isAliasNamePresent( const OSQLParseNode& _rTableNameNode )
360     {
361         return OSQLParseNode::getTableRange(_rTableNameNode.getParent()).getLength() != 0;
362     }
363 }
364 
365 //-----------------------------------------------------------------------------
impl_parseNodeToString_throw(::rtl::OUStringBuffer & rString,const SQLParseNodeParameter & rParam) const366 void OSQLParseNode::impl_parseNodeToString_throw(::rtl::OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
367 {
368     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::getTableRange" );
369     if ( isToken() )
370     {
371 		parseLeaf(rString,rParam);
372         return;
373     }
374 
375 	// einmal auswerten wieviel Subtrees dieser Knoten besitzt
376 	sal_uInt32 nCount = count();
377 
378     bool bHandled = false;
379     switch ( getKnownRuleID() )
380     {
381     // special handling for parameters
382     case parameter:
383     {
384 		if(rString.getLength())
385 			rString.appendAscii(" ");
386 		if (nCount == 1)	// ?
387 			m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam );
388 		else if (nCount == 2)	// :Name
389 		{
390 			m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam );
391 			rString.append(m_aChildren[1]->m_aNodeValue);
392 		}				    // [Name]
393 		else
394 		{
395 			m_aChildren[0]->impl_parseNodeToString_throw( rString, rParam );
396 			rString.append(m_aChildren[1]->m_aNodeValue);
397 			rString.append(m_aChildren[2]->m_aNodeValue);
398 		}
399         bHandled = true;
400 	}
401     break;
402 
403     // table refs
404     case table_ref:
405         if (  ( nCount == 2 ) || ( nCount == 3 ) || ( nCount == 5 ) )
406         {
407 		    impl_parseTableRangeNodeToString_throw( rString, rParam );
408             bHandled = true;
409         }
410         break;
411 
412     // table name - might be a query name
413     case table_name:
414         bHandled = impl_parseTableNameNodeToString_throw( rString, rParam );
415         break;
416 
417     case as:
418         if ( rParam.aMetaData.generateASBeforeCorrelationName() )
419             rString.append(::rtl::OUString::createFromAscii( " AS" ));
420         bHandled = true;
421         break;
422 
423     case like_predicate:
424 	    // je nachdem ob international angegeben wird oder nicht wird like anders behandelt
425 	    // interanational: *, ? sind Platzhalter
426 	    // sonst SQL92 konform: %, _
427 		impl_parseLikeNodeToString_throw( rString, rParam );
428         bHandled = true;
429         break;
430 
431     case general_set_fct:
432     case set_fct_spec:
433     case position_exp:
434     case extract_exp:
435     case length_exp:
436     case char_value_fct:
437 	{
438 		if (!addDateValue(rString, rParam))
439 		{
440 			// Funktionsname nicht quoten
441 			SQLParseNodeParameter aNewParam(rParam);
442 			aNewParam.bQuote = ( SQL_ISRULE(this,length_exp)	|| SQL_ISRULE(this,char_value_fct) );
443 
444 			m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam );
445 			aNewParam.bQuote = rParam.bQuote;
446 			//aNewParam.bPredicate = sal_False; // disable [ ] around names // look at i73215
447 			::rtl::OUStringBuffer aStringPara;
448 			for (sal_uInt32 i=1; i<nCount; i++)
449 			{
450 				const OSQLParseNode * pSubTree = m_aChildren[i];
451 				if (pSubTree)
452 				{
453 					pSubTree->impl_parseNodeToString_throw( aStringPara, aNewParam );
454 
455 					// bei den CommaListen zwischen alle Subtrees Commas setzen
456 					if ((m_eNodeType == SQL_NODE_COMMALISTRULE) 	&& (i < (nCount - 1)))
457 						aStringPara.appendAscii(",");
458 				}
459                 else
460                     i++;
461 			}
462 			rString.append(aStringPara.makeStringAndClear());
463 		}
464         bHandled = true;
465 	}
466     break;
467     default:
468         break;
469     }   // switch ( getKnownRuleID() )
470 
471     if ( !bHandled )
472 	{
473 		for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
474 			i != m_aChildren.end();)
475 		{
476 			const OSQLParseNode* pSubTree = *i;
477 			if ( !pSubTree )
478             {
479                 ++i;
480                 continue;
481             }
482 
483 			SQLParseNodeParameter aNewParam(rParam);
484 
485 			// don't replace the field for subqueries
486 			if (rParam.xField.is() && SQL_ISRULE(pSubTree,subquery))
487 				aNewParam.xField = NULL;
488 
489 			// if there is a field given we don't display the fieldname, if there is any
490 			if (rParam.xField.is() && SQL_ISRULE(pSubTree,column_ref))
491 			{
492 				sal_Bool bFilter = sal_False;
493 				// retrieve the fields name
494 				::rtl::OUString aFieldName;
495 				try
496 				{
497 					sal_Int32 nNamePropertyId = PROPERTY_ID_NAME;
498 					if ( rParam.xField->getPropertySetInfo()->hasPropertyByName( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_REALNAME ) ) )
499 						nNamePropertyId = PROPERTY_ID_REALNAME;
500 					rParam.xField->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( nNamePropertyId ) ) >>= aFieldName;
501 				}
502 				catch ( Exception& )
503 				{
504 				}
505 
506 				if(pSubTree->count())
507 				{
508 					const OSQLParseNode* pCol = pSubTree->m_aChildren[pSubTree->count()-1];
509 					if	(	(	SQL_ISRULE(pCol,column_val)
510 							&&	pCol->getChild(0)->getTokenValue().equalsIgnoreAsciiCase(aFieldName)
511 							)
512 						||	pCol->getTokenValue().equalsIgnoreAsciiCase(aFieldName)
513 						)
514 						bFilter = sal_True;
515 				}
516 
517 				// ok we found the field, if the following node is the
518 				// comparision operator '=' we filter it as well
519 				if (bFilter)
520 				{
521 					if (SQL_ISRULE(this, comparison_predicate))
522 					{
523 						++i;
524 						if(i != m_aChildren.end())
525 						{
526 							pSubTree = *i;
527 							if (pSubTree && pSubTree->getNodeType() == SQL_NODE_EQUAL)
528 								i++;
529 						}
530 					}
531 					else
532 						i++;
533 				}
534 				else
535 				{
536 					pSubTree->impl_parseNodeToString_throw( rString, aNewParam );
537 					i++;
538 
539 					// bei den CommaListen zwischen alle Subtrees Commas setzen
540 					if ((m_eNodeType == SQL_NODE_COMMALISTRULE) 	&& (i != m_aChildren.end()))
541 						rString.appendAscii(",");
542 				}
543 			}
544 			else
545 			{
546 				pSubTree->impl_parseNodeToString_throw( rString, aNewParam );
547 				i++;
548 
549 				// bei den CommaListen zwischen alle Subtrees Commas setzen
550 				if ((m_eNodeType == SQL_NODE_COMMALISTRULE) 	&& (i != m_aChildren.end()))
551 				{
552 					if (SQL_ISRULE(this,value_exp_commalist) && rParam.bPredicate)
553 						rString.appendAscii(";");
554 					else
555 						rString.appendAscii(",");
556 				}
557 			}
558 		}
559 	}
560 }
561 
562 //-----------------------------------------------------------------------------
impl_parseTableNameNodeToString_throw(::rtl::OUStringBuffer & rString,const SQLParseNodeParameter & rParam) const563 bool OSQLParseNode::impl_parseTableNameNodeToString_throw( ::rtl::OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const
564 {
565     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::impl_parseTableNameNodeToString_throw" );
566     // is the table_name part of a table_ref?
567     OSL_ENSURE( getParent(), "OSQLParseNode::impl_parseTableNameNodeToString_throw: table_name without parent?" );
568     if ( !getParent() || ( getParent()->getKnownRuleID() != table_ref ) )
569         return false;
570 
571     // if it's a query, maybe we need to substitute the SQL statement ...
572     if ( !rParam.bParseToSDBCLevel )
573         return false;
574 
575     if ( !rParam.xQueries.is() )
576         // connection does not support queries in queries, or was no query supplier
577         return false;
578 
579     try
580     {
581         ::rtl::OUString sTableOrQueryName( getChild(0)->getTokenValue() );
582         bool bIsQuery = rParam.xQueries->hasByName( sTableOrQueryName );
583         if ( !bIsQuery )
584             return false;
585 
586         // avoid recursion (e.g. "foo" defined as "SELECT * FROM bar" and "bar" defined as "SELECT * FROM foo".
587         if ( rParam.pSubQueryHistory->find( sTableOrQueryName ) != rParam.pSubQueryHistory->end() )
588         {
589             ::rtl::OUString sMessage( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "cyclic sub queries" ) ) );
590             OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: no parser?" );
591             if ( rParam.pParser )
592             {
593                 const SQLError& rErrors( rParam.pParser->getErrorHelper() );
594                 rErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
595             }
596             else
597             {
598                 SQLError aErrors( ::comphelper::getProcessServiceFactory() );
599                 aErrors.raiseException( sdb::ErrorCondition::PARSER_CYCLIC_SUB_QUERIES );
600             }
601         }
602         rParam.pSubQueryHistory->insert( sTableOrQueryName );
603 
604         Reference< XPropertySet > xQuery( rParam.xQueries->getByName( sTableOrQueryName ), UNO_QUERY_THROW );
605 
606         // substitute the query name with the constituting command
607         ::rtl::OUString sCommand;
608         OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_COMMAND ) ) >>= sCommand );
609 
610         sal_Bool bEscapeProcessing = sal_False;
611         OSL_VERIFY( xQuery->getPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ) ) >>= bEscapeProcessing );
612 
613         // the query we found here might itself be based on another query, so parse it recursively
614         OSL_ENSURE( rParam.pParser, "OSQLParseNode::impl_parseTableNameNodeToString_throw: cannot analyze sub queries without a parser!" );
615         if ( bEscapeProcessing && rParam.pParser )
616         {
617             ::rtl::OUString sError;
618             ::std::auto_ptr< OSQLParseNode > pSubQueryNode( rParam.pParser->parseTree( sError, sCommand, sal_False ) );
619             if ( pSubQueryNode.get() )
620             {
621                 // parse the sub-select to SDBC level, too
622                 ::rtl::OUStringBuffer sSubSelect;
623                 pSubQueryNode->impl_parseNodeToString_throw( sSubSelect, rParam );
624                 if ( sSubSelect.getLength() )
625                     sCommand = sSubSelect.makeStringAndClear();
626             }
627         }
628 
629         rString.appendAscii( " ( " );
630         rString.append(sCommand);
631         rString.appendAscii( " )" );
632 
633         // append the query name as table alias, since it might be referenced in other
634         // parts of the statement - but only if there's no other alias name present
635         if ( !lcl_isAliasNamePresent( *this ) )
636         {
637             rString.appendAscii( " AS " );
638             if ( rParam.bQuote )
639                 rString.append(SetQuotation( sTableOrQueryName,
640                     rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
641         }
642 
643         // don't forget to remove the query name from the history, else multiple inclusions
644         // won't work
645         // #i69227# / 2006-10-10 / frank.schoenheit@sun.com
646         rParam.pSubQueryHistory->erase( sTableOrQueryName );
647 
648         return true;
649     }
650     catch( const SQLException& )
651     {
652         throw;
653     }
654     catch( const Exception& )
655     {
656         DBG_UNHANDLED_EXCEPTION();
657     }
658     return false;
659 }
660 
661 //-----------------------------------------------------------------------------
impl_parseTableRangeNodeToString_throw(::rtl::OUStringBuffer & rString,const SQLParseNodeParameter & rParam) const662 void OSQLParseNode::impl_parseTableRangeNodeToString_throw(::rtl::OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
663 {
664     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::impl_parseTableRangeNodeToString_throw" );
665     OSL_PRECOND(  ( count() == 2 ) || ( count() == 3 ) || ( count() == 5 ) ,"Illegal count");
666 
667 	// rString += ::rtl::OUString::createFromAscii(" ");
668     ::std::for_each(m_aChildren.begin(),m_aChildren.end(),
669         boost::bind( &OSQLParseNode::impl_parseNodeToString_throw, _1, boost::ref( rString ), boost::cref( rParam ) ));
670 }
671 
672 //-----------------------------------------------------------------------------
impl_parseLikeNodeToString_throw(::rtl::OUStringBuffer & rString,const SQLParseNodeParameter & rParam) const673 void OSQLParseNode::impl_parseLikeNodeToString_throw( ::rtl::OUStringBuffer& rString, const SQLParseNodeParameter& rParam ) const
674 {
675     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::impl_parseLikeNodeToString_throw" );
676 	OSL_ENSURE(count() == 2,"count != 2: Prepare for GPF");
677 
678 	const OSQLParseNode* pEscNode = NULL;
679 	const OSQLParseNode* pParaNode = NULL;
680 
681 	SQLParseNodeParameter aNewParam(rParam);
682 	//aNewParam.bQuote = sal_True; // why setting this to true? @see http://www.openoffice.org/issues/show_bug.cgi?id=75557
683 
684 	// if there is a field given we don't display the fieldname, if there are any
685 	sal_Bool bAddName = sal_True;
686 	if (rParam.xField.is())
687 	{
688 		// retrieve the fields name
689 		::rtl::OUString aFieldName;
690 		try
691 		{
692 			// retrieve the fields name
693 			rtl::OUString aString;
694 			rParam.xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aString;
695 			aFieldName = aString.getStr();
696 		}
697 		catch ( Exception& )
698 		{
699 			OSL_ENSURE( false, "OSQLParseNode::impl_parseLikeNodeToString_throw Exception occured!" );
700 		}
701 		if ( !m_aChildren[0]->isLeaf() )
702 		{
703 			const OSQLParseNode* pCol = m_aChildren[0]->getChild(m_aChildren[0]->count()-1);
704 			if ((SQL_ISRULE(pCol,column_val) && pCol->getChild(0)->getTokenValue().equalsIgnoreAsciiCase(aFieldName)) ||
705 				pCol->getTokenValue().equalsIgnoreAsciiCase(aFieldName) )
706 				bAddName = sal_False;
707 		}
708 	}
709 
710 	if (bAddName)
711 		m_aChildren[0]->impl_parseNodeToString_throw( rString, aNewParam );
712 
713     const OSQLParseNode* pPart2 = m_aChildren[1];
714 	pPart2->getChild(0)->impl_parseNodeToString_throw( rString, aNewParam );
715 	pPart2->getChild(1)->impl_parseNodeToString_throw( rString, aNewParam );
716     pParaNode = pPart2->getChild(2);
717 	pEscNode  = pPart2->getChild(3);
718 
719 	if (pParaNode->isToken())
720 	{
721 		::rtl::OUString aStr = ConvertLikeToken(pParaNode, pEscNode, rParam.bInternational);
722 		rString.appendAscii(" ");
723 		rString.append(SetQuotation(aStr,::rtl::OUString::createFromAscii("\'"),::rtl::OUString::createFromAscii("\'\'")));
724 	}
725 	else
726 		pParaNode->impl_parseNodeToString_throw( rString, aNewParam );
727 
728 	pEscNode->impl_parseNodeToString_throw( rString, aNewParam );
729 }
730 
731 
732 // -----------------------------------------------------------------------------
getTableComponents(const OSQLParseNode * _pTableNode,::com::sun::star::uno::Any & _rCatalog,::rtl::OUString & _rSchema,::rtl::OUString & _rTable,const Reference<XDatabaseMetaData> & _xMetaData)733 sal_Bool OSQLParseNode::getTableComponents(const OSQLParseNode* _pTableNode,
734 											::com::sun::star::uno::Any &_rCatalog,
735 											::rtl::OUString &_rSchema,
736 											::rtl::OUString &_rTable,
737                                             const Reference< XDatabaseMetaData >& _xMetaData)
738 {
739     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::getTableComponents" );
740 	OSL_ENSURE(_pTableNode,"Wrong use of getTableComponents! _pTableNode is not allowed to be null!");
741 	if(_pTableNode)
742 	{
743         const sal_Bool bSupportsCatalog = _xMetaData.is() && _xMetaData->supportsCatalogsInDataManipulation();
744         const sal_Bool bSupportsSchema = _xMetaData.is() && _xMetaData->supportsSchemasInDataManipulation();
745 		const OSQLParseNode* pTableNode = _pTableNode;
746 		// clear the parameter given
747 		_rCatalog = Any();
748 		_rSchema = _rTable = ::rtl::OUString();
749 		// see rule catalog_name: in sqlbison.y
750 		if (SQL_ISRULE(pTableNode,catalog_name))
751 		{
752 			OSL_ENSURE(pTableNode->getChild(0) && pTableNode->getChild(0)->isToken(),"Invalid parsenode!");
753 			_rCatalog <<= pTableNode->getChild(0)->getTokenValue();
754 			pTableNode = pTableNode->getChild(2);
755 		}
756 		// check if we have schema_name rule
757 		if(SQL_ISRULE(pTableNode,schema_name))
758 		{
759             if ( bSupportsCatalog && !bSupportsSchema )
760                 _rCatalog <<= pTableNode->getChild(0)->getTokenValue();
761             else
762 			    _rSchema = pTableNode->getChild(0)->getTokenValue();
763 			pTableNode = pTableNode->getChild(2);
764 		}
765 		// check if we have table_name rule
766 		if(SQL_ISRULE(pTableNode,table_name))
767 		{
768 			_rTable = pTableNode->getChild(0)->getTokenValue();
769 		}
770 		else
771 		{
772 			OSL_ENSURE(0,"Error in parse tree!");
773 		}
774 	}
775 	return _rTable.getLength() != 0;
776 }
777 // -----------------------------------------------------------------------------
killThousandSeparator(OSQLParseNode * pLiteral)778 void OSQLParser::killThousandSeparator(OSQLParseNode* pLiteral)
779 {
780     if ( pLiteral )
781 	{
782         if ( s_xLocaleData->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
783 		{
784 		    pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace('.', sal_Unicode());
785 		    // and replace decimal
786 		    pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', '.');
787 		}
788 	    else
789 		    pLiteral->m_aNodeValue = pLiteral->m_aNodeValue.replace(',', sal_Unicode());
790 		}
791 }
792 // -----------------------------------------------------------------------------
convertNode(sal_Int32 nType,OSQLParseNode * & pLiteral)793 OSQLParseNode* OSQLParser::convertNode(sal_Int32 nType,OSQLParseNode*& pLiteral)
794 {
795     if ( !pLiteral )
796         return NULL;
797 
798     OSQLParseNode* pReturn = pLiteral;
799 
800     if ( ( pLiteral->isRule() && !SQL_ISRULE(pLiteral,value_exp) ) || SQL_ISTOKEN(pLiteral,FALSE) || SQL_ISTOKEN(pLiteral,TRUE) )
801     {
802 		switch(nType)
803 		{
804 			case DataType::CHAR:
805 			case DataType::VARCHAR:
806 			case DataType::LONGVARCHAR:
807 			case DataType::CLOB:
808 				if ( !SQL_ISRULE(pReturn,char_value_exp) && !buildStringNodes(pReturn) )
809 					pReturn = NULL;
810 			default:
811 			    break;
812 		}
813 	}
814 	else
815 	{
816 		switch(pLiteral->getNodeType())
817 		{
818         case SQL_NODE_STRING:
819             switch(nType)
820             {
821                 case DataType::CHAR:
822                 case DataType::VARCHAR:
823                 case DataType::LONGVARCHAR:
824 				case DataType::CLOB:
825                     break;
826                 case DataType::DATE:
827                 case DataType::TIME:
828                 case DataType::TIMESTAMP:
829                     if (m_xFormatter.is())
830                     pReturn = buildDate( nType, pReturn);
831                     break;
832                 default:
833                     m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_INVALID_COMPARE);
834                     break;
835             }
836             break;
837         case SQL_NODE_ACCESS_DATE:
838             switch(nType)
839             {
840                 case DataType::DATE:
841                 case DataType::TIME:
842                 case DataType::TIMESTAMP:
843                 if ( m_xFormatter.is() )
844                     pReturn = buildDate( nType, pReturn);
845                     else
846                         m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_INVALID_DATE_COMPARE);
847                     break;
848                 default:
849                     m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_INVALID_COMPARE);
850                     break;
851             }
852             break;
853         case SQL_NODE_INTNUM:
854             switch(nType)
855             {
856                 case DataType::BIT:
857                 case DataType::BOOLEAN:
858                 case DataType::DECIMAL:
859                 case DataType::NUMERIC:
860                 case DataType::TINYINT:
861                 case DataType::SMALLINT:
862                 case DataType::INTEGER:
863                 case DataType::BIGINT:
864                 case DataType::FLOAT:
865                 case DataType::REAL:
866                 case DataType::DOUBLE:
867                     // kill thousand seperators if any
868 					killThousandSeparator(pReturn);
869                     break;
870                 case DataType::CHAR:
871                 case DataType::VARCHAR:
872                 case DataType::LONGVARCHAR:
873 				case DataType::CLOB:
874 					pReturn = buildNode_STR_NUM(pReturn);
875                     break;
876                 default:
877                     m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_INVALID_INT_COMPARE);
878                     break;
879             }
880             break;
881         case SQL_NODE_APPROXNUM:
882             switch(nType)
883             {
884                 case DataType::DECIMAL:
885                 case DataType::NUMERIC:
886                 case DataType::FLOAT:
887                 case DataType::REAL:
888                 case DataType::DOUBLE:
889                         // kill thousand seperators if any
890 					killThousandSeparator(pReturn);
891                     break;
892                 case DataType::CHAR:
893                 case DataType::VARCHAR:
894                 case DataType::LONGVARCHAR:
895 				case DataType::CLOB:
896 					pReturn = buildNode_STR_NUM(pReturn);
897                     break;
898                 case DataType::INTEGER:
899                 default:
900                     m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_INVALID_REAL_COMPARE);
901                     break;
902             }
903             break;
904         default:
905             ;
906 		}
907 	}
908     return pReturn;
909 }
910 // -----------------------------------------------------------------------------
buildPredicateRule(OSQLParseNode * & pAppend,OSQLParseNode * pLiteral,OSQLParseNode * & pCompare,OSQLParseNode * pLiteral2)911 sal_Int16 OSQLParser::buildPredicateRule(OSQLParseNode*& pAppend,OSQLParseNode* pLiteral,OSQLParseNode*& pCompare,OSQLParseNode* pLiteral2)
912 {
913     OSL_ENSURE(inPredicateCheck(),"Only in predicate check allowed!");
914 	sal_Int16 nErg = 0;
915 	if ( m_xField.is() )
916 	{
917         sal_Int32 nType = 0;
918 	    try
919 	    {
920 		    m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
921 	    }
922 	    catch( Exception& )
923 	    {
924 		    return nErg;
925 		}
926 
927         OSQLParseNode* pNode1 = convertNode(nType,pLiteral);
928         if ( pNode1 )
929         {
930             OSQLParseNode* pNode2 = convertNode(nType,pLiteral2);
931             if ( !m_sErrorMessage.getLength() )
932                 nErg = buildNode(pAppend,pCompare,pNode1,pNode2);
933 		}
934 	}
935 	if (!pCompare->getParent()) // I have no parent so I was not used and I must die :-)
936 		delete pCompare;
937 	return nErg;
938 }
939 // -----------------------------------------------------------------------------
buildLikeRule(OSQLParseNode * & pAppend,OSQLParseNode * & pLiteral,const OSQLParseNode * pEscape)940 sal_Int16 OSQLParser::buildLikeRule(OSQLParseNode*& pAppend, OSQLParseNode*& pLiteral, const OSQLParseNode* pEscape)
941 {
942 	sal_Int16 nErg = 0;
943 	sal_Int32 nType = 0;
944 
945 	if (!m_xField.is())
946 		return nErg;
947 	try
948 	{
949 		Any aValue;
950 		{
951 			aValue = m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE));
952 			aValue >>= nType;
953 		}
954 	}
955 	catch( Exception& )
956 	{
957 		return nErg;
958 	}
959 
960 	switch (nType)
961 	{
962 		case DataType::CHAR:
963 		case DataType::VARCHAR:
964 		case DataType::LONGVARCHAR:
965 		case DataType::CLOB:
966 			if(pLiteral->isRule())
967 			{
968 				pAppend->append(pLiteral);
969 				nErg = 1;
970 			}
971 			else
972 			{
973 				switch(pLiteral->getNodeType())
974 				{
975 					case SQL_NODE_STRING:
976 						pLiteral->m_aNodeValue = ConvertLikeToken(pLiteral, pEscape, sal_False);
977 						pAppend->append(pLiteral);
978 						nErg = 1;
979 						break;
980 					case SQL_NODE_APPROXNUM:
981 						if (m_xFormatter.is() && m_nFormatKey)
982 						{
983 							sal_Int16 nScale = 0;
984 							try
985 							{
986 								Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, ::rtl::OUString::createFromAscii("Decimals") );
987 								aValue >>= nScale;
988 							}
989 							catch( Exception& )
990 							{
991 							}
992 
993 							pAppend->append(new OSQLInternalNode(stringToDouble(pLiteral->getTokenValue(),nScale),SQL_NODE_STRING));
994 						}
995 						else
996 							pAppend->append(new OSQLInternalNode(pLiteral->getTokenValue(),SQL_NODE_STRING));
997 
998 						delete pLiteral;
999 						nErg = 1;
1000 						break;
1001 					default:
1002 						m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_VALUE_NO_LIKE);
1003 						m_sErrorMessage = m_sErrorMessage.replaceAt(m_sErrorMessage.indexOf(::rtl::OUString::createFromAscii("#1")),2,pLiteral->getTokenValue());
1004                         break;
1005 				}
1006 			}
1007 			break;
1008 		default:
1009 			m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_FIELD_NO_LIKE);
1010             break;
1011 	}
1012 	return nErg;
1013 }
1014 //-----------------------------------------------------------------------------
buildNode_Date(const double & fValue,sal_Int32 nType)1015 OSQLParseNode* OSQLParser::buildNode_Date(const double& fValue, sal_Int32 nType)
1016 {
1017     ::rtl::OUString aEmptyString;
1018     OSQLParseNode* pNewNode = new OSQLInternalNode(aEmptyString, SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::set_fct_spec));
1019 	pNewNode->append(new OSQLInternalNode(::rtl::OUString::createFromAscii("{"), SQL_NODE_PUNCTUATION));
1020 	OSQLParseNode* pDateNode = new OSQLInternalNode(aEmptyString, SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::odbc_fct_spec));
1021 	pNewNode->append(pDateNode);
1022 	pNewNode->append(new OSQLInternalNode(::rtl::OUString::createFromAscii("}"), SQL_NODE_PUNCTUATION));
1023 
1024 	switch (nType)
1025 	{
1026 		case DataType::DATE:
1027 		{
1028 			Date aDate = DBTypeConversion::toDate(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1029 			::rtl::OUString aString = DBTypeConversion::toDateString(aDate);
1030 			pDateNode->append(new OSQLInternalNode(aEmptyString, SQL_NODE_KEYWORD, SQL_TOKEN_D));
1031 			pDateNode->append(new OSQLInternalNode(aString, SQL_NODE_STRING));
1032 			break;
1033 		}
1034 		case DataType::TIME:
1035 		{
1036 			Time aTime = DBTypeConversion::toTime(fValue);
1037 			::rtl::OUString aString = DBTypeConversion::toTimeString(aTime);
1038 			pDateNode->append(new OSQLInternalNode(aEmptyString, SQL_NODE_KEYWORD, SQL_TOKEN_T));
1039 			pDateNode->append(new OSQLInternalNode(aString, SQL_NODE_STRING));
1040 			break;
1041 		}
1042 		case DataType::TIMESTAMP:
1043 		{
1044 			DateTime aDateTime = DBTypeConversion::toDateTime(fValue,DBTypeConversion::getNULLDate(m_xFormatter->getNumberFormatsSupplier()));
1045 			if (aDateTime.Seconds || aDateTime.Minutes || aDateTime.Hours)
1046 			{
1047 				::rtl::OUString aString = DBTypeConversion::toDateTimeString(aDateTime);
1048 				pDateNode->append(new OSQLInternalNode(aEmptyString, SQL_NODE_KEYWORD, SQL_TOKEN_TS));
1049 				pDateNode->append(new OSQLInternalNode(aString, SQL_NODE_STRING));
1050 			}
1051 			else
1052 			{
1053 				Date aDate(aDateTime.Day,aDateTime.Month,aDateTime.Year);
1054 				pDateNode->append(new OSQLInternalNode(aEmptyString, SQL_NODE_KEYWORD, SQL_TOKEN_D));
1055 				pDateNode->append(new OSQLInternalNode(DBTypeConversion::toDateString(aDate), SQL_NODE_STRING));
1056 			}
1057 			break;
1058 		}
1059 	}
1060 
1061 	return pNewNode;
1062 }
1063 // -----------------------------------------------------------------------------
buildNode_STR_NUM(OSQLParseNode * & _pLiteral)1064 OSQLParseNode* OSQLParser::buildNode_STR_NUM(OSQLParseNode*& _pLiteral)
1065 {
1066 	OSQLParseNode* pReturn = NULL;
1067     if ( _pLiteral )
1068     {
1069 	    if (m_nFormatKey)
1070 	    {
1071 		    sal_Int16 nScale = 0;
1072 		    ::rtl::OUString aDec;
1073 		    try
1074 		    {
1075                 Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Decimals")) );
1076 			    aValue >>= nScale;
1077 		    }
1078 		    catch( Exception& )
1079 		    {
1080 		    }
1081 
1082             pReturn = new OSQLInternalNode(stringToDouble(_pLiteral->getTokenValue(),nScale),SQL_NODE_STRING);
1083 	    }
1084 	    else
1085             pReturn = new OSQLInternalNode(_pLiteral->getTokenValue(),SQL_NODE_STRING);
1086 
1087         delete _pLiteral;
1088         _pLiteral = NULL;
1089     }
1090     return pReturn;
1091 }
1092 // -----------------------------------------------------------------------------
stringToDouble(const::rtl::OUString & _rValue,sal_Int16 _nScale)1093 ::rtl::OUString OSQLParser::stringToDouble(const ::rtl::OUString& _rValue,sal_Int16 _nScale)
1094 {
1095 	::rtl::OUString aValue;
1096 	if(!m_xCharClass.is())
1097 		m_xCharClass  = Reference<XCharacterClassification>(m_xServiceFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.i18n.CharacterClassification")),UNO_QUERY);
1098 	if(m_xCharClass.is() && s_xLocaleData.is())
1099 	{
1100 		try
1101 		{
1102 			ParseResult aResult = m_xCharClass->parsePredefinedToken(KParseType::ANY_NUMBER,_rValue,0,m_pData->aLocale,0,::rtl::OUString(),KParseType::ANY_NUMBER,::rtl::OUString());
1103 			if((aResult.TokenType & KParseType::IDENTNAME) && aResult.EndPos == _rValue.getLength())
1104 			{
1105 				aValue = ::rtl::OUString::valueOf(aResult.Value);
1106 				sal_Int32 nPos = aValue.lastIndexOf(::rtl::OUString::createFromAscii("."));
1107 				if((nPos+_nScale) < aValue.getLength())
1108 					aValue = aValue.replaceAt(nPos+_nScale,aValue.getLength()-nPos-_nScale,::rtl::OUString());
1109 				aValue = aValue.replaceAt(aValue.lastIndexOf(::rtl::OUString::createFromAscii(".")),1,s_xLocaleData->getLocaleItem(m_pData->aLocale).decimalSeparator);
1110 				return aValue;
1111 			}
1112 		}
1113 		catch(Exception&)
1114 		{
1115 		}
1116 	}
1117 	return aValue;
1118 }
1119 // -----------------------------------------------------------------------------
1120 
getMutex()1121 ::osl::Mutex& OSQLParser::getMutex()
1122 {
1123 	static ::osl::Mutex aMutex;
1124 	return aMutex;
1125 }
1126 
1127 //-----------------------------------------------------------------------------
predicateTree(::rtl::OUString & rErrorMessage,const::rtl::OUString & rStatement,const Reference<::com::sun::star::util::XNumberFormatter> & xFormatter,const Reference<XPropertySet> & xField)1128 OSQLParseNode* OSQLParser::predicateTree(::rtl::OUString& rErrorMessage, const ::rtl::OUString& rStatement,
1129  										 const Reference< ::com::sun::star::util::XNumberFormatter > & xFormatter,
1130 										 const Reference< XPropertySet > & xField)
1131 {
1132 
1133 
1134 	// mutex for parsing
1135 	static ::osl::Mutex aMutex;
1136 
1137 	// Guard the parsing
1138 	::osl::MutexGuard aGuard(getMutex());
1139 	// must be reset
1140 	setParser(this);
1141 
1142 
1143 	// reset the parser
1144 	m_xField		= xField;
1145 	m_xFormatter	= xFormatter;
1146 
1147 	if (m_xField.is())
1148 	{
1149 		sal_Int32 nType=0;
1150 		try
1151 		{
1152 			// get the field name
1153 			rtl::OUString aString;
1154 
1155 			// retrieve the fields name
1156 			// #75243# use the RealName of the column if there is any otherwise the name which could be the alias
1157 			// of the field
1158             Reference< XPropertySetInfo> xInfo = m_xField->getPropertySetInfo();
1159 			if ( xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)))
1160 				m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME)) >>= aString;
1161 			else
1162 				m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aString;
1163 
1164 			m_sFieldName = aString;
1165 
1166 			// get the field format key
1167 			if ( xInfo->hasPropertyByName(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)))
1168 				m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) >>= m_nFormatKey;
1169 			else
1170 				m_nFormatKey = 0;
1171 
1172 			// get the field type
1173 			m_xField->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
1174 		}
1175 		catch ( Exception& )
1176 		{
1177 			OSL_ASSERT(0);
1178 		}
1179 
1180 		if (m_nFormatKey && m_xFormatter.is())
1181 		{
1182 			Any aValue = getNumberFormatProperty( m_xFormatter, m_nFormatKey, OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_LOCALE) );
1183 			OSL_ENSURE(aValue.getValueType() == ::getCppuType((const ::com::sun::star::lang::Locale*)0), "OSQLParser::PredicateTree : invalid language property !");
1184 
1185 			if (aValue.getValueType() == ::getCppuType((const ::com::sun::star::lang::Locale*)0))
1186 				aValue >>= m_pData->aLocale;
1187 		}
1188 		else
1189 			m_pData->aLocale = m_pContext->getPreferredLocale();
1190 
1191 		if ( m_xFormatter.is() )
1192 		{
1193 			try
1194 			{
1195 				Reference< ::com::sun::star::util::XNumberFormatsSupplier >  xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1196 				if ( xFormatSup.is() )
1197 				{
1198 					Reference< ::com::sun::star::util::XNumberFormats >  xFormats = xFormatSup->getNumberFormats();
1199 					if ( xFormats.is() )
1200 					{
1201 						::com::sun::star::lang::Locale aLocale;
1202 						aLocale.Language = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en"));
1203 						aLocale.Country = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("US"));
1204 						::rtl::OUString sFormat(RTL_CONSTASCII_USTRINGPARAM("YYYY-MM-DD"));
1205 						m_nDateFormatKey = xFormats->queryKey(sFormat,aLocale,sal_False);
1206 						if ( m_nDateFormatKey == sal_Int32(-1) )
1207 							m_nDateFormatKey = xFormats->addNew(sFormat, aLocale);
1208 					}
1209 				}
1210 			}
1211 			catch ( Exception& )
1212 			{
1213 				OSL_ENSURE(0,"DateFormatKey");
1214 			}
1215 		}
1216 
1217 		switch (nType)
1218 		{
1219 			case DataType::DATE:
1220 			case DataType::TIME:
1221 			case DataType::TIMESTAMP:
1222 				s_pScanner->SetRule(s_pScanner->GetDATERule());
1223 				break;
1224 			case DataType::CHAR:
1225 			case DataType::VARCHAR:
1226 			case DataType::LONGVARCHAR:
1227 			case DataType::CLOB:
1228 				s_pScanner->SetRule(s_pScanner->GetSTRINGRule());
1229 				break;
1230 			default:
1231 				if ( s_xLocaleData->getLocaleItem( m_pData->aLocale ).decimalSeparator.toChar() == ',' )
1232 					s_pScanner->SetRule(s_pScanner->GetGERRule());
1233 				else
1234 					s_pScanner->SetRule(s_pScanner->GetENGRule());
1235 		}
1236 
1237 	}
1238 	else
1239 		s_pScanner->SetRule(s_pScanner->GetSQLRule());
1240 
1241 	s_pScanner->prepareScan(rStatement, m_pContext, sal_True);
1242 
1243 	SQLyylval.pParseNode = NULL;
1244 	//	SQLyypvt = NULL;
1245 	m_pParseTree = NULL;
1246 	m_sErrorMessage= ::rtl::OUString();
1247 
1248 	// ... und den Parser anwerfen ...
1249 	if (SQLyyparse() != 0)
1250 	{
1251 		m_sFieldName= ::rtl::OUString();
1252 	m_xField.clear();
1253 	m_xFormatter.clear();
1254 		m_nFormatKey = 0;
1255 		m_nDateFormatKey = 0;
1256 
1257 		if (!m_sErrorMessage.getLength())
1258 			m_sErrorMessage = s_pScanner->getErrorMessage();
1259 		if (!m_sErrorMessage.getLength())
1260 			m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_GENERAL);
1261 
1262 		rErrorMessage = m_sErrorMessage;
1263 
1264 		// clear the garbage collector
1265         (*s_pGarbageCollector)->clearAndDelete();
1266 		return NULL;
1267 	}
1268 	else
1269 	{
1270 		(*s_pGarbageCollector)->clear();
1271 
1272 		m_sFieldName= ::rtl::OUString();
1273 	m_xField.clear();
1274 	m_xFormatter.clear();
1275 		m_nFormatKey = 0;
1276 		m_nDateFormatKey = 0;
1277 
1278 		// Das Ergebnis liefern (den Root Parse Node):
1279 
1280 		// Stattdessen setzt die Parse-Routine jetzt den Member pParseTree
1281 		// - einfach diesen zurueckliefern:
1282 		OSL_ENSURE(m_pParseTree != NULL,"OSQLParser: Parser hat keinen ParseTree geliefert");
1283 		return m_pParseTree;
1284 	}
1285 }
1286 
1287 //=============================================================================
1288 //-----------------------------------------------------------------------------
OSQLParser(const::com::sun::star::uno::Reference<::com::sun::star::lang::XMultiServiceFactory> & _xServiceFactory,const IParseContext * _pContext)1289 OSQLParser::OSQLParser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xServiceFactory,const IParseContext* _pContext)
1290 	:m_pContext(_pContext)
1291 	,m_pParseTree(NULL)
1292 	,m_pData( new OSQLParser_Data( _xServiceFactory ) )
1293 	,m_nFormatKey(0)
1294 	,m_nDateFormatKey(0)
1295 	,m_xServiceFactory(_xServiceFactory)
1296 {
1297 
1298 
1299 	setParser(this);
1300 
1301 #ifdef SQLYYDEBUG
1302 #ifdef SQLYYDEBUG_ON
1303 	SQLyydebug = 1;
1304 #endif
1305 #endif
1306 
1307 	::osl::MutexGuard aGuard(getMutex());
1308 	// do we have to initialize the data
1309 	if (s_nRefCount == 0)
1310 	{
1311 		s_pScanner = new OSQLScanner();
1312 		s_pScanner->setScanner();
1313 		s_pGarbageCollector = new OSQLParseNodesGarbageCollector();
1314 
1315 		if(!s_xLocaleData.is())
1316 			s_xLocaleData = Reference<XLocaleData>(m_xServiceFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.i18n.LocaleData")),UNO_QUERY);
1317 
1318 		// auf 0 zuruecksetzen
1319 		memset(OSQLParser::s_nRuleIDs,0,sizeof(OSQLParser::s_nRuleIDs[0]) * (OSQLParseNode::rule_count+1));
1320 
1321         struct
1322         {
1323             OSQLParseNode::Rule eRule;      // the parse node's ID for the rule
1324             ::rtl::OString      sRuleName;  // the name of the rule ("select_statement")
1325         }   aRuleDescriptions[] =
1326         {
1327             { OSQLParseNode::select_statement, "select_statement" },
1328             { OSQLParseNode::table_exp, "table_exp" },
1329             { OSQLParseNode::table_ref_commalist, "table_ref_commalist" },
1330             { OSQLParseNode::table_ref, "table_ref" },
1331             { OSQLParseNode::catalog_name, "catalog_name" },
1332             { OSQLParseNode::schema_name, "schema_name" },
1333             { OSQLParseNode::table_name, "table_name" },
1334             { OSQLParseNode::opt_column_commalist, "opt_column_commalist" },
1335             { OSQLParseNode::column_commalist, "column_commalist" },
1336             { OSQLParseNode::column_ref_commalist, "column_ref_commalist" },
1337             { OSQLParseNode::column_ref, "column_ref" },
1338             { OSQLParseNode::opt_order_by_clause, "opt_order_by_clause" },
1339             { OSQLParseNode::ordering_spec_commalist, "ordering_spec_commalist" },
1340             { OSQLParseNode::ordering_spec, "ordering_spec" },
1341             { OSQLParseNode::opt_asc_desc, "opt_asc_desc" },
1342             { OSQLParseNode::where_clause, "where_clause" },
1343             { OSQLParseNode::opt_where_clause, "opt_where_clause" },
1344             { OSQLParseNode::search_condition, "search_condition" },
1345             { OSQLParseNode::comparison_predicate, "comparison_predicate" },
1346             { OSQLParseNode::between_predicate, "between_predicate" },
1347             { OSQLParseNode::like_predicate, "like_predicate" },
1348             { OSQLParseNode::opt_escape, "opt_escape" },
1349             { OSQLParseNode::test_for_null, "test_for_null" },
1350             { OSQLParseNode::scalar_exp_commalist, "scalar_exp_commalist" },
1351             { OSQLParseNode::scalar_exp, "scalar_exp" },
1352             { OSQLParseNode::parameter_ref, "parameter_ref" },
1353             { OSQLParseNode::parameter, "parameter" },
1354             { OSQLParseNode::general_set_fct, "general_set_fct" },
1355             { OSQLParseNode::range_variable, "range_variable" },
1356             { OSQLParseNode::column, "column" },
1357             { OSQLParseNode::delete_statement_positioned, "delete_statement_positioned" },
1358             { OSQLParseNode::delete_statement_searched, "delete_statement_searched" },
1359             { OSQLParseNode::update_statement_positioned, "update_statement_positioned" },
1360             { OSQLParseNode::update_statement_searched, "update_statement_searched" },
1361             { OSQLParseNode::assignment_commalist, "assignment_commalist" },
1362             { OSQLParseNode::assignment, "assignment" },
1363             { OSQLParseNode::values_or_query_spec, "values_or_query_spec" },
1364             { OSQLParseNode::insert_statement, "insert_statement" },
1365             { OSQLParseNode::insert_atom_commalist, "insert_atom_commalist" },
1366             { OSQLParseNode::insert_atom, "insert_atom" },
1367             { OSQLParseNode::predicate_check, "predicate_check" },
1368             { OSQLParseNode::from_clause, "from_clause" },
1369             { OSQLParseNode::qualified_join, "qualified_join" },
1370             { OSQLParseNode::cross_union, "cross_union" },
1371             { OSQLParseNode::select_sublist, "select_sublist" },
1372             { OSQLParseNode::derived_column, "derived_column" },
1373             { OSQLParseNode::column_val, "column_val" },
1374             { OSQLParseNode::set_fct_spec, "set_fct_spec" },
1375             { OSQLParseNode::boolean_term, "boolean_term" },
1376             { OSQLParseNode::boolean_primary, "boolean_primary" },
1377             { OSQLParseNode::num_value_exp, "num_value_exp" },
1378             { OSQLParseNode::join_type, "join_type" },
1379             { OSQLParseNode::position_exp, "position_exp" },
1380             { OSQLParseNode::extract_exp, "extract_exp" },
1381             { OSQLParseNode::length_exp, "length_exp" },
1382             { OSQLParseNode::char_value_fct, "char_value_fct" },
1383             { OSQLParseNode::odbc_call_spec, "odbc_call_spec" },
1384             { OSQLParseNode::in_predicate, "in_predicate" },
1385             { OSQLParseNode::existence_test, "existence_test" },
1386             { OSQLParseNode::unique_test, "unique_test" },
1387             { OSQLParseNode::all_or_any_predicate, "all_or_any_predicate" },
1388             { OSQLParseNode::named_columns_join, "named_columns_join" },
1389             { OSQLParseNode::join_condition, "join_condition" },
1390             { OSQLParseNode::joined_table, "joined_table" },
1391             { OSQLParseNode::boolean_factor, "boolean_factor" },
1392             { OSQLParseNode::sql_not, "sql_not" },
1393             { OSQLParseNode::boolean_test, "boolean_test" },
1394             { OSQLParseNode::manipulative_statement, "manipulative_statement" },
1395             { OSQLParseNode::subquery, "subquery" },
1396             { OSQLParseNode::value_exp_commalist, "value_exp_commalist" },
1397             { OSQLParseNode::odbc_fct_spec, "odbc_fct_spec" },
1398             { OSQLParseNode::union_statement, "union_statement" },
1399             { OSQLParseNode::outer_join_type, "outer_join_type" },
1400             { OSQLParseNode::char_value_exp, "char_value_exp" },
1401             { OSQLParseNode::term, "term" },
1402             { OSQLParseNode::value_exp_primary, "value_exp_primary" },
1403             { OSQLParseNode::value_exp, "value_exp" },
1404             { OSQLParseNode::selection, "selection" },
1405             { OSQLParseNode::fold, "fold" },
1406             { OSQLParseNode::char_substring_fct, "char_substring_fct" },
1407             { OSQLParseNode::factor, "factor" },
1408             { OSQLParseNode::base_table_def, "base_table_def" },
1409             { OSQLParseNode::base_table_element_commalist, "base_table_element_commalist" },
1410             { OSQLParseNode::data_type, "data_type" },
1411             { OSQLParseNode::column_def, "column_def" },
1412             { OSQLParseNode::table_node, "table_node" },
1413             { OSQLParseNode::as, "as" },
1414             { OSQLParseNode::op_column_commalist, "op_column_commalist" },
1415             { OSQLParseNode::table_primary_as_range_column, "table_primary_as_range_column" },
1416             { OSQLParseNode::datetime_primary, "datetime_primary" },
1417             { OSQLParseNode::concatenation, "concatenation" },
1418             { OSQLParseNode::char_factor, "char_factor" },
1419             { OSQLParseNode::bit_value_fct, "bit_value_fct" },
1420             { OSQLParseNode::comparison_predicate_part_2, "comparison_predicate_part_2" },
1421             { OSQLParseNode::parenthesized_boolean_value_expression, "parenthesized_boolean_value_expression" },
1422             { OSQLParseNode::character_string_type, "character_string_type" },
1423             { OSQLParseNode::other_like_predicate_part_2, "other_like_predicate_part_2" },
1424             { OSQLParseNode::between_predicate_part_2, "between_predicate_part_2" },
1425             { OSQLParseNode::cast_spec, "cast_spec" }
1426         };
1427         size_t nRuleMapCount = sizeof( aRuleDescriptions ) / sizeof( aRuleDescriptions[0] );
1428         OSL_ENSURE( nRuleMapCount == size_t( OSQLParseNode::rule_count ), "OSQLParser::OSQLParser: added a new rule? Adjust this map!" );
1429 
1430         for ( size_t mapEntry = 0; mapEntry < nRuleMapCount; ++mapEntry )
1431         {
1432             // look up the rule description in the our identifier map
1433             sal_uInt32 nParserRuleID = StrToRuleID( aRuleDescriptions[ mapEntry ].sRuleName );
1434             // map the parser's rule ID to the OSQLParseNode::Rule
1435             s_aReverseRuleIDLookup[ nParserRuleID ] = aRuleDescriptions[ mapEntry ].eRule;
1436             // and map the OSQLParseNode::Rule to the parser's rule ID
1437             s_nRuleIDs[ aRuleDescriptions[ mapEntry ].eRule ] = nParserRuleID;
1438         }
1439 	}
1440 	++s_nRefCount;
1441 
1442 	if (m_pContext == NULL)
1443 		// take the default context
1444 		m_pContext = &s_aDefaultContext;
1445 
1446     m_pData->aLocale = m_pContext->getPreferredLocale();
1447 }
1448 
1449 //-----------------------------------------------------------------------------
~OSQLParser()1450 OSQLParser::~OSQLParser()
1451 {
1452 	{
1453 		::osl::MutexGuard aGuard(getMutex());
1454 		OSL_ENSURE(s_nRefCount > 0, "OSQLParser::~OSQLParser() : suspicious call : have a refcount of 0 !");
1455 		if (!--s_nRefCount)
1456 		{
1457 			s_pScanner->setScanner(sal_True);
1458 			delete s_pScanner;
1459 			s_pScanner = NULL;
1460 
1461 			delete s_pGarbageCollector;
1462 			s_pGarbageCollector = NULL;
1463 			// is only set the first time so we should delete it only when there no more instances
1464 			s_xLocaleData = NULL;
1465 
1466             RuleIDMap aEmpty;
1467             s_aReverseRuleIDLookup.swap( aEmpty );
1468 		}
1469 		m_pParseTree = NULL;
1470 	}
1471 }
1472 // -----------------------------------------------------------------------------
substituteParameterNames(OSQLParseNode * _pNode)1473 void OSQLParseNode::substituteParameterNames(OSQLParseNode* _pNode)
1474 {
1475     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::substituteParameterNames" );
1476 	sal_Int32 nCount = _pNode->count();
1477 	for(sal_Int32 i=0;i < nCount;++i)
1478 	{
1479 		OSQLParseNode* pChildNode = _pNode->getChild(i);
1480 		if(SQL_ISRULE(pChildNode,parameter) && pChildNode->count() > 1)
1481 		{
1482 			OSQLParseNode* pNewNode = new OSQLParseNode(::rtl::OUString::createFromAscii("?") ,SQL_NODE_PUNCTUATION,0);
1483 			delete pChildNode->replace(pChildNode->getChild(0),pNewNode);
1484 			sal_Int32 nChildCount = pChildNode->count();
1485 			for(sal_Int32 j=1;j < nChildCount;++j)
1486 				delete pChildNode->removeAt(1);
1487 		}
1488 		else
1489 			substituteParameterNames(pChildNode);
1490 
1491 	}
1492 }
1493 // -----------------------------------------------------------------------------
extractDate(OSQLParseNode * pLiteral,double & _rfValue)1494 bool OSQLParser::extractDate(OSQLParseNode* pLiteral,double& _rfValue)
1495 {
1496     Reference< XNumberFormatsSupplier > xFormatSup = m_xFormatter->getNumberFormatsSupplier();
1497 	Reference< XNumberFormatTypes > xFormatTypes;
1498     if ( xFormatSup.is() )
1499         xFormatTypes = xFormatTypes.query( xFormatSup->getNumberFormats() );
1500 
1501     // if there is no format key, yet, make sure we have a feasible one for our locale
1502 	try
1503 	{
1504 		if ( !m_nFormatKey && xFormatTypes.is() )
1505 			m_nFormatKey = ::dbtools::getDefaultNumberFormat( m_xField, xFormatTypes, m_pData->aLocale );
1506     }
1507     catch( Exception& ) { }
1508     ::rtl::OUString sValue = pLiteral->getTokenValue();
1509     sal_Int32 nTryFormat = m_nFormatKey;
1510     bool bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1511 
1512     // If our format key didn't do, try the default date format for our locale.
1513     if ( !bSuccess && xFormatTypes.is() )
1514     {
1515 		try
1516 		{
1517             nTryFormat = xFormatTypes->getStandardFormat( NumberFormat::DATE, m_pData->aLocale );
1518 		}
1519         catch( Exception& ) { }
1520         bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1521     }
1522 
1523     // if this also didn't do, try ISO format
1524     if ( !bSuccess && xFormatTypes.is() )
1525     {
1526 		try
1527 		{
1528             nTryFormat = xFormatTypes->getFormatIndex( NumberFormatIndex::DATE_DIN_YYYYMMDD, m_pData->aLocale );
1529 		}
1530         catch( Exception& ) { }
1531         bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1532     }
1533 
1534     // if this also didn't do, try fallback date format (en-US)
1535     if ( !bSuccess )
1536     {
1537         nTryFormat = m_nDateFormatKey;
1538         bSuccess = lcl_saveConvertToNumber( m_xFormatter, nTryFormat, sValue, _rfValue );
1539     }
1540     return bSuccess;
1541 }
1542 // -----------------------------------------------------------------------------
buildDate(sal_Int32 _nType,OSQLParseNode * & pLiteral)1543 OSQLParseNode* OSQLParser::buildDate(sal_Int32 _nType,OSQLParseNode*& pLiteral)
1544 {
1545     // try converting the string into a date, according to our format key
1546 	double fValue = 0.0;
1547     OSQLParseNode* pFCTNode = NULL;
1548 
1549     if ( extractDate(pLiteral,fValue) )
1550 		pFCTNode = buildNode_Date( fValue, _nType);
1551 
1552     delete pLiteral;
1553     pLiteral = NULL;
1554 
1555     if ( !pFCTNode )
1556 		m_sErrorMessage = m_pContext->getErrorMessage(IParseContext::ERROR_INVALID_DATE_COMPARE);
1557 
1558     return pFCTNode;
1559 }
1560 // -----------------------------------------------------------------------------
1561 //-----------------------------------------------------------------------------
OSQLParseNode(const sal_Char * pNewValue,SQLNodeType eNewNodeType,sal_uInt32 nNewNodeID)1562 OSQLParseNode::OSQLParseNode(const sal_Char * pNewValue,
1563                              SQLNodeType eNewNodeType,
1564                              sal_uInt32 nNewNodeID)
1565         :m_pParent(NULL)
1566         ,m_aNodeValue(pNewValue,strlen(pNewValue),RTL_TEXTENCODING_UTF8)
1567         ,m_eNodeType(eNewNodeType)
1568         ,m_nNodeID(nNewNodeID)
1569 {
1570     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::OSQLParseNode" );
1571 
1572     OSL_ENSURE(m_eNodeType >= SQL_NODE_RULE && m_eNodeType <= SQL_NODE_CONCAT,"OSQLParseNode: mit unzulaessigem NodeType konstruiert");
1573 }
1574 //-----------------------------------------------------------------------------
OSQLParseNode(const::rtl::OString & _rNewValue,SQLNodeType eNewNodeType,sal_uInt32 nNewNodeID)1575 OSQLParseNode::OSQLParseNode(const ::rtl::OString &_rNewValue,
1576                              SQLNodeType eNewNodeType,
1577                              sal_uInt32 nNewNodeID)
1578         :m_pParent(NULL)
1579         ,m_aNodeValue( rtl::OStringToOUString( _rNewValue, RTL_TEXTENCODING_UTF8))
1580         ,m_eNodeType(eNewNodeType)
1581         ,m_nNodeID(nNewNodeID)
1582 {
1583     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::OSQLParseNode" );
1584 
1585     OSL_ENSURE(m_eNodeType >= SQL_NODE_RULE && m_eNodeType <= SQL_NODE_CONCAT,"OSQLParseNode: mit unzulaessigem NodeType konstruiert");
1586 }
1587 //-----------------------------------------------------------------------------
OSQLParseNode(const sal_Unicode * pNewValue,SQLNodeType eNewNodeType,sal_uInt32 nNewNodeID)1588 OSQLParseNode::OSQLParseNode(const sal_Unicode * pNewValue,
1589                                  SQLNodeType eNewNodeType,
1590                                  sal_uInt32 nNewNodeID)
1591         :m_pParent(NULL)
1592         ,m_aNodeValue(pNewValue)
1593         ,m_eNodeType(eNewNodeType)
1594         ,m_nNodeID(nNewNodeID)
1595 {
1596     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::OSQLParseNode" );
1597 
1598     OSL_ENSURE(m_eNodeType >= SQL_NODE_RULE && m_eNodeType <= SQL_NODE_CONCAT,"OSQLParseNode: mit unzulaessigem NodeType konstruiert");
1599 }
1600 //-----------------------------------------------------------------------------
OSQLParseNode(const::rtl::OUString & _rNewValue,SQLNodeType eNewNodeType,sal_uInt32 nNewNodeID)1601 OSQLParseNode::OSQLParseNode(const ::rtl::OUString &_rNewValue,
1602                                  SQLNodeType eNewNodeType,
1603                                  sal_uInt32 nNewNodeID)
1604         :m_pParent(NULL)
1605         ,m_aNodeValue(_rNewValue)
1606         ,m_eNodeType(eNewNodeType)
1607         ,m_nNodeID(nNewNodeID)
1608 {
1609     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::OSQLParseNode" );
1610 
1611     OSL_ENSURE(m_eNodeType >= SQL_NODE_RULE && m_eNodeType <= SQL_NODE_CONCAT,"OSQLParseNode: mit unzulaessigem NodeType konstruiert");
1612 }
1613 //-----------------------------------------------------------------------------
OSQLParseNode(const OSQLParseNode & rParseNode)1614 OSQLParseNode::OSQLParseNode(const OSQLParseNode& rParseNode)
1615 {
1616     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::OSQLParseNode" );
1617 
1618     // klemm den getParent auf NULL
1619     m_pParent = NULL;
1620 
1621     // kopiere die member
1622     m_aNodeValue = rParseNode.m_aNodeValue;
1623     m_eNodeType  = rParseNode.m_eNodeType;
1624     m_nNodeID    = rParseNode.m_nNodeID;
1625 
1626 
1627     // denk dran, dass von Container abgeleitet wurde, laut SV-Help erzeugt
1628     // copy-Constructor des Containers einen neuen Container mit den gleichen
1629     // Zeigern als Inhalt -> d.h. nach dem Kopieren des Container wird fuer
1630     // alle Zeiger ungleich NULL eine Kopie hergestellt und anstelle des alten
1631     // Zeigers wieder eingehangen.
1632 
1633     // wenn kein Blatt, dann SubTrees bearbeiten
1634     for (OSQLParseNodes::const_iterator i = rParseNode.m_aChildren.begin();
1635          i != rParseNode.m_aChildren.end(); i++)
1636         append(new OSQLParseNode(**i));
1637 }
1638 // -----------------------------------------------------------------------------
1639 //-----------------------------------------------------------------------------
operator =(const OSQLParseNode & rParseNode)1640 OSQLParseNode& OSQLParseNode::operator=(const OSQLParseNode& rParseNode)
1641 {
1642     if (this != &rParseNode)
1643     {
1644         // kopiere die member - pParent bleibt der alte
1645         m_aNodeValue = rParseNode.m_aNodeValue;
1646         m_eNodeType  = rParseNode.m_eNodeType;
1647         m_nNodeID    = rParseNode.m_nNodeID;
1648 
1649         for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
1650             i != m_aChildren.end(); i++)
1651             delete *i;
1652 
1653         m_aChildren.clear();
1654 
1655         for (OSQLParseNodes::const_iterator j = rParseNode.m_aChildren.begin();
1656              j != rParseNode.m_aChildren.end(); j++)
1657             append(new OSQLParseNode(**j));
1658     }
1659     return *this;
1660 }
1661 
1662 //-----------------------------------------------------------------------------
operator ==(OSQLParseNode & rParseNode) const1663 sal_Bool OSQLParseNode::operator==(OSQLParseNode& rParseNode) const
1664 {
1665     // die member muessen gleich sein
1666     sal_Bool bResult = (m_nNodeID  == rParseNode.m_nNodeID) &&
1667                    (m_eNodeType == rParseNode.m_eNodeType) &&
1668                    (m_aNodeValue == rParseNode.m_aNodeValue) &&
1669                     count() == rParseNode.count();
1670 
1671     // Parameters are not equal!
1672     bResult = bResult && !SQL_ISRULE(this, parameter);
1673 
1674     // compare childs
1675     for (sal_uInt32 i=0; bResult && i < count(); i++)
1676         bResult = *getChild(i) == *rParseNode.getChild(i);
1677 
1678     return bResult;
1679 }
1680 
1681 //-----------------------------------------------------------------------------
~OSQLParseNode()1682 OSQLParseNode::~OSQLParseNode()
1683 {
1684     for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
1685          i != m_aChildren.end(); i++)
1686         delete *i;
1687     m_aChildren.clear();
1688 }
1689 
1690 //-----------------------------------------------------------------------------
append(OSQLParseNode * pNewNode)1691 void OSQLParseNode::append(OSQLParseNode* pNewNode)
1692 {
1693     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::append" );
1694 
1695     OSL_ENSURE(pNewNode != NULL, "OSQLParseNode: ungueltiger NewSubTree");
1696     OSL_ENSURE(pNewNode->getParent() == NULL, "OSQLParseNode: Knoten ist kein Waise");
1697     OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pNewNode) == m_aChildren.end(),
1698             "OSQLParseNode::append() Node already element of parent");
1699 
1700     // stelle Verbindung zum getParent her:
1701     pNewNode->setParent( this );
1702     // und haenge den SubTree hinten an
1703     m_aChildren.push_back(pNewNode);
1704 }
1705 // -----------------------------------------------------------------------------
addDateValue(::rtl::OUStringBuffer & rString,const SQLParseNodeParameter & rParam) const1706 sal_Bool OSQLParseNode::addDateValue(::rtl::OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
1707 {
1708     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::addDateValue" );
1709     // special display for date/time values
1710     if (SQL_ISRULE(this,set_fct_spec) && SQL_ISPUNCTUATION(m_aChildren[0],"{"))
1711     {
1712         const OSQLParseNode* pODBCNode = m_aChildren[1];
1713         const OSQLParseNode* pODBCNodeChild = pODBCNode->m_aChildren[0];
1714 
1715         if (pODBCNodeChild->getNodeType() == SQL_NODE_KEYWORD && (
1716             SQL_ISTOKEN(pODBCNodeChild, D) ||
1717             SQL_ISTOKEN(pODBCNodeChild, T) ||
1718             SQL_ISTOKEN(pODBCNodeChild, TS) ))
1719         {
1720 			::rtl::OUString suQuote(::rtl::OUString::createFromAscii("'"));
1721 			if (rParam.bPredicate)
1722 			{
1723 				 if (rParam.aMetaData.shouldEscapeDateTime())
1724 				 {
1725 					 suQuote = ::rtl::OUString::createFromAscii("#");
1726 				 }
1727 			}
1728 			else
1729 			{
1730 				 if (rParam.aMetaData.shouldEscapeDateTime())
1731 				 {
1732 					 // suQuote = ::rtl::OUString::createFromAscii("'");
1733 					 return sal_False;
1734 				 }
1735 			}
1736 
1737 			if (rString.getLength())
1738                 rString.appendAscii(" ");
1739 			rString.append(suQuote);
1740 			const ::rtl::OUString sTokenValue = pODBCNode->m_aChildren[1]->getTokenValue();
1741             if (SQL_ISTOKEN(pODBCNodeChild, D))
1742 			{
1743 				rString.append(rParam.bPredicate ? convertDateString(rParam, sTokenValue) : sTokenValue);
1744 			}
1745             else if (SQL_ISTOKEN(pODBCNodeChild, T))
1746 			{
1747 				rString.append(rParam.bPredicate ? convertTimeString(rParam, sTokenValue) : sTokenValue);
1748 			}
1749             else
1750 			{
1751 				rString.append(rParam.bPredicate ? convertDateTimeString(rParam, sTokenValue) : sTokenValue);
1752 			}
1753 			rString.append(suQuote);
1754             return sal_True;
1755         }
1756     }
1757     return sal_False;
1758 }
1759 // -----------------------------------------------------------------------------
replaceNodeValue(const::rtl::OUString & rTableAlias,const::rtl::OUString & rColumnName)1760 void OSQLParseNode::replaceNodeValue(const ::rtl::OUString& rTableAlias,const ::rtl::OUString& rColumnName)
1761 {
1762     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::replaceNodeValue" );
1763     for (sal_uInt32 i=0;i<count();++i)
1764     {
1765         if (SQL_ISRULE(this,column_ref) && count() == 1 && getChild(0)->getTokenValue() == rColumnName)
1766         {
1767             OSQLParseNode * pCol = removeAt((sal_uInt32)0);
1768             append(new OSQLParseNode(rTableAlias,SQL_NODE_NAME));
1769             append(new OSQLParseNode(::rtl::OUString::createFromAscii("."),SQL_NODE_PUNCTUATION));
1770             append(pCol);
1771         }
1772         else
1773             getChild(i)->replaceNodeValue(rTableAlias,rColumnName);
1774     }
1775 }
1776 //-----------------------------------------------------------------------------
getByRule(OSQLParseNode::Rule eRule) const1777 OSQLParseNode* OSQLParseNode::getByRule(OSQLParseNode::Rule eRule) const
1778 {
1779     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::getByRule" );
1780     OSQLParseNode* pRetNode = 0;
1781     if (isRule() && OSQLParser::RuleID(eRule) == getRuleID())
1782         pRetNode = (OSQLParseNode*)this;
1783     else
1784     {
1785         for (OSQLParseNodes::const_iterator i = m_aChildren.begin();
1786             !pRetNode && i != m_aChildren.end(); i++)
1787             pRetNode = (*i)->getByRule(eRule);
1788     }
1789     return pRetNode;
1790 }
1791 //-----------------------------------------------------------------------------
MakeANDNode(OSQLParseNode * pLeftLeaf,OSQLParseNode * pRightLeaf)1792 OSQLParseNode* MakeANDNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1793 {
1794     OSQLParseNode* pNewNode = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1795     pNewNode->append(pLeftLeaf);
1796     pNewNode->append(new OSQLParseNode(::rtl::OUString::createFromAscii("AND"),SQL_NODE_KEYWORD,SQL_TOKEN_AND));
1797     pNewNode->append(pRightLeaf);
1798     return pNewNode;
1799 }
1800 //-----------------------------------------------------------------------------
MakeORNode(OSQLParseNode * pLeftLeaf,OSQLParseNode * pRightLeaf)1801 OSQLParseNode* MakeORNode(OSQLParseNode *pLeftLeaf,OSQLParseNode *pRightLeaf)
1802 {
1803     OSQLParseNode* pNewNode = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::search_condition));
1804     pNewNode->append(pLeftLeaf);
1805     pNewNode->append(new OSQLParseNode(::rtl::OUString::createFromAscii("OR"),SQL_NODE_KEYWORD,SQL_TOKEN_OR));
1806     pNewNode->append(pRightLeaf);
1807     return pNewNode;
1808 }
1809 //-----------------------------------------------------------------------------
disjunctiveNormalForm(OSQLParseNode * & pSearchCondition)1810 void OSQLParseNode::disjunctiveNormalForm(OSQLParseNode*& pSearchCondition)
1811 {
1812     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::disjunctiveNormalForm" );
1813     if(!pSearchCondition) // no where condition at entry point
1814         return;
1815 
1816     OSQLParseNode::absorptions(pSearchCondition);
1817     // '(' search_condition ')'
1818     if (SQL_ISRULE(pSearchCondition,boolean_primary))
1819     {
1820         OSQLParseNode* pLeft    = pSearchCondition->getChild(1);
1821         disjunctiveNormalForm(pLeft);
1822     }
1823     // search_condition SQL_TOKEN_OR boolean_term
1824     else if (SQL_ISRULE(pSearchCondition,search_condition))
1825     {
1826         OSQLParseNode* pLeft    = pSearchCondition->getChild(0);
1827         disjunctiveNormalForm(pLeft);
1828 
1829         OSQLParseNode* pRight = pSearchCondition->getChild(2);
1830         disjunctiveNormalForm(pRight);
1831     }
1832     // boolean_term SQL_TOKEN_AND boolean_factor
1833     else if (SQL_ISRULE(pSearchCondition,boolean_term))
1834     {
1835         OSQLParseNode* pLeft    = pSearchCondition->getChild(0);
1836         disjunctiveNormalForm(pLeft);
1837 
1838         OSQLParseNode* pRight = pSearchCondition->getChild(2);
1839         disjunctiveNormalForm(pRight);
1840 
1841         OSQLParseNode* pNewNode = NULL;
1842         // '(' search_condition ')' on left side
1843         if(pLeft->count() == 3 && SQL_ISRULE(pLeft,boolean_primary) && SQL_ISRULE(pLeft->getChild(1),search_condition))
1844         {
1845             // and-or tree  on left side
1846             OSQLParseNode* pOr = pLeft->getChild(1);
1847             OSQLParseNode* pNewLeft = NULL;
1848             OSQLParseNode* pNewRight = NULL;
1849 
1850             // cut right from parent
1851             pSearchCondition->removeAt(2);
1852 
1853             pNewRight   = MakeANDNode(pOr->removeAt(2)      ,pRight);
1854             pNewLeft    = MakeANDNode(pOr->removeAt((sal_uInt32)0)  ,new OSQLParseNode(*pRight));
1855             pNewNode    = MakeORNode(pNewLeft,pNewRight);
1856             // and append new Node
1857             replaceAndReset(pSearchCondition,pNewNode);
1858 
1859             disjunctiveNormalForm(pSearchCondition);
1860         }
1861         else if(pRight->count() == 3 && SQL_ISRULE(pRight,boolean_primary) && SQL_ISRULE(pRight->getChild(1),search_condition))
1862         {   // '(' search_condition ')' on right side
1863             // and-or tree  on right side
1864             // a and (b or c)
1865             OSQLParseNode* pOr = pRight->getChild(1);
1866             OSQLParseNode* pNewLeft = NULL;
1867             OSQLParseNode* pNewRight = NULL;
1868 
1869             // cut left from parent
1870             pSearchCondition->removeAt((sal_uInt32)0);
1871 
1872             pNewRight   = MakeANDNode(pLeft,pOr->removeAt(2));
1873             pNewLeft    = MakeANDNode(new OSQLParseNode(*pLeft),pOr->removeAt((sal_uInt32)0));
1874             pNewNode    = MakeORNode(pNewLeft,pNewRight);
1875 
1876             // and append new Node
1877             replaceAndReset(pSearchCondition,pNewNode);
1878             disjunctiveNormalForm(pSearchCondition);
1879         }
1880         else if(SQL_ISRULE(pLeft,boolean_primary) && (!SQL_ISRULE(pLeft->getChild(1),search_condition) || !SQL_ISRULE(pLeft->getChild(1),boolean_term)))
1881             pSearchCondition->replace(pLeft, pLeft->removeAt(1));
1882         else if(SQL_ISRULE(pRight,boolean_primary) && (!SQL_ISRULE(pRight->getChild(1),search_condition) || !SQL_ISRULE(pRight->getChild(1),boolean_term)))
1883             pSearchCondition->replace(pRight, pRight->removeAt(1));
1884     }
1885 }
1886 //-----------------------------------------------------------------------------
negateSearchCondition(OSQLParseNode * & pSearchCondition,sal_Bool bNegate)1887 void OSQLParseNode::negateSearchCondition(OSQLParseNode*& pSearchCondition,sal_Bool bNegate)
1888 {
1889     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::negateSearchCondition" );
1890     if(!pSearchCondition) // no where condition at entry point
1891         return;
1892     // '(' search_condition ')'
1893     if (pSearchCondition->count() == 3 && SQL_ISRULE(pSearchCondition,boolean_primary))
1894     {
1895         OSQLParseNode* pRight = pSearchCondition->getChild(1);
1896         negateSearchCondition(pRight,bNegate);
1897     }
1898     // search_condition SQL_TOKEN_OR boolean_term
1899     else if (SQL_ISRULE(pSearchCondition,search_condition))
1900     {
1901         OSQLParseNode* pLeft    = pSearchCondition->getChild(0);
1902         OSQLParseNode* pRight = pSearchCondition->getChild(2);
1903         if(bNegate)
1904         {
1905             OSQLParseNode* pNewNode = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_term));
1906             pNewNode->append(pSearchCondition->removeAt((sal_uInt32)0));
1907             pNewNode->append(new OSQLParseNode(::rtl::OUString::createFromAscii("AND"),SQL_NODE_KEYWORD,SQL_TOKEN_AND));
1908             pNewNode->append(pSearchCondition->removeAt((sal_uInt32)1));
1909             replaceAndReset(pSearchCondition,pNewNode);
1910 
1911             pLeft   = pNewNode->getChild(0);
1912             pRight  = pNewNode->getChild(2);
1913         }
1914 
1915         negateSearchCondition(pLeft,bNegate);
1916         negateSearchCondition(pRight,bNegate);
1917     }
1918     // boolean_term SQL_TOKEN_AND boolean_factor
1919     else if (SQL_ISRULE(pSearchCondition,boolean_term))
1920     {
1921         OSQLParseNode* pLeft    = pSearchCondition->getChild(0);
1922         OSQLParseNode* pRight = pSearchCondition->getChild(2);
1923         if(bNegate)
1924         {
1925             OSQLParseNode* pNewNode = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::search_condition));
1926             pNewNode->append(pSearchCondition->removeAt((sal_uInt32)0));
1927             pNewNode->append(new OSQLParseNode(::rtl::OUString::createFromAscii("OR"),SQL_NODE_KEYWORD,SQL_TOKEN_OR));
1928             pNewNode->append(pSearchCondition->removeAt((sal_uInt32)1));
1929             replaceAndReset(pSearchCondition,pNewNode);
1930 
1931             pLeft   = pNewNode->getChild(0);
1932             pRight  = pNewNode->getChild(2);
1933         }
1934 
1935         negateSearchCondition(pLeft,bNegate);
1936         negateSearchCondition(pRight,bNegate);
1937     }
1938     // SQL_TOKEN_NOT ( boolean_test )
1939     else if (SQL_ISRULE(pSearchCondition,boolean_factor))
1940     {
1941         OSQLParseNode *pNot = pSearchCondition->removeAt((sal_uInt32)0);
1942         delete pNot;
1943         OSQLParseNode *pBooleanTest = pSearchCondition->removeAt((sal_uInt32)0);
1944         // TODO is this needed // pBooleanTest->setParent(NULL);
1945         replaceAndReset(pSearchCondition,pBooleanTest);
1946 
1947         if (!bNegate)
1948             negateSearchCondition(pSearchCondition,sal_True);   //  negate all deeper values
1949     }
1950     // row_value_constructor comparison row_value_constructor
1951     // row_value_constructor comparison any_all_some subquery
1952     else if(bNegate && (SQL_ISRULE(pSearchCondition,comparison_predicate) || SQL_ISRULE(pSearchCondition,all_or_any_predicate)))
1953     {
1954         OSQLParseNode* pComparison = pSearchCondition->getChild(1);
1955         OSQLParseNode* pNewComparison = NULL;
1956         switch(pComparison->getNodeType())
1957         {
1958             case SQL_NODE_EQUAL:
1959                 pNewComparison = new OSQLParseNode(::rtl::OUString::createFromAscii("<>"),SQL_NODE_NOTEQUAL,SQL_NOTEQUAL);
1960                 break;
1961             case SQL_NODE_LESS:
1962                 pNewComparison = new OSQLParseNode(::rtl::OUString::createFromAscii(">="),SQL_NODE_GREATEQ,SQL_GREATEQ);
1963                 break;
1964             case SQL_NODE_GREAT:
1965                 pNewComparison = new OSQLParseNode(::rtl::OUString::createFromAscii("<="),SQL_NODE_LESSEQ,SQL_LESSEQ);
1966                 break;
1967             case SQL_NODE_LESSEQ:
1968                 pNewComparison = new OSQLParseNode(::rtl::OUString::createFromAscii(">"),SQL_NODE_GREAT,SQL_GREAT);
1969                 break;
1970             case SQL_NODE_GREATEQ:
1971                 pNewComparison = new OSQLParseNode(::rtl::OUString::createFromAscii("<"),SQL_NODE_LESS,SQL_LESS);
1972                 break;
1973             case SQL_NODE_NOTEQUAL:
1974                 pNewComparison = new OSQLParseNode(::rtl::OUString::createFromAscii("="),SQL_NODE_EQUAL,SQL_EQUAL);
1975                 break;
1976             default:
1977                 OSL_ENSURE( false, "OSQLParseNode::negateSearchCondition: unexpected node type!" );
1978                 break;
1979         }
1980         pSearchCondition->replace(pComparison, pNewComparison);
1981         delete pComparison;
1982     }
1983 
1984     else if(bNegate && (SQL_ISRULE(pSearchCondition,test_for_null) || SQL_ISRULE(pSearchCondition,in_predicate) ||
1985                         SQL_ISRULE(pSearchCondition,between_predicate) || SQL_ISRULE(pSearchCondition,boolean_test) ))
1986     {
1987         OSQLParseNode* pPart2 = pSearchCondition;
1988         if ( !SQL_ISRULE(pSearchCondition,boolean_test) )
1989             pPart2 = pSearchCondition->getChild(1);
1990         sal_uInt32 nNotPos = 0;
1991         if  ( SQL_ISRULE( pSearchCondition, test_for_null ) )
1992             nNotPos = 1;
1993         else if ( SQL_ISRULE( pSearchCondition, boolean_test ) )
1994             nNotPos = 2;
1995 
1996         OSQLParseNode* pNot = pPart2->getChild(nNotPos);
1997         OSQLParseNode* pNotNot = NULL;
1998         if(pNot->isRule())
1999             pNotNot = new OSQLParseNode(::rtl::OUString::createFromAscii("NOT"),SQL_NODE_KEYWORD,SQL_TOKEN_NOT);
2000         else
2001             pNotNot = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::sql_not));
2002         pPart2->replace(pNot, pNotNot);
2003         delete pNot;
2004     }
2005     else if(bNegate && (SQL_ISRULE(pSearchCondition,like_predicate)))
2006     {
2007         OSQLParseNode* pNot = pSearchCondition->getChild( 1 )->getChild( 0 );
2008         OSQLParseNode* pNotNot = NULL;
2009         if(pNot->isRule())
2010             pNotNot = new OSQLParseNode(::rtl::OUString::createFromAscii("NOT"),SQL_NODE_KEYWORD,SQL_TOKEN_NOT);
2011         else
2012             pNotNot = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::sql_not));
2013         pSearchCondition->getChild( 1 )->replace(pNot, pNotNot);
2014         delete pNot;
2015     }
2016 }
2017 //-----------------------------------------------------------------------------
eraseBraces(OSQLParseNode * & pSearchCondition)2018 void OSQLParseNode::eraseBraces(OSQLParseNode*& pSearchCondition)
2019 {
2020     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::eraseBraces" );
2021     if (pSearchCondition && (SQL_ISRULE(pSearchCondition,boolean_primary) || (pSearchCondition->count() == 3 && SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
2022          SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")"))))
2023     {
2024         OSQLParseNode* pRight = pSearchCondition->getChild(1);
2025         absorptions(pRight);
2026         // if child is not a or or and tree then delete () around child
2027         if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2028             SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || // and can always stand without ()
2029             (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2030         {
2031             OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2032             replaceAndReset(pSearchCondition,pNode);
2033         }
2034     }
2035 }
2036 //-----------------------------------------------------------------------------
absorptions(OSQLParseNode * & pSearchCondition)2037 void OSQLParseNode::absorptions(OSQLParseNode*& pSearchCondition)
2038 {
2039     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::absorptions" );
2040     if(!pSearchCondition) // no where condition at entry point
2041         return;
2042 
2043     eraseBraces(pSearchCondition);
2044 
2045     if(SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2046     {
2047         OSQLParseNode* pLeft = pSearchCondition->getChild(0);
2048         absorptions(pLeft);
2049         OSQLParseNode* pRight = pSearchCondition->getChild(2);
2050         absorptions(pRight);
2051     }
2052 
2053     sal_uInt32 nPos = 0;
2054     // a and a || a or a
2055     OSQLParseNode* pNewNode = NULL;
2056     if(( SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2057         && *pSearchCondition->getChild(0) == *pSearchCondition->getChild(2))
2058     {
2059         pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2060         replaceAndReset(pSearchCondition,pNewNode);
2061     }
2062     // (a or b) and a || ( b or c ) and a
2063     // a and ( a or b) || a and ( b or c )
2064     else if (   SQL_ISRULE(pSearchCondition,boolean_term)
2065             &&  (
2066                     (       SQL_ISRULE(pSearchCondition->getChild(nPos = 0),boolean_primary)
2067                         ||  SQL_ISRULE(pSearchCondition->getChild(nPos),search_condition)
2068                     )
2069                 ||  (       SQL_ISRULE(pSearchCondition->getChild(nPos = 2),boolean_primary)
2070                         ||  SQL_ISRULE(pSearchCondition->getChild(nPos),search_condition)
2071                     )
2072                 )
2073             )
2074     {
2075         OSQLParseNode* p2ndSearch = pSearchCondition->getChild(nPos);
2076         if ( SQL_ISRULE(p2ndSearch,boolean_primary) )
2077             p2ndSearch = p2ndSearch->getChild(1);
2078 
2079         if ( *p2ndSearch->getChild(0) == *pSearchCondition->getChild(2-nPos) ) // a and ( a or b) -> a or b
2080         {
2081             pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2082             replaceAndReset(pSearchCondition,pNewNode);
2083 
2084         }
2085         else if ( *p2ndSearch->getChild(2) == *pSearchCondition->getChild(2-nPos) ) // a and ( b or a) -> a or b
2086         {
2087             pNewNode = pSearchCondition->removeAt((sal_uInt32)2);
2088             replaceAndReset(pSearchCondition,pNewNode);
2089         }
2090         else if ( p2ndSearch->getByRule(OSQLParseNode::search_condition) )
2091         {
2092             // a and ( b or c ) -> ( a and b ) or ( a and c )
2093             // ( b or c ) and a -> ( a and b ) or ( a and c )
2094             OSQLParseNode* pC = p2ndSearch->removeAt((sal_uInt32)2);
2095             OSQLParseNode* pB = p2ndSearch->removeAt((sal_uInt32)0);
2096             OSQLParseNode* pA = pSearchCondition->removeAt((sal_uInt32)2-nPos);
2097 
2098             OSQLParseNode* p1stAnd = MakeANDNode(pA,pB);
2099             OSQLParseNode* p2ndAnd = MakeANDNode(new OSQLParseNode(*pA),pC);
2100             pNewNode = MakeORNode(p1stAnd,p2ndAnd);
2101 			OSQLParseNode* pNode = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2102             pNode->append(new OSQLParseNode(::rtl::OUString::createFromAscii("("),SQL_NODE_PUNCTUATION));
2103             pNode->append(pNewNode);
2104             pNode->append(new OSQLParseNode(::rtl::OUString::createFromAscii(")"),SQL_NODE_PUNCTUATION));
2105 			OSQLParseNode::eraseBraces(p1stAnd);
2106             OSQLParseNode::eraseBraces(p2ndAnd);
2107             replaceAndReset(pSearchCondition,pNode);
2108         }
2109     }
2110     // a or a and b || a or b and a
2111     else if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(2),boolean_term))
2112     {
2113         if(*pSearchCondition->getChild(2)->getChild(0) == *pSearchCondition->getChild(0))
2114         {
2115             pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2116             replaceAndReset(pSearchCondition,pNewNode);
2117         }
2118         else if(*pSearchCondition->getChild(2)->getChild(2) == *pSearchCondition->getChild(0))
2119         {
2120             pNewNode = pSearchCondition->removeAt((sal_uInt32)0);
2121             replaceAndReset(pSearchCondition,pNewNode);
2122         }
2123     }
2124     // a and b or a || b and a or a
2125     else if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(0),boolean_term))
2126     {
2127         if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2))
2128         {
2129             pNewNode = pSearchCondition->removeAt((sal_uInt32)2);
2130             replaceAndReset(pSearchCondition,pNewNode);
2131         }
2132         else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2))
2133         {
2134             pNewNode = pSearchCondition->removeAt((sal_uInt32)2);
2135             replaceAndReset(pSearchCondition,pNewNode);
2136         }
2137     }
2138     eraseBraces(pSearchCondition);
2139 }
2140 //-----------------------------------------------------------------------------
compress(OSQLParseNode * & pSearchCondition)2141 void OSQLParseNode::compress(OSQLParseNode *&pSearchCondition)
2142 {
2143     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::compress" );
2144     if(!pSearchCondition) // no where condition at entry point
2145         return;
2146 
2147     OSQLParseNode::eraseBraces(pSearchCondition);
2148 
2149     if(SQL_ISRULE(pSearchCondition,boolean_term) || SQL_ISRULE(pSearchCondition,search_condition))
2150     {
2151         OSQLParseNode* pLeft = pSearchCondition->getChild(0);
2152         compress(pLeft);
2153 
2154         OSQLParseNode* pRight = pSearchCondition->getChild(2);
2155         compress(pRight);
2156     }
2157     else if( SQL_ISRULE(pSearchCondition,boolean_primary) || (pSearchCondition->count() == 3 && SQL_ISPUNCTUATION(pSearchCondition->getChild(0),"(") &&
2158              SQL_ISPUNCTUATION(pSearchCondition->getChild(2),")")))
2159     {
2160         OSQLParseNode* pRight = pSearchCondition->getChild(1);
2161         compress(pRight);
2162         // if child is not a or or and tree then delete () around child
2163         if(!(SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) || SQL_ISRULE(pSearchCondition->getChild(1),search_condition)) ||
2164             (SQL_ISRULE(pSearchCondition->getChild(1),boolean_term) && SQL_ISRULE(pSearchCondition->getParent(),boolean_term)) ||
2165             (SQL_ISRULE(pSearchCondition->getChild(1),search_condition) && SQL_ISRULE(pSearchCondition->getParent(),search_condition)))
2166         {
2167             OSQLParseNode* pNode = pSearchCondition->removeAt(1);
2168             replaceAndReset(pSearchCondition,pNode);
2169         }
2170     }
2171 
2172     // or with two and trees where one element of the and trees are equal
2173     if(SQL_ISRULE(pSearchCondition,search_condition) && SQL_ISRULE(pSearchCondition->getChild(0),boolean_term) && SQL_ISRULE(pSearchCondition->getChild(2),boolean_term))
2174     {
2175         if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(0))
2176         {
2177             OSQLParseNode* pLeft    = pSearchCondition->getChild(0)->removeAt(2);
2178             OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2179             OSQLParseNode* pNode    = MakeORNode(pLeft,pRight);
2180 
2181             OSQLParseNode* pNewRule = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2182             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii("("),SQL_NODE_PUNCTUATION));
2183             pNewRule->append(pNode);
2184             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii(")"),SQL_NODE_PUNCTUATION));
2185 
2186             OSQLParseNode::eraseBraces(pLeft);
2187             OSQLParseNode::eraseBraces(pRight);
2188 
2189             pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt((sal_uInt32)0),pNewRule);
2190             replaceAndReset(pSearchCondition,pNode);
2191         }
2192         else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(0))
2193         {
2194             OSQLParseNode* pLeft = pSearchCondition->getChild(0)->removeAt((sal_uInt32)0);
2195             OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt(2);
2196             OSQLParseNode* pNode = MakeORNode(pLeft,pRight);
2197 
2198             OSQLParseNode* pNewRule = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2199             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii("("),SQL_NODE_PUNCTUATION));
2200             pNewRule->append(pNode);
2201             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii(")"),SQL_NODE_PUNCTUATION));
2202 
2203             OSQLParseNode::eraseBraces(pLeft);
2204             OSQLParseNode::eraseBraces(pRight);
2205 
2206             pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2207             replaceAndReset(pSearchCondition,pNode);
2208         }
2209         else if(*pSearchCondition->getChild(0)->getChild(0) == *pSearchCondition->getChild(2)->getChild(2))
2210         {
2211             OSQLParseNode* pLeft    = pSearchCondition->getChild(0)->removeAt(2);
2212             OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt((sal_uInt32)0);
2213             OSQLParseNode* pNode    = MakeORNode(pLeft,pRight);
2214 
2215             OSQLParseNode* pNewRule = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2216             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii("("),SQL_NODE_PUNCTUATION));
2217             pNewRule->append(pNode);
2218             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii(")"),SQL_NODE_PUNCTUATION));
2219 
2220             OSQLParseNode::eraseBraces(pLeft);
2221             OSQLParseNode::eraseBraces(pRight);
2222 
2223             pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt((sal_uInt32)0),pNewRule);
2224             replaceAndReset(pSearchCondition,pNode);
2225         }
2226         else if(*pSearchCondition->getChild(0)->getChild(2) == *pSearchCondition->getChild(2)->getChild(2))
2227         {
2228             OSQLParseNode* pLeft    = pSearchCondition->getChild(0)->removeAt((sal_uInt32)0);
2229             OSQLParseNode* pRight = pSearchCondition->getChild(2)->removeAt((sal_uInt32)0);
2230             OSQLParseNode* pNode    = MakeORNode(pLeft,pRight);
2231 
2232             OSQLParseNode* pNewRule = new OSQLParseNode(::rtl::OUString(),SQL_NODE_RULE,OSQLParser::RuleID(OSQLParseNode::boolean_primary));
2233             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii("("),SQL_NODE_PUNCTUATION));
2234             pNewRule->append(pNode);
2235             pNewRule->append(new OSQLParseNode(::rtl::OUString::createFromAscii(")"),SQL_NODE_PUNCTUATION));
2236 
2237             OSQLParseNode::eraseBraces(pLeft);
2238             OSQLParseNode::eraseBraces(pRight);
2239 
2240             pNode = MakeANDNode(pSearchCondition->getChild(0)->removeAt(1),pNewRule);
2241             replaceAndReset(pSearchCondition,pNode);
2242         }
2243     }
2244 }
2245 #if OSL_DEBUG_LEVEL > 0
2246 // -----------------------------------------------------------------------------
showParseTree(::rtl::OUString & rString) const2247 void OSQLParseNode::showParseTree( ::rtl::OUString& rString ) const
2248 {
2249     ::rtl::OUStringBuffer aBuf;
2250     showParseTree( aBuf, 0 );
2251     rString = aBuf.makeStringAndClear();
2252 }
2253 
2254 // -----------------------------------------------------------------------------
showParseTree(::rtl::OUStringBuffer & _inout_rBuffer,sal_uInt32 nLevel) const2255 void OSQLParseNode::showParseTree( ::rtl::OUStringBuffer& _inout_rBuffer, sal_uInt32 nLevel ) const
2256 {
2257     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::showParseTree" );
2258 
2259     for ( sal_uInt32 j=0; j<nLevel; ++j)
2260         _inout_rBuffer.appendAscii( "  " );
2261 
2262     if ( !isToken() )
2263     {
2264         // Regelnamen als rule: ...
2265         _inout_rBuffer.appendAscii( "RULE_ID: " );
2266         _inout_rBuffer.append( (sal_Int32)getRuleID() );
2267         _inout_rBuffer.append( sal_Unicode( '(' ) );
2268         _inout_rBuffer.append( OSQLParser::RuleIDToStr( getRuleID() ) );
2269         _inout_rBuffer.append( sal_Unicode( ')' ) );
2270         _inout_rBuffer.append( sal_Unicode( '\n' ) );
2271 
2272         // hol dir den ersten Subtree
2273         for (   OSQLParseNodes::const_iterator i = m_aChildren.begin();
2274                 i != m_aChildren.end();
2275                 ++i
2276              )
2277             (*i)->showParseTree( _inout_rBuffer, nLevel+1 );
2278     }
2279     else
2280     {
2281         // ein Token gefunden
2282         switch (m_eNodeType)
2283         {
2284 
2285         case SQL_NODE_KEYWORD:
2286             _inout_rBuffer.appendAscii( "SQL_KEYWORD: " );
2287             _inout_rBuffer.append( ::rtl::OStringToOUString( OSQLParser::TokenIDToStr( getTokenID() ), RTL_TEXTENCODING_UTF8 ) );
2288             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2289             break;
2290 
2291         case SQL_NODE_COMPARISON:
2292             _inout_rBuffer.appendAscii( "SQL_COMPARISON: " );
2293             _inout_rBuffer.append( m_aNodeValue );
2294             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2295             break;
2296 
2297         case SQL_NODE_NAME:
2298             _inout_rBuffer.appendAscii( "SQL_NAME: " );
2299             _inout_rBuffer.append( sal_Unicode( '"' ) );
2300             _inout_rBuffer.append( m_aNodeValue );
2301             _inout_rBuffer.append( sal_Unicode( '"' ) );
2302             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2303              break;
2304 
2305         case SQL_NODE_STRING:
2306             _inout_rBuffer.appendAscii( "SQL_STRING: " );
2307             _inout_rBuffer.append( sal_Unicode( '\'' ) );
2308             _inout_rBuffer.append( m_aNodeValue );
2309             _inout_rBuffer.append( sal_Unicode( '\'' ) );
2310             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2311             break;
2312 
2313         case SQL_NODE_INTNUM:
2314             _inout_rBuffer.appendAscii( "SQL_INTNUM: " );
2315             _inout_rBuffer.append( m_aNodeValue );
2316             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2317             break;
2318 
2319         case SQL_NODE_APPROXNUM:
2320             _inout_rBuffer.appendAscii( "SQL_APPROXNUM: " );
2321             _inout_rBuffer.append( m_aNodeValue );
2322             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2323              break;
2324 
2325         case SQL_NODE_PUNCTUATION:
2326             _inout_rBuffer.appendAscii( "SQL_PUNCTUATION: " );
2327             _inout_rBuffer.append( m_aNodeValue );
2328             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2329             break;
2330 
2331         case SQL_NODE_AMMSC:
2332             _inout_rBuffer.appendAscii( "SQL_AMMSC: " );
2333             _inout_rBuffer.append( m_aNodeValue );
2334             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2335             break;
2336 
2337         case SQL_NODE_EQUAL:
2338         case SQL_NODE_LESS:
2339         case SQL_NODE_GREAT:
2340         case SQL_NODE_LESSEQ:
2341         case SQL_NODE_GREATEQ:
2342         case SQL_NODE_NOTEQUAL:
2343             _inout_rBuffer.append( m_aNodeValue );
2344             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2345             break;
2346 
2347         case SQL_NODE_ACCESS_DATE:
2348             _inout_rBuffer.appendAscii( "SQL_ACCESS_DATE: " );
2349             _inout_rBuffer.append( m_aNodeValue );
2350             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2351             break;
2352 
2353         case SQL_NODE_DATE:
2354             _inout_rBuffer.appendAscii( "SQL_DATE: " );
2355             _inout_rBuffer.append( m_aNodeValue );
2356             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2357             break;
2358 
2359         case SQL_NODE_CONCAT:
2360             _inout_rBuffer.appendAscii( "||" );
2361             _inout_rBuffer.append( sal_Unicode( '\n' ) );
2362             break;
2363 
2364         default:
2365             OSL_TRACE( "-- %i", int( m_eNodeType ) );
2366             OSL_ENSURE( false, "OSQLParser::ShowParseTree: unzulaessiger NodeType" );
2367         }
2368     }
2369 }
2370 #endif // OSL_DEBUG_LEVEL > 0
2371 // -----------------------------------------------------------------------------
2372 // Insert-Methoden
2373 //-----------------------------------------------------------------------------
insert(sal_uInt32 nPos,OSQLParseNode * pNewSubTree)2374 void OSQLParseNode::insert(sal_uInt32 nPos, OSQLParseNode* pNewSubTree)
2375 {
2376     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::insert" );
2377     OSL_ENSURE(pNewSubTree != NULL, "OSQLParseNode: ungueltiger NewSubTree");
2378     OSL_ENSURE(pNewSubTree->getParent() == NULL, "OSQLParseNode: Knoten ist kein Waise");
2379 
2380     // stelle Verbindung zum getParent her:
2381     pNewSubTree->setParent( this );
2382     m_aChildren.insert(m_aChildren.begin() + nPos, pNewSubTree);
2383 }
2384 
2385 // removeAt-Methoden
2386 //-----------------------------------------------------------------------------
removeAt(sal_uInt32 nPos)2387 OSQLParseNode* OSQLParseNode::removeAt(sal_uInt32 nPos)
2388 {
2389     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::removeAt" );
2390     OSL_ENSURE(nPos < m_aChildren.size(),"Illegal position for removeAt");
2391     OSQLParseNodes::iterator aPos(m_aChildren.begin() + nPos);
2392     OSQLParseNode* pNode = *aPos;
2393 
2394     // setze den getParent des removeten auf NULL
2395     pNode->setParent( NULL );
2396 
2397     m_aChildren.erase(aPos);
2398     return pNode;
2399 }
2400 //-----------------------------------------------------------------------------
remove(OSQLParseNode * pSubTree)2401 OSQLParseNode* OSQLParseNode::remove(OSQLParseNode* pSubTree)
2402 {
2403     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::remove" );
2404     OSL_ENSURE(pSubTree != NULL, "OSQLParseNode: ungueltiger SubTree");
2405     OSQLParseNodes::iterator aPos = ::std::find(m_aChildren.begin(), m_aChildren.end(), pSubTree);
2406     if (aPos != m_aChildren.end())
2407     {
2408         // setze den getParent des removeten auf NULL
2409         pSubTree->setParent( NULL );
2410         m_aChildren.erase(aPos);
2411         return pSubTree;
2412     }
2413     else
2414         return NULL;
2415 }
2416 
2417 // Replace-Methoden
2418 //-----------------------------------------------------------------------------
replaceAt(sal_uInt32 nPos,OSQLParseNode * pNewSubNode)2419 OSQLParseNode* OSQLParseNode::replaceAt(sal_uInt32 nPos, OSQLParseNode* pNewSubNode)
2420 {
2421     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::replaceAt" );
2422     OSL_ENSURE(pNewSubNode != NULL, "OSQLParseNode: invalid nodes");
2423     OSL_ENSURE(pNewSubNode->getParent() == NULL, "OSQLParseNode: node already has getParent");
2424     OSL_ENSURE(nPos < m_aChildren.size(), "OSQLParseNode: invalid position");
2425     OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pNewSubNode) == m_aChildren.end(),
2426             "OSQLParseNode::Replace() Node already element of parent");
2427 
2428     OSQLParseNode* pOldSubNode = m_aChildren[nPos];
2429 
2430     // stelle Verbindung zum getParent her:
2431     pNewSubNode->setParent( this );
2432     pOldSubNode->setParent( NULL );
2433 
2434     m_aChildren[nPos] = pNewSubNode;
2435     return pOldSubNode;
2436 }
2437 
2438 //-----------------------------------------------------------------------------
replace(OSQLParseNode * pOldSubNode,OSQLParseNode * pNewSubNode)2439 OSQLParseNode* OSQLParseNode::replace (OSQLParseNode* pOldSubNode, OSQLParseNode* pNewSubNode )
2440 {
2441     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::replace " );
2442     OSL_ENSURE(pOldSubNode != NULL && pNewSubNode != NULL, "OSQLParseNode: invalid nodes");
2443     OSL_ENSURE(pNewSubNode->getParent() == NULL, "OSQLParseNode: node already has getParent");
2444     OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pOldSubNode) != m_aChildren.end(),
2445             "OSQLParseNode::Replace() Node not element of parent");
2446     OSL_ENSURE(::std::find(m_aChildren.begin(), m_aChildren.end(), pNewSubNode) == m_aChildren.end(),
2447             "OSQLParseNode::Replace() Node already element of parent");
2448 
2449     pOldSubNode->setParent( NULL );
2450     pNewSubNode->setParent( this );
2451     ::std::replace(m_aChildren.begin(), m_aChildren.end(), pOldSubNode, pNewSubNode);
2452     return pOldSubNode;
2453 }
2454 // -----------------------------------------------------------------------------
parseLeaf(::rtl::OUStringBuffer & rString,const SQLParseNodeParameter & rParam) const2455 void OSQLParseNode::parseLeaf(::rtl::OUStringBuffer& rString, const SQLParseNodeParameter& rParam) const
2456 {
2457     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::parseLeaf" );
2458     // ein Blatt ist gefunden
2459     // Inhalt dem Ausgabestring anfuegen
2460     switch (m_eNodeType)
2461     {
2462         case SQL_NODE_KEYWORD:
2463         {
2464             if (rString.getLength())
2465                 rString.appendAscii(" ");
2466 
2467             const ::rtl::OString sT = OSQLParser::TokenIDToStr(m_nNodeID, rParam.bInternational ? &rParam.m_rContext :  NULL);
2468             rString.append( ::rtl::OStringToOUString( sT, RTL_TEXTENCODING_UTF8));
2469         }   break;
2470         case SQL_NODE_STRING:
2471             if (rString.getLength())
2472                 rString.appendAscii(" ");
2473             rString.append(SetQuotation(m_aNodeValue,::rtl::OUString::createFromAscii("\'"),::rtl::OUString::createFromAscii("\'\'")));
2474             break;
2475         case SQL_NODE_NAME:
2476             if (rString.getLength())
2477             {
2478                 switch(rString.charAt(rString.getLength()-1) )
2479                 {
2480                     case ' ' :
2481                     case '.' : break;
2482                     default  :
2483                         if  (   !rParam.aMetaData.getCatalogSeparator().getLength()
2484                             ||  rString.charAt( rString.getLength()-1 ) != rParam.aMetaData.getCatalogSeparator().toChar()
2485                             )
2486                             rString.appendAscii(" "); break;
2487                 }
2488             }
2489             if (rParam.bQuote)
2490             {
2491                 if (rParam.bPredicate)
2492                 {
2493                     rString.appendAscii("[");
2494                     rString.append(m_aNodeValue);
2495                     rString.appendAscii("]");
2496                 }
2497                 else
2498                     rString.append(SetQuotation(m_aNodeValue,
2499                         rParam.aMetaData.getIdentifierQuoteString(), rParam.aMetaData.getIdentifierQuoteString() ));
2500             }
2501             else
2502                 rString.append(m_aNodeValue);
2503             break;
2504         case SQL_NODE_ACCESS_DATE:
2505             if (rString.getLength())
2506                 rString.appendAscii(" ");
2507             rString.appendAscii("#");
2508             rString.append(m_aNodeValue);
2509             rString.appendAscii("#");
2510             break;
2511 
2512         case SQL_NODE_INTNUM:
2513         case SQL_NODE_APPROXNUM:
2514             {
2515                 ::rtl::OUString aTmp = m_aNodeValue;
2516                 if (rParam.bInternational && rParam.bPredicate && rParam.cDecSep != '.')
2517                     aTmp = aTmp.replace('.', rParam.cDecSep);
2518 
2519                 if (rString.getLength())
2520                     rString.appendAscii(" ");
2521                 rString.append(aTmp);
2522 
2523             }   break;
2524         case SQL_NODE_PUNCTUATION:
2525             if ( getParent() && SQL_ISRULE(getParent(),cast_spec) && m_aNodeValue.toChar() == '(' ) // no spaces in front of '('
2526             {
2527                 rString.append(m_aNodeValue);
2528                 break;
2529             }
2530             // fall through
2531         default:
2532             if (rString.getLength() && m_aNodeValue.toChar() != '.' && m_aNodeValue.toChar() != ':' )
2533             {
2534                 switch( rString.charAt(rString.getLength()-1) )
2535                 {
2536                     case ' ' :
2537                     case '.' : break;
2538                     default  :
2539                         if  (   !rParam.aMetaData.getCatalogSeparator().getLength()
2540                             ||  rString.charAt( rString.getLength()-1 ) != rParam.aMetaData.getCatalogSeparator().toChar()
2541                             )
2542                             rString.appendAscii(" "); break;
2543                 }
2544             }
2545             rString.append(m_aNodeValue);
2546     }
2547 }
2548 
2549 // -----------------------------------------------------------------------------
getFunctionReturnType(const::rtl::OUString & _sFunctionName,const IParseContext * pContext)2550 sal_Int32 OSQLParser::getFunctionReturnType(const ::rtl::OUString& _sFunctionName, const IParseContext* pContext)
2551 {
2552     sal_Int32 nType = DataType::VARCHAR;
2553     ::rtl::OString sFunctionName( rtl::OUStringToOString( _sFunctionName, RTL_TEXTENCODING_UTF8));
2554 
2555     if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASCII,pContext)))                     nType = DataType::INTEGER;
2556     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_BIT_LENGTH,pContext)))           nType = DataType::INTEGER;
2557     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR,pContext)))                 nType = DataType::VARCHAR;
2558     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CHAR_LENGTH,pContext)))          nType = DataType::INTEGER;
2559     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CONCAT,pContext)))               nType = DataType::VARCHAR;
2560     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DIFFERENCE,pContext)))           nType = DataType::VARCHAR;
2561     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_INSERT,pContext)))               nType = DataType::VARCHAR;
2562     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LCASE,pContext)))                nType = DataType::VARCHAR;
2563     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LEFT,pContext)))                 nType = DataType::VARCHAR;
2564     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LENGTH,pContext)))               nType = DataType::INTEGER;
2565     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE,pContext)))               nType = DataType::VARCHAR;
2566     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOCATE_2,pContext)))             nType = DataType::VARCHAR;
2567     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LTRIM,pContext)))                nType = DataType::VARCHAR;
2568     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_OCTET_LENGTH,pContext)))         nType = DataType::INTEGER;
2569     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POSITION,pContext)))             nType = DataType::INTEGER;
2570     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPEAT,pContext)))               nType = DataType::VARCHAR;
2571     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_REPLACE,pContext)))              nType = DataType::VARCHAR;
2572     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RIGHT,pContext)))                nType = DataType::VARCHAR;
2573     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RTRIM,pContext)))                nType = DataType::VARCHAR;
2574     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SOUNDEX,pContext)))              nType = DataType::VARCHAR;
2575     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SPACE,pContext)))                nType = DataType::VARCHAR;
2576     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUBSTRING,pContext)))            nType = DataType::VARCHAR;
2577     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UCASE,pContext)))                nType = DataType::VARCHAR;
2578     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_DATE,pContext)))         nType = DataType::DATE;
2579     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIME,pContext)))         nType = DataType::TIME;
2580     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURRENT_TIMESTAMP,pContext)))    nType = DataType::TIMESTAMP;
2581     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURDATE,pContext)))              nType = DataType::DATE;
2582     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEDIFF,pContext)))             nType = DataType::INTEGER;
2583     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DATEVALUE,pContext)))            nType = DataType::DATE;
2584     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CURTIME,pContext)))              nType = DataType::TIME;
2585     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYNAME,pContext)))              nType = DataType::VARCHAR;
2586     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFMONTH,pContext)))           nType = DataType::INTEGER;
2587     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFWEEK,pContext)))            nType = DataType::INTEGER;
2588     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DAYOFYEAR,pContext)))            nType = DataType::INTEGER;
2589     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXTRACT,pContext)))              nType = DataType::VARCHAR;
2590     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_HOUR,pContext)))                 nType = DataType::INTEGER;
2591     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MINUTE,pContext)))               nType = DataType::INTEGER;
2592     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTH,pContext)))                nType = DataType::INTEGER;
2593     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MONTHNAME,pContext)))            nType = DataType::VARCHAR;
2594     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_NOW,pContext)))                  nType = DataType::TIMESTAMP;
2595     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_QUARTER,pContext)))              nType = DataType::INTEGER;
2596     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SECOND,pContext)))               nType = DataType::INTEGER;
2597     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPADD,pContext)))         nType = DataType::TIMESTAMP;
2598     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMESTAMPDIFF,pContext)))        nType = DataType::TIMESTAMP;
2599     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TIMEVALUE,pContext)))            nType = DataType::TIMESTAMP;
2600     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_WEEK,pContext)))                 nType = DataType::INTEGER;
2601     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_YEAR,pContext)))                 nType = DataType::INTEGER;
2602     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ABS,pContext)))                  nType = DataType::DOUBLE;
2603     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ACOS,pContext)))                 nType = DataType::DOUBLE;
2604     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ASIN,pContext)))                 nType = DataType::DOUBLE;
2605     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN,pContext)))                 nType = DataType::DOUBLE;
2606     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ATAN2,pContext)))                nType = DataType::DOUBLE;
2607     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_CEILING,pContext)))              nType = DataType::DOUBLE;
2608     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COS,pContext)))                  nType = DataType::DOUBLE;
2609     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COT,pContext)))                  nType = DataType::DOUBLE;
2610     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_DEGREES,pContext)))              nType = DataType::DOUBLE;
2611     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_EXP,pContext)))                  nType = DataType::DOUBLE;
2612     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_FLOOR,pContext)))                nType = DataType::DOUBLE;
2613     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOGF,pContext)))                 nType = DataType::DOUBLE;
2614     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG,pContext)))                  nType = DataType::DOUBLE;
2615     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOG10,pContext)))                nType = DataType::DOUBLE;
2616     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LN,pContext)))                   nType = DataType::DOUBLE;
2617     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MOD,pContext)))                  nType = DataType::DOUBLE;
2618     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_PI,pContext)))                   nType = DataType::DOUBLE;
2619     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_POWER,pContext)))                nType = DataType::DOUBLE;
2620     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RADIANS,pContext)))              nType = DataType::DOUBLE;
2621     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_RAND,pContext)))                 nType = DataType::DOUBLE;
2622     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUND,pContext)))                nType = DataType::DOUBLE;
2623     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_ROUNDMAGIC,pContext)))           nType = DataType::DOUBLE;
2624     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIGN,pContext)))                 nType = DataType::DOUBLE;
2625     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SIN,pContext)))                  nType = DataType::DOUBLE;
2626     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SQRT,pContext)))                 nType = DataType::DOUBLE;
2627     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TAN,pContext)))                  nType = DataType::DOUBLE;
2628     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_TRUNCATE,pContext)))             nType = DataType::DOUBLE;
2629     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_COUNT,pContext)))                nType = DataType::INTEGER;
2630     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MAX,pContext)))                  nType = DataType::DOUBLE;
2631     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_MIN,pContext)))                  nType = DataType::DOUBLE;
2632     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_AVG,pContext)))                  nType = DataType::DOUBLE;
2633     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_SUM,pContext)))                  nType = DataType::DOUBLE;
2634     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_LOWER,pContext)))                nType = DataType::VARCHAR;
2635     else if(sFunctionName.equalsIgnoreAsciiCase(TokenIDToStr(SQL_TOKEN_UPPER,pContext)))                nType = DataType::VARCHAR;
2636 
2637     return nType;
2638 }
2639 // -----------------------------------------------------------------------------
getFunctionParameterType(sal_uInt32 _nTokenId,sal_uInt32 _nPos)2640 sal_Int32 OSQLParser::getFunctionParameterType(sal_uInt32 _nTokenId, sal_uInt32 _nPos)
2641 {
2642     sal_Int32 nType = DataType::VARCHAR;
2643 
2644     if(_nTokenId == SQL_TOKEN_CHAR)                 nType = DataType::INTEGER;
2645     else if(_nTokenId == SQL_TOKEN_INSERT)
2646     {
2647         if ( _nPos == 2 || _nPos == 3 )
2648             nType = DataType::INTEGER;
2649     }
2650     else if(_nTokenId == SQL_TOKEN_LEFT)
2651     {
2652         if ( _nPos == 2 )
2653             nType = DataType::INTEGER;
2654     }
2655     else if(_nTokenId == SQL_TOKEN_LOCATE)
2656     {
2657         if ( _nPos == 3 )
2658             nType = DataType::INTEGER;
2659     }
2660     else if(_nTokenId == SQL_TOKEN_LOCATE_2)
2661     {
2662         if ( _nPos == 3 )
2663             nType = DataType::INTEGER;
2664     }
2665     else if( _nTokenId == SQL_TOKEN_REPEAT || _nTokenId == SQL_TOKEN_RIGHT )
2666     {
2667         if ( _nPos == 2 )
2668             nType = DataType::INTEGER;
2669     }
2670     else if(_nTokenId == SQL_TOKEN_SPACE )
2671     {
2672         nType = DataType::INTEGER;
2673     }
2674     else if(_nTokenId == SQL_TOKEN_SUBSTRING)
2675     {
2676         if ( _nPos != 1 )
2677             nType = DataType::INTEGER;
2678     }
2679     else if(_nTokenId == SQL_TOKEN_DATEDIFF)
2680     {
2681         if ( _nPos != 1 )
2682             nType = DataType::TIMESTAMP;
2683     }
2684     else if(_nTokenId == SQL_TOKEN_DATEVALUE)
2685         nType = DataType::DATE;
2686     else if(_nTokenId == SQL_TOKEN_DAYNAME)
2687         nType = DataType::DATE;
2688     else if(_nTokenId == SQL_TOKEN_DAYOFMONTH)
2689         nType = DataType::DATE;
2690     else if(_nTokenId == SQL_TOKEN_DAYOFWEEK)
2691         nType = DataType::DATE;
2692     else if(_nTokenId == SQL_TOKEN_DAYOFYEAR)
2693         nType = DataType::DATE;
2694     else if(_nTokenId == SQL_TOKEN_EXTRACT)              nType = DataType::VARCHAR;
2695     else if(_nTokenId == SQL_TOKEN_HOUR)                 nType = DataType::TIME;
2696     else if(_nTokenId == SQL_TOKEN_MINUTE)               nType = DataType::TIME;
2697     else if(_nTokenId == SQL_TOKEN_MONTH)                nType = DataType::DATE;
2698     else if(_nTokenId == SQL_TOKEN_MONTHNAME)            nType = DataType::DATE;
2699     else if(_nTokenId == SQL_TOKEN_NOW)                  nType = DataType::TIMESTAMP;
2700     else if(_nTokenId == SQL_TOKEN_QUARTER)              nType = DataType::DATE;
2701     else if(_nTokenId == SQL_TOKEN_SECOND)               nType = DataType::TIME;
2702     else if(_nTokenId == SQL_TOKEN_TIMESTAMPADD)         nType = DataType::TIMESTAMP;
2703     else if(_nTokenId == SQL_TOKEN_TIMESTAMPDIFF)        nType = DataType::TIMESTAMP;
2704     else if(_nTokenId == SQL_TOKEN_TIMEVALUE)            nType = DataType::TIMESTAMP;
2705     else if(_nTokenId == SQL_TOKEN_WEEK)                 nType = DataType::DATE;
2706     else if(_nTokenId == SQL_TOKEN_YEAR)                 nType = DataType::DATE;
2707 
2708     else if(_nTokenId == SQL_TOKEN_ABS)                  nType = DataType::DOUBLE;
2709     else if(_nTokenId == SQL_TOKEN_ACOS)                 nType = DataType::DOUBLE;
2710     else if(_nTokenId == SQL_TOKEN_ASIN)                 nType = DataType::DOUBLE;
2711     else if(_nTokenId == SQL_TOKEN_ATAN)                 nType = DataType::DOUBLE;
2712     else if(_nTokenId == SQL_TOKEN_ATAN2)                nType = DataType::DOUBLE;
2713     else if(_nTokenId == SQL_TOKEN_CEILING)              nType = DataType::DOUBLE;
2714     else if(_nTokenId == SQL_TOKEN_COS)                  nType = DataType::DOUBLE;
2715     else if(_nTokenId == SQL_TOKEN_COT)                  nType = DataType::DOUBLE;
2716     else if(_nTokenId == SQL_TOKEN_DEGREES)              nType = DataType::DOUBLE;
2717     else if(_nTokenId == SQL_TOKEN_EXP)                  nType = DataType::DOUBLE;
2718     else if(_nTokenId == SQL_TOKEN_FLOOR)                nType = DataType::DOUBLE;
2719     else if(_nTokenId == SQL_TOKEN_LOGF)                 nType = DataType::DOUBLE;
2720     else if(_nTokenId == SQL_TOKEN_LOG)                  nType = DataType::DOUBLE;
2721     else if(_nTokenId == SQL_TOKEN_LOG10)                nType = DataType::DOUBLE;
2722     else if(_nTokenId == SQL_TOKEN_LN)                   nType = DataType::DOUBLE;
2723     else if(_nTokenId == SQL_TOKEN_MOD)                  nType = DataType::DOUBLE;
2724     else if(_nTokenId == SQL_TOKEN_PI)                   nType = DataType::DOUBLE;
2725     else if(_nTokenId == SQL_TOKEN_POWER)                nType = DataType::DOUBLE;
2726     else if(_nTokenId == SQL_TOKEN_RADIANS)              nType = DataType::DOUBLE;
2727     else if(_nTokenId == SQL_TOKEN_RAND)                 nType = DataType::DOUBLE;
2728     else if(_nTokenId == SQL_TOKEN_ROUND)                nType = DataType::DOUBLE;
2729     else if(_nTokenId == SQL_TOKEN_ROUNDMAGIC)           nType = DataType::DOUBLE;
2730     else if(_nTokenId == SQL_TOKEN_SIGN)                 nType = DataType::DOUBLE;
2731     else if(_nTokenId == SQL_TOKEN_SIN)                  nType = DataType::DOUBLE;
2732     else if(_nTokenId == SQL_TOKEN_SQRT)                 nType = DataType::DOUBLE;
2733     else if(_nTokenId == SQL_TOKEN_TAN)                  nType = DataType::DOUBLE;
2734     else if(_nTokenId == SQL_TOKEN_TRUNCATE)             nType = DataType::DOUBLE;
2735     else if(_nTokenId == SQL_TOKEN_COUNT)                nType = DataType::INTEGER;
2736     else if(_nTokenId == SQL_TOKEN_MAX)                  nType = DataType::DOUBLE;
2737     else if(_nTokenId == SQL_TOKEN_MIN)                  nType = DataType::DOUBLE;
2738     else if(_nTokenId == SQL_TOKEN_AVG)                  nType = DataType::DOUBLE;
2739     else if(_nTokenId == SQL_TOKEN_SUM)                  nType = DataType::DOUBLE;
2740 
2741     else if(_nTokenId == SQL_TOKEN_LOWER)                nType = DataType::VARCHAR;
2742     else if(_nTokenId == SQL_TOKEN_UPPER)                nType = DataType::VARCHAR;
2743 
2744     return nType;
2745 }
2746 
2747 // -----------------------------------------------------------------------------
getErrorHelper() const2748 const SQLError& OSQLParser::getErrorHelper() const
2749 {
2750     return m_pData->aErrors;
2751 }
2752 
2753 // -----------------------------------------------------------------------------
getKnownRuleID() const2754 OSQLParseNode::Rule OSQLParseNode::getKnownRuleID() const
2755 {
2756     if ( !isRule() )
2757         return UNKNOWN_RULE;
2758     return OSQLParser::RuleIDToRule( getRuleID() );
2759 }
2760 // -----------------------------------------------------------------------------
getTableRange(const OSQLParseNode * _pTableRef)2761 ::rtl::OUString OSQLParseNode::getTableRange(const OSQLParseNode* _pTableRef)
2762 {
2763     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "parse", "Ocke.Janssen@sun.com", "OSQLParseNode::getTableRange" );
2764     OSL_ENSURE(_pTableRef && _pTableRef->count() > 1 && _pTableRef->getKnownRuleID() == OSQLParseNode::table_ref,"Invalid node give, only table ref is allowed!");
2765     const sal_uInt32 nCount = _pTableRef->count();
2766     ::rtl::OUString sTableRange;
2767     if ( nCount == 2 || (nCount == 3 && !_pTableRef->getChild(0)->isToken()) || nCount == 5 )
2768     {
2769         const OSQLParseNode* pNode = _pTableRef->getChild(nCount - (nCount == 2 ? 1 : 2));
2770         OSL_ENSURE(pNode && (pNode->getKnownRuleID() == OSQLParseNode::table_primary_as_range_column
2771                           || pNode->getKnownRuleID() == OSQLParseNode::range_variable)
2772                          ,"SQL grammar changed!");
2773         if ( !pNode->isLeaf() )
2774             sTableRange = pNode->getChild(1)->getTokenValue();
2775     } // if ( nCount == 2 || nCount == 3 || nCount == 5)
2776 
2777     return sTableRange;
2778 }
2779 // -----------------------------------------------------------------------------
OSQLParseNodesContainer()2780 OSQLParseNodesContainer::OSQLParseNodesContainer()
2781 {
2782 }
2783 // -----------------------------------------------------------------------------
~OSQLParseNodesContainer()2784 OSQLParseNodesContainer::~OSQLParseNodesContainer()
2785 {
2786 }
2787 // -----------------------------------------------------------------------------
push_back(OSQLParseNode * _pNode)2788 void OSQLParseNodesContainer::push_back(OSQLParseNode* _pNode)
2789 {
2790     ::osl::MutexGuard aGuard(m_aMutex);
2791     m_aNodes.push_back(_pNode);
2792 }
2793 // -----------------------------------------------------------------------------
erase(OSQLParseNode * _pNode)2794 void OSQLParseNodesContainer::erase(OSQLParseNode* _pNode)
2795 {
2796     ::osl::MutexGuard aGuard(m_aMutex);
2797     if ( !m_aNodes.empty() )
2798     {
2799         ::std::vector< OSQLParseNode* >::iterator aFind = ::std::find(m_aNodes.begin(), m_aNodes.end(),_pNode);
2800         if ( aFind != m_aNodes.end() )
2801             m_aNodes.erase(aFind);
2802     }
2803 }
2804 // -----------------------------------------------------------------------------
empty() const2805 bool OSQLParseNodesContainer::empty() const
2806 {
2807     return m_aNodes.empty();
2808 }
2809 // -----------------------------------------------------------------------------
clear()2810 void OSQLParseNodesContainer::clear()
2811 {
2812     ::osl::MutexGuard aGuard(m_aMutex);
2813     m_aNodes.clear();
2814 }
2815 // -----------------------------------------------------------------------------
clearAndDelete()2816 void OSQLParseNodesContainer::clearAndDelete()
2817 {
2818     ::osl::MutexGuard aGuard(m_aMutex);
2819     // clear the garbage collector
2820     while ( !m_aNodes.empty() )
2821     {
2822 	    OSQLParseNode* pNode = m_aNodes[0];
2823         while ( pNode->getParent() )
2824         {
2825             pNode = pNode->getParent();
2826         }
2827         delete pNode;
2828     }
2829 }
2830 }   // namespace connectivity
2831