Version 4.3.0.0.beta1, tag libreoffice-4.3.0.0.beta1
[LibreOffice.git] / connectivity / source / commontools / dbtools.cxx
blob7ebf4a1656225b9bc8551c48353cd297f37d8584
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include "connectivity/CommonTools.hxx"
21 #include "diagnose_ex.h"
22 #include "TConnection.hxx"
23 #include "connectivity/ParameterCont.hxx"
25 #include <com/sun/star/awt/XWindow.hpp>
26 #include <com/sun/star/beans/PropertyAttribute.hpp>
27 #include <com/sun/star/container/XChild.hpp>
28 #include <com/sun/star/form/FormComponentType.hpp>
29 #include <com/sun/star/io/XInputStream.hpp>
30 #include <com/sun/star/lang/DisposedException.hpp>
31 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
32 #include <com/sun/star/sdb/DatabaseContext.hpp>
33 #include <com/sun/star/sdb/BooleanComparisonMode.hpp>
34 #include <com/sun/star/sdb/CommandType.hpp>
35 #include <com/sun/star/sdb/ErrorMessageDialog.hpp>
36 #include <com/sun/star/sdb/ParametersRequest.hpp>
37 #include <com/sun/star/sdb/RowSetVetoException.hpp>
38 #include <com/sun/star/sdb/SQLContext.hpp>
39 #include <com/sun/star/sdb/XCompletedConnection.hpp>
40 #include <com/sun/star/sdb/XInteractionSupplyParameters.hpp>
41 #include <com/sun/star/sdb/XOfficeDatabaseDocument.hpp>
42 #include <com/sun/star/sdb/XParametersSupplier.hpp>
43 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
44 #include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
45 #include <com/sun/star/sdbc/ConnectionPool.hpp>
46 #include <com/sun/star/sdbc/DataType.hpp>
47 #include <com/sun/star/sdbc/XConnection.hpp>
48 #include <com/sun/star/sdbc/XDataSource.hpp>
49 #include <com/sun/star/sdbc/XDriverManager.hpp>
50 #include <com/sun/star/sdbc/XParameters.hpp>
51 #include <com/sun/star/sdbc/XRow.hpp>
52 #include <com/sun/star/sdbc/XRowSet.hpp>
53 #include <com/sun/star/sdbc/XRowUpdate.hpp>
54 #include <com/sun/star/sdbcx/KeyType.hpp>
55 #include <com/sun/star/sdbcx/Privilege.hpp>
56 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
57 #include <com/sun/star/sdbcx/XKeysSupplier.hpp>
58 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
59 #include <com/sun/star/task/InteractionHandler.hpp>
60 #include <com/sun/star/task/XInteractionRequest.hpp>
61 #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
62 #include <com/sun/star/uno/XNamingService.hpp>
63 #include <com/sun/star/util/NumberFormat.hpp>
64 #include <com/sun/star/util/NumberFormatsSupplier.hpp>
65 #include <com/sun/star/util/XNumberFormatTypes.hpp>
67 #include <comphelper/extract.hxx>
68 #include <comphelper/interaction.hxx>
69 #include <comphelper/processfactory.hxx>
70 #include <comphelper/property.hxx>
71 #include <connectivity/conncleanup.hxx>
72 #include <connectivity/dbconversion.hxx>
73 #include <connectivity/dbexception.hxx>
74 #include <connectivity/dbtools.hxx>
75 #include <connectivity/statementcomposer.hxx>
76 #include <osl/diagnose.h>
77 #include <rtl/ustrbuf.hxx>
78 #include <tools/diagnose_ex.h>
80 #include "resource/common_res.hrc"
81 #include "resource/sharedresources.hxx"
82 #include "connectivity/OSubComponent.hxx"
84 #include <algorithm>
85 #include <iterator>
86 #include <set>
88 using namespace ::comphelper;
89 using namespace ::com::sun::star::uno;
90 using namespace ::com::sun::star::io;
91 using namespace ::com::sun::star::awt;
92 using namespace ::com::sun::star::ui::dialogs;
93 using namespace ::com::sun::star::util;
94 using namespace ::com::sun::star::lang;
95 using namespace ::com::sun::star::beans;
96 using namespace ::com::sun::star::container;
97 using namespace ::com::sun::star::sdb;
98 using namespace ::com::sun::star::sdbc;
99 using namespace ::com::sun::star::sdbcx;
100 using namespace ::com::sun::star::form;
101 using namespace connectivity;
103 namespace dbtools
105 using namespace ::com::sun::star::uno;
106 using namespace ::com::sun::star::beans;
107 using namespace ::com::sun::star::util;
108 using namespace ::com::sun::star::lang;
109 using namespace ::com::sun::star::sdbc;
110 using namespace ::com::sun::star::task;
112 namespace
114 typedef sal_Bool (SAL_CALL XDatabaseMetaData::*FMetaDataSupport)();
117 sal_Int32 getDefaultNumberFormat(const Reference< XPropertySet >& _xColumn,
118 const Reference< XNumberFormatTypes >& _xTypes,
119 const Locale& _rLocale)
121 OSL_ENSURE(_xTypes.is() && _xColumn.is(), "dbtools::getDefaultNumberFormat: invalid arg !");
122 if (!_xTypes.is() || !_xColumn.is())
123 return NumberFormat::UNDEFINED;
125 sal_Int32 nDataType = 0;
126 sal_Int32 nScale = 0;
129 // determine the datatype of the column
130 _xColumn->getPropertyValue("Type") >>= nDataType;
132 if (DataType::NUMERIC == nDataType || DataType::DECIMAL == nDataType)
133 _xColumn->getPropertyValue("Scale") >>= nScale;
135 catch (Exception&)
137 return NumberFormat::UNDEFINED;
139 return getDefaultNumberFormat(nDataType,
140 nScale,
141 ::cppu::any2bool(_xColumn->getPropertyValue("IsCurrency")),
142 _xTypes,
143 _rLocale);
146 sal_Int32 getDefaultNumberFormat(sal_Int32 _nDataType,
147 sal_Int32 _nScale,
148 bool _bIsCurrency,
149 const Reference< XNumberFormatTypes >& _xTypes,
150 const Locale& _rLocale)
152 OSL_ENSURE(_xTypes.is() , "dbtools::getDefaultNumberFormat: invalid arg !");
153 if (!_xTypes.is())
154 return NumberFormat::UNDEFINED;
156 sal_Int32 nFormat = 0;
157 sal_Int32 nNumberType = _bIsCurrency ? NumberFormat::CURRENCY : NumberFormat::NUMBER;
158 switch (_nDataType)
160 case DataType::BIT:
161 case DataType::BOOLEAN:
162 nFormat = _xTypes->getStandardFormat(NumberFormat::LOGICAL, _rLocale);
163 break;
164 case DataType::TINYINT:
165 case DataType::SMALLINT:
166 case DataType::INTEGER:
167 case DataType::BIGINT:
168 case DataType::FLOAT:
169 case DataType::REAL:
170 case DataType::DOUBLE:
171 case DataType::NUMERIC:
172 case DataType::DECIMAL:
176 nFormat = _xTypes->getStandardFormat((sal_Int16)nNumberType, _rLocale);
177 if(_nScale > 0)
179 // generate a new format if necessary
180 Reference< XNumberFormats > xFormats(_xTypes, UNO_QUERY);
181 OUString sNewFormat = xFormats->generateFormat( 0L, _rLocale, sal_False, sal_False, (sal_Int16)_nScale, sal_True);
183 // and add it to the formatter if necessary
184 nFormat = xFormats->queryKey(sNewFormat, _rLocale, sal_False);
185 if (nFormat == (sal_Int32)-1)
186 nFormat = xFormats->addNew(sNewFormat, _rLocale);
189 catch (Exception&)
191 nFormat = _xTypes->getStandardFormat((sal_Int16)nNumberType, _rLocale);
193 } break;
194 case DataType::CHAR:
195 case DataType::VARCHAR:
196 case DataType::LONGVARCHAR:
197 case DataType::CLOB:
198 nFormat = _xTypes->getStandardFormat(NumberFormat::TEXT, _rLocale);
199 break;
200 case DataType::DATE:
201 nFormat = _xTypes->getStandardFormat(NumberFormat::DATE, _rLocale);
202 break;
203 case DataType::TIME:
204 nFormat = _xTypes->getStandardFormat(NumberFormat::TIME, _rLocale);
205 break;
206 case DataType::TIMESTAMP:
207 nFormat = _xTypes->getStandardFormat(NumberFormat::DATETIME, _rLocale);
208 break;
209 case DataType::BINARY:
210 case DataType::VARBINARY:
211 case DataType::LONGVARBINARY:
212 case DataType::SQLNULL:
213 case DataType::OTHER:
214 case DataType::OBJECT:
215 case DataType::DISTINCT:
216 case DataType::STRUCT:
217 case DataType::ARRAY:
218 case DataType::BLOB:
219 case DataType::REF:
220 default:
221 nFormat = _xTypes->getStandardFormat(NumberFormat::UNDEFINED, _rLocale);
223 return nFormat;
226 Reference< XConnection> findConnection(const Reference< XInterface >& xParent)
228 Reference< XConnection> xConnection(xParent, UNO_QUERY);
229 if (!xConnection.is())
231 Reference< XChild> xChild(xParent, UNO_QUERY);
232 if (xChild.is())
233 xConnection = findConnection(xChild->getParent());
235 return xConnection;
238 Reference< XDataSource> getDataSource_allowException(
239 const OUString& _rsTitleOrPath,
240 const Reference< XComponentContext >& _rxContext )
242 ENSURE_OR_RETURN( !_rsTitleOrPath.isEmpty(), "getDataSource_allowException: invalid arg !", NULL );
244 Reference< XDatabaseContext> xDatabaseContext = DatabaseContext::create(_rxContext);
246 return Reference< XDataSource >( xDatabaseContext->getByName( _rsTitleOrPath ), UNO_QUERY );
249 Reference< XDataSource > getDataSource(
250 const OUString& _rsTitleOrPath,
251 const Reference< XComponentContext >& _rxContext )
253 Reference< XDataSource > xDS;
256 xDS = getDataSource_allowException( _rsTitleOrPath, _rxContext );
258 catch( const Exception& )
260 DBG_UNHANDLED_EXCEPTION();
263 return xDS;
266 Reference< XConnection > getConnection_allowException(
267 const OUString& _rsTitleOrPath,
268 const OUString& _rsUser,
269 const OUString& _rsPwd,
270 const Reference< XComponentContext>& _rxContext)
272 Reference< XDataSource> xDataSource( getDataSource_allowException(_rsTitleOrPath, _rxContext) );
273 Reference<XConnection> xConnection;
274 if (xDataSource.is())
276 // do it with interaction handler
277 if(_rsUser.isEmpty() || _rsPwd.isEmpty())
279 Reference<XPropertySet> xProp(xDataSource,UNO_QUERY);
280 OUString sPwd, sUser;
281 bool bPwdReq = false;
284 xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
285 bPwdReq = ::cppu::any2bool(xProp->getPropertyValue("IsPasswordRequired"));
286 xProp->getPropertyValue("User") >>= sUser;
288 catch(Exception&)
290 OSL_FAIL("dbtools::getConnection: error while retrieving data source properties!");
292 if(bPwdReq && sPwd.isEmpty())
293 { // password required, but empty -> connect using an interaction handler
294 Reference<XCompletedConnection> xConnectionCompletion(xProp, UNO_QUERY);
295 if (xConnectionCompletion.is())
296 { // instantiate the default SDB interaction handler
297 Reference< XInteractionHandler > xHandler(
298 InteractionHandler::createWithParent(_rxContext, 0), UNO_QUERY );
299 xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
302 else
303 xConnection = xDataSource->getConnection(sUser, sPwd);
305 if(!xConnection.is()) // try to get one if not already have one, just to make sure
306 xConnection = xDataSource->getConnection(_rsUser, _rsPwd);
308 return xConnection;
311 Reference< XConnection> getConnection_withFeedback(const OUString& _rDataSourceName,
312 const OUString& _rUser, const OUString& _rPwd, const Reference< XComponentContext>& _rxContext)
313 SAL_THROW ( (SQLException) )
315 Reference< XConnection > xReturn;
318 xReturn = getConnection_allowException(_rDataSourceName, _rUser, _rPwd, _rxContext);
320 catch(SQLException&)
322 // allowed to pass
323 throw;
325 catch(Exception&)
327 OSL_FAIL("::dbtools::getConnection_withFeedback: unexpected (non-SQL) exception caught!");
329 return xReturn;
332 Reference< XConnection> getConnection(const Reference< XRowSet>& _rxRowSet) throw (RuntimeException)
334 Reference< XConnection> xReturn;
335 Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
336 if (xRowSetProps.is())
337 xRowSetProps->getPropertyValue("ActiveConnection") >>= xReturn;
338 return xReturn;
341 // helper function which allows to implement both the connectRowset and the ensureRowSetConnection semantics
342 // if connectRowset (which is deprecated) is removed, this function and one of its parameters are
343 // not needed anymore, the whole implementation can be moved into ensureRowSetConnection then)
344 SharedConnection lcl_connectRowSet(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext >& _rxContext,
345 bool _bSetAsActiveConnection, bool _bAttachAutoDisposer )
346 SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
348 SharedConnection xConnection;
352 Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
353 if ( !xRowSetProps.is() )
354 break;
356 // 1. already connected?
357 Reference< XConnection > xExistingConn(
358 xRowSetProps->getPropertyValue("ActiveConnection"),
359 UNO_QUERY );
361 if ( xExistingConn.is()
362 // 2. embedded in a database?
363 || isEmbeddedInDatabase( _rxRowSet, xExistingConn )
364 // 3. is there a connection in the parent hierarchy?
365 || ( xExistingConn = findConnection( _rxRowSet ) ).is()
368 if ( _bSetAsActiveConnection )
370 xRowSetProps->setPropertyValue("ActiveConnection", makeAny( xExistingConn ) );
371 // no auto disposer needed, since we did not create the connection
374 xConnection.reset( xExistingConn, SharedConnection::NoTakeOwnership );
375 break;
378 // build a connection with its current settings (4. data source name, or 5. URL)
380 const OUString sUserProp( "User" );
381 OUString sDataSourceName;
382 xRowSetProps->getPropertyValue("DataSourceName") >>= sDataSourceName;
383 OUString sURL;
384 xRowSetProps->getPropertyValue("URL") >>= sURL;
386 Reference< XConnection > xPureConnection;
387 if (!sDataSourceName.isEmpty())
388 { // the row set's data source property is set
389 // -> try to connect, get user and pwd setting for that
390 OUString sUser, sPwd;
392 if (hasProperty(sUserProp, xRowSetProps))
393 xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
394 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
395 xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
397 xPureConnection = getConnection_allowException( sDataSourceName, sUser, sPwd, _rxContext );
399 else if (!sURL.isEmpty())
400 { // the row set has no data source, but a connection url set
401 // -> try to connection with that url
402 Reference< XConnectionPool > xDriverManager;
403 try {
404 xDriverManager = ConnectionPool::create( _rxContext );
405 } catch( const Exception& ) { }
406 if (xDriverManager.is())
408 OUString sUser, sPwd;
409 if (hasProperty(sUserProp, xRowSetProps))
410 xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
411 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
412 xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
413 if (!sUser.isEmpty())
414 { // use user and pwd together with the url
415 Sequence< PropertyValue> aInfo(2);
416 aInfo.getArray()[0].Name = "user";
417 aInfo.getArray()[0].Value <<= sUser;
418 aInfo.getArray()[1].Name = "password";
419 aInfo.getArray()[1].Value <<= sPwd;
420 xPureConnection = xDriverManager->getConnectionWithInfo( sURL, aInfo );
422 else
423 // just use the url
424 xPureConnection = xDriverManager->getConnection( sURL );
427 xConnection.reset(
428 xPureConnection,
429 _bAttachAutoDisposer ? SharedConnection::NoTakeOwnership : SharedConnection::TakeOwnership
430 /* take ownership if and only if we're *not* going to auto-dispose the connection */
433 // now if we created a connection, forward it to the row set
434 if ( xConnection.is() && _bSetAsActiveConnection )
438 if ( _bAttachAutoDisposer )
440 OAutoConnectionDisposer* pAutoDispose = new OAutoConnectionDisposer( _rxRowSet, xConnection );
441 Reference< XPropertyChangeListener > xEnsureDelete(pAutoDispose);
443 else
444 xRowSetProps->setPropertyValue(
445 OUString( "ActiveConnection" ),
446 makeAny( xConnection.getTyped() )
449 catch(Exception&)
451 OSL_FAIL("EXception when we set the new active connection!");
455 while ( false );
457 return xConnection;
460 Reference< XConnection> connectRowset(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext >& _rxContext,
461 bool _bSetAsActiveConnection ) SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
463 SharedConnection xConnection = lcl_connectRowSet( _rxRowSet, _rxContext, _bSetAsActiveConnection, true );
464 return xConnection.getTyped();
467 SharedConnection ensureRowSetConnection(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext>& _rxContext,
468 bool _bUseAutoConnectionDisposer ) SAL_THROW ( ( SQLException, WrappedTargetException, RuntimeException ) )
470 return lcl_connectRowSet( _rxRowSet, _rxContext, true, _bUseAutoConnectionDisposer );
473 Reference< XNameAccess> getTableFields(const Reference< XConnection>& _rxConn,const OUString& _rName)
475 Reference< XComponent > xDummy;
476 return getFieldsByCommandDescriptor( _rxConn, CommandType::TABLE, _rName, xDummy );
479 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Any& i_aTable)
481 const Reference< XPropertySet > xTable(i_aTable,UNO_QUERY_THROW);
482 return getPrimaryKeyColumns_throw(xTable);
485 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Reference< XPropertySet >& i_xTable)
487 Reference<XNameAccess> xKeyColumns;
488 const Reference<XKeysSupplier> xKeySup(i_xTable,UNO_QUERY);
489 if ( xKeySup.is() )
491 const Reference<XIndexAccess> xKeys = xKeySup->getKeys();
492 if ( xKeys.is() )
494 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
495 const OUString sPropName = rPropMap.getNameByIndex(PROPERTY_ID_TYPE);
496 Reference<XPropertySet> xProp;
497 const sal_Int32 nCount = xKeys->getCount();
498 for(sal_Int32 i = 0;i< nCount;++i)
500 xProp.set(xKeys->getByIndex(i),UNO_QUERY_THROW);
501 if ( xProp.is() )
503 sal_Int32 nKeyType = 0;
504 xProp->getPropertyValue(sPropName) >>= nKeyType;
505 if(KeyType::PRIMARY == nKeyType)
507 const Reference<XColumnsSupplier> xKeyColsSup(xProp,UNO_QUERY_THROW);
508 xKeyColumns = xKeyColsSup->getColumns();
509 break;
516 return xKeyColumns;
519 namespace
521 enum FieldLookupState
523 HANDLE_TABLE, HANDLE_QUERY, HANDLE_SQL, RETRIEVE_OBJECT, RETRIEVE_COLUMNS, DONE, FAILED
527 Reference< XNameAccess > getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection,
528 const sal_Int32 _nCommandType, const OUString& _rCommand,
529 Reference< XComponent >& _rxKeepFieldsAlive, SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
531 OSL_PRECOND( _rxConnection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection!" );
532 OSL_PRECOND( ( CommandType::TABLE == _nCommandType ) || ( CommandType::QUERY == _nCommandType ) || ( CommandType::COMMAND == _nCommandType ),
533 "::dbtools::getFieldsByCommandDescriptor: invalid command type!" );
534 OSL_PRECOND( !_rCommand.isEmpty(), "::dbtools::getFieldsByCommandDescriptor: invalid command (empty)!" );
536 Reference< XNameAccess > xFields;
538 // reset the error
539 if ( _pErrorInfo )
540 *_pErrorInfo = SQLExceptionInfo();
541 // reset the ownership holder
542 _rxKeepFieldsAlive.clear();
544 // go for the fields
547 // some kind of state machine to ease the sharing of code
548 FieldLookupState eState = FAILED;
549 switch ( _nCommandType )
551 case CommandType::TABLE:
552 eState = HANDLE_TABLE;
553 break;
554 case CommandType::QUERY:
555 eState = HANDLE_QUERY;
556 break;
557 case CommandType::COMMAND:
558 eState = HANDLE_SQL;
559 break;
562 // needed in various states:
563 Reference< XNameAccess > xObjectCollection;
564 Reference< XColumnsSupplier > xSupplyColumns;
566 // go!
567 while ( ( DONE != eState ) && ( FAILED != eState ) )
569 switch ( eState )
571 case HANDLE_TABLE:
573 // initial state for handling the tables
575 // get the table objects
576 Reference< XTablesSupplier > xSupplyTables( _rxConnection, UNO_QUERY );
577 if ( xSupplyTables.is() )
578 xObjectCollection = xSupplyTables->getTables();
579 // if something went wrong 'til here, then this will be handled in the next state
581 // next state: get the object
582 eState = RETRIEVE_OBJECT;
584 break;
586 case HANDLE_QUERY:
588 // initial state for handling the tables
590 // get the table objects
591 Reference< XQueriesSupplier > xSupplyQueries( _rxConnection, UNO_QUERY );
592 if ( xSupplyQueries.is() )
593 xObjectCollection = xSupplyQueries->getQueries();
594 // if something went wrong 'til here, then this will be handled in the next state
596 // next state: get the object
597 eState = RETRIEVE_OBJECT;
599 break;
601 case RETRIEVE_OBJECT:
602 // here we should have an object (aka query or table) collection, and are going
603 // to retrieve the desired object
605 // next state: default to FAILED
606 eState = FAILED;
608 OSL_ENSURE( xObjectCollection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection (no sdb.Connection, or no Tables-/QueriesSupplier)!");
609 if ( xObjectCollection.is() )
611 if ( xObjectCollection.is() && xObjectCollection->hasByName( _rCommand ) )
613 xObjectCollection->getByName( _rCommand ) >>= xSupplyColumns;
614 // (xSupplyColumns being NULL will be handled in the next state)
616 // next: go for the columns
617 eState = RETRIEVE_COLUMNS;
620 break;
622 case RETRIEVE_COLUMNS:
623 OSL_ENSURE( xSupplyColumns.is(), "::dbtools::getFieldsByCommandDescriptor: could not retrieve the columns supplier!" );
625 // next state: default to FAILED
626 eState = FAILED;
628 if ( xSupplyColumns.is() )
630 xFields = xSupplyColumns->getColumns();
631 // that's it
632 eState = DONE;
634 break;
636 case HANDLE_SQL:
638 OUString sStatementToExecute( _rCommand );
640 // well, the main problem here is to handle statements which contain a parameter
641 // If we would simply execute a parametrized statement, then this will fail because
642 // we cannot supply any parameter values.
643 // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion
644 // This should cause every driver to not really execute the statement, but to return
645 // an empty result set with the proper structure. We then can use this result set
646 // to retrieve the columns.
650 Reference< XMultiServiceFactory > xComposerFac( _rxConnection, UNO_QUERY );
652 if ( xComposerFac.is() )
654 Reference< XSingleSelectQueryComposer > xComposer(xComposerFac->createInstance("com.sun.star.sdb.SingleSelectQueryComposer"),UNO_QUERY);
655 if ( xComposer.is() )
657 xComposer->setQuery( sStatementToExecute );
659 // Now set the filter to a dummy restriction which will result in an empty
660 // result set.
661 xComposer->setFilter( OUString( "0=1" ) );
662 sStatementToExecute = xComposer->getQuery( );
666 catch( const Exception& )
668 // silent this error, this was just a try. If we're here, we did not change sStatementToExecute,
669 // so it will still be _rCommand, which then will be executed without being touched
672 // now execute
673 Reference< XPreparedStatement > xStatement = _rxConnection->prepareStatement( sStatementToExecute );
674 // transfer ownership of this temporary object to the caller
675 _rxKeepFieldsAlive = _rxKeepFieldsAlive.query( xStatement );
677 // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter
678 // failed - in this case, the MaxRows restriction should at least ensure that there
679 // is no data returned (which would be potentially expensive)
680 Reference< XPropertySet > xStatementProps( xStatement,UNO_QUERY );
683 if ( xStatementProps.is() )
684 xStatementProps->setPropertyValue(
685 OUString( "MaxRows" ),
686 makeAny( sal_Int32( 0 ) )
689 catch( const Exception& )
691 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: could not set the MaxRows!" );
692 // oh damn. Not much of a chance to recover, we will no retrieve the complete
693 // full blown result set
696 xSupplyColumns = xSupplyColumns.query( xStatement->executeQuery() );
697 // this should have given us a result set which does not contain any data, but
698 // the structural information we need
700 // so the next state is to get the columns
701 eState = RETRIEVE_COLUMNS;
703 break;
705 default:
706 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: oops! unhandled state here!" );
707 eState = FAILED;
711 catch( const SQLContext& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
712 catch( const SQLWarning& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
713 catch( const SQLException& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
714 catch( const Exception& )
716 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: caught an exception while retrieving the fields!" );
719 return xFields;
722 Sequence< OUString > getFieldNamesByCommandDescriptor( const Reference< XConnection >& _rxConnection,
723 const sal_Int32 _nCommandType, const OUString& _rCommand,
724 SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) )
726 // get the container for the fields
727 Reference< XComponent > xKeepFieldsAlive;
728 Reference< XNameAccess > xFieldContainer = getFieldsByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, xKeepFieldsAlive, _pErrorInfo );
730 // get the names of the fields
731 Sequence< OUString > aNames;
732 if ( xFieldContainer.is() )
733 aNames = xFieldContainer->getElementNames();
735 // clean up any temporary objects which have been created
736 disposeComponent( xKeepFieldsAlive );
738 // outta here
739 return aNames;
742 SQLContext prependContextInfo(const SQLException& _rException, const Reference< XInterface >& _rxContext, const OUString& _rContextDescription, const OUString& _rContextDetails)
744 return SQLContext( _rContextDescription, _rxContext, OUString(), 0, makeAny( _rException ), _rContextDetails );
747 SQLException prependErrorInfo( const SQLException& _rChainedException, const Reference< XInterface >& _rxContext,
748 const OUString& _rAdditionalError, const StandardSQLState _eSQLState, const sal_Int32 _nErrorCode )
750 return SQLException( _rAdditionalError, _rxContext,
751 _eSQLState == SQL_ERROR_UNSPECIFIED ? OUString() : getStandardSQLState( _eSQLState ),
752 _nErrorCode, makeAny( _rChainedException ) );
755 namespace
757 struct NameComponentSupport
759 const bool bCatalogs;
760 const bool bSchemas;
762 NameComponentSupport( const bool _bCatalogs, const bool _bSchemas )
763 :bCatalogs( _bCatalogs )
764 ,bSchemas( _bSchemas )
769 NameComponentSupport lcl_getNameComponentSupport( const Reference< XDatabaseMetaData >& _rxMetaData, EComposeRule _eComposeRule )
771 OSL_PRECOND( _rxMetaData.is(), "lcl_getNameComponentSupport: invalid meta data!" );
773 FMetaDataSupport pCatalogCall = &XDatabaseMetaData::supportsCatalogsInDataManipulation;
774 FMetaDataSupport pSchemaCall = &XDatabaseMetaData::supportsSchemasInDataManipulation;
775 bool bIgnoreMetaData = false;
777 switch ( _eComposeRule )
779 case eInTableDefinitions:
780 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInTableDefinitions;
781 pSchemaCall = &XDatabaseMetaData::supportsSchemasInTableDefinitions;
782 break;
783 case eInIndexDefinitions:
784 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInIndexDefinitions;
785 pSchemaCall = &XDatabaseMetaData::supportsSchemasInIndexDefinitions;
786 break;
787 case eInProcedureCalls:
788 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInProcedureCalls;
789 pSchemaCall = &XDatabaseMetaData::supportsSchemasInProcedureCalls;
790 break;
791 case eInPrivilegeDefinitions:
792 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInPrivilegeDefinitions;
793 pSchemaCall = &XDatabaseMetaData::supportsSchemasInPrivilegeDefinitions;
794 break;
795 case eComplete:
796 bIgnoreMetaData = true;
797 break;
798 case eInDataManipulation:
799 // already properly set above
800 break;
802 return NameComponentSupport(
803 bIgnoreMetaData || (_rxMetaData.get()->*pCatalogCall)(),
804 bIgnoreMetaData || (_rxMetaData.get()->*pSchemaCall)()
809 static OUString impl_doComposeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
810 const OUString& _rCatalog, const OUString& _rSchema, const OUString& _rName,
811 bool _bQuote, EComposeRule _eComposeRule )
813 OSL_ENSURE(_rxMetaData.is(), "impl_doComposeTableName : invalid meta data !");
814 if ( !_rxMetaData.is() )
815 return OUString();
816 OSL_ENSURE(!_rName.isEmpty(), "impl_doComposeTableName : at least the name should be non-empty !");
818 const OUString sQuoteString = _rxMetaData->getIdentifierQuoteString();
819 const NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxMetaData, _eComposeRule ) );
821 OUStringBuffer aComposedName;
823 OUString sCatalogSep;
824 bool bCatlogAtStart = true;
825 if ( !_rCatalog.isEmpty() && aNameComps.bCatalogs )
827 sCatalogSep = _rxMetaData->getCatalogSeparator();
828 bCatlogAtStart = _rxMetaData->isCatalogAtStart();
830 if ( bCatlogAtStart && !sCatalogSep.isEmpty())
832 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
833 aComposedName.append( sCatalogSep );
837 if ( !_rSchema.isEmpty() && aNameComps.bSchemas )
839 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rSchema ) : _rSchema );
840 aComposedName.appendAscii( "." );
843 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rName ) : _rName );
845 if ( !_rCatalog.isEmpty()
846 && !bCatlogAtStart
847 && !sCatalogSep.isEmpty()
848 && aNameComps.bCatalogs
851 aComposedName.append( sCatalogSep );
852 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
855 return aComposedName.makeStringAndClear();
858 OUString quoteTableName(const Reference< XDatabaseMetaData>& _rxMeta
859 , const OUString& _rName
860 , EComposeRule _eComposeRule)
862 OUString sCatalog, sSchema, sTable;
863 qualifiedNameComponents(_rxMeta,_rName,sCatalog,sSchema,sTable,_eComposeRule);
864 return impl_doComposeTableName( _rxMeta, sCatalog, sSchema, sTable, true, _eComposeRule );
867 void qualifiedNameComponents(const Reference< XDatabaseMetaData >& _rxConnMetaData, const OUString& _rQualifiedName, OUString& _rCatalog, OUString& _rSchema, OUString& _rName,EComposeRule _eComposeRule)
869 OSL_ENSURE(_rxConnMetaData.is(), "QualifiedNameComponents : invalid meta data!");
871 NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxConnMetaData, _eComposeRule ) );
873 OUString sSeparator = _rxConnMetaData->getCatalogSeparator();
875 OUString sName(_rQualifiedName);
876 // do we have catalogs ?
877 if ( aNameComps.bCatalogs )
879 if (_rxConnMetaData->isCatalogAtStart())
881 // search for the catalog name at the beginning
882 sal_Int32 nIndex = sName.indexOf(sSeparator);
883 if (-1 != nIndex)
885 _rCatalog = sName.copy(0, nIndex);
886 sName = sName.copy(nIndex + 1);
889 else
891 // Catalogue name at the end
892 sal_Int32 nIndex = sName.lastIndexOf(sSeparator);
893 if (-1 != nIndex)
895 _rCatalog = sName.copy(nIndex + 1);
896 sName = sName.copy(0, nIndex);
901 if ( aNameComps.bSchemas )
903 sal_Int32 nIndex = sName.indexOf((sal_Unicode)'.');
904 // OSL_ENSURE(-1 != nIndex, "QualifiedNameComponents : no schema separator!");
905 if ( nIndex != -1 )
906 _rSchema = sName.copy(0, nIndex);
907 sName = sName.copy(nIndex + 1);
910 _rName = sName;
913 Reference< XNumberFormatsSupplier> getNumberFormats(
914 const Reference< XConnection>& _rxConn,
915 bool _bAlloweDefault,
916 const Reference< XComponentContext>& _rxContext)
918 // ask the parent of the connection (should be an DatabaseAccess)
919 Reference< XNumberFormatsSupplier> xReturn;
920 Reference< XChild> xConnAsChild(_rxConn, UNO_QUERY);
921 OUString sPropFormatsSupplier( "NumberFormatsSupplier" );
922 if (xConnAsChild.is())
924 Reference< XPropertySet> xConnParentProps(xConnAsChild->getParent(), UNO_QUERY);
925 if (xConnParentProps.is() && hasProperty(sPropFormatsSupplier, xConnParentProps))
926 xConnParentProps->getPropertyValue(sPropFormatsSupplier) >>= xReturn;
928 else if(_bAlloweDefault && _rxContext.is())
930 xReturn = NumberFormatsSupplier::createWithDefaultLocale( _rxContext );
932 return xReturn;
935 void TransferFormComponentProperties(
936 const Reference< XPropertySet>& xOldProps,
937 const Reference< XPropertySet>& xNewProps,
938 const Locale& _rLocale)
942 OSL_ENSURE( xOldProps.is() && xNewProps.is(), "TransferFormComponentProperties: invalid source/dest!" );
943 if ( !xOldProps.is() || !xNewProps.is() )
944 return;
946 // First we copy all the Props, that are available in source and target and have the same description
947 Reference< XPropertySetInfo> xOldInfo( xOldProps->getPropertySetInfo());
948 Reference< XPropertySetInfo> xNewInfo( xNewProps->getPropertySetInfo());
950 Sequence< Property> aOldProperties = xOldInfo->getProperties();
951 Sequence< Property> aNewProperties = xNewInfo->getProperties();
952 int nNewLen = aNewProperties.getLength();
954 Property* pOldProps = aOldProperties.getArray();
955 Property* pNewProps = aNewProperties.getArray();
957 OUString sPropDefaultControl("DefaultControl");
958 OUString sPropLabelControl("LabelControl");
959 OUString sPropFormatsSupplier("FormatsSupplier");
960 OUString sPropCurrencySymbol("CurrencySymbol");
961 OUString sPropDecimals("Decimals");
962 OUString sPropEffectiveMin("EffectiveMin");
963 OUString sPropEffectiveMax("EffectiveMax");
964 OUString sPropEffectiveDefault("EffectiveDefault");
965 OUString sPropDefaultText("DefaultText");
966 OUString sPropDefaultDate("DefaultDate");
967 OUString sPropDefaultTime("DefaultTime");
968 OUString sPropValueMin("ValueMin");
969 OUString sPropValueMax("ValueMax");
970 OUString sPropDecimalAccuracy("DecimalAccuracy");
971 OUString sPropClassId("ClassId");
972 OUString sFormattedServiceName( "com.sun.star.form.component.FormattedField" );
974 for (sal_Int16 i=0; i<aOldProperties.getLength(); ++i)
976 if ( (!pOldProps[i].Name.equals(sPropDefaultControl))
977 && (!pOldProps[i].Name.equals(sPropLabelControl))
980 // binary search
981 Property* pResult = ::std::lower_bound(
982 pNewProps, pNewProps + nNewLen, pOldProps[i], ::comphelper::PropertyCompareByName());
984 if ( pResult
985 && ( pResult != pNewProps + nNewLen && pResult->Name == pOldProps[i].Name )
986 && ( (pResult->Attributes & PropertyAttribute::READONLY) == 0 )
987 && ( pResult->Type.equals(pOldProps[i].Type)) )
988 { // Attributes match and the property is not read-only
991 xNewProps->setPropertyValue(pResult->Name, xOldProps->getPropertyValue(pResult->Name));
993 catch(IllegalArgumentException& e)
995 OSL_UNUSED( e );
996 #ifdef DBG_UTIL
997 OUString sMessage = "TransferFormComponentProperties : could not transfer the value for property \"" +
998 pResult->Name +
999 "\"";
1000 OSL_FAIL(OUStringToOString(sMessage, RTL_TEXTENCODING_ASCII_US).getStr());
1001 #endif
1007 // for formatted fields (either old or new) we have some special treatments
1008 Reference< XServiceInfo > xSI( xOldProps, UNO_QUERY );
1009 bool bOldIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
1010 xSI = Reference< XServiceInfo >( xNewProps, UNO_QUERY );
1011 bool bNewIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
1013 if (!bOldIsFormatted && !bNewIsFormatted)
1014 return; // nothing to do
1016 if (bOldIsFormatted && bNewIsFormatted)
1017 // if both fields are formatted we do no conversions
1018 return;
1020 if (bOldIsFormatted)
1022 // get some properties from the selected format and put them in the new Set
1023 Any aFormatKey( xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) );
1024 if (aFormatKey.hasValue())
1026 Reference< XNumberFormatsSupplier> xSupplier;
1027 xOldProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1028 if (xSupplier.is())
1030 Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1031 Reference< XPropertySet> xFormat(xFormats->getByKey(getINT32(aFormatKey)));
1032 if (hasProperty(sPropCurrencySymbol, xFormat))
1034 Any aVal( xFormat->getPropertyValue(sPropCurrencySymbol) );
1035 if (aVal.hasValue() && hasProperty(sPropCurrencySymbol, xNewProps))
1036 // If the source value hasn't been set then don't copy it
1037 // so we don't overwrite the default value
1038 xNewProps->setPropertyValue(sPropCurrencySymbol, aVal);
1040 if (hasProperty(sPropDecimals, xFormat) && hasProperty(sPropDecimals, xNewProps))
1041 xNewProps->setPropertyValue(sPropDecimals, xFormat->getPropertyValue(sPropDecimals));
1045 // a potential Min-Max-Conversion
1046 Any aEffectiveMin( xOldProps->getPropertyValue(sPropEffectiveMin) );
1047 if (aEffectiveMin.hasValue())
1048 { // Unlike the ValueMin the EffectiveMin can be void
1049 if (hasProperty(sPropValueMin, xNewProps))
1051 OSL_ENSURE(aEffectiveMin.getValueType().getTypeClass() == TypeClass_DOUBLE,
1052 "TransferFormComponentProperties : invalid property type !");
1053 xNewProps->setPropertyValue(sPropValueMin, aEffectiveMin);
1056 Any aEffectiveMax( xOldProps->getPropertyValue(sPropEffectiveMax) );
1057 if (aEffectiveMax.hasValue())
1058 { // analog
1059 if (hasProperty(sPropValueMax, xNewProps))
1061 OSL_ENSURE(aEffectiveMax.getValueType().getTypeClass() == TypeClass_DOUBLE,
1062 "TransferFormComponentProperties : invalid property type !");
1063 xNewProps->setPropertyValue(sPropValueMax, aEffectiveMax);
1067 // then we can still convert and copy the default values
1068 Any aEffectiveDefault( xOldProps->getPropertyValue(sPropEffectiveDefault) );
1069 if (aEffectiveDefault.hasValue())
1071 bool bIsString = aEffectiveDefault.getValueType().getTypeClass() == TypeClass_STRING;
1072 OSL_ENSURE(bIsString || aEffectiveDefault.getValueType().getTypeClass() == TypeClass_DOUBLE,
1073 "TransferFormComponentProperties : invalid property type !");
1074 // The Effective-Properties should always be void or string or double ....
1076 if (hasProperty(sPropDefaultDate, xNewProps) && !bIsString)
1077 { // (to convert a OUString into a date will not always succeed, because it might be bound to a text-column,
1078 // but we can work with a double)
1079 Date aDate = DBTypeConversion::toDate(getDouble(aEffectiveDefault));
1080 xNewProps->setPropertyValue(sPropDefaultDate, makeAny(aDate));
1083 if (hasProperty(sPropDefaultTime, xNewProps) && !bIsString)
1084 { // Completely analogous to time
1085 Time aTime = DBTypeConversion::toTime(getDouble(aEffectiveDefault));
1086 xNewProps->setPropertyValue(sPropDefaultTime, makeAny(aTime));
1089 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xNewProps) && !bIsString)
1090 { // Here we can simply pass the double
1091 xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), aEffectiveDefault);
1094 if (hasProperty(sPropDefaultText, xNewProps) && bIsString)
1095 { // and here the OUString
1096 xNewProps->setPropertyValue(sPropDefaultText, aEffectiveDefault);
1099 // nyi: The translation between doubles and OUString would offer more alternatives
1103 // The other direction: the new Control shall be formatted
1104 if (bNewIsFormatted)
1106 // first the formatting
1107 // we can't set a Supplier, so the new Set must bring one in
1108 Reference< XNumberFormatsSupplier> xSupplier;
1109 xNewProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1110 if (xSupplier.is())
1112 Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1114 // Set number of decimals
1115 sal_Int16 nDecimals = 2;
1116 if (hasProperty(sPropDecimalAccuracy, xOldProps))
1117 xOldProps->getPropertyValue(sPropDecimalAccuracy) >>= nDecimals;
1119 // base format (depending on the ClassId of the old Set)
1120 sal_Int32 nBaseKey = 0;
1121 if (hasProperty(sPropClassId, xOldProps))
1123 Reference< XNumberFormatTypes> xTypeList(xFormats, UNO_QUERY);
1124 if (xTypeList.is())
1126 sal_Int16 nClassId = 0;
1127 xOldProps->getPropertyValue(sPropClassId) >>= nClassId;
1128 switch (nClassId)
1130 case FormComponentType::DATEFIELD :
1131 nBaseKey = xTypeList->getStandardFormat(NumberFormat::DATE, _rLocale);
1132 break;
1134 case FormComponentType::TIMEFIELD :
1135 nBaseKey = xTypeList->getStandardFormat(NumberFormat::TIME, _rLocale);
1136 break;
1138 case FormComponentType::CURRENCYFIELD :
1139 nBaseKey = xTypeList->getStandardFormat(NumberFormat::CURRENCY, _rLocale);
1140 break;
1145 // With this we can generate a new format ...
1146 OUString sNewFormat = xFormats->generateFormat(nBaseKey, _rLocale, sal_False, sal_False, nDecimals, 0);
1147 // No thousands separator, negative numbers are not in red, no leading zeros
1149 // ... and add at FormatsSupplier (if needed)
1150 sal_Int32 nKey = xFormats->queryKey(sNewFormat, _rLocale, sal_False);
1151 if (nKey == (sal_Int32)-1)
1152 { // not added yet in my formatter ...
1153 nKey = xFormats->addNew(sNewFormat, _rLocale);
1156 xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY), makeAny((sal_Int32)nKey));
1159 // min-/max-Value
1160 Any aNewMin, aNewMax;
1161 if (hasProperty(sPropValueMin, xOldProps))
1162 aNewMin = xOldProps->getPropertyValue(sPropValueMin);
1163 if (hasProperty(sPropValueMax, xOldProps))
1164 aNewMax = xOldProps->getPropertyValue(sPropValueMax);
1165 xNewProps->setPropertyValue(sPropEffectiveMin, aNewMin);
1166 xNewProps->setPropertyValue(sPropEffectiveMax, aNewMax);
1168 // Default-Value
1169 Any aNewDefault;
1170 if (hasProperty(sPropDefaultDate, xOldProps))
1172 Any aDate( xOldProps->getPropertyValue(sPropDefaultDate) );
1173 if (aDate.hasValue())
1174 aNewDefault <<= DBTypeConversion::toDouble(*(Date*)aDate.getValue());
1177 if (hasProperty(sPropDefaultTime, xOldProps))
1179 Any aTime( xOldProps->getPropertyValue(sPropDefaultTime) );
1180 if (aTime.hasValue())
1181 aNewDefault <<= DBTypeConversion::toDouble(*(Time*)aTime.getValue());
1184 // double or OUString will be copied directly
1185 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xOldProps))
1186 aNewDefault = xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE));
1187 if (hasProperty(sPropDefaultText, xOldProps))
1188 aNewDefault = xOldProps->getPropertyValue(sPropDefaultText);
1190 if (aNewDefault.hasValue())
1191 xNewProps->setPropertyValue(sPropEffectiveDefault, aNewDefault);
1194 catch(const Exception&)
1196 OSL_FAIL( "TransferFormComponentProperties: caught an exception!" );
1200 bool canInsert(const Reference< XPropertySet>& _rxCursorSet)
1202 return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::INSERT) != 0));
1205 bool canUpdate(const Reference< XPropertySet>& _rxCursorSet)
1207 return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::UPDATE) != 0));
1210 bool canDelete(const Reference< XPropertySet>& _rxCursorSet)
1212 return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::DELETE) != 0));
1215 Reference< XDataSource> findDataSource(const Reference< XInterface >& _xParent)
1217 Reference< XOfficeDatabaseDocument> xDatabaseDocument(_xParent, UNO_QUERY);
1218 Reference< XDataSource> xDataSource;
1219 if ( xDatabaseDocument.is() )
1220 xDataSource = xDatabaseDocument->getDataSource();
1221 if ( !xDataSource.is() )
1222 xDataSource.set(_xParent, UNO_QUERY);
1223 if (!xDataSource.is())
1225 Reference< XChild> xChild(_xParent, UNO_QUERY);
1226 if ( xChild.is() )
1227 xDataSource = findDataSource(xChild->getParent());
1229 return xDataSource;
1232 Reference< XSingleSelectQueryComposer > getComposedRowSetStatement( const Reference< XPropertySet >& _rxRowSet, const Reference< XComponentContext >& _rxContext )
1233 SAL_THROW( ( SQLException ) )
1235 Reference< XSingleSelectQueryComposer > xComposer;
1238 Reference< XConnection> xConn = connectRowset( Reference< XRowSet >( _rxRowSet, UNO_QUERY ), _rxContext, true );
1239 if ( xConn.is() ) // implies _rxRowSet.is()
1241 // build the statement the row set is based on (can't use the ActiveCommand property of the set
1242 // as this reflects the status after the last execute, not the currently set properties)
1244 sal_Int32 nCommandType = CommandType::COMMAND;
1245 OUString sCommand;
1246 bool bEscapeProcessing = false;
1248 OSL_VERIFY( _rxRowSet->getPropertyValue("CommandType") >>= nCommandType );
1249 OSL_VERIFY( _rxRowSet->getPropertyValue("Command") >>= sCommand );
1250 OSL_VERIFY( _rxRowSet->getPropertyValue("EscapeProcessing") >>= bEscapeProcessing );
1252 StatementComposer aComposer( xConn, sCommand, nCommandType, bEscapeProcessing );
1253 // append sort
1254 aComposer.setOrder( getString( _rxRowSet->getPropertyValue("Order") ) );
1256 // append filter
1257 bool bApplyFilter = true;
1258 _rxRowSet->getPropertyValue("ApplyFilter") >>= bApplyFilter;
1259 if ( bApplyFilter )
1260 aComposer.setFilter( getString( _rxRowSet->getPropertyValue("Filter") ) );
1262 aComposer.getQuery();
1264 xComposer = aComposer.getComposer();
1265 aComposer.setDisposeComposer( false );
1268 catch( const SQLException& )
1270 throw;
1272 catch( const Exception& )
1274 DBG_UNHANDLED_EXCEPTION();
1277 return xComposer;
1280 Reference< XSingleSelectQueryComposer > getCurrentSettingsComposer(
1281 const Reference< XPropertySet>& _rxRowSetProps,
1282 const Reference< XComponentContext>& _rxContext)
1284 Reference< XSingleSelectQueryComposer > xReturn;
1287 xReturn = getComposedRowSetStatement( _rxRowSetProps, _rxContext );
1289 catch( const SQLException& )
1291 throw;
1293 catch( const Exception& )
1295 OSL_FAIL( "::getCurrentSettingsComposer : caught an exception !" );
1298 return xReturn;
1301 OUString composeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
1302 const OUString& _rCatalog,
1303 const OUString& _rSchema,
1304 const OUString& _rName,
1305 bool _bQuote,
1306 EComposeRule _eComposeRule)
1308 return impl_doComposeTableName( _rxMetaData, _rCatalog, _rSchema, _rName, _bQuote, _eComposeRule );
1311 OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection,
1312 const OUString& _rCatalog, const OUString& _rSchema, const OUString& _rName )
1314 bool bUseCatalogInSelect = isDataSourcePropertyEnabled( _rxConnection, OUString( "UseCatalogInSelect" ), true );
1315 bool bUseSchemaInSelect = isDataSourcePropertyEnabled( _rxConnection, OUString( "UseSchemaInSelect" ), true );
1317 return impl_doComposeTableName(
1318 _rxConnection->getMetaData(),
1319 bUseCatalogInSelect ? _rCatalog : OUString(),
1320 bUseSchemaInSelect ? _rSchema : OUString(),
1321 _rName,
1322 true,
1323 eInDataManipulation
1327 namespace
1329 static void lcl_getTableNameComponents( const Reference<XPropertySet>& _xTable,
1330 OUString& _out_rCatalog, OUString& _out_rSchema, OUString& _out_rName )
1332 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
1333 Reference< XPropertySetInfo > xInfo;
1334 if (_xTable.is())
1335 xInfo = _xTable->getPropertySetInfo();
1336 if ( xInfo.is()
1337 && xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) )
1339 if ( xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME))
1340 && xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) )
1342 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)) >>= _out_rCatalog;
1343 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= _out_rSchema;
1345 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= _out_rName;
1347 else
1348 OSL_FAIL( "::dbtools::lcl_getTableNameComponents: this is no table object!" );
1352 OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const Reference<XPropertySet>& _xTable )
1354 OUString sCatalog, sSchema, sName;
1355 lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1357 return composeTableNameForSelect( _rxConnection, sCatalog, sSchema, sName );
1360 OUString composeTableName(const Reference<XDatabaseMetaData>& _xMetaData,
1361 const Reference<XPropertySet>& _xTable,
1362 EComposeRule _eComposeRule,
1363 bool _bSuppressCatalog,
1364 bool _bSuppressSchema,
1365 bool _bQuote )
1367 OUString sCatalog, sSchema, sName;
1368 lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1370 return impl_doComposeTableName(
1371 _xMetaData,
1372 _bSuppressCatalog ? OUString() : sCatalog,
1373 _bSuppressSchema ? OUString() : sSchema,
1374 sName,
1375 _bQuote,
1376 _eComposeRule
1380 sal_Int32 getSearchColumnFlag( const Reference< XConnection>& _rxConn,sal_Int32 _nDataType)
1382 sal_Int32 nSearchFlag = 0;
1383 Reference<XResultSet> xSet = _rxConn->getMetaData()->getTypeInfo();
1384 if(xSet.is())
1386 Reference<XRow> xRow(xSet,UNO_QUERY);
1387 while(xSet->next())
1389 if(xRow->getInt(2) == _nDataType)
1391 nSearchFlag = xRow->getInt(9);
1392 break;
1396 return nSearchFlag;
1399 OUString createUniqueName( const Sequence< OUString >& _rNames, const OUString& _rBaseName, bool _bStartWithNumber )
1401 ::std::set< OUString > aUsedNames;
1402 ::std::copy(
1403 _rNames.getConstArray(),
1404 _rNames.getConstArray() + _rNames.getLength(),
1405 ::std::insert_iterator< ::std::set< OUString > >( aUsedNames, aUsedNames.end() )
1408 OUString sName( _rBaseName );
1409 sal_Int32 nPos = 1;
1410 if ( _bStartWithNumber )
1411 sName += OUString::number( nPos );
1413 while ( aUsedNames.find( sName ) != aUsedNames.end() )
1415 sName = _rBaseName;
1416 sName += OUString::number( ++nPos );
1418 return sName;
1421 OUString createUniqueName(const Reference<XNameAccess>& _rxContainer,const OUString& _rBaseName, bool _bStartWithNumber)
1423 Sequence< OUString > aElementNames;
1425 OSL_ENSURE( _rxContainer.is(), "createUniqueName: invalid container!" );
1426 if ( _rxContainer.is() )
1427 aElementNames = _rxContainer->getElementNames();
1429 return createUniqueName( aElementNames, _rBaseName, _bStartWithNumber );
1432 void showError(const SQLExceptionInfo& _rInfo,
1433 const Reference< XWindow>& _xParent,
1434 const Reference< XComponentContext >& _rxContext)
1436 if (_rInfo.isValid())
1440 Reference< XExecutableDialog > xErrorDialog = ErrorMessageDialog::create( _rxContext, "", _xParent, _rInfo.get() );
1441 xErrorDialog->execute();
1443 catch(const Exception&)
1445 OSL_FAIL("showError: could not display the error message!");
1450 bool implUpdateObject(const Reference< XRowUpdate >& _rxUpdatedObject,
1451 const sal_Int32 _nColumnIndex, const Any& _rValue) SAL_THROW ( ( SQLException, RuntimeException ) )
1453 bool bSuccessfullyReRouted = true;
1454 switch (_rValue.getValueTypeClass())
1456 case TypeClass_ANY:
1458 Any aInnerValue;
1459 _rValue >>= aInnerValue;
1460 bSuccessfullyReRouted = implUpdateObject(_rxUpdatedObject, _nColumnIndex, aInnerValue);
1462 break;
1464 case TypeClass_VOID:
1465 _rxUpdatedObject->updateNull(_nColumnIndex);
1466 break;
1468 case TypeClass_STRING:
1469 _rxUpdatedObject->updateString(_nColumnIndex, *(OUString*)_rValue.getValue());
1470 break;
1472 case TypeClass_BOOLEAN:
1473 _rxUpdatedObject->updateBoolean(_nColumnIndex, *(sal_Bool *)_rValue.getValue());
1474 break;
1476 case TypeClass_BYTE:
1477 _rxUpdatedObject->updateByte(_nColumnIndex, *(sal_Int8 *)_rValue.getValue());
1478 break;
1480 case TypeClass_UNSIGNED_SHORT:
1481 case TypeClass_SHORT:
1482 _rxUpdatedObject->updateShort(_nColumnIndex, *(sal_Int16*)_rValue.getValue());
1483 break;
1485 case TypeClass_CHAR:
1486 _rxUpdatedObject->updateString(_nColumnIndex,OUString((sal_Unicode *)_rValue.getValue(),1));
1487 break;
1489 case TypeClass_UNSIGNED_LONG:
1490 case TypeClass_LONG:
1491 _rxUpdatedObject->updateInt(_nColumnIndex, *(sal_Int32*)_rValue.getValue());
1492 break;
1494 case TypeClass_HYPER:
1496 sal_Int64 nValue = 0;
1497 OSL_VERIFY( _rValue >>= nValue );
1498 _rxUpdatedObject->updateLong( _nColumnIndex, nValue );
1500 break;
1502 case TypeClass_FLOAT:
1503 _rxUpdatedObject->updateFloat(_nColumnIndex, *(float*)_rValue.getValue());
1504 break;
1506 case TypeClass_DOUBLE:
1507 _rxUpdatedObject->updateDouble(_nColumnIndex, *(double*)_rValue.getValue());
1508 break;
1510 case TypeClass_SEQUENCE:
1511 if (_rValue.getValueType() == cppu::UnoType< Sequence< sal_Int8 > >::get())
1512 _rxUpdatedObject->updateBytes(_nColumnIndex, *(Sequence<sal_Int8>*)_rValue.getValue());
1513 else
1514 bSuccessfullyReRouted = false;
1515 break;
1516 case TypeClass_STRUCT:
1517 if (_rValue.getValueType() == cppu::UnoType<DateTime>::get())
1518 _rxUpdatedObject->updateTimestamp(_nColumnIndex, *(DateTime*)_rValue.getValue());
1519 else if (_rValue.getValueType() == cppu::UnoType<Date>::get())
1520 _rxUpdatedObject->updateDate(_nColumnIndex, *(Date*)_rValue.getValue());
1521 else if (_rValue.getValueType() == cppu::UnoType<Time>::get())
1522 _rxUpdatedObject->updateTime(_nColumnIndex, *(Time*)_rValue.getValue());
1523 else
1524 bSuccessfullyReRouted = false;
1525 break;
1527 case TypeClass_INTERFACE:
1528 if (_rValue.getValueType() == cppu::UnoType<Reference< XInputStream> >::get())
1530 Reference< XInputStream > xStream;
1531 _rValue >>= xStream;
1532 _rxUpdatedObject->updateBinaryStream(_nColumnIndex, xStream, xStream->available());
1533 break;
1535 // run through
1536 default:
1537 bSuccessfullyReRouted = false;
1540 return bSuccessfullyReRouted;
1543 bool implSetObject( const Reference< XParameters >& _rxParameters,
1544 const sal_Int32 _nColumnIndex, const Any& _rValue) SAL_THROW ( ( SQLException, RuntimeException ) )
1546 bool bSuccessfullyReRouted = true;
1547 switch (_rValue.getValueTypeClass())
1549 case TypeClass_UNSIGNED_HYPER:
1551 sal_uInt64 nValue = 0;
1552 OSL_VERIFY( _rValue >>= nValue );
1553 _rxParameters->setString(_nColumnIndex, OUString::number(nValue));
1555 break;
1557 case TypeClass_UNSIGNED_LONG:
1558 case TypeClass_HYPER:
1560 sal_Int64 nValue = 0;
1561 OSL_VERIFY( _rValue >>= nValue );
1562 _rxParameters->setLong( _nColumnIndex, nValue );
1564 break;
1566 case TypeClass_ANY:
1568 Any aInnerValue;
1569 _rValue >>= aInnerValue;
1570 bSuccessfullyReRouted = implSetObject(_rxParameters, _nColumnIndex, aInnerValue);
1572 break;
1574 case TypeClass_VOID:
1575 _rxParameters->setNull(_nColumnIndex,DataType::VARCHAR);
1576 break;
1578 case TypeClass_STRING:
1579 _rxParameters->setString(_nColumnIndex, *(OUString*)_rValue.getValue());
1580 break;
1582 case TypeClass_BOOLEAN:
1583 _rxParameters->setBoolean(_nColumnIndex, *(sal_Bool *)_rValue.getValue());
1584 break;
1586 case TypeClass_BYTE:
1587 _rxParameters->setByte(_nColumnIndex, *(sal_Int8 *)_rValue.getValue());
1588 break;
1590 case TypeClass_SHORT:
1591 _rxParameters->setShort(_nColumnIndex, *(sal_Int16*)_rValue.getValue());
1592 break;
1594 case TypeClass_CHAR:
1595 _rxParameters->setString(_nColumnIndex, OUString((sal_Unicode *)_rValue.getValue(),1));
1596 break;
1598 case TypeClass_UNSIGNED_SHORT:
1599 case TypeClass_LONG:
1601 sal_Int32 nValue = 0;
1602 OSL_VERIFY( _rValue >>= nValue );
1603 _rxParameters->setInt(_nColumnIndex, nValue);
1604 break;
1607 case TypeClass_FLOAT:
1608 _rxParameters->setFloat(_nColumnIndex, *(float*)_rValue.getValue());
1609 break;
1611 case TypeClass_DOUBLE:
1612 _rxParameters->setDouble(_nColumnIndex, *(double*)_rValue.getValue());
1613 break;
1615 case TypeClass_SEQUENCE:
1616 if (_rValue.getValueType() == cppu::UnoType< Sequence< sal_Int8 > >::get())
1618 _rxParameters->setBytes(_nColumnIndex, *(Sequence<sal_Int8>*)_rValue.getValue());
1620 else
1621 bSuccessfullyReRouted = false;
1622 break;
1623 case TypeClass_STRUCT:
1624 if (_rValue.getValueType() == cppu::UnoType<DateTime>::get())
1625 _rxParameters->setTimestamp(_nColumnIndex, *(DateTime*)_rValue.getValue());
1626 else if (_rValue.getValueType() == cppu::UnoType<Date>::get())
1627 _rxParameters->setDate(_nColumnIndex, *(Date*)_rValue.getValue());
1628 else if (_rValue.getValueType() == cppu::UnoType<Time>::get())
1629 _rxParameters->setTime(_nColumnIndex, *(Time*)_rValue.getValue());
1630 else
1631 bSuccessfullyReRouted = false;
1632 break;
1634 case TypeClass_INTERFACE:
1635 if (_rValue.getValueType() == cppu::UnoType<Reference< XInputStream> >::get())
1637 Reference< XInputStream > xStream;
1638 _rValue >>= xStream;
1639 _rxParameters->setBinaryStream(_nColumnIndex, xStream, xStream->available());
1640 break;
1642 // run through
1643 default:
1644 bSuccessfullyReRouted = false;
1648 return bSuccessfullyReRouted;
1651 namespace
1653 class OParameterWrapper : public ::cppu::WeakImplHelper1< XIndexAccess >
1655 ::std::vector<bool, std::allocator<bool> > m_aSet;
1656 Reference<XIndexAccess> m_xSource;
1657 public:
1658 OParameterWrapper(const ::std::vector<bool, std::allocator<bool> >& _aSet,const Reference<XIndexAccess>& _xSource) : m_aSet(_aSet),m_xSource(_xSource){}
1659 private:
1660 // ::com::sun::star::container::XElementAccess
1661 virtual Type SAL_CALL getElementType() throw(RuntimeException, std::exception) SAL_OVERRIDE
1663 return m_xSource->getElementType();
1665 virtual sal_Bool SAL_CALL hasElements( ) throw(RuntimeException, std::exception) SAL_OVERRIDE
1667 if ( m_aSet.empty() )
1668 return m_xSource->hasElements();
1669 return ::std::count(m_aSet.begin(),m_aSet.end(),false) != 0;
1671 // ::com::sun::star::container::XIndexAccess
1672 virtual sal_Int32 SAL_CALL getCount( ) throw(RuntimeException, std::exception) SAL_OVERRIDE
1674 if ( m_aSet.empty() )
1675 return m_xSource->getCount();
1676 return ::std::count(m_aSet.begin(),m_aSet.end(),false);
1678 virtual Any SAL_CALL getByIndex( sal_Int32 Index ) throw(IndexOutOfBoundsException, WrappedTargetException, RuntimeException, std::exception) SAL_OVERRIDE
1680 if ( m_aSet.empty() )
1681 return m_xSource->getByIndex(Index);
1682 if ( m_aSet.size() < (size_t)Index )
1683 throw IndexOutOfBoundsException();
1685 ::std::vector<bool, std::allocator<bool> >::iterator aIter = m_aSet.begin();
1686 ::std::vector<bool, std::allocator<bool> >::iterator aEnd = m_aSet.end();
1687 sal_Int32 i = 0;
1688 sal_Int32 nParamPos = -1;
1689 for(; aIter != aEnd && i <= Index; ++aIter)
1691 ++nParamPos;
1692 if ( !*aIter )
1694 ++i;
1697 return m_xSource->getByIndex(nParamPos);
1702 void askForParameters(const Reference< XSingleSelectQueryComposer >& _xComposer,
1703 const Reference<XParameters>& _xParameters,
1704 const Reference< XConnection>& _xConnection,
1705 const Reference< XInteractionHandler >& _rxHandler,
1706 const ::std::vector<bool, std::allocator<bool> >& _aParametersSet)
1708 OSL_ENSURE(_xComposer.is(),"dbtools::askForParameters XSQLQueryComposer is null!");
1709 OSL_ENSURE(_xParameters.is(),"dbtools::askForParameters XParameters is null!");
1710 OSL_ENSURE(_xConnection.is(),"dbtools::askForParameters XConnection is null!");
1711 OSL_ENSURE(_rxHandler.is(),"dbtools::askForParameters XInteractionHandler is null!");
1713 // we have to set this here again because getCurrentSettingsComposer can force a setpropertyvalue
1714 Reference<XParametersSupplier> xParameters = Reference<XParametersSupplier> (_xComposer, UNO_QUERY);
1716 Reference<XIndexAccess> xParamsAsIndicies = xParameters.is() ? xParameters->getParameters() : Reference<XIndexAccess>();
1717 sal_Int32 nParamCount = xParamsAsIndicies.is() ? xParamsAsIndicies->getCount() : 0;
1718 ::std::vector<bool, std::allocator<bool> > aNewParameterSet( _aParametersSet );
1719 if ( nParamCount && ::std::count(aNewParameterSet.begin(),aNewParameterSet.end(),true) != nParamCount )
1721 static const OUString PROPERTY_NAME(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME));
1722 aNewParameterSet.resize(nParamCount ,false);
1723 typedef ::std::map< OUString, ::std::vector<sal_Int32> > TParameterPositions;
1724 TParameterPositions aParameterNames;
1725 for(sal_Int32 i = 0; i < nParamCount; ++i)
1727 Reference<XPropertySet> xParam(xParamsAsIndicies->getByIndex(i),UNO_QUERY);
1728 OUString sName;
1729 xParam->getPropertyValue(PROPERTY_NAME) >>= sName;
1731 TParameterPositions::iterator aFind = aParameterNames.find(sName);
1732 if ( aFind != aParameterNames.end() )
1733 aNewParameterSet[i] = true;
1734 aParameterNames[sName].push_back(i+1);
1736 // build an interaction request
1737 // two continuations (Ok and Cancel)
1738 OInteractionAbort* pAbort = new OInteractionAbort;
1739 OParameterContinuation* pParams = new OParameterContinuation;
1740 // the request
1741 ParametersRequest aRequest;
1742 Reference<XIndexAccess> xWrappedParameters = new OParameterWrapper(aNewParameterSet,xParamsAsIndicies);
1743 aRequest.Parameters = xWrappedParameters;
1744 aRequest.Connection = _xConnection;
1745 OInteractionRequest* pRequest = new OInteractionRequest(makeAny(aRequest));
1746 Reference< XInteractionRequest > xRequest(pRequest);
1747 // some knittings
1748 pRequest->addContinuation(pAbort);
1749 pRequest->addContinuation(pParams);
1751 // execute the request
1752 _rxHandler->handle(xRequest);
1754 if (!pParams->wasSelected())
1756 // canceled by the user (i.e. (s)he canceled the dialog)
1757 RowSetVetoException e;
1758 e.ErrorCode = ParameterInteractionCancelled;
1759 throw e;
1762 // now transfer the values from the continuation object to the parameter columns
1763 Sequence< PropertyValue > aFinalValues = pParams->getValues();
1764 const PropertyValue* pFinalValues = aFinalValues.getConstArray();
1765 for (sal_Int32 i=0; i<aFinalValues.getLength(); ++i, ++pFinalValues)
1767 Reference< XPropertySet > xParamColumn(xWrappedParameters->getByIndex(i),UNO_QUERY);
1768 if (xParamColumn.is())
1770 OUString sName;
1771 xParamColumn->getPropertyValue(PROPERTY_NAME) >>= sName;
1772 OSL_ENSURE(sName.equals(pFinalValues->Name), "::dbaui::askForParameters: inconsistent parameter names!");
1774 // determine the field type and ...
1775 sal_Int32 nParamType = 0;
1776 xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nParamType;
1777 // ... the scale of the parameter column
1778 sal_Int32 nScale = 0;
1779 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE), xParamColumn))
1780 xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
1781 // (the index of the parameters is one-based)
1782 TParameterPositions::iterator aFind = aParameterNames.find(pFinalValues->Name);
1783 ::std::vector<sal_Int32>::iterator aIterPos = aFind->second.begin();
1784 ::std::vector<sal_Int32>::iterator aEndPos = aFind->second.end();
1785 for(;aIterPos != aEndPos;++aIterPos)
1787 if ( _aParametersSet.empty() || !_aParametersSet[(*aIterPos)-1] )
1789 _xParameters->setObjectWithInfo(*aIterPos, pFinalValues->Value, nParamType, nScale);
1797 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1798 sal_Int32 parameterIndex,
1799 const Any& x,
1800 sal_Int32 sqlType,
1801 sal_Int32 scale) throw(SQLException, RuntimeException)
1803 ORowSetValue aVal;
1804 aVal.fill(x);
1805 setObjectWithInfo(_xParams,parameterIndex,aVal,sqlType,scale);
1808 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1809 sal_Int32 parameterIndex,
1810 const ::connectivity::ORowSetValue& _rValue,
1811 sal_Int32 sqlType,
1812 sal_Int32 scale) throw(SQLException, RuntimeException)
1814 if ( _rValue.isNull() )
1815 _xParams->setNull(parameterIndex,sqlType);
1816 else
1818 switch(sqlType)
1820 case DataType::DECIMAL:
1821 case DataType::NUMERIC:
1822 _xParams->setObjectWithInfo(parameterIndex,_rValue.makeAny(),sqlType,scale);
1823 break;
1824 case DataType::CHAR:
1825 case DataType::VARCHAR:
1826 case DataType::LONGVARCHAR:
1827 _xParams->setString(parameterIndex,_rValue);
1828 break;
1829 case DataType::CLOB:
1831 Any x(_rValue.makeAny());
1832 OUString sValue;
1833 if ( x >>= sValue )
1834 _xParams->setString(parameterIndex,sValue);
1835 else
1837 Reference< XClob > xClob;
1838 if(x >>= xClob)
1839 _xParams->setClob(parameterIndex,xClob);
1840 else
1842 Reference< ::com::sun::star::io::XInputStream > xStream;
1843 if(x >>= xStream)
1844 _xParams->setCharacterStream(parameterIndex,xStream,xStream->available());
1848 break;
1849 case DataType::BIGINT:
1850 if ( _rValue.isSigned() )
1851 _xParams->setLong(parameterIndex,_rValue);
1852 else
1853 _xParams->setString(parameterIndex,_rValue);
1854 break;
1856 case DataType::FLOAT:
1857 _xParams->setFloat(parameterIndex,_rValue);
1858 break;
1859 case DataType::REAL:
1860 case DataType::DOUBLE:
1861 _xParams->setDouble(parameterIndex,_rValue);
1862 break;
1863 case DataType::DATE:
1864 _xParams->setDate(parameterIndex,_rValue);
1865 break;
1866 case DataType::TIME:
1867 _xParams->setTime(parameterIndex,_rValue);
1868 break;
1869 case DataType::TIMESTAMP:
1870 _xParams->setTimestamp(parameterIndex,_rValue);
1871 break;
1872 case DataType::BINARY:
1873 case DataType::VARBINARY:
1874 case DataType::LONGVARBINARY:
1875 case DataType::BLOB:
1877 Any x(_rValue.makeAny());
1878 Sequence< sal_Int8> aBytes;
1879 if(x >>= aBytes)
1880 _xParams->setBytes(parameterIndex,aBytes);
1881 else
1883 Reference< XBlob > xBlob;
1884 if(x >>= xBlob)
1885 _xParams->setBlob(parameterIndex,xBlob);
1886 else
1888 Reference< XClob > xClob;
1889 if(x >>= xClob)
1890 _xParams->setClob(parameterIndex,xClob);
1891 else
1893 Reference< ::com::sun::star::io::XInputStream > xBinStream;
1894 if(x >>= xBinStream)
1895 _xParams->setBinaryStream(parameterIndex,xBinStream,xBinStream->available());
1900 break;
1901 case DataType::BIT:
1902 case DataType::BOOLEAN:
1903 _xParams->setBoolean(parameterIndex,static_cast<bool>(_rValue));
1904 break;
1905 case DataType::TINYINT:
1906 if ( _rValue.isSigned() )
1907 _xParams->setByte(parameterIndex,_rValue);
1908 else
1909 _xParams->setShort(parameterIndex,_rValue);
1910 break;
1911 case DataType::SMALLINT:
1912 if ( _rValue.isSigned() )
1913 _xParams->setShort(parameterIndex,_rValue);
1914 else
1915 _xParams->setInt(parameterIndex,_rValue);
1916 break;
1917 case DataType::INTEGER:
1918 if ( _rValue.isSigned() )
1919 _xParams->setInt(parameterIndex,_rValue);
1920 else
1921 _xParams->setLong(parameterIndex,_rValue);
1922 break;
1923 default:
1925 ::connectivity::SharedResources aResources;
1926 const OUString sError( aResources.getResourceStringWithSubstitution(
1927 STR_UNKNOWN_PARA_TYPE,
1928 "$position$", OUString::number(parameterIndex)
1929 ) );
1930 ::dbtools::throwGenericSQLException(sError,NULL);
1936 void getBooleanComparisonPredicate( const OUString& _rExpression, const bool _bValue, const sal_Int32 _nBooleanComparisonMode,
1937 OUStringBuffer& _out_rSQLPredicate )
1939 switch ( _nBooleanComparisonMode )
1941 case BooleanComparisonMode::IS_LITERAL:
1942 _out_rSQLPredicate.append( _rExpression );
1943 if ( _bValue )
1944 _out_rSQLPredicate.appendAscii( " IS TRUE" );
1945 else
1946 _out_rSQLPredicate.appendAscii( " IS FALSE" );
1947 break;
1949 case BooleanComparisonMode::EQUAL_LITERAL:
1950 _out_rSQLPredicate.append( _rExpression );
1951 _out_rSQLPredicate.appendAscii( _bValue ? " = TRUE" : " = FALSE" );
1952 break;
1954 case BooleanComparisonMode::ACCESS_COMPAT:
1955 if ( _bValue )
1957 _out_rSQLPredicate.appendAscii( " NOT ( ( " );
1958 _out_rSQLPredicate.append( _rExpression );
1959 _out_rSQLPredicate.appendAscii( " = 0 ) OR ( " );
1960 _out_rSQLPredicate.append( _rExpression );
1961 _out_rSQLPredicate.appendAscii( " IS NULL ) )" );
1963 else
1965 _out_rSQLPredicate.append( _rExpression );
1966 _out_rSQLPredicate.appendAscii( " = 0" );
1968 break;
1970 case BooleanComparisonMode::EQUAL_INTEGER:
1971 // fall through
1972 default:
1973 _out_rSQLPredicate.append( _rExpression );
1974 _out_rSQLPredicate.appendAscii( _bValue ? " = 1" : " = 0" );
1975 break;
1979 } // namespace dbtools
1981 namespace connectivity
1983 void release(oslInterlockedCount& _refCount,
1984 ::cppu::OBroadcastHelper& rBHelper,
1985 Reference< XInterface >& _xInterface,
1986 ::com::sun::star::lang::XComponent* _pObject)
1988 if (osl_atomic_decrement( &_refCount ) == 0)
1990 osl_atomic_increment( &_refCount );
1992 if (!rBHelper.bDisposed && !rBHelper.bInDispose)
1994 // remember the parent
1995 Reference< XInterface > xParent;
1997 ::osl::MutexGuard aGuard( rBHelper.rMutex );
1998 xParent = _xInterface;
1999 _xInterface = NULL;
2002 // First dispose
2003 _pObject->dispose();
2005 // only the alive ref holds the object
2006 OSL_ASSERT( _refCount == 1 );
2008 // release the parent in the ~
2009 if (xParent.is())
2011 ::osl::MutexGuard aGuard( rBHelper.rMutex );
2012 _xInterface = xParent;
2016 else
2017 osl_atomic_increment( &_refCount );
2020 void checkDisposed(bool _bThrow) throw ( DisposedException )
2022 if (_bThrow)
2023 throw DisposedException();
2027 OSQLColumns::Vector::const_iterator find(OSQLColumns::Vector::const_iterator __first,
2028 OSQLColumns::Vector::const_iterator __last,
2029 const OUString& _rVal,
2030 const ::comphelper::UStringMixEqual& _rCase)
2032 OUString sName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
2033 return find(__first,__last,sName,_rVal,_rCase);
2036 OSQLColumns::Vector::const_iterator findRealName(OSQLColumns::Vector::const_iterator __first,
2037 OSQLColumns::Vector::const_iterator __last,
2038 const OUString& _rVal,
2039 const ::comphelper::UStringMixEqual& _rCase)
2041 OUString sRealName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME);
2042 return find(__first,__last,sRealName,_rVal,_rCase);
2045 OSQLColumns::Vector::const_iterator find(OSQLColumns::Vector::const_iterator __first,
2046 OSQLColumns::Vector::const_iterator __last,
2047 const OUString& _rProp,
2048 const OUString& _rVal,
2049 const ::comphelper::UStringMixEqual& _rCase)
2051 while (__first != __last && !_rCase(getString((*__first)->getPropertyValue(_rProp)),_rVal))
2052 ++__first;
2053 return __first;
2055 } //namespace connectivity
2057 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */