bump product version to 5.0.4.1
[LibreOffice.git] / connectivity / source / commontools / dbtools.cxx
blobf49bdc6202de55624d30a1ad48027945b7ed1c79
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 <comphelper/propertysequence.hxx>
72 #include <connectivity/conncleanup.hxx>
73 #include <connectivity/dbconversion.hxx>
74 #include <connectivity/dbexception.hxx>
75 #include <connectivity/dbtools.hxx>
76 #include <connectivity/statementcomposer.hxx>
77 #include <osl/diagnose.h>
78 #include <rtl/ustrbuf.hxx>
79 #include <tools/diagnose_ex.h>
81 #include "resource/common_res.hrc"
82 #include "resource/sharedresources.hxx"
83 #include <connectivity/OSubComponent.hxx>
85 #include <algorithm>
86 #include <iterator>
87 #include <set>
89 using namespace ::comphelper;
90 using namespace ::com::sun::star::uno;
91 using namespace ::com::sun::star::io;
92 using namespace ::com::sun::star::awt;
93 using namespace ::com::sun::star::ui::dialogs;
94 using namespace ::com::sun::star::util;
95 using namespace ::com::sun::star::lang;
96 using namespace ::com::sun::star::beans;
97 using namespace ::com::sun::star::container;
98 using namespace ::com::sun::star::sdb;
99 using namespace ::com::sun::star::sdbc;
100 using namespace ::com::sun::star::sdbcx;
101 using namespace ::com::sun::star::form;
102 using namespace connectivity;
104 namespace dbtools
106 using namespace ::com::sun::star::uno;
107 using namespace ::com::sun::star::beans;
108 using namespace ::com::sun::star::util;
109 using namespace ::com::sun::star::lang;
110 using namespace ::com::sun::star::sdbc;
111 using namespace ::com::sun::star::task;
113 namespace
115 typedef sal_Bool (SAL_CALL XDatabaseMetaData::*FMetaDataSupport)();
118 sal_Int32 getDefaultNumberFormat(const Reference< XPropertySet >& _xColumn,
119 const Reference< XNumberFormatTypes >& _xTypes,
120 const Locale& _rLocale)
122 OSL_ENSURE(_xTypes.is() && _xColumn.is(), "dbtools::getDefaultNumberFormat: invalid arg !");
123 if (!_xTypes.is() || !_xColumn.is())
124 return NumberFormat::UNDEFINED;
126 sal_Int32 nDataType = 0;
127 sal_Int32 nScale = 0;
130 // determine the datatype of the column
131 _xColumn->getPropertyValue("Type") >>= nDataType;
133 if (DataType::NUMERIC == nDataType || DataType::DECIMAL == nDataType)
134 _xColumn->getPropertyValue("Scale") >>= nScale;
136 catch (Exception&)
138 return NumberFormat::UNDEFINED;
140 return getDefaultNumberFormat(nDataType,
141 nScale,
142 ::cppu::any2bool(_xColumn->getPropertyValue("IsCurrency")),
143 _xTypes,
144 _rLocale);
147 sal_Int32 getDefaultNumberFormat(sal_Int32 _nDataType,
148 sal_Int32 _nScale,
149 bool _bIsCurrency,
150 const Reference< XNumberFormatTypes >& _xTypes,
151 const Locale& _rLocale)
153 OSL_ENSURE(_xTypes.is() , "dbtools::getDefaultNumberFormat: invalid arg !");
154 if (!_xTypes.is())
155 return NumberFormat::UNDEFINED;
157 sal_Int32 nFormat = 0;
158 sal_Int32 nNumberType = _bIsCurrency ? NumberFormat::CURRENCY : NumberFormat::NUMBER;
159 switch (_nDataType)
161 case DataType::BIT:
162 case DataType::BOOLEAN:
163 nFormat = _xTypes->getStandardFormat(NumberFormat::LOGICAL, _rLocale);
164 break;
165 case DataType::TINYINT:
166 case DataType::SMALLINT:
167 case DataType::INTEGER:
168 case DataType::BIGINT:
169 case DataType::FLOAT:
170 case DataType::REAL:
171 case DataType::DOUBLE:
172 case DataType::NUMERIC:
173 case DataType::DECIMAL:
177 nFormat = _xTypes->getStandardFormat((sal_Int16)nNumberType, _rLocale);
178 if(_nScale > 0)
180 // generate a new format if necessary
181 Reference< XNumberFormats > xFormats(_xTypes, UNO_QUERY);
182 OUString sNewFormat = xFormats->generateFormat( 0L, _rLocale, sal_False, sal_False, (sal_Int16)_nScale, 1);
184 // and add it to the formatter if necessary
185 nFormat = xFormats->queryKey(sNewFormat, _rLocale, sal_False);
186 if (nFormat == (sal_Int32)-1)
187 nFormat = xFormats->addNew(sNewFormat, _rLocale);
190 catch (Exception&)
192 nFormat = _xTypes->getStandardFormat((sal_Int16)nNumberType, _rLocale);
194 } break;
195 case DataType::CHAR:
196 case DataType::VARCHAR:
197 case DataType::LONGVARCHAR:
198 case DataType::CLOB:
199 nFormat = _xTypes->getStandardFormat(NumberFormat::TEXT, _rLocale);
200 break;
201 case DataType::DATE:
202 nFormat = _xTypes->getStandardFormat(NumberFormat::DATE, _rLocale);
203 break;
204 case DataType::TIME:
205 nFormat = _xTypes->getStandardFormat(NumberFormat::TIME, _rLocale);
206 break;
207 case DataType::TIMESTAMP:
208 nFormat = _xTypes->getStandardFormat(NumberFormat::DATETIME, _rLocale);
209 break;
210 case DataType::BINARY:
211 case DataType::VARBINARY:
212 case DataType::LONGVARBINARY:
213 case DataType::SQLNULL:
214 case DataType::OTHER:
215 case DataType::OBJECT:
216 case DataType::DISTINCT:
217 case DataType::STRUCT:
218 case DataType::ARRAY:
219 case DataType::BLOB:
220 case DataType::REF:
221 default:
222 nFormat = _xTypes->getStandardFormat(NumberFormat::UNDEFINED, _rLocale);
224 return nFormat;
227 Reference< XConnection> findConnection(const Reference< XInterface >& xParent)
229 Reference< XConnection> xConnection(xParent, UNO_QUERY);
230 if (!xConnection.is())
232 Reference< XChild> xChild(xParent, UNO_QUERY);
233 if (xChild.is())
234 xConnection = findConnection(xChild->getParent());
236 return xConnection;
239 Reference< XDataSource> getDataSource_allowException(
240 const OUString& _rsTitleOrPath,
241 const Reference< XComponentContext >& _rxContext )
243 ENSURE_OR_RETURN( !_rsTitleOrPath.isEmpty(), "getDataSource_allowException: invalid arg !", NULL );
245 Reference< XDatabaseContext> xDatabaseContext = DatabaseContext::create(_rxContext);
247 return Reference< XDataSource >( xDatabaseContext->getByName( _rsTitleOrPath ), UNO_QUERY );
250 Reference< XDataSource > getDataSource(
251 const OUString& _rsTitleOrPath,
252 const Reference< XComponentContext >& _rxContext )
254 Reference< XDataSource > xDS;
257 xDS = getDataSource_allowException( _rsTitleOrPath, _rxContext );
259 catch( const Exception& )
261 DBG_UNHANDLED_EXCEPTION();
264 return xDS;
267 Reference< XConnection > getConnection_allowException(
268 const OUString& _rsTitleOrPath,
269 const OUString& _rsUser,
270 const OUString& _rsPwd,
271 const Reference< XComponentContext>& _rxContext)
273 Reference< XDataSource> xDataSource( getDataSource_allowException(_rsTitleOrPath, _rxContext) );
274 Reference<XConnection> xConnection;
275 if (xDataSource.is())
277 // do it with interaction handler
278 if(_rsUser.isEmpty() || _rsPwd.isEmpty())
280 Reference<XPropertySet> xProp(xDataSource,UNO_QUERY);
281 OUString sPwd, sUser;
282 bool bPwdReq = false;
285 xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
286 bPwdReq = ::cppu::any2bool(xProp->getPropertyValue("IsPasswordRequired"));
287 xProp->getPropertyValue("User") >>= sUser;
289 catch(Exception&)
291 OSL_FAIL("dbtools::getConnection: error while retrieving data source properties!");
293 if(bPwdReq && sPwd.isEmpty())
294 { // password required, but empty -> connect using an interaction handler
295 Reference<XCompletedConnection> xConnectionCompletion(xProp, UNO_QUERY);
296 if (xConnectionCompletion.is())
297 { // instantiate the default SDB interaction handler
298 Reference< XInteractionHandler > xHandler(
299 InteractionHandler::createWithParent(_rxContext, 0), UNO_QUERY );
300 xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
303 else
304 xConnection = xDataSource->getConnection(sUser, sPwd);
306 if(!xConnection.is()) // try to get one if not already have one, just to make sure
307 xConnection = xDataSource->getConnection(_rsUser, _rsPwd);
309 return xConnection;
312 Reference< XConnection> getConnection_withFeedback(const OUString& _rDataSourceName,
313 const OUString& _rUser, const OUString& _rPwd, const Reference< XComponentContext>& _rxContext)
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 )
347 SharedConnection xConnection;
351 Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
352 if ( !xRowSetProps.is() )
353 break;
355 // 1. already connected?
356 Reference< XConnection > xExistingConn(
357 xRowSetProps->getPropertyValue("ActiveConnection"),
358 UNO_QUERY );
360 if ( xExistingConn.is()
361 // 2. embedded in a database?
362 || isEmbeddedInDatabase( _rxRowSet, xExistingConn )
363 // 3. is there a connection in the parent hierarchy?
364 || ( xExistingConn = findConnection( _rxRowSet ) ).is()
367 if ( _bSetAsActiveConnection )
369 xRowSetProps->setPropertyValue("ActiveConnection", makeAny( xExistingConn ) );
370 // no auto disposer needed, since we did not create the connection
373 xConnection.reset( xExistingConn, SharedConnection::NoTakeOwnership );
374 break;
377 // build a connection with its current settings (4. data source name, or 5. URL)
379 const OUString sUserProp( "User" );
380 OUString sDataSourceName;
381 xRowSetProps->getPropertyValue("DataSourceName") >>= sDataSourceName;
382 OUString sURL;
383 xRowSetProps->getPropertyValue("URL") >>= sURL;
385 Reference< XConnection > xPureConnection;
386 if (!sDataSourceName.isEmpty())
387 { // the row set's data source property is set
388 // -> try to connect, get user and pwd setting for that
389 OUString sUser, sPwd;
391 if (hasProperty(sUserProp, xRowSetProps))
392 xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
393 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
394 xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
396 xPureConnection = getConnection_allowException( sDataSourceName, sUser, sPwd, _rxContext );
398 else if (!sURL.isEmpty())
399 { // the row set has no data source, but a connection url set
400 // -> try to connection with that url
401 Reference< XConnectionPool > xDriverManager;
402 try {
403 xDriverManager = ConnectionPool::create( _rxContext );
404 } catch( const Exception& ) { }
405 if (xDriverManager.is())
407 OUString sUser, sPwd;
408 if (hasProperty(sUserProp, xRowSetProps))
409 xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
410 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
411 xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
412 if (!sUser.isEmpty())
413 { // use user and pwd together with the url
414 auto aInfo(::comphelper::InitPropertySequence({
415 { "user", makeAny(sUser) },
416 { "password", makeAny(sPwd) }
417 }));
418 xPureConnection = xDriverManager->getConnectionWithInfo( sURL, aInfo );
420 else
421 // just use the url
422 xPureConnection = xDriverManager->getConnection( sURL );
425 xConnection.reset(
426 xPureConnection,
427 _bAttachAutoDisposer ? SharedConnection::NoTakeOwnership : SharedConnection::TakeOwnership
428 /* take ownership if and only if we're *not* going to auto-dispose the connection */
431 // now if we created a connection, forward it to the row set
432 if ( xConnection.is() && _bSetAsActiveConnection )
436 if ( _bAttachAutoDisposer )
438 OAutoConnectionDisposer* pAutoDispose = new OAutoConnectionDisposer( _rxRowSet, xConnection );
439 Reference< XPropertyChangeListener > xEnsureDelete(pAutoDispose);
441 else
442 xRowSetProps->setPropertyValue(
443 OUString( "ActiveConnection" ),
444 makeAny( xConnection.getTyped() )
447 catch(Exception&)
449 OSL_FAIL("EXception when we set the new active connection!");
453 while ( false );
455 return xConnection;
458 Reference< XConnection> connectRowset(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext >& _rxContext,
459 bool _bSetAsActiveConnection )
461 SharedConnection xConnection = lcl_connectRowSet( _rxRowSet, _rxContext, _bSetAsActiveConnection, true );
462 return xConnection.getTyped();
465 SharedConnection ensureRowSetConnection(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext>& _rxContext,
466 bool _bUseAutoConnectionDisposer )
468 return lcl_connectRowSet( _rxRowSet, _rxContext, true, _bUseAutoConnectionDisposer );
471 Reference< XNameAccess> getTableFields(const Reference< XConnection>& _rxConn,const OUString& _rName)
473 Reference< XComponent > xDummy;
474 return getFieldsByCommandDescriptor( _rxConn, CommandType::TABLE, _rName, xDummy );
477 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Any& i_aTable)
479 const Reference< XPropertySet > xTable(i_aTable,UNO_QUERY_THROW);
480 return getPrimaryKeyColumns_throw(xTable);
483 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Reference< XPropertySet >& i_xTable)
485 Reference<XNameAccess> xKeyColumns;
486 const Reference<XKeysSupplier> xKeySup(i_xTable,UNO_QUERY);
487 if ( xKeySup.is() )
489 const Reference<XIndexAccess> xKeys = xKeySup->getKeys();
490 if ( xKeys.is() )
492 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
493 const OUString sPropName = rPropMap.getNameByIndex(PROPERTY_ID_TYPE);
494 Reference<XPropertySet> xProp;
495 const sal_Int32 nCount = xKeys->getCount();
496 for(sal_Int32 i = 0;i< nCount;++i)
498 xProp.set(xKeys->getByIndex(i),UNO_QUERY_THROW);
499 if ( xProp.is() )
501 sal_Int32 nKeyType = 0;
502 xProp->getPropertyValue(sPropName) >>= nKeyType;
503 if(KeyType::PRIMARY == nKeyType)
505 const Reference<XColumnsSupplier> xKeyColsSup(xProp,UNO_QUERY_THROW);
506 xKeyColumns = xKeyColsSup->getColumns();
507 break;
514 return xKeyColumns;
517 namespace
519 enum FieldLookupState
521 HANDLE_TABLE, HANDLE_QUERY, HANDLE_SQL, RETRIEVE_OBJECT, RETRIEVE_COLUMNS, DONE, FAILED
525 Reference< XNameAccess > getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection,
526 const sal_Int32 _nCommandType, const OUString& _rCommand,
527 Reference< XComponent >& _rxKeepFieldsAlive, SQLExceptionInfo* _pErrorInfo )
529 OSL_PRECOND( _rxConnection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection!" );
530 OSL_PRECOND( ( CommandType::TABLE == _nCommandType ) || ( CommandType::QUERY == _nCommandType ) || ( CommandType::COMMAND == _nCommandType ),
531 "::dbtools::getFieldsByCommandDescriptor: invalid command type!" );
532 OSL_PRECOND( !_rCommand.isEmpty(), "::dbtools::getFieldsByCommandDescriptor: invalid command (empty)!" );
534 Reference< XNameAccess > xFields;
536 // reset the error
537 if ( _pErrorInfo )
538 *_pErrorInfo = SQLExceptionInfo();
539 // reset the ownership holder
540 _rxKeepFieldsAlive.clear();
542 // go for the fields
545 // some kind of state machine to ease the sharing of code
546 FieldLookupState eState = FAILED;
547 switch ( _nCommandType )
549 case CommandType::TABLE:
550 eState = HANDLE_TABLE;
551 break;
552 case CommandType::QUERY:
553 eState = HANDLE_QUERY;
554 break;
555 case CommandType::COMMAND:
556 eState = HANDLE_SQL;
557 break;
560 // needed in various states:
561 Reference< XNameAccess > xObjectCollection;
562 Reference< XColumnsSupplier > xSupplyColumns;
564 // go!
565 while ( ( DONE != eState ) && ( FAILED != eState ) )
567 switch ( eState )
569 case HANDLE_TABLE:
571 // initial state for handling the tables
573 // get the table objects
574 Reference< XTablesSupplier > xSupplyTables( _rxConnection, UNO_QUERY );
575 if ( xSupplyTables.is() )
576 xObjectCollection = xSupplyTables->getTables();
577 // if something went wrong 'til here, then this will be handled in the next state
579 // next state: get the object
580 eState = RETRIEVE_OBJECT;
582 break;
584 case HANDLE_QUERY:
586 // initial state for handling the tables
588 // get the table objects
589 Reference< XQueriesSupplier > xSupplyQueries( _rxConnection, UNO_QUERY );
590 if ( xSupplyQueries.is() )
591 xObjectCollection = xSupplyQueries->getQueries();
592 // if something went wrong 'til here, then this will be handled in the next state
594 // next state: get the object
595 eState = RETRIEVE_OBJECT;
597 break;
599 case RETRIEVE_OBJECT:
600 // here we should have an object (aka query or table) collection, and are going
601 // to retrieve the desired object
603 // next state: default to FAILED
604 eState = FAILED;
606 OSL_ENSURE( xObjectCollection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection (no sdb.Connection, or no Tables-/QueriesSupplier)!");
607 if ( xObjectCollection.is() )
609 if ( xObjectCollection.is() && xObjectCollection->hasByName( _rCommand ) )
611 xObjectCollection->getByName( _rCommand ) >>= xSupplyColumns;
612 // (xSupplyColumns being NULL will be handled in the next state)
614 // next: go for the columns
615 eState = RETRIEVE_COLUMNS;
618 break;
620 case RETRIEVE_COLUMNS:
621 OSL_ENSURE( xSupplyColumns.is(), "::dbtools::getFieldsByCommandDescriptor: could not retrieve the columns supplier!" );
623 // next state: default to FAILED
624 eState = FAILED;
626 if ( xSupplyColumns.is() )
628 xFields = xSupplyColumns->getColumns();
629 // that's it
630 eState = DONE;
632 break;
634 case HANDLE_SQL:
636 OUString sStatementToExecute( _rCommand );
638 // well, the main problem here is to handle statements which contain a parameter
639 // If we would simply execute a parametrized statement, then this will fail because
640 // we cannot supply any parameter values.
641 // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion
642 // This should cause every driver to not really execute the statement, but to return
643 // an empty result set with the proper structure. We then can use this result set
644 // to retrieve the columns.
648 Reference< XMultiServiceFactory > xComposerFac( _rxConnection, UNO_QUERY );
650 if ( xComposerFac.is() )
652 Reference< XSingleSelectQueryComposer > xComposer(xComposerFac->createInstance("com.sun.star.sdb.SingleSelectQueryComposer"),UNO_QUERY);
653 if ( xComposer.is() )
655 xComposer->setQuery( sStatementToExecute );
657 // Now set the filter to a dummy restriction which will result in an empty
658 // result set.
659 xComposer->setFilter( OUString( "0=1" ) );
660 sStatementToExecute = xComposer->getQuery( );
664 catch( const Exception& )
666 // silent this error, this was just a try. If we're here, we did not change sStatementToExecute,
667 // so it will still be _rCommand, which then will be executed without being touched
670 // now execute
671 Reference< XPreparedStatement > xStatement = _rxConnection->prepareStatement( sStatementToExecute );
672 // transfer ownership of this temporary object to the caller
673 _rxKeepFieldsAlive.set(xStatement, css::uno::UNO_QUERY);
675 // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter
676 // failed - in this case, the MaxRows restriction should at least ensure that there
677 // is no data returned (which would be potentially expensive)
678 Reference< XPropertySet > xStatementProps( xStatement,UNO_QUERY );
681 if ( xStatementProps.is() )
682 xStatementProps->setPropertyValue(
683 OUString( "MaxRows" ),
684 makeAny( sal_Int32( 0 ) )
687 catch( const Exception& )
689 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: could not set the MaxRows!" );
690 // oh damn. Not much of a chance to recover, we will no retrieve the complete
691 // full blown result set
694 xSupplyColumns.set(xStatement->executeQuery(), css::uno::UNO_QUERY);
695 // this should have given us a result set which does not contain any data, but
696 // the structural information we need
698 // so the next state is to get the columns
699 eState = RETRIEVE_COLUMNS;
701 break;
703 default:
704 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: oops! unhandled state here!" );
705 eState = FAILED;
709 catch( const SQLContext& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
710 catch( const SQLWarning& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
711 catch( const SQLException& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
712 catch( const Exception& )
714 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: caught an exception while retrieving the fields!" );
717 return xFields;
720 Sequence< OUString > getFieldNamesByCommandDescriptor( const Reference< XConnection >& _rxConnection,
721 const sal_Int32 _nCommandType, const OUString& _rCommand,
722 SQLExceptionInfo* _pErrorInfo )
724 // get the container for the fields
725 Reference< XComponent > xKeepFieldsAlive;
726 Reference< XNameAccess > xFieldContainer = getFieldsByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, xKeepFieldsAlive, _pErrorInfo );
728 // get the names of the fields
729 Sequence< OUString > aNames;
730 if ( xFieldContainer.is() )
731 aNames = xFieldContainer->getElementNames();
733 // clean up any temporary objects which have been created
734 disposeComponent( xKeepFieldsAlive );
736 // outta here
737 return aNames;
740 SQLException prependErrorInfo( const SQLException& _rChainedException, const Reference< XInterface >& _rxContext,
741 const OUString& _rAdditionalError, const StandardSQLState _eSQLState, const sal_Int32 _nErrorCode )
743 return SQLException( _rAdditionalError, _rxContext,
744 _eSQLState == SQL_ERROR_UNSPECIFIED ? OUString() : getStandardSQLState( _eSQLState ),
745 _nErrorCode, makeAny( _rChainedException ) );
748 namespace
750 struct NameComponentSupport
752 const bool bCatalogs;
753 const bool bSchemas;
755 NameComponentSupport( const bool _bCatalogs, const bool _bSchemas )
756 :bCatalogs( _bCatalogs )
757 ,bSchemas( _bSchemas )
762 NameComponentSupport lcl_getNameComponentSupport( const Reference< XDatabaseMetaData >& _rxMetaData, EComposeRule _eComposeRule )
764 OSL_PRECOND( _rxMetaData.is(), "lcl_getNameComponentSupport: invalid meta data!" );
766 FMetaDataSupport pCatalogCall = &XDatabaseMetaData::supportsCatalogsInDataManipulation;
767 FMetaDataSupport pSchemaCall = &XDatabaseMetaData::supportsSchemasInDataManipulation;
768 bool bIgnoreMetaData = false;
770 switch ( _eComposeRule )
772 case eInTableDefinitions:
773 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInTableDefinitions;
774 pSchemaCall = &XDatabaseMetaData::supportsSchemasInTableDefinitions;
775 break;
776 case eInIndexDefinitions:
777 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInIndexDefinitions;
778 pSchemaCall = &XDatabaseMetaData::supportsSchemasInIndexDefinitions;
779 break;
780 case eInProcedureCalls:
781 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInProcedureCalls;
782 pSchemaCall = &XDatabaseMetaData::supportsSchemasInProcedureCalls;
783 break;
784 case eInPrivilegeDefinitions:
785 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInPrivilegeDefinitions;
786 pSchemaCall = &XDatabaseMetaData::supportsSchemasInPrivilegeDefinitions;
787 break;
788 case eComplete:
789 bIgnoreMetaData = true;
790 break;
791 case eInDataManipulation:
792 // already properly set above
793 break;
795 return NameComponentSupport(
796 bIgnoreMetaData || (_rxMetaData.get()->*pCatalogCall)(),
797 bIgnoreMetaData || (_rxMetaData.get()->*pSchemaCall)()
802 static OUString impl_doComposeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
803 const OUString& _rCatalog, const OUString& _rSchema, const OUString& _rName,
804 bool _bQuote, EComposeRule _eComposeRule )
806 OSL_ENSURE(_rxMetaData.is(), "impl_doComposeTableName : invalid meta data !");
807 if ( !_rxMetaData.is() )
808 return OUString();
809 OSL_ENSURE(!_rName.isEmpty(), "impl_doComposeTableName : at least the name should be non-empty !");
811 const OUString sQuoteString = _rxMetaData->getIdentifierQuoteString();
812 const NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxMetaData, _eComposeRule ) );
814 OUStringBuffer aComposedName;
816 OUString sCatalogSep;
817 bool bCatlogAtStart = true;
818 if ( !_rCatalog.isEmpty() && aNameComps.bCatalogs )
820 sCatalogSep = _rxMetaData->getCatalogSeparator();
821 bCatlogAtStart = _rxMetaData->isCatalogAtStart();
823 if ( bCatlogAtStart && !sCatalogSep.isEmpty())
825 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
826 aComposedName.append( sCatalogSep );
830 if ( !_rSchema.isEmpty() && aNameComps.bSchemas )
832 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rSchema ) : _rSchema );
833 aComposedName.appendAscii( "." );
836 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rName ) : _rName );
838 if ( !_rCatalog.isEmpty()
839 && !bCatlogAtStart
840 && !sCatalogSep.isEmpty()
841 && aNameComps.bCatalogs
844 aComposedName.append( sCatalogSep );
845 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
848 return aComposedName.makeStringAndClear();
851 OUString quoteTableName(const Reference< XDatabaseMetaData>& _rxMeta
852 , const OUString& _rName
853 , EComposeRule _eComposeRule)
855 OUString sCatalog, sSchema, sTable;
856 qualifiedNameComponents(_rxMeta,_rName,sCatalog,sSchema,sTable,_eComposeRule);
857 return impl_doComposeTableName( _rxMeta, sCatalog, sSchema, sTable, true, _eComposeRule );
860 void qualifiedNameComponents(const Reference< XDatabaseMetaData >& _rxConnMetaData, const OUString& _rQualifiedName, OUString& _rCatalog, OUString& _rSchema, OUString& _rName,EComposeRule _eComposeRule)
862 OSL_ENSURE(_rxConnMetaData.is(), "QualifiedNameComponents : invalid meta data!");
864 NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxConnMetaData, _eComposeRule ) );
866 OUString sSeparator = _rxConnMetaData->getCatalogSeparator();
868 OUString sName(_rQualifiedName);
869 // do we have catalogs ?
870 if ( aNameComps.bCatalogs )
872 if (_rxConnMetaData->isCatalogAtStart())
874 // search for the catalog name at the beginning
875 sal_Int32 nIndex = sName.indexOf(sSeparator);
876 if (-1 != nIndex)
878 _rCatalog = sName.copy(0, nIndex);
879 sName = sName.copy(nIndex + 1);
882 else
884 // Catalogue name at the end
885 sal_Int32 nIndex = sName.lastIndexOf(sSeparator);
886 if (-1 != nIndex)
888 _rCatalog = sName.copy(nIndex + 1);
889 sName = sName.copy(0, nIndex);
894 if ( aNameComps.bSchemas )
896 sal_Int32 nIndex = sName.indexOf((sal_Unicode)'.');
897 // OSL_ENSURE(-1 != nIndex, "QualifiedNameComponents : no schema separator!");
898 if ( nIndex != -1 )
899 _rSchema = sName.copy(0, nIndex);
900 sName = sName.copy(nIndex + 1);
903 _rName = sName;
906 Reference< XNumberFormatsSupplier> getNumberFormats(
907 const Reference< XConnection>& _rxConn,
908 bool _bAlloweDefault,
909 const Reference< XComponentContext>& _rxContext)
911 // ask the parent of the connection (should be an DatabaseAccess)
912 Reference< XNumberFormatsSupplier> xReturn;
913 Reference< XChild> xConnAsChild(_rxConn, UNO_QUERY);
914 OUString sPropFormatsSupplier( "NumberFormatsSupplier" );
915 if (xConnAsChild.is())
917 Reference< XPropertySet> xConnParentProps(xConnAsChild->getParent(), UNO_QUERY);
918 if (xConnParentProps.is() && hasProperty(sPropFormatsSupplier, xConnParentProps))
919 xConnParentProps->getPropertyValue(sPropFormatsSupplier) >>= xReturn;
921 else if(_bAlloweDefault && _rxContext.is())
923 xReturn = NumberFormatsSupplier::createWithDefaultLocale( _rxContext );
925 return xReturn;
928 void TransferFormComponentProperties(
929 const Reference< XPropertySet>& xOldProps,
930 const Reference< XPropertySet>& xNewProps,
931 const Locale& _rLocale)
935 OSL_ENSURE( xOldProps.is() && xNewProps.is(), "TransferFormComponentProperties: invalid source/dest!" );
936 if ( !xOldProps.is() || !xNewProps.is() )
937 return;
939 // First we copy all the Props, that are available in source and target and have the same description
940 Reference< XPropertySetInfo> xOldInfo( xOldProps->getPropertySetInfo());
941 Reference< XPropertySetInfo> xNewInfo( xNewProps->getPropertySetInfo());
943 Sequence< Property> aOldProperties = xOldInfo->getProperties();
944 Sequence< Property> aNewProperties = xNewInfo->getProperties();
945 int nNewLen = aNewProperties.getLength();
947 Property* pOldProps = aOldProperties.getArray();
948 Property* pNewProps = aNewProperties.getArray();
950 OUString sPropDefaultControl("DefaultControl");
951 OUString sPropLabelControl("LabelControl");
952 OUString sPropFormatsSupplier("FormatsSupplier");
953 OUString sPropCurrencySymbol("CurrencySymbol");
954 OUString sPropDecimals("Decimals");
955 OUString sPropEffectiveMin("EffectiveMin");
956 OUString sPropEffectiveMax("EffectiveMax");
957 OUString sPropEffectiveDefault("EffectiveDefault");
958 OUString sPropDefaultText("DefaultText");
959 OUString sPropDefaultDate("DefaultDate");
960 OUString sPropDefaultTime("DefaultTime");
961 OUString sPropValueMin("ValueMin");
962 OUString sPropValueMax("ValueMax");
963 OUString sPropDecimalAccuracy("DecimalAccuracy");
964 OUString sPropClassId("ClassId");
965 OUString sFormattedServiceName( "com.sun.star.form.component.FormattedField" );
967 for (sal_Int16 i=0; i<aOldProperties.getLength(); ++i)
969 if ( (!pOldProps[i].Name.equals(sPropDefaultControl))
970 && (!pOldProps[i].Name.equals(sPropLabelControl))
973 // binary search
974 Property* pResult = ::std::lower_bound(
975 pNewProps, pNewProps + nNewLen, pOldProps[i], ::comphelper::PropertyCompareByName());
977 if ( pResult
978 && ( pResult != pNewProps + nNewLen && pResult->Name == pOldProps[i].Name )
979 && ( (pResult->Attributes & PropertyAttribute::READONLY) == 0 )
980 && ( pResult->Type.equals(pOldProps[i].Type)) )
981 { // Attributes match and the property is not read-only
984 xNewProps->setPropertyValue(pResult->Name, xOldProps->getPropertyValue(pResult->Name));
986 catch(IllegalArgumentException& e)
988 OSL_UNUSED( e );
989 #ifdef DBG_UTIL
990 OUString sMessage = "TransferFormComponentProperties : could not transfer the value for property \"" +
991 pResult->Name +
992 "\"";
993 OSL_FAIL(OUStringToOString(sMessage, RTL_TEXTENCODING_ASCII_US).getStr());
994 #endif
1000 // for formatted fields (either old or new) we have some special treatments
1001 Reference< XServiceInfo > xSI( xOldProps, UNO_QUERY );
1002 bool bOldIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
1003 xSI = Reference< XServiceInfo >( xNewProps, UNO_QUERY );
1004 bool bNewIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
1006 if (!bOldIsFormatted && !bNewIsFormatted)
1007 return; // nothing to do
1009 if (bOldIsFormatted && bNewIsFormatted)
1010 // if both fields are formatted we do no conversions
1011 return;
1013 if (bOldIsFormatted)
1015 // get some properties from the selected format and put them in the new Set
1016 Any aFormatKey( xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) );
1017 if (aFormatKey.hasValue())
1019 Reference< XNumberFormatsSupplier> xSupplier;
1020 xOldProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1021 if (xSupplier.is())
1023 Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1024 Reference< XPropertySet> xFormat(xFormats->getByKey(getINT32(aFormatKey)));
1025 if (hasProperty(sPropCurrencySymbol, xFormat))
1027 Any aVal( xFormat->getPropertyValue(sPropCurrencySymbol) );
1028 if (aVal.hasValue() && hasProperty(sPropCurrencySymbol, xNewProps))
1029 // If the source value hasn't been set then don't copy it
1030 // so we don't overwrite the default value
1031 xNewProps->setPropertyValue(sPropCurrencySymbol, aVal);
1033 if (hasProperty(sPropDecimals, xFormat) && hasProperty(sPropDecimals, xNewProps))
1034 xNewProps->setPropertyValue(sPropDecimals, xFormat->getPropertyValue(sPropDecimals));
1038 // a potential Min-Max-Conversion
1039 Any aEffectiveMin( xOldProps->getPropertyValue(sPropEffectiveMin) );
1040 if (aEffectiveMin.hasValue())
1041 { // Unlike the ValueMin the EffectiveMin can be void
1042 if (hasProperty(sPropValueMin, xNewProps))
1044 OSL_ENSURE(aEffectiveMin.getValueType().getTypeClass() == TypeClass_DOUBLE,
1045 "TransferFormComponentProperties : invalid property type !");
1046 xNewProps->setPropertyValue(sPropValueMin, aEffectiveMin);
1049 Any aEffectiveMax( xOldProps->getPropertyValue(sPropEffectiveMax) );
1050 if (aEffectiveMax.hasValue())
1051 { // analog
1052 if (hasProperty(sPropValueMax, xNewProps))
1054 OSL_ENSURE(aEffectiveMax.getValueType().getTypeClass() == TypeClass_DOUBLE,
1055 "TransferFormComponentProperties : invalid property type !");
1056 xNewProps->setPropertyValue(sPropValueMax, aEffectiveMax);
1060 // then we can still convert and copy the default values
1061 Any aEffectiveDefault( xOldProps->getPropertyValue(sPropEffectiveDefault) );
1062 if (aEffectiveDefault.hasValue())
1064 bool bIsString = aEffectiveDefault.getValueType().getTypeClass() == TypeClass_STRING;
1065 OSL_ENSURE(bIsString || aEffectiveDefault.getValueType().getTypeClass() == TypeClass_DOUBLE,
1066 "TransferFormComponentProperties : invalid property type !");
1067 // The Effective-Properties should always be void or string or double ....
1069 if (hasProperty(sPropDefaultDate, xNewProps) && !bIsString)
1070 { // (to convert a OUString into a date will not always succeed, because it might be bound to a text-column,
1071 // but we can work with a double)
1072 Date aDate = DBTypeConversion::toDate(getDouble(aEffectiveDefault));
1073 xNewProps->setPropertyValue(sPropDefaultDate, makeAny(aDate));
1076 if (hasProperty(sPropDefaultTime, xNewProps) && !bIsString)
1077 { // Completely analogous to time
1078 css::util::Time aTime = DBTypeConversion::toTime(getDouble(aEffectiveDefault));
1079 xNewProps->setPropertyValue(sPropDefaultTime, makeAny(aTime));
1082 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xNewProps) && !bIsString)
1083 { // Here we can simply pass the double
1084 xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), aEffectiveDefault);
1087 if (hasProperty(sPropDefaultText, xNewProps) && bIsString)
1088 { // and here the OUString
1089 xNewProps->setPropertyValue(sPropDefaultText, aEffectiveDefault);
1092 // nyi: The translation between doubles and OUString would offer more alternatives
1096 // The other direction: the new Control shall be formatted
1097 if (bNewIsFormatted)
1099 // first the formatting
1100 // we can't set a Supplier, so the new Set must bring one in
1101 Reference< XNumberFormatsSupplier> xSupplier;
1102 xNewProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1103 if (xSupplier.is())
1105 Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1107 // Set number of decimals
1108 sal_Int16 nDecimals = 2;
1109 if (hasProperty(sPropDecimalAccuracy, xOldProps))
1110 xOldProps->getPropertyValue(sPropDecimalAccuracy) >>= nDecimals;
1112 // base format (depending on the ClassId of the old Set)
1113 sal_Int32 nBaseKey = 0;
1114 if (hasProperty(sPropClassId, xOldProps))
1116 Reference< XNumberFormatTypes> xTypeList(xFormats, UNO_QUERY);
1117 if (xTypeList.is())
1119 sal_Int16 nClassId = 0;
1120 xOldProps->getPropertyValue(sPropClassId) >>= nClassId;
1121 switch (nClassId)
1123 case FormComponentType::DATEFIELD :
1124 nBaseKey = xTypeList->getStandardFormat(NumberFormat::DATE, _rLocale);
1125 break;
1127 case FormComponentType::TIMEFIELD :
1128 nBaseKey = xTypeList->getStandardFormat(NumberFormat::TIME, _rLocale);
1129 break;
1131 case FormComponentType::CURRENCYFIELD :
1132 nBaseKey = xTypeList->getStandardFormat(NumberFormat::CURRENCY, _rLocale);
1133 break;
1138 // With this we can generate a new format ...
1139 OUString sNewFormat = xFormats->generateFormat(nBaseKey, _rLocale, sal_False, sal_False, nDecimals, 0);
1140 // No thousands separator, negative numbers are not in red, no leading zeros
1142 // ... and add at FormatsSupplier (if needed)
1143 sal_Int32 nKey = xFormats->queryKey(sNewFormat, _rLocale, sal_False);
1144 if (nKey == (sal_Int32)-1)
1145 { // not added yet in my formatter ...
1146 nKey = xFormats->addNew(sNewFormat, _rLocale);
1149 xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY), makeAny((sal_Int32)nKey));
1152 // min-/max-Value
1153 Any aNewMin, aNewMax;
1154 if (hasProperty(sPropValueMin, xOldProps))
1155 aNewMin = xOldProps->getPropertyValue(sPropValueMin);
1156 if (hasProperty(sPropValueMax, xOldProps))
1157 aNewMax = xOldProps->getPropertyValue(sPropValueMax);
1158 xNewProps->setPropertyValue(sPropEffectiveMin, aNewMin);
1159 xNewProps->setPropertyValue(sPropEffectiveMax, aNewMax);
1161 // Default-Value
1162 Any aNewDefault;
1163 if (hasProperty(sPropDefaultDate, xOldProps))
1165 Any aDate( xOldProps->getPropertyValue(sPropDefaultDate) );
1166 if (aDate.hasValue())
1167 aNewDefault <<= DBTypeConversion::toDouble(*static_cast<Date const *>(aDate.getValue()));
1170 if (hasProperty(sPropDefaultTime, xOldProps))
1172 Any aTime( xOldProps->getPropertyValue(sPropDefaultTime) );
1173 if (aTime.hasValue())
1174 aNewDefault <<= DBTypeConversion::toDouble(*static_cast<Time const *>(aTime.getValue()));
1177 // double or OUString will be copied directly
1178 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xOldProps))
1179 aNewDefault = xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE));
1180 if (hasProperty(sPropDefaultText, xOldProps))
1181 aNewDefault = xOldProps->getPropertyValue(sPropDefaultText);
1183 if (aNewDefault.hasValue())
1184 xNewProps->setPropertyValue(sPropEffectiveDefault, aNewDefault);
1187 catch(const Exception&)
1189 OSL_FAIL( "TransferFormComponentProperties: caught an exception!" );
1193 bool canInsert(const Reference< XPropertySet>& _rxCursorSet)
1195 return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::INSERT) != 0));
1198 bool canUpdate(const Reference< XPropertySet>& _rxCursorSet)
1200 return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::UPDATE) != 0));
1203 bool canDelete(const Reference< XPropertySet>& _rxCursorSet)
1205 return ((_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::DELETE) != 0));
1208 Reference< XDataSource> findDataSource(const Reference< XInterface >& _xParent)
1210 Reference< XOfficeDatabaseDocument> xDatabaseDocument(_xParent, UNO_QUERY);
1211 Reference< XDataSource> xDataSource;
1212 if ( xDatabaseDocument.is() )
1213 xDataSource = xDatabaseDocument->getDataSource();
1214 if ( !xDataSource.is() )
1215 xDataSource.set(_xParent, UNO_QUERY);
1216 if (!xDataSource.is())
1218 Reference< XChild> xChild(_xParent, UNO_QUERY);
1219 if ( xChild.is() )
1220 xDataSource = findDataSource(xChild->getParent());
1222 return xDataSource;
1225 Reference< XSingleSelectQueryComposer > getComposedRowSetStatement( const Reference< XPropertySet >& _rxRowSet, const Reference< XComponentContext >& _rxContext )
1227 Reference< XSingleSelectQueryComposer > xComposer;
1230 Reference< XConnection> xConn = connectRowset( Reference< XRowSet >( _rxRowSet, UNO_QUERY ), _rxContext, true );
1231 if ( xConn.is() ) // implies _rxRowSet.is()
1233 // build the statement the row set is based on (can't use the ActiveCommand property of the set
1234 // as this reflects the status after the last execute, not the currently set properties)
1236 sal_Int32 nCommandType = CommandType::COMMAND;
1237 OUString sCommand;
1238 bool bEscapeProcessing = false;
1240 OSL_VERIFY( _rxRowSet->getPropertyValue("CommandType") >>= nCommandType );
1241 OSL_VERIFY( _rxRowSet->getPropertyValue("Command") >>= sCommand );
1242 OSL_VERIFY( _rxRowSet->getPropertyValue("EscapeProcessing") >>= bEscapeProcessing );
1244 StatementComposer aComposer( xConn, sCommand, nCommandType, bEscapeProcessing );
1245 // append sort
1246 aComposer.setOrder( getString( _rxRowSet->getPropertyValue("Order") ) );
1248 // append filter
1249 bool bApplyFilter = true;
1250 _rxRowSet->getPropertyValue("ApplyFilter") >>= bApplyFilter;
1251 if ( bApplyFilter )
1252 aComposer.setFilter( getString( _rxRowSet->getPropertyValue("Filter") ) );
1254 aComposer.getQuery();
1256 xComposer = aComposer.getComposer();
1257 aComposer.setDisposeComposer( false );
1260 catch( const SQLException& )
1262 throw;
1264 catch( const Exception& )
1266 DBG_UNHANDLED_EXCEPTION();
1269 return xComposer;
1272 Reference< XSingleSelectQueryComposer > getCurrentSettingsComposer(
1273 const Reference< XPropertySet>& _rxRowSetProps,
1274 const Reference< XComponentContext>& _rxContext)
1276 Reference< XSingleSelectQueryComposer > xReturn;
1279 xReturn = getComposedRowSetStatement( _rxRowSetProps, _rxContext );
1281 catch( const SQLException& )
1283 throw;
1285 catch( const Exception& )
1287 OSL_FAIL( "::getCurrentSettingsComposer : caught an exception !" );
1290 return xReturn;
1293 OUString composeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
1294 const OUString& _rCatalog,
1295 const OUString& _rSchema,
1296 const OUString& _rName,
1297 bool _bQuote,
1298 EComposeRule _eComposeRule)
1300 return impl_doComposeTableName( _rxMetaData, _rCatalog, _rSchema, _rName, _bQuote, _eComposeRule );
1303 OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection,
1304 const OUString& _rCatalog, const OUString& _rSchema, const OUString& _rName )
1306 bool bUseCatalogInSelect = isDataSourcePropertyEnabled( _rxConnection, OUString( "UseCatalogInSelect" ), true );
1307 bool bUseSchemaInSelect = isDataSourcePropertyEnabled( _rxConnection, OUString( "UseSchemaInSelect" ), true );
1309 return impl_doComposeTableName(
1310 _rxConnection->getMetaData(),
1311 bUseCatalogInSelect ? _rCatalog : OUString(),
1312 bUseSchemaInSelect ? _rSchema : OUString(),
1313 _rName,
1314 true,
1315 eInDataManipulation
1319 namespace
1321 static void lcl_getTableNameComponents( const Reference<XPropertySet>& _xTable,
1322 OUString& _out_rCatalog, OUString& _out_rSchema, OUString& _out_rName )
1324 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
1325 Reference< XPropertySetInfo > xInfo;
1326 if (_xTable.is())
1327 xInfo = _xTable->getPropertySetInfo();
1328 if ( xInfo.is()
1329 && xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) )
1331 if ( xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME))
1332 && xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) )
1334 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)) >>= _out_rCatalog;
1335 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= _out_rSchema;
1337 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= _out_rName;
1339 else
1340 OSL_FAIL( "::dbtools::lcl_getTableNameComponents: this is no table object!" );
1344 OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const Reference<XPropertySet>& _xTable )
1346 OUString sCatalog, sSchema, sName;
1347 lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1349 return composeTableNameForSelect( _rxConnection, sCatalog, sSchema, sName );
1352 OUString composeTableName(const Reference<XDatabaseMetaData>& _xMetaData,
1353 const Reference<XPropertySet>& _xTable,
1354 EComposeRule _eComposeRule,
1355 bool _bSuppressCatalog,
1356 bool _bSuppressSchema,
1357 bool _bQuote )
1359 OUString sCatalog, sSchema, sName;
1360 lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1362 return impl_doComposeTableName(
1363 _xMetaData,
1364 _bSuppressCatalog ? OUString() : sCatalog,
1365 _bSuppressSchema ? OUString() : sSchema,
1366 sName,
1367 _bQuote,
1368 _eComposeRule
1372 sal_Int32 getSearchColumnFlag( const Reference< XConnection>& _rxConn,sal_Int32 _nDataType)
1374 sal_Int32 nSearchFlag = 0;
1375 Reference<XResultSet> xSet = _rxConn->getMetaData()->getTypeInfo();
1376 if(xSet.is())
1378 Reference<XRow> xRow(xSet,UNO_QUERY);
1379 while(xSet->next())
1381 if(xRow->getInt(2) == _nDataType)
1383 nSearchFlag = xRow->getInt(9);
1384 break;
1388 return nSearchFlag;
1391 OUString createUniqueName( const Sequence< OUString >& _rNames, const OUString& _rBaseName, bool _bStartWithNumber )
1393 ::std::set< OUString > aUsedNames;
1394 ::std::copy(
1395 _rNames.getConstArray(),
1396 _rNames.getConstArray() + _rNames.getLength(),
1397 ::std::insert_iterator< ::std::set< OUString > >( aUsedNames, aUsedNames.end() )
1400 OUString sName( _rBaseName );
1401 sal_Int32 nPos = 1;
1402 if ( _bStartWithNumber )
1403 sName += OUString::number( nPos );
1405 while ( aUsedNames.find( sName ) != aUsedNames.end() )
1407 sName = _rBaseName;
1408 sName += OUString::number( ++nPos );
1410 return sName;
1413 OUString createUniqueName(const Reference<XNameAccess>& _rxContainer,const OUString& _rBaseName, bool _bStartWithNumber)
1415 Sequence< OUString > aElementNames;
1417 OSL_ENSURE( _rxContainer.is(), "createUniqueName: invalid container!" );
1418 if ( _rxContainer.is() )
1419 aElementNames = _rxContainer->getElementNames();
1421 return createUniqueName( aElementNames, _rBaseName, _bStartWithNumber );
1424 void showError(const SQLExceptionInfo& _rInfo,
1425 const Reference< XWindow>& _xParent,
1426 const Reference< XComponentContext >& _rxContext)
1428 if (_rInfo.isValid())
1432 Reference< XExecutableDialog > xErrorDialog = ErrorMessageDialog::create( _rxContext, "", _xParent, _rInfo.get() );
1433 xErrorDialog->execute();
1435 catch(const Exception&)
1437 OSL_FAIL("showError: could not display the error message!");
1442 bool implUpdateObject(const Reference< XRowUpdate >& _rxUpdatedObject,
1443 const sal_Int32 _nColumnIndex, const Any& _rValue)
1445 bool bSuccessfullyReRouted = true;
1446 switch (_rValue.getValueTypeClass())
1448 case TypeClass_ANY:
1450 Any aInnerValue;
1451 _rValue >>= aInnerValue;
1452 bSuccessfullyReRouted = implUpdateObject(_rxUpdatedObject, _nColumnIndex, aInnerValue);
1454 break;
1456 case TypeClass_VOID:
1457 _rxUpdatedObject->updateNull(_nColumnIndex);
1458 break;
1460 case TypeClass_STRING:
1461 _rxUpdatedObject->updateString(_nColumnIndex, *static_cast<OUString const *>(_rValue.getValue()));
1462 break;
1464 case TypeClass_BOOLEAN:
1465 _rxUpdatedObject->updateBoolean(_nColumnIndex, *static_cast<sal_Bool const *>(_rValue.getValue()));
1466 break;
1468 case TypeClass_BYTE:
1469 _rxUpdatedObject->updateByte(_nColumnIndex, *static_cast<sal_Int8 const *>(_rValue.getValue()));
1470 break;
1472 case TypeClass_UNSIGNED_SHORT:
1473 case TypeClass_SHORT:
1474 _rxUpdatedObject->updateShort(_nColumnIndex, *static_cast<sal_Int16 const *>(_rValue.getValue()));
1475 break;
1477 case TypeClass_CHAR:
1478 _rxUpdatedObject->updateString(_nColumnIndex,OUString(static_cast<sal_Unicode const *>(_rValue.getValue()),1));
1479 break;
1481 case TypeClass_UNSIGNED_LONG:
1482 case TypeClass_LONG:
1483 _rxUpdatedObject->updateInt(_nColumnIndex, *static_cast<sal_Int32 const *>(_rValue.getValue()));
1484 break;
1486 case TypeClass_HYPER:
1488 sal_Int64 nValue = 0;
1489 OSL_VERIFY( _rValue >>= nValue );
1490 _rxUpdatedObject->updateLong( _nColumnIndex, nValue );
1492 break;
1494 case TypeClass_FLOAT:
1495 _rxUpdatedObject->updateFloat(_nColumnIndex, *static_cast<float const *>(_rValue.getValue()));
1496 break;
1498 case TypeClass_DOUBLE:
1499 _rxUpdatedObject->updateDouble(_nColumnIndex, *static_cast<double const *>(_rValue.getValue()));
1500 break;
1502 case TypeClass_SEQUENCE:
1503 if (_rValue.getValueType() == cppu::UnoType< Sequence< sal_Int8 > >::get())
1504 _rxUpdatedObject->updateBytes(_nColumnIndex, *static_cast<Sequence<sal_Int8> const *>(_rValue.getValue()));
1505 else
1506 bSuccessfullyReRouted = false;
1507 break;
1508 case TypeClass_STRUCT:
1509 if (_rValue.getValueType() == cppu::UnoType<DateTime>::get())
1510 _rxUpdatedObject->updateTimestamp(_nColumnIndex, *static_cast<DateTime const *>(_rValue.getValue()));
1511 else if (_rValue.getValueType() == cppu::UnoType<Date>::get())
1512 _rxUpdatedObject->updateDate(_nColumnIndex, *static_cast<Date const *>(_rValue.getValue()));
1513 else if (_rValue.getValueType() == cppu::UnoType<Time>::get())
1514 _rxUpdatedObject->updateTime(_nColumnIndex, *static_cast<Time const *>(_rValue.getValue()));
1515 else
1516 bSuccessfullyReRouted = false;
1517 break;
1519 case TypeClass_INTERFACE:
1520 if (_rValue.getValueType() == cppu::UnoType<XInputStream>::get())
1522 Reference< XInputStream > xStream;
1523 _rValue >>= xStream;
1524 _rxUpdatedObject->updateBinaryStream(_nColumnIndex, xStream, xStream->available());
1525 break;
1527 // run through
1528 default:
1529 bSuccessfullyReRouted = false;
1532 return bSuccessfullyReRouted;
1535 bool implSetObject( const Reference< XParameters >& _rxParameters,
1536 const sal_Int32 _nColumnIndex, const Any& _rValue)
1538 bool bSuccessfullyReRouted = true;
1539 switch (_rValue.getValueTypeClass())
1541 case TypeClass_UNSIGNED_HYPER:
1543 sal_uInt64 nValue = 0;
1544 OSL_VERIFY( _rValue >>= nValue );
1545 _rxParameters->setString(_nColumnIndex, OUString::number(nValue));
1547 break;
1549 case TypeClass_UNSIGNED_LONG:
1550 case TypeClass_HYPER:
1552 sal_Int64 nValue = 0;
1553 OSL_VERIFY( _rValue >>= nValue );
1554 _rxParameters->setLong( _nColumnIndex, nValue );
1556 break;
1558 case TypeClass_ANY:
1560 Any aInnerValue;
1561 _rValue >>= aInnerValue;
1562 bSuccessfullyReRouted = implSetObject(_rxParameters, _nColumnIndex, aInnerValue);
1564 break;
1566 case TypeClass_VOID:
1567 _rxParameters->setNull(_nColumnIndex,DataType::VARCHAR);
1568 break;
1570 case TypeClass_STRING:
1571 _rxParameters->setString(_nColumnIndex, *static_cast<OUString const *>(_rValue.getValue()));
1572 break;
1574 case TypeClass_BOOLEAN:
1575 _rxParameters->setBoolean(_nColumnIndex, *static_cast<sal_Bool const *>(_rValue.getValue()));
1576 break;
1578 case TypeClass_BYTE:
1579 _rxParameters->setByte(_nColumnIndex, *static_cast<sal_Int8 const *>(_rValue.getValue()));
1580 break;
1582 case TypeClass_SHORT:
1583 _rxParameters->setShort(_nColumnIndex, *static_cast<sal_Int16 const *>(_rValue.getValue()));
1584 break;
1586 case TypeClass_CHAR:
1587 _rxParameters->setString(_nColumnIndex, OUString(static_cast<sal_Unicode const *>(_rValue.getValue()),1));
1588 break;
1590 case TypeClass_UNSIGNED_SHORT:
1591 case TypeClass_LONG:
1593 sal_Int32 nValue = 0;
1594 OSL_VERIFY( _rValue >>= nValue );
1595 _rxParameters->setInt(_nColumnIndex, nValue);
1596 break;
1599 case TypeClass_FLOAT:
1600 _rxParameters->setFloat(_nColumnIndex, *static_cast<float const *>(_rValue.getValue()));
1601 break;
1603 case TypeClass_DOUBLE:
1604 _rxParameters->setDouble(_nColumnIndex, *static_cast<double const *>(_rValue.getValue()));
1605 break;
1607 case TypeClass_SEQUENCE:
1608 if (_rValue.getValueType() == cppu::UnoType< Sequence< sal_Int8 > >::get())
1610 _rxParameters->setBytes(_nColumnIndex, *static_cast<Sequence<sal_Int8> const *>(_rValue.getValue()));
1612 else
1613 bSuccessfullyReRouted = false;
1614 break;
1615 case TypeClass_STRUCT:
1616 if (_rValue.getValueType() == cppu::UnoType<DateTime>::get())
1617 _rxParameters->setTimestamp(_nColumnIndex, *static_cast<DateTime const *>(_rValue.getValue()));
1618 else if (_rValue.getValueType() == cppu::UnoType<Date>::get())
1619 _rxParameters->setDate(_nColumnIndex, *static_cast<Date const *>(_rValue.getValue()));
1620 else if (_rValue.getValueType() == cppu::UnoType<Time>::get())
1621 _rxParameters->setTime(_nColumnIndex, *static_cast<Time const *>(_rValue.getValue()));
1622 else
1623 bSuccessfullyReRouted = false;
1624 break;
1626 case TypeClass_INTERFACE:
1627 if (_rValue.getValueType() == cppu::UnoType<XInputStream>::get())
1629 Reference< XInputStream > xStream;
1630 _rValue >>= xStream;
1631 _rxParameters->setBinaryStream(_nColumnIndex, xStream, xStream->available());
1632 break;
1634 // run through
1635 default:
1636 bSuccessfullyReRouted = false;
1640 return bSuccessfullyReRouted;
1643 namespace
1645 class OParameterWrapper : public ::cppu::WeakImplHelper1< XIndexAccess >
1647 ::std::vector<bool, std::allocator<bool> > m_aSet;
1648 Reference<XIndexAccess> m_xSource;
1649 public:
1650 OParameterWrapper(const ::std::vector<bool, std::allocator<bool> >& _aSet,const Reference<XIndexAccess>& _xSource) : m_aSet(_aSet),m_xSource(_xSource){}
1651 private:
1652 // ::com::sun::star::container::XElementAccess
1653 virtual Type SAL_CALL getElementType() throw(RuntimeException, std::exception) SAL_OVERRIDE
1655 return m_xSource->getElementType();
1657 virtual sal_Bool SAL_CALL hasElements( ) throw(RuntimeException, std::exception) SAL_OVERRIDE
1659 if ( m_aSet.empty() )
1660 return m_xSource->hasElements();
1661 return ::std::count(m_aSet.begin(),m_aSet.end(),false) != 0;
1663 // ::com::sun::star::container::XIndexAccess
1664 virtual sal_Int32 SAL_CALL getCount( ) throw(RuntimeException, std::exception) SAL_OVERRIDE
1666 if ( m_aSet.empty() )
1667 return m_xSource->getCount();
1668 return ::std::count(m_aSet.begin(),m_aSet.end(),false);
1670 virtual Any SAL_CALL getByIndex( sal_Int32 Index ) throw(IndexOutOfBoundsException, WrappedTargetException, RuntimeException, std::exception) SAL_OVERRIDE
1672 if ( m_aSet.empty() )
1673 return m_xSource->getByIndex(Index);
1674 if ( m_aSet.size() < (size_t)Index )
1675 throw IndexOutOfBoundsException();
1677 ::std::vector<bool, std::allocator<bool> >::iterator aIter = m_aSet.begin();
1678 ::std::vector<bool, std::allocator<bool> >::iterator aEnd = m_aSet.end();
1679 sal_Int32 i = 0;
1680 sal_Int32 nParamPos = -1;
1681 for(; aIter != aEnd && i <= Index; ++aIter)
1683 ++nParamPos;
1684 if ( !*aIter )
1686 ++i;
1689 return m_xSource->getByIndex(nParamPos);
1694 void askForParameters(const Reference< XSingleSelectQueryComposer >& _xComposer,
1695 const Reference<XParameters>& _xParameters,
1696 const Reference< XConnection>& _xConnection,
1697 const Reference< XInteractionHandler >& _rxHandler,
1698 const ::std::vector<bool, std::allocator<bool> >& _aParametersSet)
1700 OSL_ENSURE(_xComposer.is(),"dbtools::askForParameters XSQLQueryComposer is null!");
1701 OSL_ENSURE(_xParameters.is(),"dbtools::askForParameters XParameters is null!");
1702 OSL_ENSURE(_xConnection.is(),"dbtools::askForParameters XConnection is null!");
1703 OSL_ENSURE(_rxHandler.is(),"dbtools::askForParameters XInteractionHandler is null!");
1705 // we have to set this here again because getCurrentSettingsComposer can force a setpropertyvalue
1706 Reference<XParametersSupplier> xParameters = Reference<XParametersSupplier> (_xComposer, UNO_QUERY);
1708 Reference<XIndexAccess> xParamsAsIndicies = xParameters.is() ? xParameters->getParameters() : Reference<XIndexAccess>();
1709 sal_Int32 nParamCount = xParamsAsIndicies.is() ? xParamsAsIndicies->getCount() : 0;
1710 ::std::vector<bool, std::allocator<bool> > aNewParameterSet( _aParametersSet );
1711 if ( nParamCount && ::std::count(aNewParameterSet.begin(),aNewParameterSet.end(),true) != nParamCount )
1713 static const OUString PROPERTY_NAME(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME));
1714 aNewParameterSet.resize(nParamCount ,false);
1715 typedef ::std::map< OUString, ::std::vector<sal_Int32> > TParameterPositions;
1716 TParameterPositions aParameterNames;
1717 for(sal_Int32 i = 0; i < nParamCount; ++i)
1719 Reference<XPropertySet> xParam(xParamsAsIndicies->getByIndex(i),UNO_QUERY);
1720 OUString sName;
1721 xParam->getPropertyValue(PROPERTY_NAME) >>= sName;
1723 TParameterPositions::iterator aFind = aParameterNames.find(sName);
1724 if ( aFind != aParameterNames.end() )
1725 aNewParameterSet[i] = true;
1726 aParameterNames[sName].push_back(i+1);
1728 // build an interaction request
1729 // two continuations (Ok and Cancel)
1730 OInteractionAbort* pAbort = new OInteractionAbort;
1731 OParameterContinuation* pParams = new OParameterContinuation;
1732 // the request
1733 ParametersRequest aRequest;
1734 Reference<XIndexAccess> xWrappedParameters = new OParameterWrapper(aNewParameterSet,xParamsAsIndicies);
1735 aRequest.Parameters = xWrappedParameters;
1736 aRequest.Connection = _xConnection;
1737 OInteractionRequest* pRequest = new OInteractionRequest(makeAny(aRequest));
1738 Reference< XInteractionRequest > xRequest(pRequest);
1739 // some knittings
1740 pRequest->addContinuation(pAbort);
1741 pRequest->addContinuation(pParams);
1743 // execute the request
1744 _rxHandler->handle(xRequest);
1746 if (!pParams->wasSelected())
1748 // canceled by the user (i.e. (s)he canceled the dialog)
1749 RowSetVetoException e;
1750 e.ErrorCode = ParameterInteractionCancelled;
1751 throw e;
1754 // now transfer the values from the continuation object to the parameter columns
1755 Sequence< PropertyValue > aFinalValues = pParams->getValues();
1756 const PropertyValue* pFinalValues = aFinalValues.getConstArray();
1757 for (sal_Int32 i=0; i<aFinalValues.getLength(); ++i, ++pFinalValues)
1759 Reference< XPropertySet > xParamColumn(xWrappedParameters->getByIndex(i),UNO_QUERY);
1760 if (xParamColumn.is())
1762 OUString sName;
1763 xParamColumn->getPropertyValue(PROPERTY_NAME) >>= sName;
1764 OSL_ENSURE(sName.equals(pFinalValues->Name), "::dbaui::askForParameters: inconsistent parameter names!");
1766 // determine the field type and ...
1767 sal_Int32 nParamType = 0;
1768 xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nParamType;
1769 // ... the scale of the parameter column
1770 sal_Int32 nScale = 0;
1771 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE), xParamColumn))
1772 xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
1773 // (the index of the parameters is one-based)
1774 TParameterPositions::iterator aFind = aParameterNames.find(pFinalValues->Name);
1775 ::std::vector<sal_Int32>::iterator aIterPos = aFind->second.begin();
1776 ::std::vector<sal_Int32>::iterator aEndPos = aFind->second.end();
1777 for(;aIterPos != aEndPos;++aIterPos)
1779 if ( _aParametersSet.empty() || !_aParametersSet[(*aIterPos)-1] )
1781 _xParameters->setObjectWithInfo(*aIterPos, pFinalValues->Value, nParamType, nScale);
1789 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1790 sal_Int32 parameterIndex,
1791 const Any& x,
1792 sal_Int32 sqlType,
1793 sal_Int32 scale) throw(SQLException, RuntimeException)
1795 ORowSetValue aVal;
1796 aVal.fill(x);
1797 setObjectWithInfo(_xParams,parameterIndex,aVal,sqlType,scale);
1800 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1801 sal_Int32 parameterIndex,
1802 const ::connectivity::ORowSetValue& _rValue,
1803 sal_Int32 sqlType,
1804 sal_Int32 scale) throw(SQLException, RuntimeException)
1806 if ( _rValue.isNull() )
1807 _xParams->setNull(parameterIndex,sqlType);
1808 else
1810 switch(sqlType)
1812 case DataType::DECIMAL:
1813 case DataType::NUMERIC:
1814 _xParams->setObjectWithInfo(parameterIndex,_rValue.makeAny(),sqlType,scale);
1815 break;
1816 case DataType::CHAR:
1817 case DataType::VARCHAR:
1818 case DataType::LONGVARCHAR:
1819 _xParams->setString(parameterIndex,_rValue);
1820 break;
1821 case DataType::CLOB:
1823 Any x(_rValue.makeAny());
1824 OUString sValue;
1825 if ( x >>= sValue )
1826 _xParams->setString(parameterIndex,sValue);
1827 else
1829 Reference< XClob > xClob;
1830 if(x >>= xClob)
1831 _xParams->setClob(parameterIndex,xClob);
1832 else
1834 Reference< ::com::sun::star::io::XInputStream > xStream;
1835 if(x >>= xStream)
1836 _xParams->setCharacterStream(parameterIndex,xStream,xStream->available());
1840 break;
1841 case DataType::BIGINT:
1842 if ( _rValue.isSigned() )
1843 _xParams->setLong(parameterIndex,_rValue);
1844 else
1845 _xParams->setString(parameterIndex,_rValue);
1846 break;
1848 case DataType::FLOAT:
1849 _xParams->setFloat(parameterIndex,_rValue);
1850 break;
1851 case DataType::REAL:
1852 case DataType::DOUBLE:
1853 _xParams->setDouble(parameterIndex,_rValue);
1854 break;
1855 case DataType::DATE:
1856 _xParams->setDate(parameterIndex,_rValue);
1857 break;
1858 case DataType::TIME:
1859 _xParams->setTime(parameterIndex,_rValue);
1860 break;
1861 case DataType::TIMESTAMP:
1862 _xParams->setTimestamp(parameterIndex,_rValue);
1863 break;
1864 case DataType::BINARY:
1865 case DataType::VARBINARY:
1866 case DataType::LONGVARBINARY:
1867 case DataType::BLOB:
1869 Any x(_rValue.makeAny());
1870 Sequence< sal_Int8> aBytes;
1871 if(x >>= aBytes)
1872 _xParams->setBytes(parameterIndex,aBytes);
1873 else
1875 Reference< XBlob > xBlob;
1876 if(x >>= xBlob)
1877 _xParams->setBlob(parameterIndex,xBlob);
1878 else
1880 Reference< XClob > xClob;
1881 if(x >>= xClob)
1882 _xParams->setClob(parameterIndex,xClob);
1883 else
1885 Reference< ::com::sun::star::io::XInputStream > xBinStream;
1886 if(x >>= xBinStream)
1887 _xParams->setBinaryStream(parameterIndex,xBinStream,xBinStream->available());
1892 break;
1893 case DataType::BIT:
1894 case DataType::BOOLEAN:
1895 _xParams->setBoolean(parameterIndex,static_cast<bool>(_rValue));
1896 break;
1897 case DataType::TINYINT:
1898 if ( _rValue.isSigned() )
1899 _xParams->setByte(parameterIndex,_rValue);
1900 else
1901 _xParams->setShort(parameterIndex,_rValue);
1902 break;
1903 case DataType::SMALLINT:
1904 if ( _rValue.isSigned() )
1905 _xParams->setShort(parameterIndex,_rValue);
1906 else
1907 _xParams->setInt(parameterIndex,_rValue);
1908 break;
1909 case DataType::INTEGER:
1910 if ( _rValue.isSigned() )
1911 _xParams->setInt(parameterIndex,_rValue);
1912 else
1913 _xParams->setLong(parameterIndex,_rValue);
1914 break;
1915 default:
1917 ::connectivity::SharedResources aResources;
1918 const OUString sError( aResources.getResourceStringWithSubstitution(
1919 STR_UNKNOWN_PARA_TYPE,
1920 "$position$", OUString::number(parameterIndex)
1921 ) );
1922 ::dbtools::throwGenericSQLException(sError,NULL);
1928 void getBooleanComparisonPredicate( const OUString& _rExpression, const bool _bValue, const sal_Int32 _nBooleanComparisonMode,
1929 OUStringBuffer& _out_rSQLPredicate )
1931 switch ( _nBooleanComparisonMode )
1933 case BooleanComparisonMode::IS_LITERAL:
1934 _out_rSQLPredicate.append( _rExpression );
1935 if ( _bValue )
1936 _out_rSQLPredicate.appendAscii( " IS TRUE" );
1937 else
1938 _out_rSQLPredicate.appendAscii( " IS FALSE" );
1939 break;
1941 case BooleanComparisonMode::EQUAL_LITERAL:
1942 _out_rSQLPredicate.append( _rExpression );
1943 _out_rSQLPredicate.appendAscii( _bValue ? " = TRUE" : " = FALSE" );
1944 break;
1946 case BooleanComparisonMode::ACCESS_COMPAT:
1947 if ( _bValue )
1949 _out_rSQLPredicate.appendAscii( " NOT ( ( " );
1950 _out_rSQLPredicate.append( _rExpression );
1951 _out_rSQLPredicate.appendAscii( " = 0 ) OR ( " );
1952 _out_rSQLPredicate.append( _rExpression );
1953 _out_rSQLPredicate.appendAscii( " IS NULL ) )" );
1955 else
1957 _out_rSQLPredicate.append( _rExpression );
1958 _out_rSQLPredicate.appendAscii( " = 0" );
1960 break;
1962 case BooleanComparisonMode::EQUAL_INTEGER:
1963 // fall through
1964 default:
1965 _out_rSQLPredicate.append( _rExpression );
1966 _out_rSQLPredicate.appendAscii( _bValue ? " = 1" : " = 0" );
1967 break;
1971 } // namespace dbtools
1973 namespace connectivity
1975 void release(oslInterlockedCount& _refCount,
1976 ::cppu::OBroadcastHelper& rBHelper,
1977 Reference< XInterface >& _xInterface,
1978 ::com::sun::star::lang::XComponent* _pObject)
1980 if (osl_atomic_decrement( &_refCount ) == 0)
1982 osl_atomic_increment( &_refCount );
1984 if (!rBHelper.bDisposed && !rBHelper.bInDispose)
1986 // remember the parent
1987 Reference< XInterface > xParent;
1989 ::osl::MutexGuard aGuard( rBHelper.rMutex );
1990 xParent = _xInterface;
1991 _xInterface = NULL;
1994 // First dispose
1995 _pObject->dispose();
1997 // only the alive ref holds the object
1998 OSL_ASSERT( _refCount == 1 );
2000 // release the parent in the ~
2001 if (xParent.is())
2003 ::osl::MutexGuard aGuard( rBHelper.rMutex );
2004 _xInterface = xParent;
2008 else
2009 osl_atomic_increment( &_refCount );
2012 void checkDisposed(bool _bThrow) throw ( DisposedException )
2014 if (_bThrow)
2015 throw DisposedException();
2019 OSQLColumns::Vector::const_iterator find(OSQLColumns::Vector::const_iterator __first,
2020 OSQLColumns::Vector::const_iterator __last,
2021 const OUString& _rVal,
2022 const ::comphelper::UStringMixEqual& _rCase)
2024 OUString sName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
2025 return find(__first,__last,sName,_rVal,_rCase);
2028 OSQLColumns::Vector::const_iterator findRealName(OSQLColumns::Vector::const_iterator __first,
2029 OSQLColumns::Vector::const_iterator __last,
2030 const OUString& _rVal,
2031 const ::comphelper::UStringMixEqual& _rCase)
2033 OUString sRealName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME);
2034 return find(__first,__last,sRealName,_rVal,_rCase);
2037 OSQLColumns::Vector::const_iterator find(OSQLColumns::Vector::const_iterator __first,
2038 OSQLColumns::Vector::const_iterator __last,
2039 const OUString& _rProp,
2040 const OUString& _rVal,
2041 const ::comphelper::UStringMixEqual& _rCase)
2043 while (__first != __last && !_rCase(getString((*__first)->getPropertyValue(_rProp)),_rVal))
2044 ++__first;
2045 return __first;
2047 } //namespace connectivity
2049 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */