1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_connectivity.hxx"
26 #include <osl/diagnose.h>
27 #include "file/FStatement.hxx"
28 #include "file/FConnection.hxx"
29 #include "file/FDriver.hxx"
30 #include "file/FResultSet.hxx"
31 #include <comphelper/property.hxx>
32 #include <comphelper/uno3.hxx>
33 #include <osl/thread.h>
34 #include <com/sun/star/sdbc/ResultSetConcurrency.hpp>
35 #include <com/sun/star/sdbc/ResultSetType.hpp>
36 #include <com/sun/star/sdbc/FetchDirection.hpp>
37 #include <com/sun/star/lang/DisposedException.hpp>
38 #include <comphelper/sequence.hxx>
39 #include <cppuhelper/typeprovider.hxx>
40 #include "connectivity/dbexception.hxx"
41 #include "resource/file_res.hrc"
42 #include <algorithm>
43 #include <tools/debug.hxx>
44 #include <rtl/logfile.hxx>
45 
46 #define THROW_SQL(x) \
47 	OTools::ThrowException(x,m_aStatementHandle,SQL_HANDLE_STMT,*this)
48 
49 namespace connectivity
50 {
51 	namespace file
52 	{
53 
54 //------------------------------------------------------------------------------
55 using namespace dbtools;
56 using namespace com::sun::star::uno;
57 using namespace com::sun::star::lang;
58 using namespace com::sun::star::beans;
59 using namespace com::sun::star::sdbc;
60 using namespace com::sun::star::sdbcx;
61 using namespace com::sun::star::container;
DBG_NAME(file_OStatement_Base)62 DBG_NAME( file_OStatement_Base )
63 
64 //------------------------------------------------------------------------------
65 OStatement_Base::OStatement_Base(OConnection* _pConnection )
66     :OStatement_BASE(m_aMutex)
67 	,::comphelper::OPropertyContainer(OStatement_BASE::rBHelper)
68     ,m_xDBMetaData(_pConnection->getMetaData())
69 	,m_aParser(_pConnection->getDriver()->getFactory())
70 	,m_aSQLIterator( _pConnection, _pConnection->createCatalog()->getTables(), m_aParser, NULL )
71     ,m_pConnection(_pConnection)
72     ,m_pParseTree(NULL)
73     ,m_pSQLAnalyzer(NULL)
74     ,m_pEvaluationKeySet(NULL)
75     ,m_pTable(NULL)
76 	,m_nMaxFieldSize(0)
77 	,m_nMaxRows(0)
78 	,m_nQueryTimeOut(0)
79 	,m_nFetchSize(0)
80 	,m_nResultSetType(ResultSetType::FORWARD_ONLY)
81 	,m_nFetchDirection(FetchDirection::FORWARD)
82 	,m_nResultSetConcurrency(ResultSetConcurrency::UPDATABLE)
83     ,m_bEscapeProcessing(sal_True)
84     ,rBHelper(OStatement_BASE::rBHelper)
85 {
86     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::OStatement_Base" );
87 	DBG_CTOR( file_OStatement_Base, NULL );
88 
89 	m_pConnection->acquire();
90 
91 	sal_Int32 nAttrib = 0;
92 
93 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME),		PROPERTY_ID_CURSORNAME,			nAttrib,&m_aCursorName,		::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
94 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_MAXFIELDSIZE),	PROPERTY_ID_MAXFIELDSIZE,		nAttrib,&m_nMaxFieldSize,		::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
95 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_MAXROWS),			PROPERTY_ID_MAXROWS,			nAttrib,&m_nMaxRows,		::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
96 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_QUERYTIMEOUT),	PROPERTY_ID_QUERYTIMEOUT,		nAttrib,&m_nQueryTimeOut,	::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
97 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE),		PROPERTY_ID_FETCHSIZE,			nAttrib,&m_nFetchSize,		::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
98 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE),	PROPERTY_ID_RESULTSETTYPE,		nAttrib,&m_nResultSetType,	::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
99 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION),	PROPERTY_ID_FETCHDIRECTION,		nAttrib,&m_nFetchDirection,	::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
100 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ESCAPEPROCESSING),PROPERTY_ID_ESCAPEPROCESSING,	nAttrib,&m_bEscapeProcessing,::getCppuBooleanType());
101 
102 	registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY),		PROPERTY_ID_RESULTSETCONCURRENCY,	nAttrib,&m_nResultSetConcurrency,		::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
103 }
104 // -----------------------------------------------------------------------------
~OStatement_Base()105 OStatement_Base::~OStatement_Base()
106 {
107 	osl_incrementInterlockedCount( &m_refCount );
108 	disposing();
109 	delete m_pSQLAnalyzer;
110 
111 	DBG_DTOR( file_OStatement_Base, NULL );
112 }
113 //------------------------------------------------------------------------------
disposeResultSet()114 void OStatement_Base::disposeResultSet()
115 {
116     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::disposeResultSet" );
117 	// free the cursor if alive
118     Reference< XComponent > xComp(m_xResultSet.get(), UNO_QUERY);
119 	if (xComp.is())
120 		xComp->dispose();
121     m_xResultSet = Reference< XResultSet>();
122 }
123 //------------------------------------------------------------------------------
disposing()124 void OStatement_BASE2::disposing()
125 {
126 	::osl::MutexGuard aGuard(m_aMutex);
127 
128 	disposeResultSet();
129 
130 	if(m_pSQLAnalyzer)
131 		m_pSQLAnalyzer->dispose();
132 
133 	if(m_aRow.isValid())
134 	{
135 		m_aRow->get().clear();
136 		m_aRow = NULL;
137 	}
138 
139 	m_aSQLIterator.dispose();
140 
141 	if(m_pTable)
142 	{
143 		m_pTable->release();
144 		m_pTable = NULL;
145 	}
146 
147 	if (m_pConnection)
148 	{
149 		m_pConnection->release();
150 		m_pConnection = NULL;
151 	}
152 
153 	dispose_ChildImpl();
154 
155 	if ( m_pParseTree )
156 	{
157 		delete m_pParseTree;
158 		m_pParseTree = NULL;
159 	}
160 
161 	OStatement_Base::disposing();
162 }
163 // -----------------------------------------------------------------------------
acquire()164 void SAL_CALL OStatement_Base::acquire() throw()
165 {
166 	OStatement_BASE::acquire();
167 }
168 //-----------------------------------------------------------------------------
release()169 void SAL_CALL OStatement_BASE2::release() throw()
170 {
171 	relase_ChildImpl();
172 }
173 //-----------------------------------------------------------------------------
queryInterface(const Type & rType)174 Any SAL_CALL OStatement_Base::queryInterface( const Type & rType ) throw(RuntimeException)
175 {
176     //RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::queryInterface" );
177     const Any aRet = OStatement_BASE::queryInterface(rType);
178 	return aRet.hasValue() ? aRet : OPropertySetHelper::queryInterface(rType);
179 }
180 // -------------------------------------------------------------------------
getTypes()181 Sequence< Type > SAL_CALL OStatement_Base::getTypes(  ) throw(RuntimeException)
182 {
183     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::getTypes" );
184     ::cppu::OTypeCollection aTypes( ::getCppuType( (const Reference< ::com::sun::star::beans::XMultiPropertySet > *)0 ),
185                                                                     ::getCppuType( (const Reference< ::com::sun::star::beans::XFastPropertySet > *)0 ),
186                                                                     ::getCppuType( (const Reference< ::com::sun::star::beans::XPropertySet > *)0 ));
187 
188 	return ::comphelper::concatSequences(aTypes.getTypes(),OStatement_BASE::getTypes());
189 }
190 // -------------------------------------------------------------------------
191 
cancel()192 void SAL_CALL OStatement_Base::cancel(  ) throw(RuntimeException)
193 {
194     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::cancel" );
195 }
196 // -------------------------------------------------------------------------
197 
close()198 void SAL_CALL OStatement_Base::close(  ) throw(SQLException, RuntimeException)
199 {
200     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::close" );
201 	{
202 		::osl::MutexGuard aGuard( m_aMutex );
203 		checkDisposed(OStatement_BASE::rBHelper.bDisposed);
204 	}
205 	dispose();
206 }
207 // -------------------------------------------------------------------------
208 
reset()209 void OStatement_Base::reset() throw (SQLException)
210 {
211     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::reset" );
212 	::osl::MutexGuard aGuard( m_aMutex );
213 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
214 
215 
216 	clearWarnings ();
217 
218 	if (m_xResultSet.get().is())
219 		clearMyResultSet();
220 }
221 //--------------------------------------------------------------------
222 // clearMyResultSet
223 // If a ResultSet was created for this Statement, close it
224 //--------------------------------------------------------------------
225 
clearMyResultSet()226 void OStatement_Base::clearMyResultSet () throw (SQLException)
227 {
228     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::clearMyResultSet " );
229 	::osl::MutexGuard aGuard( m_aMutex );
230 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
231 
232     try
233     {
234         Reference<XCloseable> xCloseable;
235         if ( ::comphelper::query_interface( m_xResultSet.get(), xCloseable ) )
236             xCloseable->close();
237     }
238     catch( const DisposedException& ) { }
239 
240 	m_xResultSet = Reference< XResultSet>();
241 }
242 //--------------------------------------------------------------------
243 // setWarning
244 // Sets the warning
245 //--------------------------------------------------------------------
246 
setWarning(const SQLWarning & ex)247 void OStatement_Base::setWarning (const SQLWarning &ex) throw( SQLException)
248 {
249     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::setWarning " );
250 	::osl::MutexGuard aGuard( m_aMutex );
251 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
252 
253 
254 	m_aLastWarning = ex;
255 }
256 
257 // -------------------------------------------------------------------------
getWarnings()258 Any SAL_CALL OStatement_Base::getWarnings(  ) throw(SQLException, RuntimeException)
259 {
260     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::getWarnings" );
261 	::osl::MutexGuard aGuard( m_aMutex );
262 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
263 
264 	return makeAny(m_aLastWarning);
265 }
266 // -------------------------------------------------------------------------
clearWarnings()267 void SAL_CALL OStatement_Base::clearWarnings(  ) throw(SQLException, RuntimeException)
268 {
269     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::clearWarnings" );
270 	::osl::MutexGuard aGuard( m_aMutex );
271 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
272 
273 	m_aLastWarning = SQLWarning();
274 }
275 // -------------------------------------------------------------------------
createArrayHelper() const276 ::cppu::IPropertyArrayHelper* OStatement_Base::createArrayHelper( ) const
277 {
278     //RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::createArrayHelper" );
279 	Sequence< Property > aProps;
280 	describeProperties(aProps);
281 	return new ::cppu::OPropertyArrayHelper(aProps);
282 }
283 
284 // -------------------------------------------------------------------------
getInfoHelper()285 ::cppu::IPropertyArrayHelper & OStatement_Base::getInfoHelper()
286 {
287     //RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::getInfoHelper" );
288 	return *const_cast<OStatement_Base*>(this)->getArrayHelper();
289 }
290 // -------------------------------------------------------------------------
createResultSet()291 OResultSet* OStatement::createResultSet()
292 {
293 	return new OResultSet(this,m_aSQLIterator);
294 }
295 // -------------------------------------------------------------------------
296 IMPLEMENT_SERVICE_INFO(OStatement,"com.sun.star.sdbc.driver.file.Statement","com.sun.star.sdbc.Statement");
297 // -----------------------------------------------------------------------------
acquire()298 void SAL_CALL OStatement::acquire() throw()
299 {
300 	OStatement_BASE2::acquire();
301 }
302 // -----------------------------------------------------------------------------
release()303 void SAL_CALL OStatement::release() throw()
304 {
305 	OStatement_BASE2::release();
306 }
307 // -----------------------------------------------------------------------------
308 // -------------------------------------------------------------------------
execute(const::rtl::OUString & sql)309 sal_Bool SAL_CALL OStatement::execute( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
310 {
311 	::osl::MutexGuard aGuard( m_aMutex );
312 
313     executeQuery(sql);
314 
315 	return m_aSQLIterator.getStatementType() == SQL_STATEMENT_SELECT;
316 }
317 
318 // -------------------------------------------------------------------------
319 
executeQuery(const::rtl::OUString & sql)320 Reference< XResultSet > SAL_CALL OStatement::executeQuery( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
321 {
322 	::osl::MutexGuard aGuard( m_aMutex );
323 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
324 
325     construct(sql);
326     Reference< XResultSet > xRS;
327 	OResultSet* pResult = createResultSet();
328 	xRS = pResult;
329 	initializeResultSet(pResult);
330     m_xResultSet = Reference<XResultSet>(pResult);
331 
332 	pResult->OpenImpl();
333 
334 	return xRS;
335 }
336 // -------------------------------------------------------------------------
getConnection()337 Reference< XConnection > SAL_CALL OStatement::getConnection(  ) throw(SQLException, RuntimeException)
338 {
339 	return (Reference< XConnection >)m_pConnection;
340 }
341 // -------------------------------------------------------------------------
executeUpdate(const::rtl::OUString & sql)342 sal_Int32 SAL_CALL OStatement::executeUpdate( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
343 {
344 	::osl::MutexGuard aGuard( m_aMutex );
345 	checkDisposed(OStatement_BASE::rBHelper.bDisposed);
346 
347 
348 	construct(sql);
349 	OResultSet* pResult = createResultSet();
350 	Reference< XResultSet > xRS = pResult;
351 	initializeResultSet(pResult);
352 	pResult->OpenImpl();
353 
354 	return pResult->getRowCountResult();
355 }
356 
357 // -----------------------------------------------------------------------------
disposing(void)358 void SAL_CALL OStatement_Base::disposing(void)
359 {
360     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::disposing" );
361 	if(m_aEvaluateRow.isValid())
362 	{
363 		m_aEvaluateRow->get().clear();
364 		m_aEvaluateRow = NULL;
365 	}
366 	delete m_pEvaluationKeySet;
367 	OStatement_BASE::disposing();
368 }
369 // -----------------------------------------------------------------------------
getPropertySetInfo()370 Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OStatement_Base::getPropertySetInfo(  ) throw(RuntimeException)
371 {
372     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::getPropertySetInfo" );
373 	return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
374 }
375 // -----------------------------------------------------------------------------
queryInterface(const Type & rType)376 Any SAL_CALL OStatement::queryInterface( const Type & rType ) throw(RuntimeException)
377 {
378 	Any aRet = OStatement_XStatement::queryInterface( rType);
379 	return aRet.hasValue() ? aRet : OStatement_BASE2::queryInterface( rType);
380 }
381 // -----------------------------------------------------------------------------
createAnalyzer()382 OSQLAnalyzer* OStatement_Base::createAnalyzer()
383 {
384     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::createAnalyzer" );
385 	return new OSQLAnalyzer(m_pConnection);
386 }
387 // -----------------------------------------------------------------------------
anylizeSQL()388 void OStatement_Base::anylizeSQL()
389 {
390     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::anylizeSQL" );
391 	OSL_ENSURE(m_pSQLAnalyzer,"OResultSet::anylizeSQL: Analyzer isn't set!");
392 	// start analysing the statement
393 	m_pSQLAnalyzer->setOrigColumns(m_xColNames);
394 	m_pSQLAnalyzer->start(m_pParseTree);
395 
396 	const OSQLParseNode* pOrderbyClause = m_aSQLIterator.getOrderTree();
397 	if(pOrderbyClause)
398 	{
399 		OSQLParseNode * pOrderingSpecCommalist = pOrderbyClause->getChild(2);
400 		OSL_ENSURE(SQL_ISRULE(pOrderingSpecCommalist,ordering_spec_commalist),"OResultSet: Fehler im Parse Tree");
401 
402 		for (sal_uInt32 m = 0; m < pOrderingSpecCommalist->count(); m++)
403 		{
404 			OSQLParseNode * pOrderingSpec = pOrderingSpecCommalist->getChild(m);
405 			OSL_ENSURE(SQL_ISRULE(pOrderingSpec,ordering_spec),"OResultSet: Fehler im Parse Tree");
406 			OSL_ENSURE(pOrderingSpec->count() == 2,"OResultSet: Fehler im Parse Tree");
407 
408 			OSQLParseNode * pColumnRef = pOrderingSpec->getChild(0);
409 			if(!SQL_ISRULE(pColumnRef,column_ref))
410 			{
411 				throw SQLException();
412 			}
413 			OSQLParseNode * pAscendingDescending = pOrderingSpec->getChild(1);
414 			setOrderbyColumn(pColumnRef,pAscendingDescending);
415 		}
416 	}
417 }
418 //------------------------------------------------------------------
setOrderbyColumn(OSQLParseNode * pColumnRef,OSQLParseNode * pAscendingDescending)419 void OStatement_Base::setOrderbyColumn(	OSQLParseNode* pColumnRef,
420 										OSQLParseNode* pAscendingDescending)
421 {
422     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::setOrderbyColumn" );
423 	::rtl::OUString aColumnName;
424 	if (pColumnRef->count() == 1)
425 		aColumnName = pColumnRef->getChild(0)->getTokenValue();
426 	else if (pColumnRef->count() == 3)
427 	{
428 		// Nur die Table Range-Variable darf hier vorkommen:
429 //		if (!(pColumnRef->getChild(0)->getTokenValue() == aTableRange))
430 //		{
431 //			aStatus.Set(SQL_STAT_ERROR,
432 //						String::CreateFromAscii("S1000"),
433 //						aStatus.CreateErrorMessage(String(SdbResId(STR_STAT_INVALID_RANGE_VAR))),
434 //						0, String() );
435 			//	return;
436 		//	}
437 		pColumnRef->getChild(2)->parseNodeToStr( aColumnName, getOwnConnection(), NULL, sal_False, sal_False );
438 	}
439 	else
440 	{
441 		//	aStatus.SetStatementTooComplex();
442 		throw SQLException();
443 	}
444 
445 	Reference<XColumnLocate> xColLocate(m_xColNames,UNO_QUERY);
446 	if(!xColLocate.is())
447 		return;
448 	// Alles geprueft und wir haben den Namen der Column.
449 	// Die wievielte Column ist das?
450 	::vos::ORef<OSQLColumns> aSelectColumns = m_aSQLIterator.getSelectColumns();
451 	::comphelper::UStringMixEqual aCase;
452 	OSQLColumns::Vector::const_iterator aFind = ::connectivity::find(aSelectColumns->get().begin(),aSelectColumns->get().end(),aColumnName,aCase);
453 	if ( aFind == aSelectColumns->get().end() )
454 		throw SQLException();
455 	m_aOrderbyColumnNumber.push_back((aFind - aSelectColumns->get().begin()) + 1);
456 
457 	// Ascending or Descending?
458 	m_aOrderbyAscending.push_back((SQL_ISTOKEN(pAscendingDescending,DESC)) ? SQL_DESC : SQL_ASC);
459 }
460 
461 // -----------------------------------------------------------------------------
construct(const::rtl::OUString & sql)462 void OStatement_Base::construct(const ::rtl::OUString& sql)  throw(SQLException, RuntimeException)
463 {
464     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::construct" );
465 	::rtl::OUString aErr;
466 	m_pParseTree = m_aParser.parseTree(aErr,sql);
467 	if(m_pParseTree)
468 	{
469 		m_aSQLIterator.setParseTree(m_pParseTree);
470 		m_aSQLIterator.traverseAll();
471 		const OSQLTables& xTabs = m_aSQLIterator.getTables();
472 
473         // sanity checks
474 		if ( xTabs.empty() )
475             // no tables -> nothing to operate on -> error
476             m_pConnection->throwGenericSQLException(STR_QUERY_NO_TABLE,*this);
477 
478         if ( xTabs.size() > 1 || m_aSQLIterator.hasErrors() )
479             // more than one table -> can't operate on them -> error
480             m_pConnection->throwGenericSQLException(STR_QUERY_MORE_TABLES,*this);
481 
482 		if ( (m_aSQLIterator.getStatementType() == SQL_STATEMENT_SELECT) && m_aSQLIterator.getSelectColumns()->get().empty() )
483             // SELECT statement without columns -> error
484             m_pConnection->throwGenericSQLException(STR_QUERY_NO_COLUMN,*this);
485 
486 		switch(m_aSQLIterator.getStatementType())
487 		{
488 			case SQL_STATEMENT_CREATE_TABLE:
489 			case SQL_STATEMENT_ODBC_CALL:
490 			case SQL_STATEMENT_UNKNOWN:
491 				m_pConnection->throwGenericSQLException(STR_QUERY_TOO_COMPLEX,*this);
492 				break;
493 			default:
494 				break;
495 		}
496 
497 		// at this moment we support only one table per select statement
498 		Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(xTabs.begin()->second,UNO_QUERY);
499 		if(xTunnel.is())
500 		{
501 			if(m_pTable)
502 				m_pTable->release();
503 			m_pTable = reinterpret_cast<OFileTable*>(xTunnel->getSomething(OFileTable::getUnoTunnelImplementationId()));
504 			if(m_pTable)
505 				m_pTable->acquire();
506 		}
507 		OSL_ENSURE(m_pTable,"No table!");
508         if ( m_pTable )
509 		    m_xColNames		= m_pTable->getColumns();
510 		Reference<XIndexAccess> xNames(m_xColNames,UNO_QUERY);
511 		// set the binding of the resultrow
512 		m_aRow			= new OValueRefVector(xNames->getCount());
513 		(m_aRow->get())[0]->setBound(sal_True);
514 		::std::for_each(m_aRow->get().begin()+1,m_aRow->get().end(),TSetRefBound(sal_False));
515 
516 		// set the binding of the resultrow
517 		m_aEvaluateRow	= new OValueRefVector(xNames->getCount());
518 
519 		(m_aEvaluateRow->get())[0]->setBound(sal_True);
520 		::std::for_each(m_aEvaluateRow->get().begin()+1,m_aEvaluateRow->get().end(),TSetRefBound(sal_False));
521 
522 		// set the select row
523 		m_aSelectRow = new OValueRefVector(m_aSQLIterator.getSelectColumns()->get().size());
524 		::std::for_each(m_aSelectRow->get().begin(),m_aSelectRow->get().end(),TSetRefBound(sal_True));
525 
526 		// create the column mapping
527 		createColumnMapping();
528 
529 		m_pSQLAnalyzer	= createAnalyzer();
530 
531 		Reference<XIndexesSupplier> xIndexSup(xTunnel,UNO_QUERY);
532 		if(xIndexSup.is())
533 			m_pSQLAnalyzer->setIndexes(xIndexSup->getIndexes());
534 
535 		anylizeSQL();
536 	}
537 	else
538 		throw SQLException(aErr,*this,::rtl::OUString(),0,Any());
539 }
540 // -----------------------------------------------------------------------------
createColumnMapping()541 void OStatement_Base::createColumnMapping()
542 {
543     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::createColumnMapping" );
544 	// initialize the column index map (mapping select columns to table columns)
545 	::vos::ORef<connectivity::OSQLColumns>	xColumns = m_aSQLIterator.getSelectColumns();
546 	m_aColMapping.resize(xColumns->get().size() + 1);
547 	for (sal_Int32 i=0; i<(sal_Int32)m_aColMapping.size(); ++i)
548 		m_aColMapping[i] = i;
549 
550 	Reference<XIndexAccess> xNames(m_xColNames,UNO_QUERY);
551 	// now check which columns are bound
552 	OResultSet::setBoundedColumns(m_aRow,m_aSelectRow,xColumns,xNames,sal_True,m_xDBMetaData,m_aColMapping);
553 }
554 // -----------------------------------------------------------------------------
initializeResultSet(OResultSet * _pResult)555 void OStatement_Base::initializeResultSet(OResultSet* _pResult)
556 {
557     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::initializeResultSet" );
558 	GetAssignValues();
559 
560 	_pResult->setSqlAnalyzer(m_pSQLAnalyzer);
561 	_pResult->setOrderByColumns(m_aOrderbyColumnNumber);
562 	_pResult->setOrderByAscending(m_aOrderbyAscending);
563 	_pResult->setBindingRow(m_aRow);
564 	_pResult->setColumnMapping(m_aColMapping);
565 	_pResult->setEvaluationRow(m_aEvaluateRow);
566 	_pResult->setAssignValues(m_aAssignValues);
567 	_pResult->setSelectRow(m_aSelectRow);
568 
569 	m_pSQLAnalyzer->bindSelectRow(m_aRow);
570 	m_pEvaluationKeySet = m_pSQLAnalyzer->bindEvaluationRow(m_aEvaluateRow);	// Werte im Code des Compilers setzen
571 	_pResult->setEvaluationKeySet(m_pEvaluationKeySet);
572 }
573 // -----------------------------------------------------------------------------
GetAssignValues()574 void OStatement_Base::GetAssignValues()
575 {
576     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::GetAssignValues" );
577 	if (m_pParseTree == NULL)
578 	{
579 		::dbtools::throwFunctionSequenceException(*this);
580 		return;
581 	}
582 
583 	if (SQL_ISRULE(m_pParseTree,select_statement))
584 		// Keine zu setzenden Werte bei SELECT
585 		return;
586 	else if (SQL_ISRULE(m_pParseTree,insert_statement))
587 	{
588 		// Row fuer die zu setzenden Werte anlegen (Referenz durch new)
589 		if(m_aAssignValues.isValid())
590 			m_aAssignValues->get().clear();
591 		sal_Int32 nCount = Reference<XIndexAccess>(m_xColNames,UNO_QUERY)->getCount();
592 		m_aAssignValues = new OAssignValues(nCount);
593 		// unbound all
594 		::std::for_each(m_aAssignValues->get().begin()+1,m_aAssignValues->get().end(),TSetRefBound(sal_False));
595 
596 		m_aParameterIndexes.resize(nCount+1,SQL_NO_PARAMETER);
597 
598 		// Liste der Columns-Namen, die in der column_commalist vorkommen (mit ; getrennt):
599 		::std::vector<String> aColumnNameList;
600 
601 		OSL_ENSURE(m_pParseTree->count() >= 4,"OResultSet: Fehler im Parse Tree");
602 
603 		OSQLParseNode * pOptColumnCommalist = m_pParseTree->getChild(3);
604 		OSL_ENSURE(pOptColumnCommalist != NULL,"OResultSet: Fehler im Parse Tree");
605 		OSL_ENSURE(SQL_ISRULE(pOptColumnCommalist,opt_column_commalist),"OResultSet: Fehler im Parse Tree");
606 		if (pOptColumnCommalist->count() == 0)
607 		{
608 			const Sequence< ::rtl::OUString>& aNames = m_xColNames->getElementNames();
609 			const ::rtl::OUString* pBegin = aNames.getConstArray();
610 			const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
611             for (; pBegin != pEnd; ++pBegin)
612                 aColumnNameList.push_back(*pBegin);
613 		}
614 		else
615 		{
616 			OSL_ENSURE(pOptColumnCommalist->count() == 3,"OResultSet: Fehler im Parse Tree");
617 
618 			OSQLParseNode * pColumnCommalist = pOptColumnCommalist->getChild(1);
619 			OSL_ENSURE(pColumnCommalist != NULL,"OResultSet: Fehler im Parse Tree");
620 			OSL_ENSURE(SQL_ISRULE(pColumnCommalist,column_commalist),"OResultSet: Fehler im Parse Tree");
621 			OSL_ENSURE(pColumnCommalist->count() > 0,"OResultSet: Fehler im Parse Tree");
622 
623 			// Alle Columns in der column_commalist ...
624 			for (sal_uInt32 i = 0; i < pColumnCommalist->count(); i++)
625 			{
626 				OSQLParseNode * pCol = pColumnCommalist->getChild(i);
627 				OSL_ENSURE(pCol != NULL,"OResultSet: Fehler im Parse Tree");
628 				aColumnNameList.push_back(pCol->getTokenValue());
629 			}
630 		}
631 		if ( aColumnNameList.empty() )
632 			throwFunctionSequenceException(*this);
633 
634 		// Werte ...
635 		OSQLParseNode * pValuesOrQuerySpec = m_pParseTree->getChild(4);
636 		OSL_ENSURE(pValuesOrQuerySpec != NULL,"OResultSet: pValuesOrQuerySpec darf nicht NULL sein!");
637 		OSL_ENSURE(SQL_ISRULE(pValuesOrQuerySpec,values_or_query_spec),"OResultSet: ! SQL_ISRULE(pValuesOrQuerySpec,values_or_query_spec)");
638 		OSL_ENSURE(pValuesOrQuerySpec->count() > 0,"OResultSet: pValuesOrQuerySpec->count() <= 0");
639 
640 		// nur "VALUES" ist erlaubt ...
641 		if (! SQL_ISTOKEN(pValuesOrQuerySpec->getChild(0),VALUES))
642 			throwFunctionSequenceException(*this);
643 
644 		OSL_ENSURE(pValuesOrQuerySpec->count() == 4,"OResultSet: pValuesOrQuerySpec->count() != 4");
645 
646 		// Liste von Werten
647 		OSQLParseNode * pInsertAtomCommalist = pValuesOrQuerySpec->getChild(2);
648 		OSL_ENSURE(pInsertAtomCommalist != NULL,"OResultSet: pInsertAtomCommalist darf nicht NULL sein!");
649 		OSL_ENSURE(pInsertAtomCommalist->count() > 0,"OResultSet: pInsertAtomCommalist <= 0");
650 
651 		String aColumnName;
652 		OSQLParseNode * pRow_Value_Const;
653 		xub_StrLen nIndex=0;
654 		for (sal_uInt32 i = 0; i < pInsertAtomCommalist->count(); i++)
655 		{
656 			pRow_Value_Const = pInsertAtomCommalist->getChild(i); // row_value_constructor
657 			OSL_ENSURE(pRow_Value_Const != NULL,"OResultSet: pRow_Value_Const darf nicht NULL sein!");
658 			if(SQL_ISRULE(pRow_Value_Const,parameter))
659 			{
660 				ParseAssignValues(aColumnNameList,pRow_Value_Const,nIndex++); // kann nur ein Columnname vorhanden sein pro Schleife
661 			}
662 			else if(pRow_Value_Const->isToken())
663 				ParseAssignValues(aColumnNameList,pRow_Value_Const,static_cast<xub_StrLen>(i));
664 			else
665 			{
666 				if(pRow_Value_Const->count() == aColumnNameList.size())
667 				{
668 					for (sal_uInt32 j = 0; j < pRow_Value_Const->count(); ++j)
669 						ParseAssignValues(aColumnNameList,pRow_Value_Const->getChild(j),nIndex++);
670 				}
671 				else
672 					throwFunctionSequenceException(*this);
673 			}
674 		}
675 	}
676 	else if (SQL_ISRULE(m_pParseTree,update_statement_searched))
677 	{
678 		if(m_aAssignValues.isValid())
679 			m_aAssignValues->get().clear();
680 		sal_Int32 nCount = Reference<XIndexAccess>(m_xColNames,UNO_QUERY)->getCount();
681 		m_aAssignValues = new OAssignValues(nCount);
682 		// unbound all
683 		::std::for_each(m_aAssignValues->get().begin()+1,m_aAssignValues->get().end(),TSetRefBound(sal_False));
684 
685 		m_aParameterIndexes.resize(nCount+1,SQL_NO_PARAMETER);
686 
687 		OSL_ENSURE(m_pParseTree->count() >= 4,"OResultSet: Fehler im Parse Tree");
688 
689 		OSQLParseNode * pAssignmentCommalist = m_pParseTree->getChild(3);
690 		OSL_ENSURE(pAssignmentCommalist != NULL,"OResultSet: pAssignmentCommalist == NULL");
691 		OSL_ENSURE(SQL_ISRULE(pAssignmentCommalist,assignment_commalist),"OResultSet: Fehler im Parse Tree");
692 		OSL_ENSURE(pAssignmentCommalist->count() > 0,"OResultSet: pAssignmentCommalist->count() <= 0");
693 
694 		// Alle Zuweisungen (Kommaliste) bearbeiten ...
695 		::std::vector< String> aList(1);
696 		for (sal_uInt32 i = 0; i < pAssignmentCommalist->count(); i++)
697 		{
698 			OSQLParseNode * pAssignment = pAssignmentCommalist->getChild(i);
699 			OSL_ENSURE(pAssignment != NULL,"OResultSet: pAssignment == NULL");
700 			OSL_ENSURE(SQL_ISRULE(pAssignment,assignment),"OResultSet: Fehler im Parse Tree");
701 			OSL_ENSURE(pAssignment->count() == 3,"OResultSet: pAssignment->count() != 3");
702 
703 			OSQLParseNode * pCol = pAssignment->getChild(0);
704 			OSL_ENSURE(pCol != NULL,"OResultSet: pCol == NULL");
705 
706 			OSQLParseNode * pComp = pAssignment->getChild(1);
707 			OSL_ENSURE(pComp != NULL,"OResultSet: pComp == NULL");
708 			OSL_ENSURE(pComp->getNodeType() == SQL_NODE_EQUAL,"OResultSet: pComp->getNodeType() != SQL_NODE_COMPARISON");
709 			if (pComp->getTokenValue().toChar() != '=')
710 			{
711 				//	aStatus.SetInvalidStatement();
712 				throwFunctionSequenceException(*this);
713 			}
714 
715 			OSQLParseNode * pVal = pAssignment->getChild(2);
716 			OSL_ENSURE(pVal != NULL,"OResultSet: pVal == NULL");
717 			aList[0] = pCol->getTokenValue();
718 			ParseAssignValues(aList,pVal,0);
719 		}
720 
721 	}
722 }
723 // -------------------------------------------------------------------------
ParseAssignValues(const::std::vector<String> & aColumnNameList,OSQLParseNode * pRow_Value_Constructor_Elem,xub_StrLen nIndex)724 void OStatement_Base::ParseAssignValues(const ::std::vector< String>& aColumnNameList,OSQLParseNode* pRow_Value_Constructor_Elem,xub_StrLen nIndex)
725 {
726     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::ParseAssignValues" );
727 	OSL_ENSURE(nIndex <= aColumnNameList.size(),"SdbFileCursor::ParseAssignValues: nIndex > aColumnNameList.GetTokenCount()");
728 	String aColumnName(aColumnNameList[nIndex]);
729 	OSL_ENSURE(aColumnName.Len() > 0,"OResultSet: Column-Name nicht gefunden");
730 	OSL_ENSURE(pRow_Value_Constructor_Elem != NULL,"OResultSet: pRow_Value_Constructor_Elem darf nicht NULL sein!");
731 
732 	if (pRow_Value_Constructor_Elem->getNodeType() == SQL_NODE_STRING ||
733 		pRow_Value_Constructor_Elem->getNodeType() == SQL_NODE_INTNUM ||
734 		pRow_Value_Constructor_Elem->getNodeType() == SQL_NODE_APPROXNUM)
735 	{
736 		// Wert setzen:
737 		SetAssignValue(aColumnName, pRow_Value_Constructor_Elem->getTokenValue());
738 	}
739 	else if (SQL_ISTOKEN(pRow_Value_Constructor_Elem,NULL))
740 	{
741 		// NULL setzen
742 		SetAssignValue(aColumnName, String(), sal_True);
743 	}
744 	else if (SQL_ISRULE(pRow_Value_Constructor_Elem,parameter))
745 		parseParamterElem(aColumnName,pRow_Value_Constructor_Elem);
746 	else
747 	{
748 		//	aStatus.SetStatementTooComplex();
749 		throwFunctionSequenceException(*this);
750 	}
751 }
752 //------------------------------------------------------------------
SetAssignValue(const String & aColumnName,const String & aValue,sal_Bool bSetNull,sal_uInt32 nParameter)753 void OStatement_Base::SetAssignValue(const String& aColumnName,
754 								   const String& aValue,
755 								   sal_Bool bSetNull,
756 								   sal_uInt32 nParameter)
757 {
758     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::SetAssignValue" );
759 	Reference<XPropertySet> xCol;
760 	m_xColNames->getByName(aColumnName) >>= xCol;
761 	sal_Int32 nId = Reference<XColumnLocate>(m_xColNames,UNO_QUERY)->findColumn(aColumnName);
762 	// Kommt diese Column ueberhaupt in der Datei vor?
763 
764 	if (!xCol.is())
765 	{
766 		// Diese Column gibt es nicht!
767 //		aStatus.Set(SQL_STAT_ERROR,
768 //					String::CreateFromAscii("S0022"),
769 //					aStatus.CreateErrorMessage(String(SdbResId(STR_STAT_COLUMN_NOT_FOUND))),
770 //					0, String() );
771 		throwFunctionSequenceException(*this);
772 	}
773 
774 	// Value an die Row mit den zuzuweisenden Werten binden:
775 	//	const ODbVariantRef& xValue = (*aAssignValues)[pFileColumn->GetId()];
776 
777 	// Alles geprueft und wir haben den Namen der Column.
778 	// Jetzt eine Value allozieren, den Wert setzen und die Value an die Row binden.
779 	if (bSetNull)
780 		(m_aAssignValues->get())[nId]->setNull();
781 	else
782 	{
783 		switch (::comphelper::getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))))
784 		{
785 			// Kriterium je nach Typ als String oder double in die Variable packen ...
786 			case DataType::CHAR:
787 			case DataType::VARCHAR:
788             case DataType::LONGVARCHAR:
789 				*(m_aAssignValues->get())[nId] = ORowSetValue(aValue);
790 				// Zeichensatz ist bereits konvertiert, da ja das gesamte Statement konvertiert wurde
791 				break;
792 
793 			case DataType::BIT:
794 				{
795 					if (aValue.EqualsIgnoreCaseAscii("TRUE")  || aValue.GetChar(0) == '1')
796 						*(m_aAssignValues->get())[nId] = sal_True;
797 					else if (aValue.EqualsIgnoreCaseAscii("FALSE") || aValue.GetChar(0) == '0')
798 						*(m_aAssignValues->get())[nId] = sal_False;
799 					else
800 					{
801 						//	aStatus.Set(SQL_STAT_ERROR);	// nyi: genauer!
802 						throwFunctionSequenceException(*this);
803 					}
804 				}
805 				break;
806 			case DataType::TINYINT:
807 			case DataType::SMALLINT:
808 			case DataType::INTEGER:
809 			case DataType::DECIMAL:
810 			case DataType::NUMERIC:
811 			case DataType::REAL:
812 			case DataType::DOUBLE:
813 			case DataType::DATE:
814 			case DataType::TIME:
815 			case DataType::TIMESTAMP:
816 			{
817 				*(m_aAssignValues->get())[nId] = ORowSetValue(aValue); // .ToDouble
818 //				try
819 //				{
820 //					double n = xValue->toDouble();
821 //					xValue->setDouble(n);
822 //				}
823 //				catch ( ... )
824 //				{
825 //					aStatus.SetDriverNotCapableError();
826 //				}
827 			}	break;
828 			default:
829 				throwFunctionSequenceException(*this);
830 		}
831 	}
832 
833 	// Parameter-Nr. merken (als User Data)
834 	// SQL_NO_PARAMETER = kein Parameter.
835 	m_aAssignValues->setParameterIndex(nId,nParameter);
836 	if(nParameter != SQL_NO_PARAMETER)
837 		m_aParameterIndexes[nParameter] = nId;
838 }
839 // -----------------------------------------------------------------------------
parseParamterElem(const String &,OSQLParseNode *)840 void OStatement_Base::parseParamterElem(const String& /*_sColumnName*/,OSQLParseNode* /*pRow_Value_Constructor_Elem*/)
841 {
842     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "file", "Ocke.Janssen@sun.com", "OStatement_Base::parseParamterElem" );
843 	// do nothing here
844 }
845 // =============================================================================
846 	} // namespace file
847 // =============================================================================
848 }// namespace connectivity
849 // -----------------------------------------------------------------------------
850