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