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