bump product version to 6.3.0.0.beta1
[LibreOffice.git] / connectivity / source / commontools / dbtools.cxx
blob1e3f51ec00e2fc181a3178d1590ad8b1599eb978
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 <TConnection.hxx>
22 #include <connectivity/ParameterCont.hxx>
24 #include <com/sun/star/awt/XWindow.hpp>
25 #include <com/sun/star/beans/PropertyAttribute.hpp>
26 #include <com/sun/star/container/XChild.hpp>
27 #include <com/sun/star/form/FormComponentType.hpp>
28 #include <com/sun/star/io/XInputStream.hpp>
29 #include <com/sun/star/lang/DisposedException.hpp>
30 #include <com/sun/star/lang/IndexOutOfBoundsException.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/property.hxx>
70 #include <comphelper/propertysequence.hxx>
71 #include <comphelper/types.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 <o3tl/any.hxx>
78 #include <osl/diagnose.h>
79 #include <rtl/ustrbuf.hxx>
80 #include <sal/log.hxx>
81 #include <tools/diagnose_ex.h>
82 #include <tools/stream.hxx>
83 #include <cppuhelper/implbase.hxx>
84 #include <strings.hrc>
85 #include <resource/sharedresources.hxx>
87 #include <algorithm>
88 #include <iterator>
89 #include <set>
91 using namespace ::comphelper;
92 using namespace ::com::sun::star::uno;
93 using namespace ::com::sun::star::io;
94 using namespace ::com::sun::star::awt;
95 using namespace ::com::sun::star::ui::dialogs;
96 using namespace ::com::sun::star::util;
97 using namespace ::com::sun::star::lang;
98 using namespace ::com::sun::star::beans;
99 using namespace ::com::sun::star::container;
100 using namespace ::com::sun::star::sdb;
101 using namespace ::com::sun::star::sdbc;
102 using namespace ::com::sun::star::sdbcx;
103 using namespace ::com::sun::star::task;
104 using namespace ::com::sun::star::form;
105 using namespace connectivity;
107 namespace dbtools
110 namespace
112 typedef sal_Bool (SAL_CALL XDatabaseMetaData::*FMetaDataSupport)();
115 sal_Int32 getDefaultNumberFormat(const Reference< XPropertySet >& _xColumn,
116 const Reference< XNumberFormatTypes >& _xTypes,
117 const Locale& _rLocale)
119 OSL_ENSURE(_xTypes.is() && _xColumn.is(), "dbtools::getDefaultNumberFormat: invalid arg !");
120 if (!_xTypes.is() || !_xColumn.is())
121 return NumberFormat::UNDEFINED;
123 sal_Int32 nDataType = 0;
124 sal_Int32 nScale = 0;
127 // determine the datatype of the column
128 _xColumn->getPropertyValue("Type") >>= nDataType;
130 if (DataType::NUMERIC == nDataType || DataType::DECIMAL == nDataType)
131 _xColumn->getPropertyValue("Scale") >>= nScale;
133 catch (Exception&)
135 return NumberFormat::UNDEFINED;
137 return getDefaultNumberFormat(nDataType,
138 nScale,
139 ::cppu::any2bool(_xColumn->getPropertyValue("IsCurrency")),
140 _xTypes,
141 _rLocale);
144 sal_Int32 getDefaultNumberFormat(sal_Int32 _nDataType,
145 sal_Int32 _nScale,
146 bool _bIsCurrency,
147 const Reference< XNumberFormatTypes >& _xTypes,
148 const Locale& _rLocale)
150 OSL_ENSURE(_xTypes.is() , "dbtools::getDefaultNumberFormat: invalid arg !");
151 if (!_xTypes.is())
152 return NumberFormat::UNDEFINED;
154 sal_Int32 nFormat = 0;
155 sal_Int32 nNumberType = _bIsCurrency ? NumberFormat::CURRENCY : NumberFormat::NUMBER;
156 switch (_nDataType)
158 case DataType::BIT:
159 case DataType::BOOLEAN:
160 nFormat = _xTypes->getStandardFormat(NumberFormat::LOGICAL, _rLocale);
161 break;
162 case DataType::TINYINT:
163 case DataType::SMALLINT:
164 case DataType::INTEGER:
165 case DataType::BIGINT:
166 case DataType::FLOAT:
167 case DataType::REAL:
168 case DataType::DOUBLE:
169 case DataType::NUMERIC:
170 case DataType::DECIMAL:
174 nFormat = _xTypes->getStandardFormat(static_cast<sal_Int16>(nNumberType), _rLocale);
175 if(_nScale > 0)
177 // generate a new format if necessary
178 Reference< XNumberFormats > xFormats(_xTypes, UNO_QUERY);
179 OUString sNewFormat = xFormats->generateFormat( 0, _rLocale, false, false, static_cast<sal_Int16>(_nScale), 1);
181 // and add it to the formatter if necessary
182 nFormat = xFormats->queryKey(sNewFormat, _rLocale, false);
183 if (nFormat == sal_Int32(-1))
184 nFormat = xFormats->addNew(sNewFormat, _rLocale);
187 catch (Exception&)
189 nFormat = _xTypes->getStandardFormat(static_cast<sal_Int16>(nNumberType), _rLocale);
191 } break;
192 case DataType::CHAR:
193 case DataType::VARCHAR:
194 case DataType::LONGVARCHAR:
195 case DataType::CLOB:
196 nFormat = _xTypes->getStandardFormat(NumberFormat::TEXT, _rLocale);
197 break;
198 case DataType::DATE:
199 nFormat = _xTypes->getStandardFormat(NumberFormat::DATE, _rLocale);
200 break;
201 case DataType::TIME:
202 nFormat = _xTypes->getStandardFormat(NumberFormat::TIME, _rLocale);
203 break;
204 case DataType::TIMESTAMP:
205 nFormat = _xTypes->getStandardFormat(NumberFormat::DATETIME, _rLocale);
206 break;
207 case DataType::BINARY:
208 case DataType::VARBINARY:
209 case DataType::LONGVARBINARY:
210 case DataType::SQLNULL:
211 case DataType::OTHER:
212 case DataType::OBJECT:
213 case DataType::DISTINCT:
214 case DataType::STRUCT:
215 case DataType::ARRAY:
216 case DataType::BLOB:
217 case DataType::REF:
218 default:
219 nFormat = _xTypes->getStandardFormat(NumberFormat::UNDEFINED, _rLocale);
221 return nFormat;
224 static Reference< XConnection> findConnection(const Reference< XInterface >& xParent)
226 Reference< XConnection> xConnection(xParent, UNO_QUERY);
227 if (!xConnection.is())
229 Reference< XChild> xChild(xParent, UNO_QUERY);
230 if (xChild.is())
231 xConnection = findConnection(xChild->getParent());
233 return xConnection;
236 static Reference< XDataSource> getDataSource_allowException(
237 const OUString& _rsTitleOrPath,
238 const Reference< XComponentContext >& _rxContext )
240 ENSURE_OR_RETURN( !_rsTitleOrPath.isEmpty(), "getDataSource_allowException: invalid arg !", nullptr );
242 Reference< XDatabaseContext> xDatabaseContext = DatabaseContext::create(_rxContext);
244 return Reference< XDataSource >( xDatabaseContext->getByName( _rsTitleOrPath ), UNO_QUERY );
247 Reference< XDataSource > getDataSource(
248 const OUString& _rsTitleOrPath,
249 const Reference< XComponentContext >& _rxContext )
251 Reference< XDataSource > xDS;
254 xDS = getDataSource_allowException( _rsTitleOrPath, _rxContext );
256 catch( const Exception& )
258 DBG_UNHANDLED_EXCEPTION("connectivity.commontools");
261 return xDS;
264 static Reference< XConnection > getConnection_allowException(
265 const OUString& _rsTitleOrPath,
266 const OUString& _rsUser,
267 const OUString& _rsPwd,
268 const Reference< XComponentContext>& _rxContext)
270 Reference< XDataSource> xDataSource( getDataSource_allowException(_rsTitleOrPath, _rxContext) );
271 Reference<XConnection> xConnection;
272 if (xDataSource.is())
274 // do it with interaction handler
275 if(_rsUser.isEmpty() || _rsPwd.isEmpty())
277 Reference<XPropertySet> xProp(xDataSource,UNO_QUERY);
278 OUString sPwd, sUser;
279 bool bPwdReq = false;
282 xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
283 bPwdReq = ::cppu::any2bool(xProp->getPropertyValue("IsPasswordRequired"));
284 xProp->getPropertyValue("User") >>= sUser;
286 catch(Exception&)
288 OSL_FAIL("dbtools::getConnection: error while retrieving data source properties!");
290 if(bPwdReq && sPwd.isEmpty())
291 { // password required, but empty -> connect using an interaction handler
292 Reference<XCompletedConnection> xConnectionCompletion(xProp, UNO_QUERY);
293 if (xConnectionCompletion.is())
294 { // instantiate the default SDB interaction handler
295 Reference< XInteractionHandler > xHandler(
296 InteractionHandler::createWithParent(_rxContext, nullptr), UNO_QUERY );
297 xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
300 else
301 xConnection = xDataSource->getConnection(sUser, sPwd);
303 if(!xConnection.is()) // try to get one if not already have one, just to make sure
304 xConnection = xDataSource->getConnection(_rsUser, _rsPwd);
306 return xConnection;
309 Reference< XConnection> getConnection_withFeedback(const OUString& _rDataSourceName,
310 const OUString& _rUser, const OUString& _rPwd, const Reference< XComponentContext>& _rxContext)
312 Reference< XConnection > xReturn;
315 xReturn = getConnection_allowException(_rDataSourceName, _rUser, _rPwd, _rxContext);
317 catch(SQLException&)
319 // allowed to pass
320 throw;
322 catch(Exception&)
324 OSL_FAIL("::dbtools::getConnection_withFeedback: unexpected (non-SQL) exception caught!");
326 return xReturn;
329 Reference< XConnection> getConnection(const Reference< XRowSet>& _rxRowSet)
331 Reference< XConnection> xReturn;
332 Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
333 if (xRowSetProps.is())
334 xRowSetProps->getPropertyValue("ActiveConnection") >>= xReturn;
335 return xReturn;
338 // helper function which allows to implement both the connectRowset and the ensureRowSetConnection semantics
339 // if connectRowset (which is deprecated) is removed, this function and one of its parameters are
340 // not needed anymore, the whole implementation can be moved into ensureRowSetConnection then)
341 static SharedConnection lcl_connectRowSet(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext >& _rxContext,
342 bool _bAttachAutoDisposer )
344 SharedConnection xConnection;
348 Reference< XPropertySet> xRowSetProps(_rxRowSet, UNO_QUERY);
349 if ( !xRowSetProps.is() )
350 break;
352 // 1. already connected?
353 Reference< XConnection > xExistingConn(
354 xRowSetProps->getPropertyValue("ActiveConnection"),
355 UNO_QUERY );
357 if ( xExistingConn.is()
358 // 2. embedded in a database?
359 || isEmbeddedInDatabase( _rxRowSet, xExistingConn )
360 // 3. is there a connection in the parent hierarchy?
361 || ( xExistingConn = findConnection( _rxRowSet ) ).is()
364 xRowSetProps->setPropertyValue("ActiveConnection", makeAny( xExistingConn ) );
365 // no auto disposer needed, since we did not create the connection
367 xConnection.reset( xExistingConn, SharedConnection::NoTakeOwnership );
368 break;
371 // build a connection with its current settings (4. data source name, or 5. URL)
373 const OUString sUserProp( "User" );
374 OUString sDataSourceName;
375 xRowSetProps->getPropertyValue("DataSourceName") >>= sDataSourceName;
376 OUString sURL;
377 xRowSetProps->getPropertyValue("URL") >>= sURL;
379 Reference< XConnection > xPureConnection;
380 if (!sDataSourceName.isEmpty())
381 { // the row set's data source property is set
382 // -> try to connect, get user and pwd setting for that
383 OUString sUser, sPwd;
385 if (hasProperty(sUserProp, xRowSetProps))
386 xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
387 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
388 xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
390 xPureConnection = getConnection_allowException( sDataSourceName, sUser, sPwd, _rxContext );
392 else if (!sURL.isEmpty())
393 { // the row set has no data source, but a connection url set
394 // -> try to connection with that url
395 Reference< XConnectionPool > xDriverManager;
396 try {
397 xDriverManager = ConnectionPool::create( _rxContext );
398 } catch( const Exception& ) { }
399 if (xDriverManager.is())
401 OUString sUser, sPwd;
402 if (hasProperty(sUserProp, xRowSetProps))
403 xRowSetProps->getPropertyValue(sUserProp) >>= sUser;
404 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD), xRowSetProps))
405 xRowSetProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPwd;
406 if (!sUser.isEmpty())
407 { // use user and pwd together with the url
408 auto aInfo(::comphelper::InitPropertySequence({
409 { "user", makeAny(sUser) },
410 { "password", makeAny(sPwd) }
411 }));
412 xPureConnection = xDriverManager->getConnectionWithInfo( sURL, aInfo );
414 else
415 // just use the url
416 xPureConnection = xDriverManager->getConnection( sURL );
419 xConnection.reset(
420 xPureConnection,
421 _bAttachAutoDisposer ? SharedConnection::NoTakeOwnership : SharedConnection::TakeOwnership
422 /* take ownership if and only if we're *not* going to auto-dispose the connection */
425 // now if we created a connection, forward it to the row set
426 if ( xConnection.is() )
430 if ( _bAttachAutoDisposer )
432 rtl::Reference<OAutoConnectionDisposer> pAutoDispose = new OAutoConnectionDisposer( _rxRowSet, xConnection );
434 else
435 xRowSetProps->setPropertyValue(
436 "ActiveConnection",
437 makeAny( xConnection.getTyped() )
440 catch(Exception&)
442 OSL_FAIL("EXception when we set the new active connection!");
446 while ( false );
448 return xConnection;
451 Reference< XConnection> connectRowset(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext >& _rxContext )
453 SharedConnection xConnection = lcl_connectRowSet( _rxRowSet, _rxContext, true );
454 return xConnection.getTyped();
457 SharedConnection ensureRowSetConnection(const Reference< XRowSet>& _rxRowSet, const Reference< XComponentContext>& _rxContext )
459 return lcl_connectRowSet( _rxRowSet, _rxContext, false/*bUseAutoConnectionDisposer*/ );
462 Reference< XNameAccess> getTableFields(const Reference< XConnection>& _rxConn,const OUString& _rName)
464 Reference< XComponent > xDummy;
465 return getFieldsByCommandDescriptor( _rxConn, CommandType::TABLE, _rName, xDummy );
468 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Any& i_aTable)
470 const Reference< XPropertySet > xTable(i_aTable,UNO_QUERY_THROW);
471 return getPrimaryKeyColumns_throw(xTable);
474 Reference< XNameAccess> getPrimaryKeyColumns_throw(const Reference< XPropertySet >& i_xTable)
476 Reference<XNameAccess> xKeyColumns;
477 const Reference<XKeysSupplier> xKeySup(i_xTable,UNO_QUERY);
478 if ( xKeySup.is() )
480 const Reference<XIndexAccess> xKeys = xKeySup->getKeys();
481 if ( xKeys.is() )
483 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
484 const OUString& sPropName = rPropMap.getNameByIndex(PROPERTY_ID_TYPE);
485 Reference<XPropertySet> xProp;
486 const sal_Int32 nCount = xKeys->getCount();
487 for(sal_Int32 i = 0;i< nCount;++i)
489 xProp.set(xKeys->getByIndex(i),UNO_QUERY_THROW);
490 sal_Int32 nKeyType = 0;
491 xProp->getPropertyValue(sPropName) >>= nKeyType;
492 if(KeyType::PRIMARY == nKeyType)
494 const Reference<XColumnsSupplier> xKeyColsSup(xProp,UNO_QUERY_THROW);
495 xKeyColumns = xKeyColsSup->getColumns();
496 break;
502 return xKeyColumns;
505 namespace
507 enum FieldLookupState
509 HANDLE_TABLE, HANDLE_QUERY, HANDLE_SQL, RETRIEVE_OBJECT, RETRIEVE_COLUMNS, DONE, FAILED
513 Reference< XNameAccess > getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection,
514 const sal_Int32 _nCommandType, const OUString& _rCommand,
515 Reference< XComponent >& _rxKeepFieldsAlive, SQLExceptionInfo* _pErrorInfo )
517 OSL_PRECOND( _rxConnection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection!" );
518 OSL_PRECOND( ( CommandType::TABLE == _nCommandType ) || ( CommandType::QUERY == _nCommandType ) || ( CommandType::COMMAND == _nCommandType ),
519 "::dbtools::getFieldsByCommandDescriptor: invalid command type!" );
520 OSL_PRECOND( !_rCommand.isEmpty(), "::dbtools::getFieldsByCommandDescriptor: invalid command (empty)!" );
522 Reference< XNameAccess > xFields;
524 // reset the error
525 if ( _pErrorInfo )
526 *_pErrorInfo = SQLExceptionInfo();
527 // reset the ownership holder
528 _rxKeepFieldsAlive.clear();
530 // go for the fields
533 // some kind of state machine to ease the sharing of code
534 FieldLookupState eState = FAILED;
535 switch ( _nCommandType )
537 case CommandType::TABLE:
538 eState = HANDLE_TABLE;
539 break;
540 case CommandType::QUERY:
541 eState = HANDLE_QUERY;
542 break;
543 case CommandType::COMMAND:
544 eState = HANDLE_SQL;
545 break;
548 // needed in various states:
549 Reference< XNameAccess > xObjectCollection;
550 Reference< XColumnsSupplier > xSupplyColumns;
552 // go!
553 while ( ( DONE != eState ) && ( FAILED != eState ) )
555 switch ( eState )
557 case HANDLE_TABLE:
559 // initial state for handling the tables
561 // get the table objects
562 Reference< XTablesSupplier > xSupplyTables( _rxConnection, UNO_QUERY );
563 if ( xSupplyTables.is() )
564 xObjectCollection = xSupplyTables->getTables();
565 // if something went wrong 'til here, then this will be handled in the next state
567 // next state: get the object
568 eState = RETRIEVE_OBJECT;
570 break;
572 case HANDLE_QUERY:
574 // initial state for handling the tables
576 // get the table objects
577 Reference< XQueriesSupplier > xSupplyQueries( _rxConnection, UNO_QUERY );
578 if ( xSupplyQueries.is() )
579 xObjectCollection = xSupplyQueries->getQueries();
580 // if something went wrong 'til here, then this will be handled in the next state
582 // next state: get the object
583 eState = RETRIEVE_OBJECT;
585 break;
587 case RETRIEVE_OBJECT:
588 // here we should have an object (aka query or table) collection, and are going
589 // to retrieve the desired object
591 // next state: default to FAILED
592 eState = FAILED;
594 OSL_ENSURE( xObjectCollection.is(), "::dbtools::getFieldsByCommandDescriptor: invalid connection (no sdb.Connection, or no Tables-/QueriesSupplier)!");
595 if ( xObjectCollection.is() && xObjectCollection->hasByName( _rCommand ) )
597 xObjectCollection->getByName( _rCommand ) >>= xSupplyColumns;
598 // (xSupplyColumns being NULL will be handled in the next state)
600 // next: go for the columns
601 eState = RETRIEVE_COLUMNS;
603 break;
605 case RETRIEVE_COLUMNS:
606 OSL_ENSURE( xSupplyColumns.is(), "::dbtools::getFieldsByCommandDescriptor: could not retrieve the columns supplier!" );
608 // next state: default to FAILED
609 eState = FAILED;
611 if ( xSupplyColumns.is() )
613 xFields = xSupplyColumns->getColumns();
614 // that's it
615 eState = DONE;
617 break;
619 case HANDLE_SQL:
621 OUString sStatementToExecute( _rCommand );
623 // well, the main problem here is to handle statements which contain a parameter
624 // If we would simply execute a parametrized statement, then this will fail because
625 // we cannot supply any parameter values.
626 // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion
627 // This should cause every driver to not really execute the statement, but to return
628 // an empty result set with the proper structure. We then can use this result set
629 // to retrieve the columns.
633 Reference< XMultiServiceFactory > xComposerFac( _rxConnection, UNO_QUERY );
635 if ( xComposerFac.is() )
637 Reference< XSingleSelectQueryComposer > xComposer(xComposerFac->createInstance("com.sun.star.sdb.SingleSelectQueryComposer"),UNO_QUERY);
638 if ( xComposer.is() )
640 xComposer->setQuery( sStatementToExecute );
642 // Now set the filter to a dummy restriction which will result in an empty
643 // result set.
644 xComposer->setFilter( "0=1" );
645 sStatementToExecute = xComposer->getQuery( );
649 catch( const Exception& )
651 // silent this error, this was just a try. If we're here, we did not change sStatementToExecute,
652 // so it will still be _rCommand, which then will be executed without being touched
655 // now execute
656 Reference< XPreparedStatement > xStatement = _rxConnection->prepareStatement( sStatementToExecute );
657 // transfer ownership of this temporary object to the caller
658 _rxKeepFieldsAlive.set(xStatement, css::uno::UNO_QUERY);
660 // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter
661 // failed - in this case, the MaxRows restriction should at least ensure that there
662 // is no data returned (which would be potentially expensive)
663 Reference< XPropertySet > xStatementProps( xStatement,UNO_QUERY );
666 if ( xStatementProps.is() )
667 xStatementProps->setPropertyValue( "MaxRows", makeAny( sal_Int32( 0 ) ) );
669 catch( const Exception& )
671 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: could not set the MaxRows!" );
672 // oh damn. Not much of a chance to recover, we will no retrieve the complete
673 // full blown result set
676 xSupplyColumns.set(xStatement->executeQuery(), css::uno::UNO_QUERY);
677 // this should have given us a result set which does not contain any data, but
678 // the structural information we need
680 // so the next state is to get the columns
681 eState = RETRIEVE_COLUMNS;
683 break;
685 default:
686 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: oops! unhandled state here!" );
687 eState = FAILED;
691 catch( const SQLContext& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
692 catch( const SQLWarning& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
693 catch( const SQLException& e ) { if ( _pErrorInfo ) *_pErrorInfo = SQLExceptionInfo( e ); }
694 catch( const Exception& )
696 OSL_FAIL( "::dbtools::getFieldsByCommandDescriptor: caught an exception while retrieving the fields!" );
699 return xFields;
702 Sequence< OUString > getFieldNamesByCommandDescriptor( const Reference< XConnection >& _rxConnection,
703 const sal_Int32 _nCommandType, const OUString& _rCommand,
704 SQLExceptionInfo* _pErrorInfo )
706 // get the container for the fields
707 Reference< XComponent > xKeepFieldsAlive;
708 Reference< XNameAccess > xFieldContainer = getFieldsByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, xKeepFieldsAlive, _pErrorInfo );
710 // get the names of the fields
711 Sequence< OUString > aNames;
712 if ( xFieldContainer.is() )
713 aNames = xFieldContainer->getElementNames();
715 // clean up any temporary objects which have been created
716 disposeComponent( xKeepFieldsAlive );
718 // outta here
719 return aNames;
722 SQLException prependErrorInfo( const SQLException& _rChainedException, const Reference< XInterface >& _rxContext,
723 const OUString& _rAdditionalError, const StandardSQLState _eSQLState )
725 return SQLException( _rAdditionalError, _rxContext,
726 _eSQLState == StandardSQLState::ERROR_UNSPECIFIED ? OUString() : getStandardSQLState( _eSQLState ),
727 0, makeAny( _rChainedException ) );
730 namespace
732 struct NameComponentSupport
734 const bool bCatalogs;
735 const bool bSchemas;
737 NameComponentSupport( const bool _bCatalogs, const bool _bSchemas )
738 :bCatalogs( _bCatalogs )
739 ,bSchemas( _bSchemas )
744 NameComponentSupport lcl_getNameComponentSupport( const Reference< XDatabaseMetaData >& _rxMetaData, EComposeRule _eComposeRule )
746 OSL_PRECOND( _rxMetaData.is(), "lcl_getNameComponentSupport: invalid meta data!" );
748 FMetaDataSupport pCatalogCall = &XDatabaseMetaData::supportsCatalogsInDataManipulation;
749 FMetaDataSupport pSchemaCall = &XDatabaseMetaData::supportsSchemasInDataManipulation;
750 bool bIgnoreMetaData = false;
752 switch ( _eComposeRule )
754 case EComposeRule::InTableDefinitions:
755 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInTableDefinitions;
756 pSchemaCall = &XDatabaseMetaData::supportsSchemasInTableDefinitions;
757 break;
758 case EComposeRule::InIndexDefinitions:
759 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInIndexDefinitions;
760 pSchemaCall = &XDatabaseMetaData::supportsSchemasInIndexDefinitions;
761 break;
762 case EComposeRule::InProcedureCalls:
763 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInProcedureCalls;
764 pSchemaCall = &XDatabaseMetaData::supportsSchemasInProcedureCalls;
765 break;
766 case EComposeRule::InPrivilegeDefinitions:
767 pCatalogCall = &XDatabaseMetaData::supportsCatalogsInPrivilegeDefinitions;
768 pSchemaCall = &XDatabaseMetaData::supportsSchemasInPrivilegeDefinitions;
769 break;
770 case EComposeRule::Complete:
771 bIgnoreMetaData = true;
772 break;
773 case EComposeRule::InDataManipulation:
774 // already properly set above
775 break;
777 return NameComponentSupport(
778 bIgnoreMetaData || (_rxMetaData.get()->*pCatalogCall)(),
779 bIgnoreMetaData || (_rxMetaData.get()->*pSchemaCall)()
784 static OUString impl_doComposeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
785 const OUString& _rCatalog, const OUString& _rSchema, const OUString& _rName,
786 bool _bQuote, EComposeRule _eComposeRule )
788 OSL_ENSURE(_rxMetaData.is(), "impl_doComposeTableName : invalid meta data !");
789 if ( !_rxMetaData.is() )
790 return OUString();
791 OSL_ENSURE(!_rName.isEmpty(), "impl_doComposeTableName : at least the name should be non-empty !");
793 const OUString sQuoteString = _rxMetaData->getIdentifierQuoteString();
794 const NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxMetaData, _eComposeRule ) );
796 OUStringBuffer aComposedName;
798 OUString sCatalogSep;
799 bool bCatlogAtStart = true;
800 if ( !_rCatalog.isEmpty() && aNameComps.bCatalogs )
802 sCatalogSep = _rxMetaData->getCatalogSeparator();
803 bCatlogAtStart = _rxMetaData->isCatalogAtStart();
805 if ( bCatlogAtStart && !sCatalogSep.isEmpty())
807 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
808 aComposedName.append( sCatalogSep );
812 if ( !_rSchema.isEmpty() && aNameComps.bSchemas )
814 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rSchema ) : _rSchema );
815 aComposedName.append( "." );
818 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rName ) : _rName );
820 if ( !_rCatalog.isEmpty()
821 && !bCatlogAtStart
822 && !sCatalogSep.isEmpty()
823 && aNameComps.bCatalogs
826 aComposedName.append( sCatalogSep );
827 aComposedName.append( _bQuote ? quoteName( sQuoteString, _rCatalog ) : _rCatalog );
830 return aComposedName.makeStringAndClear();
833 OUString quoteTableName(const Reference< XDatabaseMetaData>& _rxMeta
834 , const OUString& _rName
835 , EComposeRule _eComposeRule)
837 OUString sCatalog, sSchema, sTable;
838 qualifiedNameComponents(_rxMeta,_rName,sCatalog,sSchema,sTable,_eComposeRule);
839 return impl_doComposeTableName( _rxMeta, sCatalog, sSchema, sTable, true, _eComposeRule );
842 void qualifiedNameComponents(const Reference< XDatabaseMetaData >& _rxConnMetaData, const OUString& _rQualifiedName, OUString& _rCatalog, OUString& _rSchema, OUString& _rName,EComposeRule _eComposeRule)
844 OSL_ENSURE(_rxConnMetaData.is(), "QualifiedNameComponents : invalid meta data!");
846 NameComponentSupport aNameComps( lcl_getNameComponentSupport( _rxConnMetaData, _eComposeRule ) );
848 OUString sSeparator = _rxConnMetaData->getCatalogSeparator();
850 OUString sName(_rQualifiedName);
851 // do we have catalogs?
852 if ( aNameComps.bCatalogs )
854 if (_rxConnMetaData->isCatalogAtStart())
856 // search for the catalog name at the beginning
857 sal_Int32 nIndex = sName.indexOf(sSeparator);
858 if (-1 != nIndex)
860 _rCatalog = sName.copy(0, nIndex);
861 sName = sName.copy(nIndex + 1);
864 else
866 // Catalog name at the end
867 sal_Int32 nIndex = sName.lastIndexOf(sSeparator);
868 if (-1 != nIndex)
870 _rCatalog = sName.copy(nIndex + 1);
871 sName = sName.copy(0, nIndex);
876 if ( aNameComps.bSchemas )
878 sal_Int32 nIndex = sName.indexOf('.');
879 // OSL_ENSURE(-1 != nIndex, "QualifiedNameComponents: no schema separator!");
880 if ( nIndex != -1 )
881 _rSchema = sName.copy(0, nIndex);
882 sName = sName.copy(nIndex + 1);
885 _rName = sName;
888 Reference< XNumberFormatsSupplier> getNumberFormats(
889 const Reference< XConnection>& _rxConn,
890 bool _bAlloweDefault,
891 const Reference< XComponentContext>& _rxContext)
893 // ask the parent of the connection (should be a DatabaseAccess)
894 Reference< XNumberFormatsSupplier> xReturn;
895 Reference< XChild> xConnAsChild(_rxConn, UNO_QUERY);
896 OUString sPropFormatsSupplier( "NumberFormatsSupplier" );
897 if (xConnAsChild.is())
899 Reference< XPropertySet> xConnParentProps(xConnAsChild->getParent(), UNO_QUERY);
900 if (xConnParentProps.is() && hasProperty(sPropFormatsSupplier, xConnParentProps))
901 xConnParentProps->getPropertyValue(sPropFormatsSupplier) >>= xReturn;
903 else if(_bAlloweDefault && _rxContext.is())
905 xReturn = NumberFormatsSupplier::createWithDefaultLocale( _rxContext );
907 return xReturn;
910 void TransferFormComponentProperties(
911 const Reference< XPropertySet>& xOldProps,
912 const Reference< XPropertySet>& xNewProps,
913 const Locale& _rLocale)
917 OSL_ENSURE( xOldProps.is() && xNewProps.is(), "TransferFormComponentProperties: invalid source/dest!" );
918 if ( !xOldProps.is() || !xNewProps.is() )
919 return;
921 // First we copy all the Props, that are available in source and target and have the same description
922 Reference< XPropertySetInfo> xOldInfo( xOldProps->getPropertySetInfo());
923 Reference< XPropertySetInfo> xNewInfo( xNewProps->getPropertySetInfo());
925 Sequence< Property> aOldProperties = xOldInfo->getProperties();
926 Sequence< Property> aNewProperties = xNewInfo->getProperties();
927 int nNewLen = aNewProperties.getLength();
929 Property* pOldProps = aOldProperties.getArray();
930 Property* pNewProps = aNewProperties.getArray();
932 OUString sPropFormatsSupplier("FormatsSupplier");
933 OUString sPropCurrencySymbol("CurrencySymbol");
934 OUString sPropDecimals("Decimals");
935 OUString sPropEffectiveMin("EffectiveMin");
936 OUString sPropEffectiveMax("EffectiveMax");
937 OUString sPropEffectiveDefault("EffectiveDefault");
938 OUString sPropDefaultText("DefaultText");
939 OUString sPropDefaultDate("DefaultDate");
940 OUString sPropDefaultTime("DefaultTime");
941 OUString sPropValueMin("ValueMin");
942 OUString sPropValueMax("ValueMax");
943 OUString sPropDecimalAccuracy("DecimalAccuracy");
944 OUString sPropClassId("ClassId");
945 OUString sFormattedServiceName( "com.sun.star.form.component.FormattedField" );
947 for (sal_Int32 i=0; i<aOldProperties.getLength(); ++i)
949 if ( pOldProps[i].Name != "DefaultControl" && pOldProps[i].Name != "LabelControl" )
951 // binary search
952 Property* pResult = std::lower_bound(
953 pNewProps, pNewProps + nNewLen, pOldProps[i], ::comphelper::PropertyCompareByName());
955 if ( ( pResult != aNewProperties.end() )
956 && ( pResult->Name == pOldProps[i].Name )
957 && ( (pResult->Attributes & PropertyAttribute::READONLY) == 0 )
958 && ( pResult->Type.equals(pOldProps[i].Type)) )
959 { // Attributes match and the property is not read-only
962 xNewProps->setPropertyValue(pResult->Name, xOldProps->getPropertyValue(pResult->Name));
964 catch(IllegalArgumentException const & exc)
966 SAL_WARN( "connectivity.commontools", "TransferFormComponentProperties : could not transfer the value for property \""
967 << pResult->Name << "\" " << exc);
973 // for formatted fields (either old or new) we have some special treatments
974 Reference< XServiceInfo > xSI( xOldProps, UNO_QUERY );
975 bool bOldIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
976 xSI.set( xNewProps, UNO_QUERY );
977 bool bNewIsFormatted = xSI.is() && xSI->supportsService( sFormattedServiceName );
979 if (!bOldIsFormatted && !bNewIsFormatted)
980 return; // nothing to do
982 if (bOldIsFormatted && bNewIsFormatted)
983 // if both fields are formatted we do no conversions
984 return;
986 if (bOldIsFormatted)
988 // get some properties from the selected format and put them in the new Set
989 Any aFormatKey( xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY)) );
990 if (aFormatKey.hasValue())
992 Reference< XNumberFormatsSupplier> xSupplier;
993 xOldProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
994 if (xSupplier.is())
996 Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
997 Reference< XPropertySet> xFormat(xFormats->getByKey(getINT32(aFormatKey)));
998 if (hasProperty(sPropCurrencySymbol, xFormat))
1000 Any aVal( xFormat->getPropertyValue(sPropCurrencySymbol) );
1001 if (aVal.hasValue() && hasProperty(sPropCurrencySymbol, xNewProps))
1002 // If the source value hasn't been set then don't copy it
1003 // so we don't overwrite the default value
1004 xNewProps->setPropertyValue(sPropCurrencySymbol, aVal);
1006 if (hasProperty(sPropDecimals, xFormat) && hasProperty(sPropDecimals, xNewProps))
1007 xNewProps->setPropertyValue(sPropDecimals, xFormat->getPropertyValue(sPropDecimals));
1011 // a potential Min-Max-Conversion
1012 Any aEffectiveMin( xOldProps->getPropertyValue(sPropEffectiveMin) );
1013 if (aEffectiveMin.hasValue())
1014 { // Unlike the ValueMin the EffectiveMin can be void
1015 if (hasProperty(sPropValueMin, xNewProps))
1017 OSL_ENSURE(aEffectiveMin.getValueType().getTypeClass() == TypeClass_DOUBLE,
1018 "TransferFormComponentProperties : invalid property type !");
1019 xNewProps->setPropertyValue(sPropValueMin, aEffectiveMin);
1022 Any aEffectiveMax( xOldProps->getPropertyValue(sPropEffectiveMax) );
1023 if (aEffectiveMax.hasValue())
1024 { // analog
1025 if (hasProperty(sPropValueMax, xNewProps))
1027 OSL_ENSURE(aEffectiveMax.getValueType().getTypeClass() == TypeClass_DOUBLE,
1028 "TransferFormComponentProperties : invalid property type !");
1029 xNewProps->setPropertyValue(sPropValueMax, aEffectiveMax);
1033 // then we can still convert and copy the default values
1034 Any aEffectiveDefault( xOldProps->getPropertyValue(sPropEffectiveDefault) );
1035 if (aEffectiveDefault.hasValue())
1037 bool bIsString = aEffectiveDefault.getValueType().getTypeClass() == TypeClass_STRING;
1038 OSL_ENSURE(bIsString || aEffectiveDefault.getValueType().getTypeClass() == TypeClass_DOUBLE,
1039 "TransferFormComponentProperties : invalid property type !");
1040 // The Effective-Properties should always be void or string or double ....
1042 if (hasProperty(sPropDefaultDate, xNewProps) && !bIsString)
1043 { // (to convert an OUString into a date will not always succeed, because it might be bound to a text-column,
1044 // but we can work with a double)
1045 Date aDate = DBTypeConversion::toDate(getDouble(aEffectiveDefault));
1046 xNewProps->setPropertyValue(sPropDefaultDate, makeAny(aDate));
1049 if (hasProperty(sPropDefaultTime, xNewProps) && !bIsString)
1050 { // Completely analogous to time
1051 css::util::Time aTime = DBTypeConversion::toTime(getDouble(aEffectiveDefault));
1052 xNewProps->setPropertyValue(sPropDefaultTime, makeAny(aTime));
1055 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xNewProps) && !bIsString)
1056 { // Here we can simply pass the double
1057 xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), aEffectiveDefault);
1060 if (hasProperty(sPropDefaultText, xNewProps) && bIsString)
1061 { // and here the OUString
1062 xNewProps->setPropertyValue(sPropDefaultText, aEffectiveDefault);
1065 // nyi: The translation between doubles and OUString would offer more alternatives
1069 // The other direction: the new Control shall be formatted
1070 if (bNewIsFormatted)
1072 // first the formatting
1073 // we can't set a Supplier, so the new Set must bring one in
1074 Reference< XNumberFormatsSupplier> xSupplier;
1075 xNewProps->getPropertyValue(sPropFormatsSupplier) >>= xSupplier;
1076 if (xSupplier.is())
1078 Reference< XNumberFormats> xFormats(xSupplier->getNumberFormats());
1080 // Set number of decimals
1081 sal_Int16 nDecimals = 2;
1082 if (hasProperty(sPropDecimalAccuracy, xOldProps))
1083 xOldProps->getPropertyValue(sPropDecimalAccuracy) >>= nDecimals;
1085 // base format (depending on the ClassId of the old Set)
1086 sal_Int32 nBaseKey = 0;
1087 if (hasProperty(sPropClassId, xOldProps))
1089 Reference< XNumberFormatTypes> xTypeList(xFormats, UNO_QUERY);
1090 if (xTypeList.is())
1092 sal_Int16 nClassId = 0;
1093 xOldProps->getPropertyValue(sPropClassId) >>= nClassId;
1094 switch (nClassId)
1096 case FormComponentType::DATEFIELD :
1097 nBaseKey = xTypeList->getStandardFormat(NumberFormat::DATE, _rLocale);
1098 break;
1100 case FormComponentType::TIMEFIELD :
1101 nBaseKey = xTypeList->getStandardFormat(NumberFormat::TIME, _rLocale);
1102 break;
1104 case FormComponentType::CURRENCYFIELD :
1105 nBaseKey = xTypeList->getStandardFormat(NumberFormat::CURRENCY, _rLocale);
1106 break;
1111 // With this we can generate a new format ...
1112 OUString sNewFormat = xFormats->generateFormat(nBaseKey, _rLocale, false, false, nDecimals, 0);
1113 // No thousands separator, negative numbers are not in red, no leading zeros
1115 // ... and add at FormatsSupplier (if needed)
1116 sal_Int32 nKey = xFormats->queryKey(sNewFormat, _rLocale, false);
1117 if (nKey == sal_Int32(-1))
1118 { // not added yet in my formatter ...
1119 nKey = xFormats->addNew(sNewFormat, _rLocale);
1122 xNewProps->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FORMATKEY), makeAny(nKey));
1125 // min-/max-Value
1126 Any aNewMin, aNewMax;
1127 if (hasProperty(sPropValueMin, xOldProps))
1128 aNewMin = xOldProps->getPropertyValue(sPropValueMin);
1129 if (hasProperty(sPropValueMax, xOldProps))
1130 aNewMax = xOldProps->getPropertyValue(sPropValueMax);
1131 xNewProps->setPropertyValue(sPropEffectiveMin, aNewMin);
1132 xNewProps->setPropertyValue(sPropEffectiveMax, aNewMax);
1134 // Default-Value
1135 Any aNewDefault;
1136 if (hasProperty(sPropDefaultDate, xOldProps))
1138 Any aDate( xOldProps->getPropertyValue(sPropDefaultDate) );
1139 if (aDate.hasValue())
1140 aNewDefault <<= DBTypeConversion::toDouble(*o3tl::doAccess<Date>(aDate));
1143 if (hasProperty(sPropDefaultTime, xOldProps))
1145 Any aTime( xOldProps->getPropertyValue(sPropDefaultTime) );
1146 if (aTime.hasValue())
1147 aNewDefault <<= DBTypeConversion::toDouble(*o3tl::doAccess<Time>(aTime));
1150 // double or OUString will be copied directly
1151 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE), xOldProps))
1152 aNewDefault = xOldProps->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE));
1153 if (hasProperty(sPropDefaultText, xOldProps))
1154 aNewDefault = xOldProps->getPropertyValue(sPropDefaultText);
1156 if (aNewDefault.hasValue())
1157 xNewProps->setPropertyValue(sPropEffectiveDefault, aNewDefault);
1160 catch(const Exception&)
1162 OSL_FAIL( "TransferFormComponentProperties: caught an exception!" );
1166 bool canInsert(const Reference< XPropertySet>& _rxCursorSet)
1168 return (_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::INSERT) != 0);
1171 bool canUpdate(const Reference< XPropertySet>& _rxCursorSet)
1173 return (_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::UPDATE) != 0);
1176 bool canDelete(const Reference< XPropertySet>& _rxCursorSet)
1178 return (_rxCursorSet.is() && (getINT32(_rxCursorSet->getPropertyValue("Privileges")) & Privilege::DELETE) != 0);
1181 Reference< XDataSource> findDataSource(const Reference< XInterface >& _xParent)
1183 Reference< XOfficeDatabaseDocument> xDatabaseDocument(_xParent, UNO_QUERY);
1184 Reference< XDataSource> xDataSource;
1185 if ( xDatabaseDocument.is() )
1186 xDataSource = xDatabaseDocument->getDataSource();
1187 if ( !xDataSource.is() )
1188 xDataSource.set(_xParent, UNO_QUERY);
1189 if (!xDataSource.is())
1191 Reference< XChild> xChild(_xParent, UNO_QUERY);
1192 if ( xChild.is() )
1193 xDataSource = findDataSource(xChild->getParent());
1195 return xDataSource;
1198 static Reference< XSingleSelectQueryComposer > getComposedRowSetStatement( const Reference< XPropertySet >& _rxRowSet, const Reference< XComponentContext >& _rxContext )
1200 Reference< XSingleSelectQueryComposer > xComposer;
1203 Reference< XConnection> xConn = connectRowset( Reference< XRowSet >( _rxRowSet, UNO_QUERY ), _rxContext );
1204 if ( xConn.is() ) // implies _rxRowSet.is()
1206 // build the statement the row set is based on (can't use the ActiveCommand property of the set
1207 // as this reflects the status after the last execute, not the currently set properties)
1209 sal_Int32 nCommandType = CommandType::COMMAND;
1210 OUString sCommand;
1211 bool bEscapeProcessing = false;
1213 OSL_VERIFY( _rxRowSet->getPropertyValue("CommandType") >>= nCommandType );
1214 OSL_VERIFY( _rxRowSet->getPropertyValue("Command") >>= sCommand );
1215 OSL_VERIFY( _rxRowSet->getPropertyValue("EscapeProcessing") >>= bEscapeProcessing );
1217 StatementComposer aComposer( xConn, sCommand, nCommandType, bEscapeProcessing );
1218 // append sort
1219 aComposer.setOrder( getString( _rxRowSet->getPropertyValue("Order") ) );
1221 // append filter
1222 bool bApplyFilter = true;
1223 _rxRowSet->getPropertyValue("ApplyFilter") >>= bApplyFilter;
1224 if ( bApplyFilter )
1225 aComposer.setFilter( getString( _rxRowSet->getPropertyValue("Filter") ) );
1227 aComposer.getQuery();
1229 xComposer = aComposer.getComposer();
1230 aComposer.setDisposeComposer( false );
1233 catch( const SQLException& )
1235 throw;
1237 catch( const Exception& )
1239 DBG_UNHANDLED_EXCEPTION("connectivity.commontools");
1242 return xComposer;
1245 Reference< XSingleSelectQueryComposer > getCurrentSettingsComposer(
1246 const Reference< XPropertySet>& _rxRowSetProps,
1247 const Reference< XComponentContext>& _rxContext)
1249 Reference< XSingleSelectQueryComposer > xReturn;
1252 xReturn = getComposedRowSetStatement( _rxRowSetProps, _rxContext );
1254 catch( const SQLException& )
1256 throw;
1258 catch( const Exception& )
1260 OSL_FAIL( "::getCurrentSettingsComposer : caught an exception !" );
1263 return xReturn;
1266 OUString composeTableName( const Reference< XDatabaseMetaData >& _rxMetaData,
1267 const OUString& _rCatalog,
1268 const OUString& _rSchema,
1269 const OUString& _rName,
1270 bool _bQuote,
1271 EComposeRule _eComposeRule)
1273 return impl_doComposeTableName( _rxMetaData, _rCatalog, _rSchema, _rName, _bQuote, _eComposeRule );
1276 OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection,
1277 const OUString& _rCatalog, const OUString& _rSchema, const OUString& _rName )
1279 bool bUseCatalogInSelect = isDataSourcePropertyEnabled( _rxConnection, "UseCatalogInSelect", true );
1280 bool bUseSchemaInSelect = isDataSourcePropertyEnabled( _rxConnection, "UseSchemaInSelect", true );
1282 return impl_doComposeTableName(
1283 _rxConnection->getMetaData(),
1284 bUseCatalogInSelect ? _rCatalog : OUString(),
1285 bUseSchemaInSelect ? _rSchema : OUString(),
1286 _rName,
1287 true,
1288 EComposeRule::InDataManipulation
1292 namespace
1294 void lcl_getTableNameComponents( const Reference<XPropertySet>& _xTable,
1295 OUString& _out_rCatalog, OUString& _out_rSchema, OUString& _out_rName )
1297 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
1298 Reference< XPropertySetInfo > xInfo;
1299 if (_xTable.is())
1300 xInfo = _xTable->getPropertySetInfo();
1301 if ( xInfo.is()
1302 && xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) )
1304 if ( xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME))
1305 && xInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) )
1307 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)) >>= _out_rCatalog;
1308 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= _out_rSchema;
1310 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= _out_rName;
1312 else
1313 OSL_FAIL( "::dbtools::lcl_getTableNameComponents: this is no table object!" );
1317 OUString composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const Reference<XPropertySet>& _xTable )
1319 OUString sCatalog, sSchema, sName;
1320 lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1322 return composeTableNameForSelect( _rxConnection, sCatalog, sSchema, sName );
1325 OUString composeTableName(const Reference<XDatabaseMetaData>& _xMetaData,
1326 const Reference<XPropertySet>& _xTable,
1327 EComposeRule _eComposeRule,
1328 bool _bQuote )
1330 OUString sCatalog, sSchema, sName;
1331 lcl_getTableNameComponents( _xTable, sCatalog, sSchema, sName );
1333 return impl_doComposeTableName(
1334 _xMetaData,
1335 sCatalog,
1336 sSchema,
1337 sName,
1338 _bQuote,
1339 _eComposeRule
1343 sal_Int32 getSearchColumnFlag( const Reference< XConnection>& _rxConn,sal_Int32 _nDataType)
1345 sal_Int32 nSearchFlag = 0;
1346 Reference<XResultSet> xSet = _rxConn->getMetaData()->getTypeInfo();
1347 if(xSet.is())
1349 Reference<XRow> xRow(xSet,UNO_QUERY);
1350 while(xSet->next())
1352 if(xRow->getInt(2) == _nDataType)
1354 nSearchFlag = xRow->getInt(9);
1355 break;
1359 return nSearchFlag;
1362 OUString createUniqueName( const Sequence< OUString >& _rNames, const OUString& _rBaseName, bool _bStartWithNumber )
1364 std::set< OUString > aUsedNames;
1365 std::copy(
1366 _rNames.begin(),
1367 _rNames.end(),
1368 std::insert_iterator< std::set< OUString > >( aUsedNames, aUsedNames.end() )
1371 OUString sName( _rBaseName );
1372 sal_Int32 nPos = 1;
1373 if ( _bStartWithNumber )
1374 sName += OUString::number( nPos );
1376 while ( aUsedNames.find( sName ) != aUsedNames.end() )
1378 sName = _rBaseName + OUString::number( ++nPos );
1380 return sName;
1383 OUString createUniqueName(const Reference<XNameAccess>& _rxContainer,const OUString& _rBaseName, bool _bStartWithNumber)
1385 Sequence< OUString > aElementNames;
1387 OSL_ENSURE( _rxContainer.is(), "createUniqueName: invalid container!" );
1388 if ( _rxContainer.is() )
1389 aElementNames = _rxContainer->getElementNames();
1391 return createUniqueName( aElementNames, _rBaseName, _bStartWithNumber );
1394 void showError(const SQLExceptionInfo& _rInfo,
1395 const Reference< XWindow>& _xParent,
1396 const Reference< XComponentContext >& _rxContext)
1398 if (_rInfo.isValid())
1402 Reference< XExecutableDialog > xErrorDialog = ErrorMessageDialog::create( _rxContext, "", _xParent, _rInfo.get() );
1403 xErrorDialog->execute();
1405 catch(const Exception&)
1407 OSL_FAIL("showError: could not display the error message!");
1412 bool implUpdateObject(const Reference< XRowUpdate >& _rxUpdatedObject,
1413 const sal_Int32 _nColumnIndex, const Any& _rValue)
1415 bool bSuccessfullyReRouted = true;
1416 switch (_rValue.getValueTypeClass())
1418 case TypeClass_ANY:
1420 bSuccessfullyReRouted = implUpdateObject(_rxUpdatedObject, _nColumnIndex, _rValue);
1422 break;
1424 case TypeClass_VOID:
1425 _rxUpdatedObject->updateNull(_nColumnIndex);
1426 break;
1428 case TypeClass_STRING:
1429 _rxUpdatedObject->updateString(_nColumnIndex, *o3tl::forceAccess<OUString>(_rValue));
1430 break;
1432 case TypeClass_BOOLEAN:
1433 _rxUpdatedObject->updateBoolean(_nColumnIndex, *o3tl::forceAccess<bool>(_rValue));
1434 break;
1436 case TypeClass_BYTE:
1437 _rxUpdatedObject->updateByte(_nColumnIndex, *o3tl::forceAccess<sal_Int8>(_rValue));
1438 break;
1440 case TypeClass_UNSIGNED_SHORT:
1441 case TypeClass_SHORT:
1442 _rxUpdatedObject->updateShort(_nColumnIndex, *o3tl::forceAccess<sal_Int16>(_rValue));
1443 break;
1445 case TypeClass_CHAR:
1446 _rxUpdatedObject->updateString(_nColumnIndex,OUString(*o3tl::forceAccess<sal_Unicode>(_rValue)));
1447 break;
1449 case TypeClass_UNSIGNED_LONG:
1450 case TypeClass_LONG:
1451 _rxUpdatedObject->updateInt(_nColumnIndex, *o3tl::forceAccess<sal_Int32>(_rValue));
1452 break;
1454 case TypeClass_HYPER:
1456 sal_Int64 nValue = 0;
1457 OSL_VERIFY( _rValue >>= nValue );
1458 _rxUpdatedObject->updateLong( _nColumnIndex, nValue );
1460 break;
1462 case TypeClass_FLOAT:
1463 _rxUpdatedObject->updateFloat(_nColumnIndex, *o3tl::forceAccess<float>(_rValue));
1464 break;
1466 case TypeClass_DOUBLE:
1467 _rxUpdatedObject->updateDouble(_nColumnIndex, *o3tl::forceAccess<double>(_rValue));
1468 break;
1470 case TypeClass_SEQUENCE:
1471 if (auto s = o3tl::tryAccess<Sequence< sal_Int8 >>(_rValue))
1472 _rxUpdatedObject->updateBytes(_nColumnIndex, *s);
1473 else
1474 bSuccessfullyReRouted = false;
1475 break;
1476 case TypeClass_STRUCT:
1477 if (auto s1 = o3tl::tryAccess<DateTime>(_rValue))
1478 _rxUpdatedObject->updateTimestamp(_nColumnIndex, *s1);
1479 else if (auto s2 = o3tl::tryAccess<Date>(_rValue))
1480 _rxUpdatedObject->updateDate(_nColumnIndex, *s2);
1481 else if (auto s3 = o3tl::tryAccess<Time>(_rValue))
1482 _rxUpdatedObject->updateTime(_nColumnIndex, *s3);
1483 else
1484 bSuccessfullyReRouted = false;
1485 break;
1487 case TypeClass_INTERFACE:
1488 if (auto xStream = o3tl::tryAccess<Reference<XInputStream>>(_rValue))
1490 _rxUpdatedObject->updateBinaryStream(_nColumnIndex, *xStream, (*xStream)->available());
1491 break;
1493 [[fallthrough]];
1494 default:
1495 bSuccessfullyReRouted = false;
1498 return bSuccessfullyReRouted;
1501 bool implSetObject( const Reference< XParameters >& _rxParameters,
1502 const sal_Int32 _nColumnIndex, const Any& _rValue)
1504 bool bSuccessfullyReRouted = true;
1505 switch (_rValue.getValueTypeClass())
1507 case TypeClass_UNSIGNED_HYPER:
1509 sal_uInt64 nValue = 0;
1510 OSL_VERIFY( _rValue >>= nValue );
1511 _rxParameters->setString(_nColumnIndex, OUString::number(nValue));
1513 break;
1515 case TypeClass_UNSIGNED_LONG:
1516 case TypeClass_HYPER:
1518 sal_Int64 nValue = 0;
1519 OSL_VERIFY( _rValue >>= nValue );
1520 _rxParameters->setLong( _nColumnIndex, nValue );
1522 break;
1524 case TypeClass_ANY:
1526 bSuccessfullyReRouted = implSetObject(_rxParameters, _nColumnIndex, _rValue);
1528 break;
1530 case TypeClass_VOID:
1531 _rxParameters->setNull(_nColumnIndex,DataType::VARCHAR);
1532 break;
1534 case TypeClass_STRING:
1535 _rxParameters->setString(_nColumnIndex, *o3tl::forceAccess<OUString>(_rValue));
1536 break;
1538 case TypeClass_BOOLEAN:
1539 _rxParameters->setBoolean(_nColumnIndex, *o3tl::forceAccess<bool>(_rValue));
1540 break;
1542 case TypeClass_BYTE:
1543 _rxParameters->setByte(_nColumnIndex, *o3tl::forceAccess<sal_Int8>(_rValue));
1544 break;
1546 case TypeClass_SHORT:
1547 _rxParameters->setShort(_nColumnIndex, *o3tl::forceAccess<sal_Int16>(_rValue));
1548 break;
1550 case TypeClass_CHAR:
1551 _rxParameters->setString(_nColumnIndex, OUString(*o3tl::forceAccess<sal_Unicode>(_rValue)));
1552 break;
1554 case TypeClass_UNSIGNED_SHORT:
1555 case TypeClass_LONG:
1557 sal_Int32 nValue = 0;
1558 OSL_VERIFY( _rValue >>= nValue );
1559 _rxParameters->setInt(_nColumnIndex, nValue);
1560 break;
1563 case TypeClass_FLOAT:
1564 _rxParameters->setFloat(_nColumnIndex, *o3tl::forceAccess<float>(_rValue));
1565 break;
1567 case TypeClass_DOUBLE:
1568 _rxParameters->setDouble(_nColumnIndex, *o3tl::forceAccess<double>(_rValue));
1569 break;
1571 case TypeClass_SEQUENCE:
1572 if (auto s = o3tl::tryAccess<Sequence< sal_Int8 >>(_rValue))
1574 _rxParameters->setBytes(_nColumnIndex, *s);
1576 else
1577 bSuccessfullyReRouted = false;
1578 break;
1579 case TypeClass_STRUCT:
1580 if (auto s1 = o3tl::tryAccess<DateTime>(_rValue))
1581 _rxParameters->setTimestamp(_nColumnIndex, *s1);
1582 else if (auto s2 = o3tl::tryAccess<Date>(_rValue))
1583 _rxParameters->setDate(_nColumnIndex, *s2);
1584 else if (auto s3 = o3tl::tryAccess<Time>(_rValue))
1585 _rxParameters->setTime(_nColumnIndex, *s3);
1586 else
1587 bSuccessfullyReRouted = false;
1588 break;
1590 case TypeClass_INTERFACE:
1591 if (_rValue.getValueType() == cppu::UnoType<XInputStream>::get())
1593 Reference< XInputStream > xStream;
1594 _rValue >>= xStream;
1595 _rxParameters->setBinaryStream(_nColumnIndex, xStream, xStream->available());
1596 break;
1598 [[fallthrough]];
1599 default:
1600 bSuccessfullyReRouted = false;
1604 return bSuccessfullyReRouted;
1607 namespace
1609 class OParameterWrapper : public ::cppu::WeakImplHelper< XIndexAccess >
1611 std::vector<bool, std::allocator<bool> > m_aSet;
1612 Reference<XIndexAccess> m_xSource;
1613 public:
1614 OParameterWrapper(const std::vector<bool, std::allocator<bool> >& _aSet,const Reference<XIndexAccess>& _xSource) : m_aSet(_aSet),m_xSource(_xSource){}
1615 private:
1616 // css::container::XElementAccess
1617 virtual Type SAL_CALL getElementType() override
1619 return m_xSource->getElementType();
1621 virtual sal_Bool SAL_CALL hasElements( ) override
1623 if ( m_aSet.empty() )
1624 return m_xSource->hasElements();
1625 return std::count(m_aSet.begin(),m_aSet.end(),false) != 0;
1627 // css::container::XIndexAccess
1628 virtual sal_Int32 SAL_CALL getCount( ) override
1630 if ( m_aSet.empty() )
1631 return m_xSource->getCount();
1632 return std::count(m_aSet.begin(),m_aSet.end(),false);
1634 virtual Any SAL_CALL getByIndex( sal_Int32 Index ) override
1636 if ( m_aSet.empty() )
1637 return m_xSource->getByIndex(Index);
1638 if ( m_aSet.size() < static_cast<size_t>(Index) )
1639 throw IndexOutOfBoundsException();
1641 std::vector<bool, std::allocator<bool> >::const_iterator aIter = m_aSet.begin();
1642 std::vector<bool, std::allocator<bool> >::const_iterator aEnd = m_aSet.end();
1643 sal_Int32 i = 0;
1644 for(; aIter != aEnd && i <= Index; ++aIter)
1646 if ( !*aIter )
1648 ++i;
1651 auto nParamPos = static_cast<sal_Int32>(std::distance(m_aSet.cbegin(), aIter)) - 1;
1652 return m_xSource->getByIndex(nParamPos);
1657 void askForParameters(const Reference< XSingleSelectQueryComposer >& _xComposer,
1658 const Reference<XParameters>& _xParameters,
1659 const Reference< XConnection>& _xConnection,
1660 const Reference< XInteractionHandler >& _rxHandler,
1661 const std::vector<bool, std::allocator<bool> >& _aParametersSet)
1663 OSL_ENSURE(_xComposer.is(),"dbtools::askForParameters XSQLQueryComposer is null!");
1664 OSL_ENSURE(_xParameters.is(),"dbtools::askForParameters XParameters is null!");
1665 OSL_ENSURE(_xConnection.is(),"dbtools::askForParameters XConnection is null!");
1666 OSL_ENSURE(_rxHandler.is(),"dbtools::askForParameters XInteractionHandler is null!");
1668 // we have to set this here again because getCurrentSettingsComposer can force a setpropertyvalue
1669 Reference<XParametersSupplier> xParameters(_xComposer, UNO_QUERY);
1671 Reference<XIndexAccess> xParamsAsIndicies = xParameters.is() ? xParameters->getParameters() : Reference<XIndexAccess>();
1672 sal_Int32 nParamCount = xParamsAsIndicies.is() ? xParamsAsIndicies->getCount() : 0;
1673 std::vector<bool, std::allocator<bool> > aNewParameterSet( _aParametersSet );
1674 if ( nParamCount && std::count(aNewParameterSet.begin(),aNewParameterSet.end(),true) != nParamCount )
1676 static const OUString PROPERTY_NAME(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME));
1677 aNewParameterSet.resize(nParamCount ,false);
1678 typedef std::map< OUString, std::vector<sal_Int32> > TParameterPositions;
1679 TParameterPositions aParameterNames;
1680 for(sal_Int32 i = 0; i < nParamCount; ++i)
1682 Reference<XPropertySet> xParam(xParamsAsIndicies->getByIndex(i),UNO_QUERY);
1683 OUString sName;
1684 xParam->getPropertyValue(PROPERTY_NAME) >>= sName;
1686 TParameterPositions::const_iterator aFind = aParameterNames.find(sName);
1687 if ( aFind != aParameterNames.end() )
1688 aNewParameterSet[i] = true;
1689 aParameterNames[sName].push_back(i+1);
1691 // build an interaction request
1692 // two continuations (Ok and Cancel)
1693 OInteractionAbort* pAbort = new OInteractionAbort;
1694 OParameterContinuation* pParams = new OParameterContinuation;
1695 // the request
1696 ParametersRequest aRequest;
1697 Reference<XIndexAccess> xWrappedParameters = new OParameterWrapper(aNewParameterSet,xParamsAsIndicies);
1698 aRequest.Parameters = xWrappedParameters;
1699 aRequest.Connection = _xConnection;
1700 OInteractionRequest* pRequest = new OInteractionRequest(makeAny(aRequest));
1701 Reference< XInteractionRequest > xRequest(pRequest);
1702 // some knittings
1703 pRequest->addContinuation(pAbort);
1704 pRequest->addContinuation(pParams);
1706 // execute the request
1707 _rxHandler->handle(xRequest);
1709 if (!pParams->wasSelected())
1711 // canceled by the user (i.e. (s)he canceled the dialog)
1712 RowSetVetoException e;
1713 e.ErrorCode = ParameterInteractionCancelled;
1714 throw e;
1717 // now transfer the values from the continuation object to the parameter columns
1718 Sequence< PropertyValue > aFinalValues = pParams->getValues();
1719 const PropertyValue* pFinalValues = aFinalValues.getConstArray();
1720 for (sal_Int32 i=0; i<aFinalValues.getLength(); ++i, ++pFinalValues)
1722 Reference< XPropertySet > xParamColumn(xWrappedParameters->getByIndex(i),UNO_QUERY);
1723 if (xParamColumn.is())
1725 OUString sName;
1726 xParamColumn->getPropertyValue(PROPERTY_NAME) >>= sName;
1727 OSL_ENSURE(sName == pFinalValues->Name, "::dbaui::askForParameters: inconsistent parameter names!");
1729 // determine the field type and ...
1730 sal_Int32 nParamType = 0;
1731 xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nParamType;
1732 // ... the scale of the parameter column
1733 sal_Int32 nScale = 0;
1734 if (hasProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE), xParamColumn))
1735 xParamColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
1736 // (the index of the parameters is one-based)
1737 TParameterPositions::const_iterator aFind = aParameterNames.find(pFinalValues->Name);
1738 for(const auto& rItem : aFind->second)
1740 if ( _aParametersSet.empty() || !_aParametersSet[rItem-1] )
1742 _xParameters->setObjectWithInfo(rItem, pFinalValues->Value, nParamType, nScale);
1750 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1751 sal_Int32 parameterIndex,
1752 const Any& x,
1753 sal_Int32 sqlType,
1754 sal_Int32 scale)
1756 ORowSetValue aVal;
1757 aVal.fill(x);
1758 setObjectWithInfo(_xParams,parameterIndex,aVal,sqlType,scale);
1761 void setObjectWithInfo(const Reference<XParameters>& _xParams,
1762 sal_Int32 parameterIndex,
1763 const ::connectivity::ORowSetValue& _rValue,
1764 sal_Int32 sqlType,
1765 sal_Int32 scale)
1767 if ( _rValue.isNull() )
1768 _xParams->setNull(parameterIndex,sqlType);
1769 else
1771 switch(sqlType)
1773 case DataType::DECIMAL:
1774 case DataType::NUMERIC:
1775 _xParams->setObjectWithInfo(parameterIndex,_rValue.makeAny(),sqlType,scale);
1776 break;
1777 case DataType::CHAR:
1778 case DataType::VARCHAR:
1779 case DataType::LONGVARCHAR:
1780 _xParams->setString(parameterIndex,_rValue);
1781 break;
1782 case DataType::CLOB:
1784 Any x(_rValue.makeAny());
1785 OUString sValue;
1786 if ( x >>= sValue )
1787 _xParams->setString(parameterIndex,sValue);
1788 else
1790 Reference< XClob > xClob;
1791 if(x >>= xClob)
1792 _xParams->setClob(parameterIndex,xClob);
1793 else
1795 Reference< css::io::XInputStream > xStream;
1796 if(x >>= xStream)
1797 _xParams->setCharacterStream(parameterIndex,xStream,xStream->available());
1801 break;
1802 case DataType::BIGINT:
1803 if ( _rValue.isSigned() )
1804 _xParams->setLong(parameterIndex,_rValue);
1805 else
1806 _xParams->setString(parameterIndex,_rValue);
1807 break;
1809 case DataType::FLOAT:
1810 _xParams->setFloat(parameterIndex,_rValue);
1811 break;
1812 case DataType::REAL:
1813 case DataType::DOUBLE:
1814 _xParams->setDouble(parameterIndex,_rValue);
1815 break;
1816 case DataType::DATE:
1817 _xParams->setDate(parameterIndex,_rValue);
1818 break;
1819 case DataType::TIME:
1820 _xParams->setTime(parameterIndex,_rValue);
1821 break;
1822 case DataType::TIMESTAMP:
1823 _xParams->setTimestamp(parameterIndex,_rValue);
1824 break;
1825 case DataType::BINARY:
1826 case DataType::VARBINARY:
1827 case DataType::LONGVARBINARY:
1828 case DataType::BLOB:
1830 Any x(_rValue.makeAny());
1831 Sequence< sal_Int8> aBytes;
1832 if(x >>= aBytes)
1833 _xParams->setBytes(parameterIndex,aBytes);
1834 else
1836 Reference< XBlob > xBlob;
1837 if(x >>= xBlob)
1838 _xParams->setBlob(parameterIndex,xBlob);
1839 else
1841 Reference< XClob > xClob;
1842 if(x >>= xClob)
1843 _xParams->setClob(parameterIndex,xClob);
1844 else
1846 Reference< css::io::XInputStream > xBinStream;
1847 if(x >>= xBinStream)
1848 _xParams->setBinaryStream(parameterIndex,xBinStream,xBinStream->available());
1853 break;
1854 case DataType::BIT:
1855 case DataType::BOOLEAN:
1856 _xParams->setBoolean(parameterIndex,static_cast<bool>(_rValue));
1857 break;
1858 case DataType::TINYINT:
1859 if ( _rValue.isSigned() )
1860 _xParams->setByte(parameterIndex,_rValue);
1861 else
1862 _xParams->setShort(parameterIndex,_rValue);
1863 break;
1864 case DataType::SMALLINT:
1865 if ( _rValue.isSigned() )
1866 _xParams->setShort(parameterIndex,_rValue);
1867 else
1868 _xParams->setInt(parameterIndex,_rValue);
1869 break;
1870 case DataType::INTEGER:
1871 if ( _rValue.isSigned() )
1872 _xParams->setInt(parameterIndex,_rValue);
1873 else
1874 _xParams->setLong(parameterIndex,_rValue);
1875 break;
1876 default:
1878 ::connectivity::SharedResources aResources;
1879 const OUString sError( aResources.getResourceStringWithSubstitution(
1880 STR_UNKNOWN_PARA_TYPE,
1881 "$position$", OUString::number(parameterIndex)
1882 ) );
1883 ::dbtools::throwGenericSQLException(sError,nullptr);
1889 void getBooleanComparisonPredicate( const OUString& _rExpression, const bool _bValue, const sal_Int32 _nBooleanComparisonMode,
1890 OUStringBuffer& _out_rSQLPredicate )
1892 switch ( _nBooleanComparisonMode )
1894 case BooleanComparisonMode::IS_LITERAL:
1895 _out_rSQLPredicate.append( _rExpression );
1896 if ( _bValue )
1897 _out_rSQLPredicate.append( " IS TRUE" );
1898 else
1899 _out_rSQLPredicate.append( " IS FALSE" );
1900 break;
1902 case BooleanComparisonMode::EQUAL_LITERAL:
1903 _out_rSQLPredicate.append( _rExpression );
1904 _out_rSQLPredicate.appendAscii( _bValue ? " = TRUE" : " = FALSE" );
1905 break;
1907 case BooleanComparisonMode::ACCESS_COMPAT:
1908 if ( _bValue )
1910 _out_rSQLPredicate.append( " NOT ( ( " );
1911 _out_rSQLPredicate.append( _rExpression );
1912 _out_rSQLPredicate.append( " = 0 ) OR ( " );
1913 _out_rSQLPredicate.append( _rExpression );
1914 _out_rSQLPredicate.append( " IS NULL ) )" );
1916 else
1918 _out_rSQLPredicate.append( _rExpression );
1919 _out_rSQLPredicate.append( " = 0" );
1921 break;
1923 case BooleanComparisonMode::EQUAL_INTEGER:
1924 // fall through
1925 default:
1926 _out_rSQLPredicate.append( _rExpression );
1927 _out_rSQLPredicate.appendAscii( _bValue ? " = 1" : " = 0" );
1928 break;
1932 } // namespace dbtools
1934 namespace connectivity
1936 void checkDisposed(bool _bThrow)
1938 if (_bThrow)
1939 throw DisposedException();
1943 OSQLColumns::Vector::const_iterator find(const OSQLColumns::Vector::const_iterator& first,
1944 const OSQLColumns::Vector::const_iterator& last,
1945 const OUString& _rVal,
1946 const ::comphelper::UStringMixEqual& _rCase)
1948 OUString sName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
1949 return find(first,last,sName,_rVal,_rCase);
1952 OSQLColumns::Vector::const_iterator findRealName(const OSQLColumns::Vector::const_iterator& first,
1953 const OSQLColumns::Vector::const_iterator& last,
1954 const OUString& _rVal,
1955 const ::comphelper::UStringMixEqual& _rCase)
1957 OUString sRealName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME);
1958 return find(first,last,sRealName,_rVal,_rCase);
1961 OSQLColumns::Vector::const_iterator find(OSQLColumns::Vector::const_iterator first,
1962 const OSQLColumns::Vector::const_iterator& last,
1963 const OUString& _rProp,
1964 const OUString& _rVal,
1965 const ::comphelper::UStringMixEqual& _rCase)
1967 while (first != last && !_rCase(getString((*first)->getPropertyValue(_rProp)),_rVal))
1968 ++first;
1969 return first;
1972 namespace dbase
1974 bool dbfDecodeCharset(rtl_TextEncoding &_out_encoding, sal_uInt8 nType, sal_uInt8 nCodepage)
1976 switch (nType)
1978 // dBaseIII header doesn't contain language driver ID
1979 // See http://dbase.free.fr/tlcharge/structure%20tables.pdf
1980 case dBaseIII:
1981 case dBaseIIIMemo:
1982 break;
1983 case dBaseIV:
1984 case dBaseV:
1985 case VisualFoxPro:
1986 case VisualFoxProAuto:
1987 case dBaseFS:
1988 case dBaseFSMemo:
1989 case dBaseIVMemoSQL:
1990 case FoxProMemo:
1992 if (nCodepage != 0x00)
1994 auto eEncoding(RTL_TEXTENCODING_DONTKNOW);
1995 switch(nCodepage)
1997 case 0x01: eEncoding = RTL_TEXTENCODING_IBM_437; break; // DOS USA code page 437
1998 case 0x02: eEncoding = RTL_TEXTENCODING_IBM_850; break; // DOS Multilingual code page 850
1999 case 0x03: eEncoding = RTL_TEXTENCODING_MS_1252; break; // Windows ANSI code page 1252
2000 case 0x04: eEncoding = RTL_TEXTENCODING_APPLE_ROMAN; break; // Standard Macintosh
2001 case 0x64: eEncoding = RTL_TEXTENCODING_IBM_852; break; // EE MS-DOS code page 852
2002 case 0x65: eEncoding = RTL_TEXTENCODING_IBM_866; break; // Russian MS-DOS code page 866
2003 case 0x66: eEncoding = RTL_TEXTENCODING_IBM_865; break; // Nordic MS-DOS code page 865
2004 case 0x67: eEncoding = RTL_TEXTENCODING_IBM_861; break; // Icelandic MS-DOS
2005 //case 0x68: eEncoding = ; break; // Kamenicky (Czech) MS-DOS
2006 //case 0x69: eEncoding = ; break; // Mazovia (Polish) MS-DOS
2007 case 0x6A: eEncoding = RTL_TEXTENCODING_IBM_737; break; // Greek MS-DOS (437G)
2008 case 0x6B: eEncoding = RTL_TEXTENCODING_IBM_857; break; // Turkish MS-DOS
2009 case 0x6C: eEncoding = RTL_TEXTENCODING_IBM_863; break; // MS-DOS, Canada
2010 case 0x78: eEncoding = RTL_TEXTENCODING_MS_950; break; // Windows, Traditional Chinese
2011 case 0x79: eEncoding = RTL_TEXTENCODING_MS_949; break; // Windows, Korean (Hangul)
2012 case 0x7A: eEncoding = RTL_TEXTENCODING_MS_936; break; // Windows, Simplified Chinese
2013 case 0x7B: eEncoding = RTL_TEXTENCODING_MS_932; break; // Windows, Japanese (Shift-jis)
2014 case 0x7C: eEncoding = RTL_TEXTENCODING_MS_874; break; // Windows, Thai
2015 case 0x7D: eEncoding = RTL_TEXTENCODING_MS_1255; break; // Windows, Hebrew
2016 case 0x7E: eEncoding = RTL_TEXTENCODING_MS_1256; break; // Windows, Arabic
2017 case 0x96: eEncoding = RTL_TEXTENCODING_APPLE_CYRILLIC; break; // Russian Macintosh
2018 case 0x97: eEncoding = RTL_TEXTENCODING_APPLE_CENTEURO; break; // Eastern European Macintosh
2019 case 0x98: eEncoding = RTL_TEXTENCODING_APPLE_GREEK; break; // Greek Macintosh
2020 case 0xC8: eEncoding = RTL_TEXTENCODING_MS_1250; break; // Windows EE code page 1250
2021 case 0xC9: eEncoding = RTL_TEXTENCODING_MS_1251; break; // Russian Windows
2022 case 0xCA: eEncoding = RTL_TEXTENCODING_MS_1254; break; // Turkish Windows
2023 case 0xCB: eEncoding = RTL_TEXTENCODING_MS_1253; break; // Greek Windows
2024 case 0xCC: eEncoding = RTL_TEXTENCODING_MS_1257; break; // Windows, Baltic
2026 if(eEncoding != RTL_TEXTENCODING_DONTKNOW)
2028 _out_encoding = eEncoding;
2029 return true;
2034 return false;
2037 bool dbfReadCharset(rtl_TextEncoding &nCharSet, SvStream* dbf_Stream)
2039 sal_uInt8 nType=0;
2040 dbf_Stream->ReadUChar( nType );
2042 dbf_Stream->Seek(STREAM_SEEK_TO_BEGIN + 29);
2043 if (dbf_Stream->eof())
2045 return false;
2047 else
2049 sal_uInt8 nEncoding=0;
2050 dbf_Stream->ReadUChar( nEncoding );
2051 return dbfDecodeCharset(nCharSet, nType, nEncoding);
2057 } //namespace connectivity
2059 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */