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 #include "connectivity/CommonTools.hxx"
32 #include "diagnose_ex.h"
33 #include "TConnection.hxx"
34 #include "connectivity/ParameterCont.hxx"
35 
36 /** === begin UNO includes === **/
37 #include <com/sun/star/awt/XWindow.hpp>
38 #include <com/sun/star/beans/PropertyAttribute.hpp>
39 #include <com/sun/star/container/XChild.hpp>
40 #include <com/sun/star/form/FormComponentType.hpp>
41 #include <com/sun/star/io/XInputStream.hpp>
42 #include <com/sun/star/lang/DisposedException.hpp>
43 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
44 #include <com/sun/star/sdb/BooleanComparisonMode.hpp>
45 #include <com/sun/star/sdb/CommandType.hpp>
46 #include <com/sun/star/sdb/ParametersRequest.hpp>
47 #include <com/sun/star/sdb/RowSetVetoException.hpp>
48 #include <com/sun/star/sdb/SQLContext.hpp>
49 #include <com/sun/star/sdb/XCompletedConnection.hpp>
50 #include <com/sun/star/sdb/XInteractionSupplyParameters.hpp>
51 #include <com/sun/star/sdb/XOfficeDatabaseDocument.hpp>
52 #include <com/sun/star/sdb/XParametersSupplier.hpp>
53 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
54 #include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
55 #include <com/sun/star/sdbc/DataType.hpp>
56 #include <com/sun/star/sdbc/XConnection.hpp>
57 #include <com/sun/star/sdbc/XDataSource.hpp>
58 #include <com/sun/star/sdbc/XDriverManager.hpp>
59 #include <com/sun/star/sdbc/XParameters.hpp>
60 #include <com/sun/star/sdbc/XRow.hpp>
61 #include <com/sun/star/sdbc/XRowSet.hpp>
62 #include <com/sun/star/sdbc/XRowUpdate.hpp>
63 #include <com/sun/star/sdbcx/KeyType.hpp>
64 #include <com/sun/star/sdbcx/Privilege.hpp>
65 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
66 #include <com/sun/star/sdbcx/XKeysSupplier.hpp>
67 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
68 #include <com/sun/star/task/XInteractionHandler.hpp>
69 #include <com/sun/star/task/XInteractionRequest.hpp>
70 #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
71 #include <com/sun/star/uno/XNamingService.hpp>
72 #include <com/sun/star/util/NumberFormat.hpp>
73 #include <com/sun/star/util/XNumberFormatsSupplier.hpp>
74 #include <com/sun/star/util/XNumberFormatTypes.hpp>
75 /** === end UNO includes === **/
76 
77 #include <comphelper/extract.hxx>
78 #include <comphelper/interaction.hxx>
79 #include <comphelper/property.hxx>
80 #include <connectivity/conncleanup.hxx>
81 #include <connectivity/dbconversion.hxx>
82 #include <connectivity/dbexception.hxx>
83 #include <connectivity/dbtools.hxx>
84 #include <connectivity/statementcomposer.hxx>
85 #include <osl/diagnose.h>
86 #include <rtl/ustrbuf.hxx>
87 #include <tools/diagnose_ex.h>
88 
89 #include "resource/common_res.hrc"
90 #include "resource/sharedresources.hxx"
91 #include "OSubComponent.hxx"
92 
93 #include <algorithm>
94 
95 using namespace ::comphelper;
96 using namespace ::com::sun::star::uno;
97 using namespace ::com::sun::star::io;
98 using namespace ::com::sun::star::awt;
99 using namespace ::com::sun::star::ui::dialogs;
100 using namespace ::com::sun::star::util;
101 using namespace ::com::sun::star::lang;
102 using namespace ::com::sun::star::beans;
103 using namespace ::com::sun::star::container;
104 using namespace ::com::sun::star::sdb;
105 using namespace ::com::sun::star::sdbc;
106 using namespace ::com::sun::star::sdbcx;
107 using namespace ::com::sun::star::form;
108 using namespace connectivity;
109 
110 //.........................................................................
111 namespace dbtools
112 {
113 //.........................................................................
114 
115 	using namespace ::com::sun::star::uno;
116 	using namespace ::com::sun::star::beans;
117 	using namespace ::com::sun::star::util;
118 	using namespace ::com::sun::star::task;
119 	using namespace ::com::sun::star::uno;
120 	using namespace ::com::sun::star::lang;
121 	using namespace ::com::sun::star::sdbc;
122 	using namespace ::com::sun::star::task;
123 //	using namespace cppu;
124 //	using namespace osl;
125 
126 //==============================================================================
127 //==============================================================================
128 namespace
129 {
130     typedef sal_Bool (SAL_CALL XDatabaseMetaData::*FMetaDataSupport)();
131 }
132 //==============================================================================
133 //==============================================================================
134 sal_Int32 getDefaultNumberFormat(const Reference< XPropertySet >& _xColumn,
135 								 const Reference< XNumberFormatTypes >& _xTypes,
136 								 const Locale& _rLocale)
137 {
138 	OSL_ENSURE(_xTypes.is() && _xColumn.is(), "dbtools::getDefaultNumberFormat: invalid arg !");
139 	if (!_xTypes.is() || !_xColumn.is())
140 		return NumberFormat::UNDEFINED;
141 
142 	sal_Int32 nDataType = 0;
143 	sal_Int32 nScale = 0;
144 	try
145 	{
146 		// determine the datatype of the column
147 		_xColumn->getPropertyValue(::rtl::OUString::createFromAscii("Type")) >>= nDataType;
148 
149 		if (DataType::NUMERIC == nDataType || DataType::DECIMAL == nDataType)
150 			_xColumn->getPropertyValue(::rtl::OUString::createFromAscii("Scale")) >>= nScale;
151 	}
152 	catch (Exception&)
153 	{
154 		return NumberFormat::UNDEFINED;
155 	}
156 	return getDefaultNumberFormat(nDataType,
157 					nScale,
158 					::cppu::any2bool(_xColumn->getPropertyValue(::rtl::OUString::createFromAscii("IsCurrency"))),
159 					_xTypes,
160 					_rLocale);
161 }
162 
163 //------------------------------------------------------------------
164 sal_Int32 getDefaultNumberFormat(sal_Int32 _nDataType,
165 								 sal_Int32 _nScale,
166 								 sal_Bool _bIsCurrency,
167 								 const Reference< XNumberFormatTypes >& _xTypes,
168 								 const Locale& _rLocale)
169 {
170 	OSL_ENSURE(_xTypes.is() , "dbtools::getDefaultNumberFormat: invalid arg !");
171 	if (!_xTypes.is())
172 		return NumberFormat::UNDEFINED;
173 
174 	sal_Int32 nFormat = 0;
175 	sal_Int32 nNumberType	= _bIsCurrency ? NumberFormat::CURRENCY : NumberFormat::NUMBER;
176 	switch (_nDataType)
177 	{
178 		case DataType::BIT:
179 		case DataType::BOOLEAN:
180 			nFormat = _xTypes->getStandardFormat(NumberFormat::LOGICAL, _rLocale);
181 			break;
182 		case DataType::TINYINT:
183 		case DataType::SMALLINT:
184 		case DataType::INTEGER:
185 		case DataType::BIGINT:
186 		case DataType::FLOAT:
187 		case DataType::REAL:
188 		case DataType::DOUBLE:
189 		case DataType::NUMERIC:
190 		case DataType::DECIMAL:
191 		{
192 			try
193 			{
194 				nFormat = _xTypes->getStandardFormat((sal_Int16)nNumberType, _rLocale);
195 				if(_nScale > 0)
196 				{
197 					// generate a new format if necessary
198 					Reference< XNumberFormats > xFormats(_xTypes, UNO_QUERY);
199 					::rtl::OUString sNewFormat = xFormats->generateFormat( 0L, _rLocale, sal_False, sal_False, (sal_Int16)_nScale, sal_True);
200 
201 					// and add it to the formatter if necessary
202 					nFormat = xFormats->queryKey(sNewFormat, _rLocale, sal_False);
203 					if (nFormat == (sal_Int32)-1)
204 						nFormat = xFormats->addNew(sNewFormat, _rLocale);
205 				}
206 			}
207 			catch (Exception&)
208 			{
209 				nFormat = _xTypes->getStandardFormat((sal_Int16)nNumberType, _rLocale);
210 			}
211 		}	break;
212 		case DataType::CHAR:
213 		case DataType::VARCHAR:
214 		case DataType::LONGVARCHAR:
215 		case DataType::CLOB:
216 			nFormat = _xTypes->getStandardFormat(NumberFormat::TEXT, _rLocale);
217 			break;
218 		case DataType::DATE:
219 			nFormat = _xTypes->getStandardFormat(NumberFormat::DATE, _rLocale);
220 			break;
221 		case DataType::TIME:
222 			nFormat = _xTypes->getStandardFormat(NumberFormat::TIME, _rLocale);
223 			break;
224 		case DataType::TIMESTAMP:
225 			nFormat = _xTypes->getStandardFormat(NumberFormat::DATETIME, _rLocale);
226 			break;
227 		case DataType::BINARY:
228 		case DataType::VARBINARY:
229 		case DataType::LONGVARBINARY:
230 		case DataType::SQLNULL:
231 		case DataType::OTHER:
232 		case DataType::OBJECT:
233 		case DataType::DISTINCT:
234 		case DataType::STRUCT:
235 		case DataType::ARRAY:
236 		case DataType::BLOB:
237 		case DataType::REF:
238 		default:
239 			nFormat = _xTypes->getStandardFormat(NumberFormat::UNDEFINED, _rLocale);
240 			//nFormat = NumberFormat::UNDEFINED;
241 	}
242 	return nFormat;
243 }
244 
245 //==============================================================================
246 //------------------------------------------------------------------------------
247 Reference< XConnection> findConnection(const Reference< XInterface >& xParent)
248 {
249 	Reference< XConnection> xConnection(xParent, UNO_QUERY);
250 	if (!xConnection.is())
251 	{
252 		Reference< XChild> xChild(xParent, UNO_QUERY);
253 		if (xChild.is())
254 			xConnection = findConnection(xChild->getParent());
255 	}
256 	return xConnection;
257 }
258 
259 //------------------------------------------------------------------------------
260 Reference< XDataSource> getDataSource_allowException(
261 			const ::rtl::OUString& _rsTitleOrPath,
262 			const Reference< XMultiServiceFactory >& _rxFactory )
263 {
264 	ENSURE_OR_RETURN( _rsTitleOrPath.getLength(), "getDataSource_allowException: invalid arg !", NULL );
265 
266 	Reference< XNameAccess> xDatabaseContext(
267 		_rxFactory->createInstance(
268 			::rtl::OUString::createFromAscii( "com.sun.star.sdb.DatabaseContext" ) ),UNO_QUERY );
269     OSL_ENSURE( xDatabaseContext.is(), "getDataSource_allowException: could not obtain the database context!" );
270 
271 	return Reference< XDataSource >( xDatabaseContext->getByName( _rsTitleOrPath ), UNO_QUERY );
272 }
273 
274 //------------------------------------------------------------------------------
275 Reference< XDataSource > getDataSource(
276 			const ::rtl::OUString& _rsTitleOrPath,
277 			const Reference< XMultiServiceFactory >& _rxFactory )
278 {
279     Reference< XDataSource > xDS;
280 	try
281 	{
282         xDS = getDataSource_allowException( _rsTitleOrPath, _rxFactory );
283 	}
284 	catch( const Exception& )
285 	{
286         DBG_UNHANDLED_EXCEPTION();
287     }
288 
289     return xDS;
290 }
291 
292 //------------------------------------------------------------------------------
293 Reference< XConnection > getConnection_allowException(
294 			const ::rtl::OUString& _rsTitleOrPath,
295 			const ::rtl::OUString& _rsUser,
296 			const ::rtl::OUString& _rsPwd,
297 			const Reference< XMultiServiceFactory>& _rxFactory)
298 {
299 	Reference< XDataSource> xDataSource( getDataSource_allowException(_rsTitleOrPath, _rxFactory) );
300 	Reference<XConnection> xConnection;
301 	if (xDataSource.is())
302 	{
303 		// do it with interaction handler
304 		if(!_rsUser.getLength() || !_rsPwd.getLength())
305 		{
306 			Reference<XPropertySet> xProp(xDataSource,UNO_QUERY);
307 			::rtl::OUString sPwd, sUser;
308 			sal_Bool bPwdReq = sal_False;
309 			try
310 			{
311 				xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
312 				bPwdReq = ::cppu::any2bool(xProp->getPropertyValue(::rtl::OUString::createFromAscii("IsPasswordRequired")));
313 				xProp->getPropertyValue(::rtl::OUString::createFromAscii("User")) >>= sUser;
314 			}
315 			catch(Exception&)
316 			{
317 				OSL_ENSURE(sal_False, "dbtools::getConnection: error while retrieving data source properties!");
318 			}
319 			if(bPwdReq && !sPwd.getLength())
320 			{	// password required, but empty -> connect using an interaction handler
321 				Reference<XCompletedConnection> xConnectionCompletion(xProp, UNO_QUERY);
322 				if (xConnectionCompletion.is())
323 				{	// instantiate the default SDB interaction handler
324 					Reference< XInteractionHandler > xHandler(_rxFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.task.InteractionHandler")), UNO_QUERY);
325 					OSL_ENSURE(xHandler.is(), "dbtools::getConnection service com.sun.star.task.InteractionHandler not available!");
326 					if (xHandler.is())
327 					{
328 						xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
329 					}
330 				}
331 			}
332 			else
333 				xConnection = xDataSource->getConnection(sUser, sPwd);
334 		}
335 		if(!xConnection.is()) // try to get one if not already have one, just to make sure
336 			xConnection = xDataSource->getConnection(_rsUser, _rsPwd);
337 	}
338 	return xConnection;
339 }
340 
341 //------------------------------------------------------------------------------
342 Reference< XConnection> getConnection_withFeedback(const ::rtl::OUString& _rDataSourceName,
343 		const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const Reference< XMultiServiceFactory>& _rxFactory)
344 	SAL_THROW ( (SQLException) )
345 {
346 	Reference< XConnection > xReturn;
347 	try
348 	{
349 		xReturn = getConnection_allowException(_rDataSourceName, _rUser, _rPwd, _rxFactory);
350 	}
351 	catch(SQLException&)
352 	{
353 		// allowed to pass
354 		throw;
355 	}
356 	catch(Exception&)
357 	{
358 		OSL_ENSURE(sal_False, "::dbtools::getConnection_withFeedback: unexpected (non-SQL) exception caught!");
359 	}
360 	return xReturn;
361 }
362 
363 //------------------------------------------------------------------------------
364 Reference< XConnection> getConnection(
365 			const ::rtl::OUString& _rsTitleOrPath,
366 			const ::rtl::OUString& _rsUser,
367 			const ::rtl::OUString& _rsPwd,
368 			const Reference< XMultiServiceFactory>& _rxFactory)
369 {
370 	Reference< XConnection > xReturn;
371 	try
372 	{
373 		xReturn = getConnection_allowException(_rsTitleOrPath, _rsUser, _rsPwd, _rxFactory);
374 	}
375 	catch(Exception&)
376 	{
377 	}
378 
379 	// TODO: if there were not dozens of places which rely on getConnection not throwing an exception ....
380 	// I would change this ...
381 
382 	return xReturn;
383 }
384 
385 //------------------------------------------------------------------------------
386 Reference< XConnection> getConnection(const Reference< XRowSet>& _rxRowSet) throw (RuntimeException)
387 {
388 	Reference< XConnection> xReturn;
389 	Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
390 	if (xRowSetProps.is())
391 		xRowSetProps->getPropertyValue(::rtl::OUString::createFromAscii("ActiveConnection")) >>= xReturn;
392 	return xReturn;
393 }
394 
395 //------------------------------------------------------------------------------
396 // helper function which allows to implement both the connectRowset and the ensureRowSetConnection semantics
397 // if connectRowset (which is deprecated) is removed, this function and one of its parameters are
398 // not needed anymore, the whole implementation can be moved into ensureRowSetConnection then)
399 SharedConnection lcl_connectRowSet(const Reference< XRowSet>& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory,
400         bool _bSetAsActiveConnection, bool _bAttachAutoDisposer )
401     SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
402 {
403     SharedConnection xConnection;
404 
405     do
406     {
407         Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
408 	    if ( !xRowSetProps.is() )
409             break;
410 
411         // 1. already connected?
412         Reference< XConnection > xExistingConn(
413             xRowSetProps->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ActiveConnection" ) ) ),
414             UNO_QUERY );
415 
416         if  (   xExistingConn.is()
417             // 2. embedded in a database?
418             ||  isEmbeddedInDatabase( _rxRowSet, xExistingConn )
419             // 3. is there a connection in the parent hierarchy?
420             ||  ( xExistingConn = findConnection( _rxRowSet ) ).is()
421             )
422         {
423             if ( _bSetAsActiveConnection )
424             {
425                 xRowSetProps->setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ActiveConnection" ) ), makeAny( xExistingConn ) );
426                 // no auto disposer needed, since we did not create the connection
427             }
428 
429             xConnection.reset( xExistingConn, SharedConnection::NoTakeOwnership );
430             break;
431         }
432 
433 		// build a connection with it's current settings (4. data source name, or 5. URL)
434 
435         const ::rtl::OUString sUserProp = ::rtl::OUString::createFromAscii("User");
436 		::rtl::OUString sDataSourceName;
437 		xRowSetProps->getPropertyValue(::rtl::OUString::createFromAscii("DataSourceName")) >>= sDataSourceName;
438 		::rtl::OUString sURL;
439 		xRowSetProps->getPropertyValue(::rtl::OUString::createFromAscii("URL")) >>= sURL;
440 
441         Reference< XConnection > xPureConnection;
442 		if (sDataSourceName.getLength())
443 		{	// the row set's data source property is set
444 			// -> try to connect, get user and pwd setting for that
445 			::rtl::OUString sUser, sPwd;
446 
447 			if (hasProperty(sUserProp, xRowSetProps))
448 				xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
449 			if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
450 				xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
451 
452             xPureConnection = getConnection_allowException( sDataSourceName, sUser, sPwd, _rxFactory );
453 		}
454 		else if (sURL.getLength())
455 		{	// the row set has no data source, but a connection url set
456 			// -> try to connection with that url
457 			Reference< XDriverManager > xDriverManager(
458 				_rxFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ConnectionPool")), UNO_QUERY);
459 			if (xDriverManager.is())
460 			{
461 				::rtl::OUString sUser, sPwd;
462 				if (hasProperty(sUserProp, xRowSetProps))
463 					xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
464 				if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
465 					xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
466 				if (sUser.getLength())
467 				{	// use user and pwd together with the url
468 					Sequence< PropertyValue> aInfo(2);
469 					aInfo.getArray()[0].Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("user"));
470 					aInfo.getArray()[0].Value <<= sUser;
471 					aInfo.getArray()[1].Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("password"));
472 					aInfo.getArray()[1].Value <<= sPwd;
473                     xPureConnection = xDriverManager->getConnectionWithInfo( sURL, aInfo );
474 				}
475 				else
476 					// just use the url
477                     xPureConnection = xDriverManager->getConnection( sURL );
478 			}
479 		}
480         xConnection.reset(
481             xPureConnection,
482             _bAttachAutoDisposer ? SharedConnection::NoTakeOwnership : SharedConnection::TakeOwnership
483             /* take ownership if and only if we're *not* going to auto-dispose the connection */
484         );
485 
486         // now if we created a connection, forward it to the row set
487 		if ( xConnection.is() && _bSetAsActiveConnection )
488 		{
489 			try
490 			{
491                 if ( _bAttachAutoDisposer )
492                 {
493 				    OAutoConnectionDisposer* pAutoDispose = new OAutoConnectionDisposer( _rxRowSet, xConnection );
494 				    Reference< XPropertyChangeListener > xEnsureDelete(pAutoDispose);
495                 }
496                 else
497                     xRowSetProps->setPropertyValue(
498                         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ActiveConnection" ) ),
499                         makeAny( xConnection.getTyped() )
500                     );
501 			}
502 			catch(Exception&)
503 			{
504 				OSL_ENSURE(0,"EXception when we set the new active connection!");
505 			}
506 		}
507 	}
508     while ( false );
509 
510 	return xConnection;
511 }
512 
513 //------------------------------------------------------------------------------
514 Reference< XConnection> connectRowset(const Reference< XRowSet>& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory,
515 	sal_Bool _bSetAsActiveConnection )	SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
516 {
517     SharedConnection xConnection = lcl_connectRowSet( _rxRowSet, _rxFactory, _bSetAsActiveConnection, true );
518     return xConnection.getTyped();
519 }
520 
521 //------------------------------------------------------------------------------
522 SharedConnection ensureRowSetConnection(const Reference< XRowSet>& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory,
523     bool _bUseAutoConnectionDisposer )	SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
524 {
525     return lcl_connectRowSet( _rxRowSet, _rxFactory, true, _bUseAutoConnectionDisposer );
526 }
527 
528 //------------------------------------------------------------------------------
529 Reference< XNameAccess> getTableFields(const Reference< XConnection>& _rxConn,const ::rtl::OUString& _rName)
530 {
531 	Reference< XComponent > xDummy;
532 	return getFieldsByCommandDescriptor( _rxConn, CommandType::TABLE, _rName, xDummy );
533 }
534 //------------------------------------------------------------------------------
535 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Any& i_aTable)
536 {
537     const Reference< XPropertySet > xTable(i_aTable,UNO_QUERY_THROW);
538     return getPrimaryKeyColumns_throw(xTable);
539 }
540 //------------------------------------------------------------------------------
541 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Reference< XPropertySet >& i_xTable)
542 {
543 	Reference<XNameAccess> xKeyColumns;
544     const Reference<XKeysSupplier> xKeySup(i_xTable,UNO_QUERY);
545     if ( xKeySup.is() )
546     {
547 	    const Reference<XIndexAccess> xKeys = xKeySup->getKeys();
548 	    if ( xKeys.is() )
549 	    {
550             ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
551             const ::rtl::OUString sPropName = rPropMap.getNameByIndex(PROPERTY_ID_TYPE);
552 		    Reference<XPropertySet> xProp;
553 		    const sal_Int32 nCount = xKeys->getCount();
554 		    for(sal_Int32 i = 0;i< nCount;++i)
555 		    {
556 			    xProp.set(xKeys->getByIndex(i),UNO_QUERY_THROW);
557 			    if ( xProp.is() )
558 			    {
559 				    sal_Int32 nKeyType = 0;
560 				    xProp->getPropertyValue(sPropName) >>= nKeyType;
561 				    if(KeyType::PRIMARY == nKeyType)
562 				    {
563 					    const Reference<XColumnsSupplier> xKeyColsSup(xProp,UNO_QUERY_THROW);
564 					    xKeyColumns = xKeyColsSup->getColumns();
565 					    break;
566 				    }
567 			    }
568 		    }
569 	    }
570     }
571 
572 	return xKeyColumns;
573 }
574 
575 //------------------------------------------------------------------------------
576 namespace
577 {
578 	enum FieldLookupState
579 	{
580 		HANDLE_TABLE, HANDLE_QUERY, HANDLE_SQL, RETRIEVE_OBJECT, RETRIEVE_COLUMNS, DONE, FAILED
581 	};
582 }
583 
584 //------------------------------------------------------------------------------
585 Reference< XNameAccess > getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection,
586 	const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand,
587 	Reference< XComponent >& _rxKeepFieldsAlive, SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
588 {
589 	OSL_PRECOND( _rxConnection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection!" );
590 	OSL_PRECOND( ( CommandType::TABLE == _nCommandType ) || ( CommandType::QUERY == _nCommandType ) || ( CommandType::COMMAND == _nCommandType ),
591 		"::dbtools::getFieldsByCommandDescriptor: invalid command type!" );
592 	OSL_PRECOND( _rCommand.getLength(), "::dbtools::getFieldsByCommandDescriptor: invalid command (empty)!" );
593 
594 	Reference< XNameAccess > xFields;
595 
596 	// reset the error
597 	if ( _pErrorInfo )
598 		*_pErrorInfo = SQLExceptionInfo();
599 	// reset the ownership holder
600 	_rxKeepFieldsAlive.clear();
601 
602 	// go for the fields
603 	try
604 	{
605 		// some kind of state machine to ease the sharing of code
606 		FieldLookupState eState = FAILED;
607 		switch ( _nCommandType )
608 		{
609 			case CommandType::TABLE:
610 				eState = HANDLE_TABLE;
611 				break;
612 			case CommandType::QUERY:
613 				eState = HANDLE_QUERY;
614 				break;
615 			case CommandType::COMMAND:
616 				eState = HANDLE_SQL;
617 				break;
618 		}
619 
620 		// needed in various states:
621 		Reference< XNameAccess > xObjectCollection;
622 		Reference< XColumnsSupplier > xSupplyColumns;
623 
624 		// go!
625 		while ( ( DONE != eState ) && ( FAILED != eState ) )
626 		{
627 			switch ( eState )
628 			{
629 				case HANDLE_TABLE:
630 				{
631 					// initial state for handling the tables
632 
633 					// get the table objects
634 					Reference< XTablesSupplier > xSupplyTables( _rxConnection, UNO_QUERY );
635 					if ( xSupplyTables.is() )
636 						xObjectCollection = xSupplyTables->getTables();
637 					// if something went wrong 'til here, then this will be handled in the next state
638 
639 					// next state: get the object
640 					eState = RETRIEVE_OBJECT;
641 				}
642 				break;
643 
644 				case HANDLE_QUERY:
645 				{
646 					// initial state for handling the tables
647 
648 					// get the table objects
649 					Reference< XQueriesSupplier > xSupplyQueries( _rxConnection, UNO_QUERY );
650 					if ( xSupplyQueries.is() )
651 						xObjectCollection = xSupplyQueries->getQueries();
652 					// if something went wrong 'til here, then this will be handled in the next state
653 
654 					// next state: get the object
655 					eState = RETRIEVE_OBJECT;
656 				}
657 				break;
658 
659 				case RETRIEVE_OBJECT:
660 					// here we should have an object (aka query or table) collection, and are going
661 					// to retrieve the desired object
662 
663 					// next state: default to FAILED
664 					eState = FAILED;
665 
666 					OSL_ENSURE( xObjectCollection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection (no sdb.Connection, or no Tables-/QueriesSupplier)!");
667 					if ( xObjectCollection.is() )
668 					{
669 						if ( xObjectCollection.is() && xObjectCollection->hasByName( _rCommand ) )
670 						{
671 							xObjectCollection->getByName( _rCommand ) >>= xSupplyColumns;
672 								// (xSupplyColumns being NULL will be handled in the next state)
673 
674 							// next: go for the columns
675 							eState = RETRIEVE_COLUMNS;
676 						}
677 					}
678 					break;
679 
680 				case RETRIEVE_COLUMNS:
681 					OSL_ENSURE( xSupplyColumns.is(), "::dbtools::getFieldsByCommandDescriptor: could not retrieve the columns supplier!" );
682 
683 					// next state: default to FAILED
684 					eState = FAILED;
685 
686 					if ( xSupplyColumns.is() )
687 					{
688 						xFields = xSupplyColumns->getColumns();
689 						// that's it
690 						eState = DONE;
691 					}
692 					break;
693 
694 				case HANDLE_SQL:
695 				{
696 					::rtl::OUString sStatementToExecute( _rCommand );
697 
698 					// well, the main problem here is to handle statements which contain a parameter
699 					// If we would simply execute a parametrized statement, then this will fail because
700 					// we cannot supply any parameter values.
701 					// Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion
702 					// This should cause every driver to not really execute the statement, but to return
703 					// an empty result set with the proper structure. We then can use this result set
704 					// to retrieve the columns.
705 
706 					try
707 					{
708 						Reference< XMultiServiceFactory > xComposerFac( _rxConnection, UNO_QUERY );
709 
710 						if ( xComposerFac.is() )
711 						{
712 							Reference< XSingleSelectQueryComposer > xComposer(xComposerFac->createInstance( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.SingleSelectQueryComposer"))),UNO_QUERY);
713 							if ( xComposer.is() )
714 							{
715 								xComposer->setQuery( sStatementToExecute );
716 
717 								// Now set the filter to a dummy restriction which will result in an empty
718 								// result set.
719 								xComposer->setFilter( ::rtl::OUString::createFromAscii( "0=1" ) );
720 								sStatementToExecute = xComposer->getQuery( );
721 							}
722 						}
723 					}
724 					catch( const Exception& )
725 					{
726 						// silent this error, this was just a try. If we're here, we did not change sStatementToExecute,
727 						// so it will still be _rCommand, which then will be executed without being touched
728 					}
729 
730 					// now execute
731 					Reference< XPreparedStatement > xStatement = _rxConnection->prepareStatement( sStatementToExecute );
732 					// transfer ownership of this temporary object to the caller
733 					_rxKeepFieldsAlive = _rxKeepFieldsAlive.query( xStatement );
734 
735 					// set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter
736 					// failed - in this case, the MaxRows restriction should at least ensure that there
737 					// is no data returned (which would be potentially expensive)
738 					Reference< XPropertySet > xStatementProps( xStatement,UNO_QUERY );
739 					try
740 					{
741 						if ( xStatementProps.is() )
742 							xStatementProps->setPropertyValue(
743 								::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MaxRows" ) ),
744 								makeAny( sal_Int32( 0 ) )
745 							);
746 					}
747 					catch( const Exception& )
748 					{
749 						OSL_ENSURE( sal_False, "::dbtools::getFieldsByCommandDescriptor: could not set the MaxRows!" );
750 						// oh damn. Not much of a chance to recover, we will no retrieve the complete
751 						// full blown result set
752 					}
753 
754 					xSupplyColumns = xSupplyColumns.query( xStatement->executeQuery() );
755 					// this should have given us a result set which does not contain any data, but
756 					// the structural information we need
757 
758 					// so the next state is to get the columns
759 					eState = RETRIEVE_COLUMNS;
760 				}
761 				break;
762 
763 				default:
764 					OSL_ENSURE( sal_False, "::dbtools::getFieldsByCommandDescriptor: oops! unhandled state here!" );
765 					eState = FAILED;
766 			}
767 		}
768 	}
769 	catch( const SQLContext& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
770 	catch( const SQLWarning& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
771 	catch( const SQLException& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
772 	catch( const Exception& )
773 	{
774 		OSL_ENSURE( sal_False, "::dbtools::getFieldsByCommandDescriptor: caught an exception while retrieving the fields!" );
775 	}
776 
777 	return xFields;
778 }
779 
780 //------------------------------------------------------------------------------
781 Sequence< ::rtl::OUString > getFieldNamesByCommandDescriptor( const Reference< XConnection >& _rxConnection,
782 	const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand,
783 	SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
784 {
785 	// get the container for the fields
786 	Reference< XComponent > xKeepFieldsAlive;
787 	Reference< XNameAccess > xFieldContainer = getFieldsByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, xKeepFieldsAlive, _pErrorInfo );
788 
789 	// get the names of the fields
790 	Sequence< ::rtl::OUString > aNames;
791 	if ( xFieldContainer.is() )
792 		aNames = xFieldContainer->getElementNames();
793 
794 	// clean up any temporary objects which have been created
795 	disposeComponent( xKeepFieldsAlive );
796 
797 	// outta here
798 	return aNames;
799 }
800 
801 //------------------------------------------------------------------------------
802 SQLContext prependContextInfo(const SQLException& _rException, const Reference< XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails)
803 {
804 	return SQLContext( _rContextDescription, _rxContext, ::rtl::OUString(), 0, makeAny( _rException ), _rContextDetails );
805 }
806 //------------------------------------------------------------------------------
807 SQLException prependErrorInfo( const SQLException& _rChainedException, const Reference< XInterface >& _rxContext,
808     const ::rtl::OUString& _rAdditionalError, const StandardSQLState _eSQLState, const sal_Int32 _nErrorCode )
809 {
810     return SQLException( _rAdditionalError, _rxContext,
811         _eSQLState == SQL_ERROR_UNSPECIFIED ? ::rtl::OUString() : getStandardSQLState( _eSQLState ),
812         _nErrorCode, makeAny( _rChainedException ) );
813 }
814 
815 //--------------------------------------------------------------------------
816 namespace
817 {
818     struct NameComponentSupport
819     {
820         const bool  bCatalogs;
821         const bool  bSchemas;
822 
823         NameComponentSupport( )
824             :bCatalogs( true )
825             ,bSchemas( true )
826         {
827         }
828 
829         NameComponentSupport( const bool _bCatalogs, const bool _bSchemas )
830             :bCatalogs( _bCatalogs )
831             ,bSchemas( _bSchemas )
832         {
833         }
834     };
835 
836     NameComponentSupport lcl_getNameComponentSupport( const Reference< XDatabaseMetaData >& _rxMetaData, EComposeRule _eComposeRule )
837     {
838         OSL_PRECOND( _rxMetaData.is(), "lcl_getNameComponentSupport: invalid meta data!" );
839 
840         FMetaDataSupport pCatalogCall = &XDatabaseMetaData::supportsCatalogsInDataManipulation;
841         FMetaDataSupport pSchemaCall = &XDatabaseMetaData::supportsSchemasInDataManipulation;
842         bool bIgnoreMetaData = false;
843 
844 	    switch ( _eComposeRule )
845 	    {
846 		    case eInTableDefinitions:
847 			    pCatalogCall = &XDatabaseMetaData::supportsCatalogsInTableDefinitions;
848 			    pSchemaCall = &XDatabaseMetaData::supportsSchemasInTableDefinitions;
849 			    break;
850 		    case eInIndexDefinitions:
851 			    pCatalogCall = &XDatabaseMetaData::supportsCatalogsInIndexDefinitions;
852 			    pSchemaCall = &XDatabaseMetaData::supportsSchemasInIndexDefinitions;
853 			    break;
854 		    case eInProcedureCalls:
855 			    pCatalogCall = &XDatabaseMetaData::supportsCatalogsInProcedureCalls;
856 			    pSchemaCall = &XDatabaseMetaData::supportsSchemasInProcedureCalls;
857 			    break;
858 		    case eInPrivilegeDefinitions:
859 			    pCatalogCall = &XDatabaseMetaData::supportsCatalogsInPrivilegeDefinitions;
860 			    pSchemaCall = &XDatabaseMetaData::supportsSchemasInPrivilegeDefinitions;
861 			    break;
862             case eComplete:
863                 bIgnoreMetaData = true;
864                 break;
865             case eInDataManipulation:
866                 // already properly set above
867                 break;
868 	    }
869         return NameComponentSupport(
870             bIgnoreMetaData ? true : (_rxMetaData.get()->*pCatalogCall)(),
871             bIgnoreMetaData ? true : (_rxMetaData.get()->*pSchemaCall)()
872         );
873     }
874 }
875 
876 //--------------------------------------------------------------------------
877 static ::rtl::OUString impl_doComposeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
878                 const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName,
879                 sal_Bool _bQuote, EComposeRule _eComposeRule )
880 {
881 	OSL_ENSURE(_rxMetaData.is(), "impl_doComposeTableName : invalid meta data !");
882     if ( !_rxMetaData.is() )
883         return ::rtl::OUString();
884 	OSL_ENSURE(_rName.getLength(), "impl_doComposeTableName : at least the name should be non-empty !");
885 
886 	const ::rtl::OUString sQuoteString = _rxMetaData->getIdentifierQuoteString();
887     const NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxMetaData, _eComposeRule ) );
888 
889     ::rtl::OUStringBuffer aComposedName;
890 
891     ::rtl::OUString sCatalogSep;
892 	sal_Bool bCatlogAtStart = sal_True;
893 	if ( _rCatalog.getLength() && aNameComps.bCatalogs )
894 	{
895 		sCatalogSep		= _rxMetaData->getCatalogSeparator();
896 		bCatlogAtStart	= _rxMetaData->isCatalogAtStart();
897 
898 		if ( bCatlogAtStart && sCatalogSep.getLength())
899 		{
900             aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
901 			aComposedName.append( sCatalogSep );
902 		}
903 	}
904 
905 	if ( _rSchema.getLength() && aNameComps.bSchemas )
906 	{
907         aComposedName.append( _bQuote ? quoteName( sQuoteString, _rSchema ) : _rSchema );
908         aComposedName.appendAscii( "." );
909 	}
910 
911     aComposedName.append( _bQuote ? quoteName( sQuoteString, _rName ) : _rName );
912 
913 	if  (   _rCatalog.getLength()
914         &&  !bCatlogAtStart
915         &&  sCatalogSep.getLength()
916         &&  aNameComps.bCatalogs
917         )
918 	{
919 		aComposedName.append( sCatalogSep );
920         aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
921 	}
922 
923     return aComposedName.makeStringAndClear();
924 }
925 
926 //------------------------------------------------------------------------------
927 ::rtl::OUString quoteTableName(const Reference< XDatabaseMetaData>& _rxMeta
928 							   , const ::rtl::OUString& _rName
929 							   , EComposeRule _eComposeRule)
930 {
931 	::rtl::OUString sCatalog, sSchema, sTable;
932 	qualifiedNameComponents(_rxMeta,_rName,sCatalog,sSchema,sTable,_eComposeRule);
933 	return impl_doComposeTableName( _rxMeta, sCatalog, sSchema, sTable, sal_True, _eComposeRule );
934 }
935 
936 //------------------------------------------------------------------------------
937 void qualifiedNameComponents(const Reference< XDatabaseMetaData >& _rxConnMetaData, const ::rtl::OUString& _rQualifiedName, ::rtl::OUString& _rCatalog, ::rtl::OUString& _rSchema, ::rtl::OUString& _rName,EComposeRule _eComposeRule)
938 {
939 	OSL_ENSURE(_rxConnMetaData.is(), "QualifiedNameComponents : invalid meta data!");
940 
941     NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxConnMetaData, _eComposeRule ) );
942 
943 	::rtl::OUString sSeparator = _rxConnMetaData->getCatalogSeparator();
944 
945 	::rtl::OUString sName(_rQualifiedName);
946 	// do we have catalogs ?
947 	if ( aNameComps.bCatalogs )
948 	{
949 		if (_rxConnMetaData->isCatalogAtStart())
950 		{
951 			// search for the catalog name at the beginning
952 			sal_Int32 nIndex = sName.indexOf(sSeparator);
953 			if (-1 != nIndex)
954 			{
955 				_rCatalog = sName.copy(0, nIndex);
956 				sName = sName.copy(nIndex + 1);
957 			}
958 		}
959 		else
960 		{
961 			// Katalogname am Ende
962 			sal_Int32 nIndex = sName.lastIndexOf(sSeparator);
963 			if (-1 != nIndex)
964 			{
965 				_rCatalog = sName.copy(nIndex + 1);
966 				sName = sName.copy(0, nIndex);
967 			}
968 		}
969 	}
970 
971 	if ( aNameComps.bSchemas )
972 	{
973 		sal_Int32 nIndex = sName.indexOf((sal_Unicode)'.');
974 		//	OSL_ENSURE(-1 != nIndex, "QualifiedNameComponents : no schema separator!");
975 		if ( nIndex != -1 )
976 			_rSchema = sName.copy(0, nIndex);
977 		sName = sName.copy(nIndex + 1);
978 	}
979 
980 	_rName = sName;
981 }
982 
983 //------------------------------------------------------------------------------
984 Reference< XNumberFormatsSupplier> getNumberFormats(
985 			const Reference< XConnection>& _rxConn,
986 			sal_Bool _bAlloweDefault,
987 			const Reference< XMultiServiceFactory>& _rxFactory)
988 {
989 	// ask the parent of the connection (should be an DatabaseAccess)
990 	Reference< XNumberFormatsSupplier> xReturn;
991 	Reference< XChild> xConnAsChild(_rxConn, UNO_QUERY);
992 	::rtl::OUString sPropFormatsSupplier = ::rtl::OUString::createFromAscii("NumberFormatsSupplier");
993 	if (xConnAsChild.is())
994 	{
995 		Reference< XPropertySet> xConnParentProps(xConnAsChild->getParent(), UNO_QUERY);
996 		if (xConnParentProps.is() && hasProperty(sPropFormatsSupplier, xConnParentProps))
997 			xConnParentProps->getPropertyValue(sPropFormatsSupplier) >>= xReturn;
998 	}
999 	else if(_bAlloweDefault && _rxFactory.is())
1000 	{
1001 		xReturn = Reference< XNumberFormatsSupplier>(_rxFactory->createInstance(::rtl::OUString::createFromAscii("com.sun.star.util.NumberFormatsSupplier")),UNO_QUERY);
1002 	}
1003 	return xReturn;
1004 }
1005 
1006 //==============================================================================
1007 //------------------------------------------------------------------------------
1008 void TransferFormComponentProperties(
1009 			const Reference< XPropertySet>& xOldProps,
1010 			const Reference< XPropertySet>& xNewProps,
1011 			const Locale& _rLocale)
1012 {
1013 try
1014 {
1015     OSL_ENSURE( xOldProps.is() && xNewProps.is(), "TransferFormComponentProperties: invalid source/dest!" );
1016     if ( !xOldProps.is() || !xNewProps.is() )
1017         return;
1018 
1019 	// kopieren wir erst mal alle Props, die in Quelle und Ziel vorhanden sind und identische Beschreibungen haben
1020 	Reference< XPropertySetInfo> xOldInfo( xOldProps->getPropertySetInfo());
1021 	Reference< XPropertySetInfo> xNewInfo( xNewProps->getPropertySetInfo());
1022 
1023 	Sequence< Property> aOldProperties = xOldInfo->getProperties();
1024 	Sequence< Property> aNewProperties = xNewInfo->getProperties();
1025 	int nNewLen = aNewProperties.getLength();
1026 
1027 	Property* pOldProps = aOldProperties.getArray();
1028 	Property* pNewProps = aNewProperties.getArray();
1029 
1030 	::rtl::OUString sPropDefaultControl(::rtl::OUString::createFromAscii("DefaultControl"));
1031 	::rtl::OUString sPropLabelControl(::rtl::OUString::createFromAscii("LabelControl"));
1032 	::rtl::OUString sPropFormatsSupplier(::rtl::OUString::createFromAscii("FormatsSupplier"));
1033 	::rtl::OUString sPropCurrencySymbol(::rtl::OUString::createFromAscii("CurrencySymbol"));
1034 	::rtl::OUString sPropDecimals(::rtl::OUString::createFromAscii("Decimals"));
1035 	::rtl::OUString sPropEffectiveMin(::rtl::OUString::createFromAscii("EffectiveMin"));
1036 	::rtl::OUString sPropEffectiveMax(::rtl::OUString::createFromAscii("EffectiveMax"));
1037 	::rtl::OUString sPropEffectiveDefault(::rtl::OUString::createFromAscii("EffectiveDefault"));
1038 	::rtl::OUString sPropDefaultText(::rtl::OUString::createFromAscii("DefaultText"));
1039 	::rtl::OUString sPropDefaultDate(::rtl::OUString::createFromAscii("DefaultDate"));
1040 	::rtl::OUString sPropDefaultTime(::rtl::OUString::createFromAscii("DefaultTime"));
1041 	::rtl::OUString sPropValueMin(::rtl::OUString::createFromAscii("ValueMin"));
1042 	::rtl::OUString sPropValueMax(::rtl::OUString::createFromAscii("ValueMax"));
1043 	::rtl::OUString sPropDecimalAccuracy(::rtl::OUString::createFromAscii("DecimalAccuracy"));
1044 	::rtl::OUString sPropClassId(::rtl::OUString::createFromAscii("ClassId"));
1045 	::rtl::OUString sFormattedServiceName( ::rtl::OUString::createFromAscii( "com.sun.star.form.component.FormattedField" ) );
1046 
1047 	for (sal_Int16 i=0; i<aOldProperties.getLength(); ++i)
1048 	{
1049 		if	(	(!pOldProps[i].Name.equals(sPropDefaultControl))
1050 			&&	(!pOldProps[i].Name.equals(sPropLabelControl))
1051 			)
1052 		{
1053 			// binaere Suche
1054 			Property* pResult = ::std::lower_bound(pNewProps, pNewProps + nNewLen,pOldProps[i].Name, ::comphelper::PropertyStringLessFunctor());
1055 			if (    pResult
1056 				&& ( pResult != pNewProps + nNewLen && pResult->Name == pOldProps[i].Name )
1057 				&& ( (pResult->Attributes & PropertyAttribute::READONLY) == 0 )
1058 				&& ( pResult->Type.equals(pOldProps[i].Type)) )
1059 			{	// Attribute stimmen ueberein und Property ist nicht read-only
1060 				try
1061 				{
1062 					xNewProps->setPropertyValue(pResult->Name, xOldProps->getPropertyValue(pResult->Name));
1063 				}
1064 				catch(IllegalArgumentException& e)
1065 				{
1066 					OSL_UNUSED( e );
1067 #ifdef DBG_UTIL
1068 					::rtl::OUString sMessage = ::rtl::OUString::createFromAscii("TransferFormComponentProperties : could not transfer the value for property \"");
1069 					sMessage += pResult->Name;
1070 					sMessage += ::rtl::OUString::createFromAscii("\"");;
1071 					OSL_ENSURE(sal_False, ::rtl::OUStringToOString(sMessage, RTL_TEXTENCODING_ASCII_US));
1072 #endif
1073 				}
1074 			}
1075 		}
1076 	}
1077 
1078 
1079 	// fuer formatierte Felder (entweder alt oder neu) haben wir ein paar Sonderbehandlungen
1080 	Reference< XServiceInfo > xSI( xOldProps, UNO_QUERY );
1081 	sal_Bool bOldIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
1082 	xSI = Reference< XServiceInfo >( xNewProps, UNO_QUERY );
1083 	sal_Bool bNewIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
1084 
1085 	if (!bOldIsFormatted && !bNewIsFormatted)
1086 		return;	// nothing to do
1087 
1088 	if (bOldIsFormatted && bNewIsFormatted)
1089 		// nein, wenn beide formatierte Felder sind, dann machen wir keinerlei Konvertierungen
1090 		// Das geht zu weit ;)
1091 		return;
1092 
1093 	if (bOldIsFormatted)
1094 	{
1095 		// aus dem eingestellten Format ein paar Properties rausziehen und zum neuen Set durchschleifen
1096 		Any aFormatKey( xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) );
1097 		if (aFormatKey.hasValue())
1098 		{
1099 			Reference< XNumberFormatsSupplier> xSupplier;
1100 			xOldProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1101 			if (xSupplier.is())
1102 			{
1103 				Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1104 				Reference< XPropertySet> xFormat(xFormats->getByKey(getINT32(aFormatKey)));
1105 				if (hasProperty(sPropCurrencySymbol, xFormat))
1106 				{
1107 					Any aVal( xFormat->getPropertyValue(sPropCurrencySymbol) );
1108 					if (aVal.hasValue() && hasProperty(sPropCurrencySymbol, xNewProps))
1109 						// (wenn die Quelle das nicht gesetzt hat, dann auch nicht kopieren, um den
1110 						// Default-Wert nicht zu ueberschreiben
1111 						xNewProps->setPropertyValue(sPropCurrencySymbol, aVal);
1112 				}
1113 				if (hasProperty(sPropDecimals, xFormat) && hasProperty(sPropDecimals, xNewProps))
1114 					xNewProps->setPropertyValue(sPropDecimals, xFormat->getPropertyValue(sPropDecimals));
1115 			}
1116 		}
1117 
1118 		// eine eventuelle-Min-Max-Konvertierung
1119 		Any aEffectiveMin( xOldProps->getPropertyValue(sPropEffectiveMin) );
1120 		if (aEffectiveMin.hasValue())
1121 		{	// im Gegensatz zu ValueMin kann EffectiveMin void sein
1122 			if (hasProperty(sPropValueMin, xNewProps))
1123 			{
1124 				OSL_ENSURE(aEffectiveMin.getValueType().getTypeClass() == TypeClass_DOUBLE,
1125 					"TransferFormComponentProperties : invalid property type !");
1126 				xNewProps->setPropertyValue(sPropValueMin, aEffectiveMin);
1127 			}
1128 		}
1129 		Any aEffectiveMax( xOldProps->getPropertyValue(sPropEffectiveMax) );
1130 		if (aEffectiveMax.hasValue())
1131 		{	// analog
1132 			if (hasProperty(sPropValueMax, xNewProps))
1133 			{
1134 				OSL_ENSURE(aEffectiveMax.getValueType().getTypeClass() == TypeClass_DOUBLE,
1135 					"TransferFormComponentProperties : invalid property type !");
1136 				xNewProps->setPropertyValue(sPropValueMax, aEffectiveMax);
1137 			}
1138 		}
1139 
1140 		// dann koennen wir noch Default-Werte konvertieren und uebernehmen
1141 		Any aEffectiveDefault( xOldProps->getPropertyValue(sPropEffectiveDefault) );
1142 		if (aEffectiveDefault.hasValue())
1143 		{
1144 			sal_Bool bIsString = aEffectiveDefault.getValueType().getTypeClass() == TypeClass_STRING;
1145 			OSL_ENSURE(bIsString || aEffectiveDefault.getValueType().getTypeClass() == TypeClass_DOUBLE,
1146 				"TransferFormComponentProperties : invalid property type !");
1147 				// die Effective-Properties sollten immer void oder string oder double sein ....
1148 
1149 			if (hasProperty(sPropDefaultDate, xNewProps) && !bIsString)
1150 			{	// (einen ::rtl::OUString in ein Datum zu konvertieren muss nicht immer klappen, denn das ganze kann ja an
1151 				// eine Textspalte gebunden gewesen sein, aber mit einem double koennen wir was anfangen)
1152 				Date aDate = DBTypeConversion::toDate(getDouble(aEffectiveDefault));
1153 				xNewProps->setPropertyValue(sPropDefaultDate, makeAny(aDate));
1154 			}
1155 
1156 			if (hasProperty(sPropDefaultTime, xNewProps) && !bIsString)
1157 			{	// voellig analog mit Zeit
1158 				Time aTime = DBTypeConversion::toTime(getDouble(aEffectiveDefault));
1159 				xNewProps->setPropertyValue(sPropDefaultTime, makeAny(aTime));
1160 			}
1161 
1162 			if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xNewProps) && !bIsString)
1163 			{	// hier koennen wir einfach das double durchreichen
1164 				xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), aEffectiveDefault);
1165 			}
1166 
1167 			if (hasProperty(sPropDefaultText, xNewProps) && bIsString)
1168 			{	// und hier den ::rtl::OUString
1169 				xNewProps->setPropertyValue(sPropDefaultText, aEffectiveDefault);
1170 			}
1171 
1172 			// nyi: die Uebersetzung zwischen doubles und ::rtl::OUString wuerde noch mehr Moeglichkeien eroeffnen
1173 		}
1174 	}
1175 
1176 	// die andere Richtung : das neu Control soll formatiert sein
1177 	if (bNewIsFormatted)
1178 	{
1179 		// zuerst die Formatierung
1180 		// einen Supplier koennen wir nicht setzen, also muss das neue Set schon einen mitbringen
1181 		Reference< XNumberFormatsSupplier> xSupplier;
1182 		xNewProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1183 		if (xSupplier.is())
1184 		{
1185 			Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1186 
1187 			// Dezimal-Stellen
1188 			sal_Int16 nDecimals = 2;
1189 			if (hasProperty(sPropDecimalAccuracy, xOldProps))
1190 				xOldProps->getPropertyValue(sPropDecimalAccuracy) >>= nDecimals;
1191 
1192 			// Grund-Format (je nach ClassId des alten Sets)
1193 			sal_Int32 nBaseKey = 0;
1194 			if (hasProperty(sPropClassId, xOldProps))
1195 			{
1196 				Reference< XNumberFormatTypes> xTypeList(xFormats, UNO_QUERY);
1197 				if (xTypeList.is())
1198 				{
1199 					sal_Int16 nClassId = 0;
1200 					xOldProps->getPropertyValue(sPropClassId) >>= nClassId;
1201 					switch (nClassId)
1202 					{
1203 						case FormComponentType::DATEFIELD :
1204 							nBaseKey = xTypeList->getStandardFormat(NumberFormat::DATE, _rLocale);
1205 							break;
1206 
1207 						case FormComponentType::TIMEFIELD :
1208 							nBaseKey = xTypeList->getStandardFormat(NumberFormat::TIME, _rLocale);
1209 							break;
1210 
1211 						case FormComponentType::CURRENCYFIELD :
1212 							nBaseKey = xTypeList->getStandardFormat(NumberFormat::CURRENCY, _rLocale);
1213 							break;
1214 					}
1215 				}
1216 			}
1217 
1218 			// damit koennen wir ein neues Format basteln ...
1219 			::rtl::OUString sNewFormat = xFormats->generateFormat(nBaseKey, _rLocale, sal_False, sal_False, nDecimals, 0);
1220 				// kein Tausender-Trennzeichen, negative Zahlen nicht in Rot, keine fuehrenden Nullen
1221 
1222 			// ... und zum FormatsSupplier hinzufuegen (wenn noetig)
1223 			sal_Int32 nKey = xFormats->queryKey(sNewFormat, _rLocale, sal_False);
1224 			if (nKey == (sal_Int32)-1)
1225 			{	// noch nicht vorhanden in meinem Formatter ...
1226 				nKey = xFormats->addNew(sNewFormat, _rLocale);
1227 			}
1228 
1229 			xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY), makeAny((sal_Int32)nKey));
1230 		}
1231 
1232 		// min-/max-Werte
1233 		Any aNewMin, aNewMax;
1234 		if (hasProperty(sPropValueMin, xOldProps))
1235 			aNewMin = xOldProps->getPropertyValue(sPropValueMin);
1236 		if (hasProperty(sPropValueMax, xOldProps))
1237 			aNewMax = xOldProps->getPropertyValue(sPropValueMax);
1238 		xNewProps->setPropertyValue(sPropEffectiveMin, aNewMin);
1239 		xNewProps->setPropertyValue(sPropEffectiveMax, aNewMax);
1240 
1241 		// Default-Wert
1242 		Any aNewDefault;
1243 		if (hasProperty(sPropDefaultDate, xOldProps))
1244 		{
1245 			Any aDate( xOldProps->getPropertyValue(sPropDefaultDate) );
1246 			if (aDate.hasValue())
1247 				aNewDefault <<= DBTypeConversion::toDouble(*(Date*)aDate.getValue());
1248 		}
1249 
1250 		if (hasProperty(sPropDefaultTime, xOldProps))
1251 		{
1252 			Any aTime( xOldProps->getPropertyValue(sPropDefaultTime) );
1253 			if (aTime.hasValue())
1254 				aNewDefault <<= DBTypeConversion::toDouble(*(Time*)aTime.getValue());
1255 		}
1256 
1257 		// double oder ::rtl::OUString werden direkt uebernommen
1258 		if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xOldProps))
1259 			aNewDefault = xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE));
1260 		if (hasProperty(sPropDefaultText, xOldProps))
1261 			aNewDefault = xOldProps->getPropertyValue(sPropDefaultText);
1262 
1263 		if (aNewDefault.hasValue())
1264 			xNewProps->setPropertyValue(sPropEffectiveDefault, aNewDefault);
1265 	}
1266 }
1267 catch(const Exception&)
1268 {
1269 	OSL_ENSURE( sal_False, "TransferFormComponentProperties: caught an exception!" );
1270 }
1271 }
1272 
1273 //------------------------------------------------------------------------------
1274 sal_Bool canInsert(const Reference< XPropertySet>& _rxCursorSet)
1275 {
1276 	return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue(::rtl::OUString::createFromAscii("Privileges"))) & Privilege::INSERT) != 0));
1277 }
1278 
1279 //------------------------------------------------------------------------------
1280 sal_Bool canUpdate(const Reference< XPropertySet>& _rxCursorSet)
1281 {
1282 	return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue(::rtl::OUString::createFromAscii("Privileges"))) & Privilege::UPDATE) != 0));
1283 }
1284 
1285 //------------------------------------------------------------------------------
1286 sal_Bool canDelete(const Reference< XPropertySet>& _rxCursorSet)
1287 {
1288 	return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue(::rtl::OUString::createFromAscii("Privileges"))) & Privilege::DELETE) != 0));
1289 }
1290 // -----------------------------------------------------------------------------
1291 Reference< XDataSource> findDataSource(const Reference< XInterface >& _xParent)
1292 {
1293 	Reference< XOfficeDatabaseDocument> xDatabaseDocument(_xParent, UNO_QUERY);
1294 	Reference< XDataSource> xDataSource;
1295 	if ( xDatabaseDocument.is() )
1296 		xDataSource = xDatabaseDocument->getDataSource();
1297 	if ( !xDataSource.is() )
1298 		xDataSource.set(_xParent, UNO_QUERY);
1299 	if (!xDataSource.is())
1300 	{
1301 		Reference< XChild> xChild(_xParent, UNO_QUERY);
1302 		if ( xChild.is() )
1303 			xDataSource = findDataSource(xChild->getParent());
1304 	}
1305 	return xDataSource;
1306 }
1307 
1308 //------------------------------------------------------------------------------
1309 ::rtl::OUString getComposedRowSetStatement( const Reference< XPropertySet >& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory,
1310                                    sal_Bool _bUseRowSetFilter, sal_Bool _bUseRowSetOrder, Reference< XSingleSelectQueryComposer >* _pxComposer )
1311     SAL_THROW( ( SQLException ) )
1312 {
1313     ::rtl::OUString sStatement;
1314 	try
1315 	{
1316         Reference< XConnection> xConn = connectRowset( Reference< XRowSet >( _rxRowSet, UNO_QUERY ), _rxFactory, sal_True );
1317 		if ( xConn.is() )		// implies _rxRowSet.is()
1318 		{
1319 			// build the statement the row set is based on (can't use the ActiveCommand property of the set
1320 			// as this reflects the status after the last execute, not the currently set properties)
1321 
1322             sal_Int32 nCommandType = CommandType::COMMAND;
1323             ::rtl::OUString sCommand;
1324             sal_Bool bEscapeProcessing = sal_False;
1325 
1326             OSL_VERIFY( _rxRowSet->getPropertyValue( ::rtl::OUString::createFromAscii( "CommandType" )      ) >>= nCommandType      );
1327 			OSL_VERIFY( _rxRowSet->getPropertyValue( ::rtl::OUString::createFromAscii( "Command" )          ) >>= sCommand          );
1328 			OSL_VERIFY( _rxRowSet->getPropertyValue( ::rtl::OUString::createFromAscii( "EscapeProcessing" ) ) >>= bEscapeProcessing );
1329 
1330             StatementComposer aComposer( xConn, sCommand, nCommandType, bEscapeProcessing );
1331 			// append sort
1332             if ( _bUseRowSetOrder )
1333 				aComposer.setOrder( getString( _rxRowSet->getPropertyValue( ::rtl::OUString::createFromAscii( "Order" ) ) ) );
1334 
1335             // append filter
1336             if ( _bUseRowSetFilter )
1337             {
1338 				sal_Bool bApplyFilter = sal_True;
1339                 _rxRowSet->getPropertyValue( ::rtl::OUString::createFromAscii( "ApplyFilter" ) ) >>= bApplyFilter;
1340 				if ( bApplyFilter )
1341 					aComposer.setFilter( getString( _rxRowSet->getPropertyValue( ::rtl::OUString::createFromAscii( "Filter" ) ) ) );
1342             }
1343 
1344             sStatement = aComposer.getQuery();
1345 
1346             if ( _pxComposer )
1347             {
1348                 *_pxComposer = aComposer.getComposer();
1349                 aComposer.setDisposeComposer( false );
1350             }
1351 		}
1352 	}
1353 	catch( const SQLException& )
1354 	{
1355 		throw;
1356 	}
1357 	catch( const Exception& )
1358 	{
1359         DBG_UNHANDLED_EXCEPTION();
1360 	}
1361 
1362     return sStatement;
1363 }
1364 
1365 //------------------------------------------------------------------------------
1366 ::rtl::OUString getComposedRowSetStatement(
1367                     const Reference< XPropertySet >& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory,
1368                     sal_Bool _bUseRowSetFilter, sal_Bool _bUseRowSetOrder )
1369 {
1370     return getComposedRowSetStatement( _rxRowSet, _rxFactory, _bUseRowSetFilter, _bUseRowSetOrder, NULL );
1371 }
1372 
1373 //------------------------------------------------------------------------------
1374 Reference< XSingleSelectQueryComposer > getCurrentSettingsComposer(
1375 				const Reference< XPropertySet>& _rxRowSetProps,
1376 				const Reference< XMultiServiceFactory>& _rxFactory)
1377 {
1378 	Reference< XSingleSelectQueryComposer > xReturn;
1379 	try
1380 	{
1381         getComposedRowSetStatement( _rxRowSetProps, _rxFactory, sal_True, sal_True, &xReturn );
1382 	}
1383 	catch( const SQLException& )
1384 	{
1385 		throw;
1386 	}
1387 	catch( const Exception& )
1388 	{
1389 		OSL_ENSURE( sal_False, "::getCurrentSettingsComposer : caught an exception !" );
1390 	}
1391 
1392 	return xReturn;
1393 }
1394 //--------------------------------------------------------------------------
1395 ::rtl::OUString composeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
1396 						const ::rtl::OUString& _rCatalog,
1397 						const ::rtl::OUString& _rSchema,
1398 						const ::rtl::OUString& _rName,
1399 						sal_Bool _bQuote,
1400 						EComposeRule _eComposeRule)
1401 {
1402     return impl_doComposeTableName( _rxMetaData, _rCatalog, _rSchema, _rName, _bQuote, _eComposeRule );
1403 }
1404 
1405 // -----------------------------------------------------------------------------
1406 ::rtl::OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection,
1407     const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName )
1408 {
1409 	sal_Bool bUseCatalogInSelect = isDataSourcePropertyEnabled( _rxConnection, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "UseCatalogInSelect" ) ), sal_True );
1410 	sal_Bool bUseSchemaInSelect = isDataSourcePropertyEnabled( _rxConnection, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "UseSchemaInSelect" ) ), sal_True );
1411 
1412     return impl_doComposeTableName(
1413         _rxConnection->getMetaData(),
1414         bUseCatalogInSelect ? _rCatalog : ::rtl::OUString(),
1415         bUseSchemaInSelect ? _rSchema : ::rtl::OUString(),
1416         _rName,
1417         true,
1418         eInDataManipulation
1419     );
1420 }
1421 
1422 // -----------------------------------------------------------------------------
1423 namespace
1424 {
1425     static void lcl_getTableNameComponents( const Reference<XPropertySet>& _xTable,
1426         ::rtl::OUString& _out_rCatalog, ::rtl::OUString& _out_rSchema, ::rtl::OUString& _out_rName )
1427     {
1428         ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
1429         Reference< XPropertySetInfo > xInfo = _xTable->getPropertySetInfo();
1430         if (	xInfo.is()
1431             &&	xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) )
1432         {
1433 
1434 	        ::rtl::OUString aCatalog;
1435 	        ::rtl::OUString aSchema;
1436 	        ::rtl::OUString aTable;
1437             if (    xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME))
1438 	            &&	xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) )
1439             {
1440 	            _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME))	>>= _out_rCatalog;
1441 	            _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME))	>>= _out_rSchema;
1442             }
1443 	        _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))		>>= _out_rName;
1444         }
1445         else
1446             OSL_ENSURE( false, "::dbtools::lcl_getTableNameComponents: this is no table object!" );
1447     }
1448 }
1449 
1450 // -----------------------------------------------------------------------------
1451 ::rtl::OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const Reference<XPropertySet>& _xTable )
1452 {
1453     ::rtl::OUString sCatalog, sSchema, sName;
1454     lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1455 
1456     return composeTableNameForSelect( _rxConnection, sCatalog, sSchema, sName );
1457 }
1458 
1459 // -----------------------------------------------------------------------------
1460 ::rtl::OUString composeTableName(const Reference<XDatabaseMetaData>& _xMetaData,
1461 								 const Reference<XPropertySet>& _xTable,
1462 								 EComposeRule _eComposeRule,
1463                                  bool _bSuppressCatalog,
1464                                  bool _bSuppressSchema,
1465                                  bool _bQuote )
1466 {
1467     ::rtl::OUString sCatalog, sSchema, sName;
1468     lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1469 
1470     return impl_doComposeTableName(
1471             _xMetaData,
1472             _bSuppressCatalog ? ::rtl::OUString() : sCatalog,
1473             _bSuppressSchema ? ::rtl::OUString() : sSchema,
1474             sName,
1475             _bQuote,
1476             _eComposeRule
1477         );
1478 }
1479 // -----------------------------------------------------------------------------
1480 sal_Int32 getSearchColumnFlag( const Reference< XConnection>& _rxConn,sal_Int32 _nDataType)
1481 {
1482 	sal_Int32 nSearchFlag = 0;
1483 	Reference<XResultSet> xSet = _rxConn->getMetaData()->getTypeInfo();
1484 	if(xSet.is())
1485 	{
1486 		Reference<XRow> xRow(xSet,UNO_QUERY);
1487 		while(xSet->next())
1488 		{
1489 			if(xRow->getInt(2) == _nDataType)
1490 			{
1491 				nSearchFlag = xRow->getInt(9);
1492 				break;
1493 			}
1494 		}
1495 	}
1496 	return nSearchFlag;
1497 }
1498 
1499 // -----------------------------------------------------------------------------
1500 ::rtl::OUString createUniqueName( const Sequence< ::rtl::OUString >& _rNames, const ::rtl::OUString& _rBaseName, sal_Bool _bStartWithNumber )
1501 {
1502     ::std::set< ::rtl::OUString > aUsedNames;
1503     ::std::copy(
1504         _rNames.getConstArray(),
1505         _rNames.getConstArray() + _rNames.getLength(),
1506         ::std::insert_iterator< ::std::set< ::rtl::OUString > >( aUsedNames, aUsedNames.end() )
1507     );
1508 
1509 	::rtl::OUString sName( _rBaseName );
1510 	sal_Int32 nPos = 1;
1511 	if ( _bStartWithNumber )
1512 		sName += ::rtl::OUString::valueOf( nPos );
1513 
1514     while ( aUsedNames.find( sName ) != aUsedNames.end() )
1515 	{
1516 		sName = _rBaseName;
1517 		sName += ::rtl::OUString::valueOf( ++nPos );
1518 	}
1519 	return sName;
1520 }
1521 
1522 // -----------------------------------------------------------------------------
1523 ::rtl::OUString createUniqueName(const Reference<XNameAccess>& _rxContainer,const ::rtl::OUString& _rBaseName,sal_Bool _bStartWithNumber)
1524 {
1525     Sequence< ::rtl::OUString > aElementNames;
1526 
1527     OSL_ENSURE( _rxContainer.is(), "createUniqueName: invalid container!" );
1528 	if ( _rxContainer.is() )
1529         aElementNames = _rxContainer->getElementNames();
1530 
1531     return createUniqueName( aElementNames, _rBaseName, _bStartWithNumber );
1532 }
1533 
1534 // -----------------------------------------------------------------------------
1535 void showError(const SQLExceptionInfo& _rInfo,
1536 			   const Reference< XWindow>& _xParent,
1537 			   const Reference< XMultiServiceFactory >& _xFactory)
1538 {
1539 	if (_rInfo.isValid())
1540 	{
1541 		try
1542 		{
1543 			Sequence< Any > aArgs(2);
1544 			aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("SQLException"), 0, _rInfo.get(), PropertyState_DIRECT_VALUE);
1545 			aArgs[1] <<= PropertyValue(::rtl::OUString::createFromAscii("ParentWindow"), 0, makeAny(_xParent), PropertyState_DIRECT_VALUE);
1546 
1547 			static ::rtl::OUString s_sDialogServiceName = ::rtl::OUString::createFromAscii("com.sun.star.sdb.ErrorMessageDialog");
1548 			Reference< XExecutableDialog > xErrorDialog(
1549 				_xFactory->createInstanceWithArguments(s_sDialogServiceName, aArgs), UNO_QUERY);
1550 			if (xErrorDialog.is())
1551 				xErrorDialog->execute();
1552 			else
1553 			{
1554 				OSL_ENSURE(0,"dbtools::showError: no XExecutableDialog found!");
1555 			}
1556 		}
1557 		catch(Exception&)
1558 		{
1559 			OSL_ENSURE(0,"showError: could not display the error message!");
1560 		}
1561 	}
1562 }
1563 
1564 // -------------------------------------------------------------------------
1565 sal_Bool implUpdateObject(const Reference< XRowUpdate >& _rxUpdatedObject,
1566 	const sal_Int32 _nColumnIndex, const Any& _rValue) SAL_THROW ( ( SQLException, RuntimeException ) )
1567 {
1568 	sal_Bool bSuccessfullyReRouted = sal_True;
1569 	switch (_rValue.getValueTypeClass())
1570 	{
1571 		case TypeClass_ANY:
1572 		{
1573 			Any aInnerValue;
1574 			_rValue >>= aInnerValue;
1575 			bSuccessfullyReRouted = implUpdateObject(_rxUpdatedObject, _nColumnIndex, aInnerValue);
1576 		}
1577 		break;
1578 
1579 		case TypeClass_VOID:
1580 			_rxUpdatedObject->updateNull(_nColumnIndex);
1581 			break;
1582 
1583 		case TypeClass_STRING:
1584 			_rxUpdatedObject->updateString(_nColumnIndex, *(rtl::OUString*)_rValue.getValue());
1585 			break;
1586 
1587 		case TypeClass_BOOLEAN:
1588 			_rxUpdatedObject->updateBoolean(_nColumnIndex, *(sal_Bool *)_rValue.getValue());
1589 			break;
1590 
1591 		case TypeClass_BYTE:
1592 			_rxUpdatedObject->updateByte(_nColumnIndex, *(sal_Int8 *)_rValue.getValue());
1593 			break;
1594 
1595 		case TypeClass_UNSIGNED_SHORT:
1596 		case TypeClass_SHORT:
1597 			_rxUpdatedObject->updateShort(_nColumnIndex, *(sal_Int16*)_rValue.getValue());
1598 			break;
1599 
1600 		case TypeClass_CHAR:
1601 			_rxUpdatedObject->updateString(_nColumnIndex,::rtl::OUString((sal_Unicode *)_rValue.getValue(),1));
1602 			break;
1603 
1604 		case TypeClass_UNSIGNED_LONG:
1605 		case TypeClass_LONG:
1606 			_rxUpdatedObject->updateInt(_nColumnIndex, *(sal_Int32*)_rValue.getValue());
1607 			break;
1608 
1609         case TypeClass_HYPER:
1610 		{
1611 			sal_Int64 nValue = 0;
1612 			OSL_VERIFY( _rValue >>= nValue );
1613 			_rxUpdatedObject->updateLong( _nColumnIndex, nValue );
1614 		}
1615 		break;
1616 
1617 		case TypeClass_FLOAT:
1618 			_rxUpdatedObject->updateFloat(_nColumnIndex, *(float*)_rValue.getValue());
1619 			break;
1620 
1621 		case TypeClass_DOUBLE:
1622 			_rxUpdatedObject->updateDouble(_nColumnIndex, *(double*)_rValue.getValue());
1623 			break;
1624 
1625 		case TypeClass_SEQUENCE:
1626 			if (_rValue.getValueType() == ::getCppuType((const Sequence< sal_Int8 > *)0))
1627 				_rxUpdatedObject->updateBytes(_nColumnIndex, *(Sequence<sal_Int8>*)_rValue.getValue());
1628 			else
1629 				bSuccessfullyReRouted = sal_False;
1630 			break;
1631 		case TypeClass_STRUCT:
1632 			if (_rValue.getValueType() == ::getCppuType((const DateTime*)0))
1633 				_rxUpdatedObject->updateTimestamp(_nColumnIndex, *(DateTime*)_rValue.getValue());
1634 			else if (_rValue.getValueType() == ::getCppuType((const Date*)0))
1635 				_rxUpdatedObject->updateDate(_nColumnIndex, *(Date*)_rValue.getValue());
1636 			else if (_rValue.getValueType() == ::getCppuType((const Time*)0))
1637 				_rxUpdatedObject->updateTime(_nColumnIndex, *(Time*)_rValue.getValue());
1638 			else
1639 				bSuccessfullyReRouted = sal_False;
1640 			break;
1641 
1642 		case TypeClass_INTERFACE:
1643 			if (_rValue.getValueType() == ::getCppuType(static_cast<Reference< XInputStream>*>(NULL)))
1644 			{
1645 				Reference< XInputStream >  xStream;
1646 				_rValue >>= xStream;
1647 				_rxUpdatedObject->updateBinaryStream(_nColumnIndex, xStream, xStream->available());
1648 				break;
1649 			}
1650 			// run through
1651 		default:
1652 			bSuccessfullyReRouted = sal_False;
1653 	}
1654 
1655 	return bSuccessfullyReRouted;
1656 }
1657 // -------------------------------------------------------------------------
1658 sal_Bool implSetObject(	const Reference< XParameters >& _rxParameters,
1659 						const sal_Int32 _nColumnIndex, const Any& _rValue) SAL_THROW ( ( SQLException, RuntimeException ) )
1660 {
1661 	sal_Bool bSuccessfullyReRouted = sal_True;
1662 	switch (_rValue.getValueTypeClass())
1663 	{
1664 		case TypeClass_HYPER:
1665 		{
1666 			sal_Int64 nValue = 0;
1667 			OSL_VERIFY( _rValue >>= nValue );
1668 			_rxParameters->setLong( _nColumnIndex, nValue );
1669 		}
1670 		break;
1671 
1672 		case TypeClass_ANY:
1673 		{
1674 			Any aInnerValue;
1675 			_rValue >>= aInnerValue;
1676 			bSuccessfullyReRouted = implSetObject(_rxParameters, _nColumnIndex, aInnerValue);
1677 		}
1678 		break;
1679 
1680 		case TypeClass_VOID:
1681 			_rxParameters->setNull(_nColumnIndex,DataType::VARCHAR);
1682 			break;
1683 
1684 		case TypeClass_STRING:
1685 			_rxParameters->setString(_nColumnIndex, *(rtl::OUString*)_rValue.getValue());
1686 			break;
1687 
1688 		case TypeClass_BOOLEAN:
1689 			_rxParameters->setBoolean(_nColumnIndex, *(sal_Bool *)_rValue.getValue());
1690 			break;
1691 
1692 		case TypeClass_BYTE:
1693 			_rxParameters->setByte(_nColumnIndex, *(sal_Int8 *)_rValue.getValue());
1694 			break;
1695 
1696 		case TypeClass_UNSIGNED_SHORT:
1697 		case TypeClass_SHORT:
1698 			_rxParameters->setShort(_nColumnIndex, *(sal_Int16*)_rValue.getValue());
1699 			break;
1700 
1701 		case TypeClass_CHAR:
1702 			_rxParameters->setString(_nColumnIndex, ::rtl::OUString((sal_Unicode *)_rValue.getValue(),1));
1703 			break;
1704 
1705 		case TypeClass_UNSIGNED_LONG:
1706 		case TypeClass_LONG:
1707 			_rxParameters->setInt(_nColumnIndex, *(sal_Int32*)_rValue.getValue());
1708 			break;
1709 
1710 		case TypeClass_FLOAT:
1711 			_rxParameters->setFloat(_nColumnIndex, *(float*)_rValue.getValue());
1712 			break;
1713 
1714 		case TypeClass_DOUBLE:
1715 			_rxParameters->setDouble(_nColumnIndex, *(double*)_rValue.getValue());
1716 			break;
1717 
1718 		case TypeClass_SEQUENCE:
1719 			if (_rValue.getValueType() == ::getCppuType((const Sequence< sal_Int8 > *)0))
1720 			{
1721 				_rxParameters->setBytes(_nColumnIndex, *(Sequence<sal_Int8>*)_rValue.getValue());
1722 			}
1723 			else
1724 				bSuccessfullyReRouted = sal_False;
1725 			break;
1726 		case TypeClass_STRUCT:
1727 			if (_rValue.getValueType() == ::getCppuType((const DateTime*)0))
1728 				_rxParameters->setTimestamp(_nColumnIndex, *(DateTime*)_rValue.getValue());
1729 			else if (_rValue.getValueType() == ::getCppuType((const Date*)0))
1730 				_rxParameters->setDate(_nColumnIndex, *(Date*)_rValue.getValue());
1731 			else if (_rValue.getValueType() == ::getCppuType((const Time*)0))
1732 				_rxParameters->setTime(_nColumnIndex, *(Time*)_rValue.getValue());
1733 			else
1734 				bSuccessfullyReRouted = sal_False;
1735 			break;
1736 
1737 		case TypeClass_INTERFACE:
1738 			if (_rValue.getValueType() == ::getCppuType(static_cast<Reference< XInputStream>*>(NULL)))
1739 			{
1740 				Reference< XInputStream >  xStream;
1741 				_rValue >>= xStream;
1742 				_rxParameters->setBinaryStream(_nColumnIndex, xStream, xStream->available());
1743 				break;
1744 			}
1745 			// run through
1746 		default:
1747 			bSuccessfullyReRouted = sal_False;
1748 
1749 	}
1750 
1751 	return bSuccessfullyReRouted;
1752 }
1753 
1754 //..................................................................
1755 namespace
1756 {
1757     class OParameterWrapper : public ::cppu::WeakImplHelper1< XIndexAccess >
1758     {
1759         ::std::bit_vector       m_aSet;
1760         Reference<XIndexAccess> m_xSource;
1761     public:
1762         OParameterWrapper(const ::std::bit_vector& _aSet,const Reference<XIndexAccess>& _xSource) : m_aSet(_aSet),m_xSource(_xSource){}
1763     private:
1764         // ::com::sun::star::container::XElementAccess
1765         virtual Type SAL_CALL getElementType() throw(RuntimeException)
1766         {
1767             return m_xSource->getElementType();
1768         }
1769 		virtual sal_Bool SAL_CALL hasElements(  ) throw(RuntimeException)
1770         {
1771             if ( m_aSet.empty() )
1772                 return m_xSource->hasElements();
1773             return ::std::count(m_aSet.begin(),m_aSet.end(),false) != 0;
1774         }
1775         // ::com::sun::star::container::XIndexAccess
1776         virtual sal_Int32 SAL_CALL getCount(  ) throw(RuntimeException)
1777         {
1778             if ( m_aSet.empty() )
1779                 return m_xSource->getCount();
1780             return ::std::count(m_aSet.begin(),m_aSet.end(),false);
1781         }
1782         virtual Any SAL_CALL getByIndex( sal_Int32 Index ) throw(IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
1783         {
1784             if ( m_aSet.empty() )
1785                 return m_xSource->getByIndex(Index);
1786             if ( m_aSet.size() < (size_t)Index )
1787                 throw IndexOutOfBoundsException();
1788 
1789             ::std::bit_vector::iterator aIter = m_aSet.begin();
1790             ::std::bit_vector::iterator aEnd = m_aSet.end();
1791             sal_Int32 i = 0;
1792             sal_Int32 nParamPos = -1;
1793             for(; aIter != aEnd && i <= Index; ++aIter)
1794             {
1795                 ++nParamPos;
1796                 if ( !*aIter )
1797                 {
1798                     ++i;
1799                 }
1800             }
1801             return m_xSource->getByIndex(nParamPos);
1802         }
1803     };
1804 }
1805 
1806 // -----------------------------------------------------------------------------
1807 void askForParameters(const Reference< XSingleSelectQueryComposer >& _xComposer,
1808 					  const Reference<XParameters>& _xParameters,
1809 					  const Reference< XConnection>& _xConnection,
1810 					  const Reference< XInteractionHandler >& _rxHandler,
1811                       const ::std::bit_vector& _aParametersSet)
1812 {
1813 	OSL_ENSURE(_xComposer.is(),"dbtools::askForParameters XSQLQueryComposer is null!");
1814 	OSL_ENSURE(_xParameters.is(),"dbtools::askForParameters XParameters is null!");
1815 	OSL_ENSURE(_xConnection.is(),"dbtools::askForParameters XConnection is null!");
1816 	OSL_ENSURE(_rxHandler.is(),"dbtools::askForParameters XInteractionHandler is null!");
1817 
1818 	// we have to set this here again because getCurrentSettingsComposer can force a setpropertyvalue
1819 	Reference<XParametersSupplier>  xParameters = Reference<XParametersSupplier> (_xComposer, UNO_QUERY);
1820 
1821 	Reference<XIndexAccess>  xParamsAsIndicies = xParameters.is() ? xParameters->getParameters() : Reference<XIndexAccess>();
1822 	Reference<XNameAccess>   xParamsAsNames(xParamsAsIndicies, UNO_QUERY);
1823 	sal_Int32 nParamCount = xParamsAsIndicies.is() ? xParamsAsIndicies->getCount() : 0;
1824     ::std::bit_vector aNewParameterSet( _aParametersSet );
1825     if ( nParamCount || ::std::count(aNewParameterSet.begin(),aNewParameterSet.end(),true) != nParamCount )
1826     {
1827         static const ::rtl::OUString PROPERTY_NAME(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME));
1828         aNewParameterSet.resize(nParamCount ,false);
1829         typedef ::std::map< ::rtl::OUString, ::std::vector<sal_Int32> > TParameterPositions;
1830         TParameterPositions aParameterNames;
1831         for(sal_Int32 i = 0; i < nParamCount; ++i)
1832         {
1833             Reference<XPropertySet> xParam(xParamsAsIndicies->getByIndex(i),UNO_QUERY);
1834             ::rtl::OUString sName;
1835             xParam->getPropertyValue(PROPERTY_NAME) >>= sName;
1836 
1837             TParameterPositions::iterator aFind = aParameterNames.find(sName);
1838             if ( aFind != aParameterNames.end() )
1839                 aNewParameterSet[i] = true;
1840             aParameterNames[sName].push_back(i+1);
1841         }
1842 		// build an interaction request
1843 		// two continuations (Ok and Cancel)
1844 		OInteractionAbort* pAbort = new OInteractionAbort;
1845 		OParameterContinuation* pParams = new OParameterContinuation;
1846 		// the request
1847 		ParametersRequest aRequest;
1848         Reference<XIndexAccess> xWrappedParameters = new OParameterWrapper(aNewParameterSet,xParamsAsIndicies);
1849 		aRequest.Parameters = xWrappedParameters;
1850 		aRequest.Connection = _xConnection;
1851 		OInteractionRequest* pRequest = new OInteractionRequest(makeAny(aRequest));
1852 		Reference< XInteractionRequest > xRequest(pRequest);
1853 		// some knittings
1854 		pRequest->addContinuation(pAbort);
1855 		pRequest->addContinuation(pParams);
1856 
1857 		// execute the request
1858 		_rxHandler->handle(xRequest);
1859 
1860 		if (!pParams->wasSelected())
1861 		{
1862 			// canceled by the user (i.e. (s)he canceled the dialog)
1863 			RowSetVetoException e;
1864 			e.ErrorCode = ParameterInteractionCancelled;
1865 			throw e;
1866 		}
1867 
1868 		// now transfer the values from the continuation object to the parameter columns
1869 		Sequence< PropertyValue > aFinalValues = pParams->getValues();
1870 		const PropertyValue* pFinalValues = aFinalValues.getConstArray();
1871 		for (sal_Int32 i=0; i<aFinalValues.getLength(); ++i, ++pFinalValues)
1872 		{
1873 			Reference< XPropertySet > xParamColumn(xWrappedParameters->getByIndex(i),UNO_QUERY);
1874 			if (xParamColumn.is())
1875 			{
1876 				::rtl::OUString sName;
1877 				xParamColumn->getPropertyValue(PROPERTY_NAME) >>= sName;
1878 				OSL_ENSURE(sName.equals(pFinalValues->Name), "::dbaui::askForParameters: inconsistent parameter names!");
1879 
1880 				// determine the field type and ...
1881 				sal_Int32 nParamType = 0;
1882 				xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nParamType;
1883 				// ... the scale of the parameter column
1884 				sal_Int32 nScale = 0;
1885 				if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE), xParamColumn))
1886 					xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
1887 					// (the index of the parameters is one-based)
1888                 TParameterPositions::iterator aFind = aParameterNames.find(pFinalValues->Name);
1889                 ::std::vector<sal_Int32>::iterator aIterPos = aFind->second.begin();
1890                 ::std::vector<sal_Int32>::iterator aEndPos = aFind->second.end();
1891                 for(;aIterPos != aEndPos;++aIterPos)
1892                 {
1893                     if ( _aParametersSet.empty() || !_aParametersSet[(*aIterPos)-1] )
1894                     {
1895                         _xParameters->setObjectWithInfo(*aIterPos, pFinalValues->Value, nParamType, nScale);
1896                     }
1897                 }
1898 			}
1899 		}
1900 	}
1901 }
1902 // -----------------------------------------------------------------------------
1903 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1904 					   sal_Int32 parameterIndex,
1905 					   const Any& x,
1906 					   sal_Int32 sqlType,
1907 					   sal_Int32 scale)  throw(SQLException, RuntimeException)
1908 {
1909 	ORowSetValue aVal;
1910 	aVal.fill(x);
1911 	setObjectWithInfo(_xParams,parameterIndex,aVal,sqlType,scale);
1912 }
1913 // -----------------------------------------------------------------------------
1914 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1915 					   sal_Int32 parameterIndex,
1916 					   const ::connectivity::ORowSetValue& _rValue,
1917 					   sal_Int32 sqlType,
1918 					   sal_Int32 scale)  throw(SQLException, RuntimeException)
1919 {
1920 	if ( _rValue.isNull() )
1921 		_xParams->setNull(parameterIndex,sqlType);
1922 	else
1923 	{
1924 		switch(sqlType)
1925 		{
1926             case DataType::DECIMAL:
1927             case DataType::NUMERIC:
1928                 _xParams->setObjectWithInfo(parameterIndex,_rValue.makeAny(),sqlType,scale);
1929                 break;
1930 			case DataType::CHAR:
1931 			case DataType::VARCHAR:
1932 			case DataType::LONGVARCHAR:
1933 				_xParams->setString(parameterIndex,_rValue);
1934 				break;
1935 			case DataType::CLOB:
1936 				{
1937 					Any x(_rValue.makeAny());
1938 					::rtl::OUString sValue;
1939 					if ( x >>= sValue )
1940 						_xParams->setString(parameterIndex,sValue);
1941 					else
1942 					{
1943 						Reference< XClob > xClob;
1944 						if(x >>= xClob)
1945 							_xParams->setClob(parameterIndex,xClob);
1946 						else
1947 						{
1948 							Reference< ::com::sun::star::io::XInputStream > xStream;
1949 							if(x >>= xStream)
1950 								_xParams->setCharacterStream(parameterIndex,xStream,xStream->available());
1951 						}
1952 					}
1953 				}
1954 				break;
1955 			case DataType::BIGINT:
1956 				if ( _rValue.isSigned() )
1957 					_xParams->setLong(parameterIndex,_rValue);
1958 				else
1959 					_xParams->setString(parameterIndex,_rValue);
1960 				break;
1961 
1962 			case DataType::FLOAT:
1963 				_xParams->setFloat(parameterIndex,_rValue);
1964 				break;
1965 			case DataType::REAL:
1966 			case DataType::DOUBLE:
1967 				_xParams->setDouble(parameterIndex,_rValue);
1968 				break;
1969 			case DataType::DATE:
1970 				_xParams->setDate(parameterIndex,_rValue);
1971 				break;
1972 			case DataType::TIME:
1973 				_xParams->setTime(parameterIndex,_rValue);
1974 				break;
1975 			case DataType::TIMESTAMP:
1976 				_xParams->setTimestamp(parameterIndex,_rValue);
1977 				break;
1978 			case DataType::BINARY:
1979 			case DataType::VARBINARY:
1980 			case DataType::LONGVARBINARY:
1981 			case DataType::BLOB:
1982 				{
1983 					Any x(_rValue.makeAny());
1984 					Sequence< sal_Int8> aBytes;
1985 					if(x >>= aBytes)
1986 						_xParams->setBytes(parameterIndex,aBytes);
1987 					else
1988 					{
1989 						Reference< XBlob > xBlob;
1990 						if(x >>= xBlob)
1991 							_xParams->setBlob(parameterIndex,xBlob);
1992 						else
1993 						{
1994 							Reference< XClob > xClob;
1995 							if(x >>= xClob)
1996 								_xParams->setClob(parameterIndex,xClob);
1997 							else
1998 							{
1999 								Reference< ::com::sun::star::io::XInputStream > xBinStream;
2000 								if(x >>= xBinStream)
2001 									_xParams->setBinaryStream(parameterIndex,xBinStream,xBinStream->available());
2002 							}
2003 						}
2004 					}
2005 				}
2006 				break;
2007 			case DataType::BIT:
2008 			case DataType::BOOLEAN:
2009 				_xParams->setBoolean(parameterIndex,_rValue);
2010 				break;
2011 			case DataType::TINYINT:
2012 			    if ( _rValue.isSigned() )
2013 					_xParams->setByte(parameterIndex,_rValue);
2014 				else
2015 					_xParams->setShort(parameterIndex,_rValue);
2016 				break;
2017 			case DataType::SMALLINT:
2018 				if ( _rValue.isSigned() )
2019 					_xParams->setShort(parameterIndex,_rValue);
2020 				else
2021 					_xParams->setInt(parameterIndex,_rValue);
2022 				break;
2023 			case DataType::INTEGER:
2024 				if ( _rValue.isSigned() )
2025 					_xParams->setInt(parameterIndex,_rValue);
2026 				else
2027 					_xParams->setLong(parameterIndex,_rValue);
2028 				break;
2029 			default:
2030 				{
2031                     ::connectivity::SharedResources aResources;
2032                     const ::rtl::OUString sError( aResources.getResourceStringWithSubstitution(
2033                             STR_UNKNOWN_PARA_TYPE,
2034                             "$position$", ::rtl::OUString::valueOf(parameterIndex)
2035                          ) );
2036 		            ::dbtools::throwGenericSQLException(sError,NULL);
2037 				}
2038 		}
2039 	}
2040 }
2041 
2042 // --------------------------------------------------------------------
2043 void getBoleanComparisonPredicate( const ::rtl::OUString& _rExpression, const sal_Bool _bValue, const sal_Int32 _nBooleanComparisonMode,
2044     ::rtl::OUStringBuffer& _out_rSQLPredicate )
2045 {
2046     switch ( _nBooleanComparisonMode )
2047     {
2048     case BooleanComparisonMode::IS_LITERAL:
2049         _out_rSQLPredicate.append( _rExpression );
2050         if ( _bValue )
2051             _out_rSQLPredicate.appendAscii( " IS TRUE" );
2052         else
2053             _out_rSQLPredicate.appendAscii( " IS FALSE" );
2054         break;
2055 
2056     case BooleanComparisonMode::EQUAL_LITERAL:
2057         _out_rSQLPredicate.append( _rExpression );
2058         _out_rSQLPredicate.appendAscii( _bValue ? " = TRUE" : " = FALSE" );
2059         break;
2060 
2061     case BooleanComparisonMode::ACCESS_COMPAT:
2062         if ( _bValue )
2063         {
2064             _out_rSQLPredicate.appendAscii( " NOT ( ( " );
2065             _out_rSQLPredicate.append( _rExpression );
2066             _out_rSQLPredicate.appendAscii( " = 0 ) OR ( " );
2067             _out_rSQLPredicate.append( _rExpression );
2068             _out_rSQLPredicate.appendAscii( " IS NULL ) )" );
2069         }
2070         else
2071         {
2072             _out_rSQLPredicate.append( _rExpression );
2073             _out_rSQLPredicate.appendAscii( " = 0" );
2074         }
2075         break;
2076 
2077     case BooleanComparisonMode::EQUAL_INTEGER:
2078         // fall through
2079     default:
2080         _out_rSQLPredicate.append( _rExpression );
2081         _out_rSQLPredicate.appendAscii( _bValue ? " = 1" : " = 0" );
2082         break;
2083     }
2084 }
2085 
2086 //.........................................................................
2087 }	// namespace dbtools
2088 //.........................................................................
2089 
2090 //.........................................................................
2091 namespace connectivity
2092 {
2093 //.........................................................................
2094 
2095 void release(oslInterlockedCount& _refCount,
2096 			 ::cppu::OBroadcastHelper& rBHelper,
2097 			 Reference< XInterface >& _xInterface,
2098 			 ::com::sun::star::lang::XComponent* _pObject)
2099 {
2100 	if (osl_decrementInterlockedCount( &_refCount ) == 0)
2101 	{
2102 		osl_incrementInterlockedCount( &_refCount );
2103 
2104 		if (!rBHelper.bDisposed && !rBHelper.bInDispose)
2105 		{
2106 			// remember the parent
2107 			Reference< XInterface > xParent;
2108 			{
2109 				::osl::MutexGuard aGuard( rBHelper.rMutex );
2110 				xParent = _xInterface;
2111 				_xInterface = NULL;
2112 			}
2113 
2114 			// First dispose
2115 			_pObject->dispose();
2116 
2117 			// only the alive ref holds the object
2118 			OSL_ASSERT( _refCount == 1 );
2119 
2120 			// release the parent in the ~
2121 			if (xParent.is())
2122 			{
2123 				::osl::MutexGuard aGuard( rBHelper.rMutex );
2124 				_xInterface = xParent;
2125 			}
2126 
2127 //					// destroy the object if xHoldAlive decrement the refcount to 0
2128 //					m_pDerivedImplementation->WEAK::release();
2129 		}
2130 	}
2131 	else
2132 		osl_incrementInterlockedCount( &_refCount );
2133 }
2134 
2135 void checkDisposed(sal_Bool _bThrow) throw ( DisposedException )
2136 {
2137 	if (_bThrow)
2138 		throw DisposedException();
2139 
2140 }
2141 // -------------------------------------------------------------------------
2142 	OSQLColumns::Vector::const_iterator find(	OSQLColumns::Vector::const_iterator __first,
2143 										OSQLColumns::Vector::const_iterator __last,
2144 										const ::rtl::OUString& _rVal,
2145 										const ::comphelper::UStringMixEqual& _rCase)
2146 	{
2147 		::rtl::OUString sName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
2148 		return find(__first,__last,sName,_rVal,_rCase);
2149 	}
2150 	// -------------------------------------------------------------------------
2151 	OSQLColumns::Vector::const_iterator findRealName(	OSQLColumns::Vector::const_iterator __first,
2152 										OSQLColumns::Vector::const_iterator __last,
2153 										const ::rtl::OUString& _rVal,
2154 										const ::comphelper::UStringMixEqual& _rCase)
2155 	{
2156 		::rtl::OUString sRealName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME);
2157 		return find(__first,__last,sRealName,_rVal,_rCase);
2158 	}
2159 	// -------------------------------------------------------------------------
2160 	OSQLColumns::Vector::const_iterator find(	OSQLColumns::Vector::const_iterator __first,
2161 										OSQLColumns::Vector::const_iterator __last,
2162 										const ::rtl::OUString& _rProp,
2163 										const ::rtl::OUString& _rVal,
2164 										const ::comphelper::UStringMixEqual& _rCase)
2165 	{
2166 		while (__first != __last && !_rCase(getString((*__first)->getPropertyValue(_rProp)),_rVal))
2167 			++__first;
2168 		return __first;
2169 	}
2170 
2171 // -----------------------------------------------------------------------------
2172 } //namespace connectivity
2173 // -----------------------------------------------------------------------------
2174 
2175