diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:06:44 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:06:44 +0000 |
commit | ed5640d8b587fbcfed7dd7967f3de04b37a76f26 (patch) | |
tree | 7a5f7c6c9d02226d7471cb3cc8fbbf631b415303 /connectivity/source/drivers/odbc | |
parent | Initial commit. (diff) | |
download | libreoffice-cb75148ebd0135178ff46f89a30139c44f8d2040.tar.xz libreoffice-cb75148ebd0135178ff46f89a30139c44f8d2040.zip |
Adding upstream version 4:7.4.7.upstream/4%7.4.7upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'connectivity/source/drivers/odbc')
-rw-r--r-- | connectivity/source/drivers/odbc/OConnection.cxx | 547 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/ODatabaseMetaData.cxx | 1717 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/ODatabaseMetaDataResultSet.cxx | 1330 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/ODriver.cxx | 192 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/OFunctions.cxx | 245 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/OPreparedStatement.cxx | 924 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/ORealDriver.cxx | 291 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/OResultSet.cxx | 1847 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/OResultSetMetaData.cxx | 291 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/OStatement.cxx | 1140 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/OTools.cxx | 797 | ||||
-rw-r--r-- | connectivity/source/drivers/odbc/odbc.component | 26 |
12 files changed, 9347 insertions, 0 deletions
diff --git a/connectivity/source/drivers/odbc/OConnection.cxx b/connectivity/source/drivers/odbc/OConnection.cxx new file mode 100644 index 000000000..7ae8c4680 --- /dev/null +++ b/connectivity/source/drivers/odbc/OConnection.cxx @@ -0,0 +1,547 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/OTools.hxx> +#include <odbc/OConnection.hxx> +#include <odbc/ODatabaseMetaData.hxx> +#include <odbc/OFunctions.hxx> +#include <odbc/ODriver.hxx> +#include <odbc/OStatement.hxx> +#include <odbc/OPreparedStatement.hxx> +#include <connectivity/dbcharset.hxx> +#include <connectivity/dbexception.hxx> + +#include <sal/log.hxx> + +#include <string.h> + +using namespace connectivity::odbc; +using namespace connectivity; +using namespace dbtools; + + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; + +OConnection::OConnection(const SQLHANDLE _pDriverHandle,ODBCDriver* _pDriver) + :m_xDriver(_pDriver) + ,m_aConnectionHandle(nullptr) + ,m_pDriverHandleCopy(_pDriverHandle) + ,m_nStatementCount(0) + ,m_bClosed(false) + ,m_bUseCatalog(false) + ,m_bUseOldDateFormat(false) + ,m_bIgnoreDriverPrivileges(false) + ,m_bPreventGetVersionColumns(false) + ,m_bReadOnly(true) +{ +} + +OConnection::~OConnection() +{ + if(!isClosed( )) + close(); + + if ( SQL_NULL_HANDLE == m_aConnectionHandle ) + return; + + SQLRETURN rc; + + if (!m_bClosed) + { + rc = N3SQLDisconnect( m_aConnectionHandle ); + OSL_ENSURE( rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO, "Failure from SQLDisconnect" ); + } + + rc = N3SQLFreeHandle( SQL_HANDLE_DBC, m_aConnectionHandle ); + OSL_ENSURE( rc == SQL_SUCCESS , "Failure from SQLFreeHandle for connection"); + + m_aConnectionHandle = SQL_NULL_HANDLE; +} + +oslGenericFunction OConnection::getOdbcFunction(ODBC3SQLFunctionId _nIndex) const +{ + OSL_ENSURE(m_xDriver, "OConnection::getOdbcFunction: m_xDriver is null!"); + return m_xDriver->getOdbcFunction(_nIndex); +} + +SQLRETURN OConnection::OpenConnection(const OUString& aConnectStr, sal_Int32 nTimeOut, bool bSilent) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + if (m_aConnectionHandle == SQL_NULL_HANDLE) + return -1; + + SQLRETURN nSQLRETURN = 0; + SDB_ODBC_CHAR szConnStrOut[4096] = {}; + SDB_ODBC_CHAR szConnStrIn[2048] = {}; + SQLSMALLINT cbConnStrOut; + OString aConStr(OUStringToOString(aConnectStr,getTextEncoding())); + memcpy(szConnStrIn, aConStr.getStr(), std::min<sal_Int32>(sal_Int32(2048),aConStr.getLength())); + +#ifndef MACOSX + N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_LOGIN_TIMEOUT,reinterpret_cast<SQLPOINTER>(nTimeOut),SQL_IS_UINTEGER); +#else + (void)nTimeOut; /* WaE */ +#endif + +#ifdef LINUX + (void) bSilent; + nSQLRETURN = N3SQLDriverConnect(m_aConnectionHandle, + nullptr, + szConnStrIn, + static_cast<SQLSMALLINT>(std::min(sal_Int32(2048),aConStr.getLength())), + szConnStrOut, + SQLSMALLINT(sizeof(szConnStrOut)/sizeof(SDB_ODBC_CHAR)) -1, + &cbConnStrOut, + SQL_DRIVER_NOPROMPT); + if (nSQLRETURN == SQL_ERROR || nSQLRETURN == SQL_NO_DATA || SQL_SUCCESS_WITH_INFO == nSQLRETURN) + return nSQLRETURN; +#else + + SQLUSMALLINT nSilent = bSilent ? SQL_DRIVER_NOPROMPT : SQL_DRIVER_COMPLETE; + nSQLRETURN = N3SQLDriverConnect(m_aConnectionHandle, + nullptr, + szConnStrIn, + static_cast<SQLSMALLINT>(std::min<sal_Int32>(sal_Int32(2048),aConStr.getLength())), + szConnStrOut, + SQLSMALLINT(sizeof szConnStrOut), + &cbConnStrOut, + nSilent); + if (nSQLRETURN == SQL_ERROR || nSQLRETURN == SQL_NO_DATA) + return nSQLRETURN; + + m_bClosed = false; + +#endif //LINUX + + try + { + OUString aVal; + OTools::GetInfo(this,m_aConnectionHandle,SQL_DATA_SOURCE_READ_ONLY,aVal,*this,getTextEncoding()); + m_bReadOnly = aVal == "Y"; + } + catch(Exception&) + { + m_bReadOnly = true; + } + try + { + OUString sVersion; + OTools::GetInfo(this,m_aConnectionHandle,SQL_DRIVER_ODBC_VER,sVersion,*this,getTextEncoding()); + m_bUseOldDateFormat = sVersion == "02.50" || sVersion == "02.00"; + } + catch(Exception&) + { + } + + + // autocommit is always default + + if (!m_bReadOnly) + N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_ON),SQL_IS_INTEGER); + + return nSQLRETURN; +} + +SQLRETURN OConnection::Construct(const OUString& url,const Sequence< PropertyValue >& info) +{ + m_aConnectionHandle = SQL_NULL_HANDLE; + m_sURL = url; + setConnectionInfo(info); + + N3SQLAllocHandle(SQL_HANDLE_DBC,m_pDriverHandleCopy,&m_aConnectionHandle); + if(m_aConnectionHandle == SQL_NULL_HANDLE) + throw SQLException(); + + sal_Int32 nLen = url.indexOf(':'); + nLen = url.indexOf(':',nLen+2); + OUString aDSN("DSN="), aUID, aPWD, aSysDrvSettings; + aDSN += url.subView(nLen+1); + + sal_Int32 nTimeout = 20; + bool bSilent = true; + const PropertyValue *pBegin = info.getConstArray(); + const PropertyValue *pEnd = pBegin + info.getLength(); + for(;pBegin != pEnd;++pBegin) + { + if( pBegin->Name == "Timeout") + { + if( ! (pBegin->Value >>= nTimeout) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property Timeout"); + } + else if( pBegin->Name == "Silent") + { + if( ! (pBegin->Value >>= bSilent) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property Silent"); + } + else if( pBegin->Name == "IgnoreDriverPrivileges") + { + if( ! (pBegin->Value >>= m_bIgnoreDriverPrivileges) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property IgnoreDriverPrivileges"); + } + else if( pBegin->Name == "PreventGetVersionColumns") + { + if( ! (pBegin->Value >>= m_bPreventGetVersionColumns) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property PreventGetVersionColumns"); + } + else if( pBegin->Name == "IsAutoRetrievingEnabled") + { + bool bAutoRetrievingEnabled = false; + if( ! (pBegin->Value >>= bAutoRetrievingEnabled) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property IsAutoRetrievingEnabled"); + enableAutoRetrievingEnabled(bAutoRetrievingEnabled); + } + else if( pBegin->Name == "AutoRetrievingStatement") + { + OUString sGeneratedValueStatement; + if( ! (pBegin->Value >>= sGeneratedValueStatement) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property AutoRetrievingStatement"); + setAutoRetrievingStatement(sGeneratedValueStatement); + } + else if( pBegin->Name == "user") + { + if( ! (pBegin->Value >>= aUID) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property user"); + aDSN += ";UID=" + aUID; + } + else if( pBegin->Name == "password") + { + if( ! (pBegin->Value >>= aPWD) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property password"); + aDSN += ";PWD=" + aPWD; + } + else if( pBegin->Name == "UseCatalog") + { + if( !( pBegin->Value >>= m_bUseCatalog) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property UseCatalog"); + } + else if( pBegin->Name == "SystemDriverSettings") + { + if( ! (pBegin->Value >>= aSysDrvSettings) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property SystemDriverSettings"); + aDSN += ";" + aSysDrvSettings; + } + else if( pBegin->Name == "CharSet") + { + OUString sIanaName; + if( ! (pBegin->Value >>= sIanaName) ) + SAL_WARN("connectivity.odbc", "Construct: unable to get property CharSet"); + + ::dbtools::OCharsetMap aLookupIanaName; + ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.findIanaName(sIanaName); + if (aLookup != aLookupIanaName.end()) + m_nTextEncoding = (*aLookup).getEncoding(); + else + m_nTextEncoding = RTL_TEXTENCODING_DONTKNOW; + if(m_nTextEncoding == RTL_TEXTENCODING_DONTKNOW) + m_nTextEncoding = osl_getThreadTextEncoding(); + } + } + m_sUser = aUID; + + SQLRETURN nSQLRETURN = OpenConnection(aDSN,nTimeout, bSilent); + if (nSQLRETURN == SQL_ERROR || nSQLRETURN == SQL_NO_DATA) + { + OTools::ThrowException(this,nSQLRETURN,m_aConnectionHandle,SQL_HANDLE_DBC,*this,false); + } + return nSQLRETURN; +} +// XServiceInfo + +IMPLEMENT_SERVICE_INFO(OConnection, "com.sun.star.sdbc.drivers.odbc.OConnection", "com.sun.star.sdbc.Connection") + + +Reference< XStatement > SAL_CALL OConnection::createStatement( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + Reference< XStatement > xReturn = new OStatement(this); + m_aStatements.push_back(WeakReferenceHelper(xReturn)); + return xReturn; +} + +Reference< XPreparedStatement > SAL_CALL OConnection::prepareStatement( const OUString& sql ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + Reference< XPreparedStatement > xReturn = new OPreparedStatement(this,sql); + m_aStatements.push_back(WeakReferenceHelper(xReturn)); + return xReturn; +} + +Reference< XPreparedStatement > SAL_CALL OConnection::prepareCall( const OUString& /*sql*/ ) +{ + ::dbtools::throwFeatureNotImplementedSQLException( "XConnection::prepareCall", *this ); + return nullptr; +} + +OUString SAL_CALL OConnection::nativeSQL( const OUString& sql ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + OString aSql(OUStringToOString(sql,getTextEncoding())); + char pOut[2048]; + SQLINTEGER nOutLen; + OTools::ThrowException(this,N3SQLNativeSql(m_aConnectionHandle,reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(aSql.getStr())),aSql.getLength(),reinterpret_cast<SDB_ODBC_CHAR*>(pOut),sizeof pOut - 1,&nOutLen),m_aConnectionHandle,SQL_HANDLE_DBC,*this); + return OUString(pOut,nOutLen,getTextEncoding()); +} + +void SAL_CALL OConnection::setAutoCommit( sal_Bool autoCommit ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + OTools::ThrowException(this,N3SQLSetConnectAttr(m_aConnectionHandle, + SQL_ATTR_AUTOCOMMIT, + reinterpret_cast<SQLPOINTER>((autoCommit) ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF) ,SQL_IS_INTEGER), + m_aConnectionHandle,SQL_HANDLE_DBC,*this); +} + +sal_Bool SAL_CALL OConnection::getAutoCommit( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + sal_uInt32 nOption = 0; + OTools::ThrowException(this,N3SQLGetConnectAttr(m_aConnectionHandle, + SQL_ATTR_AUTOCOMMIT, &nOption,0,nullptr),m_aConnectionHandle,SQL_HANDLE_DBC,*this); + return nOption == SQL_AUTOCOMMIT_ON ; +} + +void SAL_CALL OConnection::commit( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + OTools::ThrowException(this,N3SQLEndTran(SQL_HANDLE_DBC,m_aConnectionHandle,SQL_COMMIT),m_aConnectionHandle,SQL_HANDLE_DBC,*this); +} + +void SAL_CALL OConnection::rollback( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + OTools::ThrowException(this,N3SQLEndTran(SQL_HANDLE_DBC,m_aConnectionHandle,SQL_ROLLBACK),m_aConnectionHandle,SQL_HANDLE_DBC,*this); +} + +sal_Bool SAL_CALL OConnection::isClosed( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + return OConnection_BASE::rBHelper.bDisposed; +} + +Reference< XDatabaseMetaData > SAL_CALL OConnection::getMetaData( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + Reference< XDatabaseMetaData > xMetaData = m_xMetaData; + if(!xMetaData.is()) + { + xMetaData = new ODatabaseMetaData(m_aConnectionHandle,this); + m_xMetaData = xMetaData; + } + + return xMetaData; +} + +void SAL_CALL OConnection::setReadOnly( sal_Bool readOnly ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + OTools::ThrowException(this, + N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_ACCESS_MODE,reinterpret_cast< SQLPOINTER >( readOnly ),SQL_IS_INTEGER), + m_aConnectionHandle,SQL_HANDLE_DBC,*this); +} + +sal_Bool SAL_CALL OConnection::isReadOnly() +{ + // const member which will initialized only once + return m_bReadOnly; +} + +void SAL_CALL OConnection::setCatalog( const OUString& catalog ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + OString aCat(OUStringToOString(catalog,getTextEncoding())); + OTools::ThrowException(this, + N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_CURRENT_CATALOG,const_cast<char *>(aCat.getStr()),SQL_NTS), + m_aConnectionHandle,SQL_HANDLE_DBC,*this); +} + +OUString SAL_CALL OConnection::getCatalog( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + SQLINTEGER nValueLen; + char pCat[1024]; + OTools::ThrowException(this, + N3SQLGetConnectAttr(m_aConnectionHandle,SQL_ATTR_CURRENT_CATALOG,pCat,(sizeof pCat)-1,&nValueLen), + m_aConnectionHandle,SQL_HANDLE_DBC,*this); + + return OUString(pCat,nValueLen,getTextEncoding()); +} + +void SAL_CALL OConnection::setTransactionIsolation( sal_Int32 level ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + OTools::ThrowException(this,N3SQLSetConnectAttr(m_aConnectionHandle, + SQL_ATTR_TXN_ISOLATION, + reinterpret_cast<SQLPOINTER>(level),SQL_IS_INTEGER), + m_aConnectionHandle,SQL_HANDLE_DBC,*this); +} + +sal_Int32 SAL_CALL OConnection::getTransactionIsolation( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + sal_Int32 nTxn = 0; + SQLINTEGER nValueLen; + OTools::ThrowException(this, + N3SQLGetConnectAttr(m_aConnectionHandle,SQL_ATTR_TXN_ISOLATION,&nTxn,sizeof nTxn,&nValueLen), + m_aConnectionHandle,SQL_HANDLE_DBC,*this); + return nTxn; +} + +Reference< css::container::XNameAccess > SAL_CALL OConnection::getTypeMap( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + return nullptr; +} + +void SAL_CALL OConnection::setTypeMap( const Reference< css::container::XNameAccess >& /*typeMap*/ ) +{ + ::dbtools::throwFeatureNotImplementedSQLException( "XConnection::setTypeMap", *this ); +} + +// XCloseable +void SAL_CALL OConnection::close( ) +{ + { + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + } + dispose(); +} + +// XWarningsSupplier +Any SAL_CALL OConnection::getWarnings( ) +{ + return Any(); +} + +void SAL_CALL OConnection::clearWarnings( ) +{ +} + +void OConnection::disposing() +{ + ::osl::MutexGuard aGuard(m_aMutex); + + OConnection_BASE::disposing(); + + for (auto const& connection : m_aConnections) + connection.second->dispose(); + + m_aConnections.clear(); + + if(!m_bClosed) + N3SQLDisconnect(m_aConnectionHandle); + m_bClosed = true; +} + +SQLHANDLE OConnection::createStatementHandle() +{ + rtl::Reference<OConnection> xConnectionTemp = this; + bool bNew = false; + try + { + sal_Int32 nMaxStatements = getMetaData()->getMaxStatements(); + if(nMaxStatements && nMaxStatements <= m_nStatementCount) + { + rtl::Reference xConnection(new OConnection(m_pDriverHandleCopy,m_xDriver.get())); + xConnection->Construct(m_sURL,getConnectionInfo()); + xConnectionTemp = xConnection; + bNew = true; + } + } + catch(SQLException&) + { + } + + SQLHANDLE aStatementHandle = SQL_NULL_HANDLE; + N3SQLAllocHandle(SQL_HANDLE_STMT,xConnectionTemp->getConnection(),&aStatementHandle); + ++m_nStatementCount; + if(bNew) + m_aConnections.emplace(aStatementHandle,xConnectionTemp); + + return aStatementHandle; + +} + +void OConnection::freeStatementHandle(SQLHANDLE& _pHandle) +{ + if( SQL_NULL_HANDLE == _pHandle ) + return; + + auto aFind = m_aConnections.find(_pHandle); + + N3SQLFreeStmt(_pHandle,SQL_RESET_PARAMS); + N3SQLFreeStmt(_pHandle,SQL_UNBIND); + N3SQLFreeStmt(_pHandle,SQL_CLOSE); + N3SQLFreeHandle(SQL_HANDLE_STMT,_pHandle); + + _pHandle = SQL_NULL_HANDLE; + + if(aFind != m_aConnections.end()) + { + aFind->second->dispose(); + m_aConnections.erase(aFind); + } + --m_nStatementCount; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/ODatabaseMetaData.cxx b/connectivity/source/drivers/odbc/ODatabaseMetaData.cxx new file mode 100644 index 000000000..ce3f107e2 --- /dev/null +++ b/connectivity/source/drivers/odbc/ODatabaseMetaData.cxx @@ -0,0 +1,1717 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/ODatabaseMetaData.hxx> +#include <odbc/OTools.hxx> +#include <odbc/ODatabaseMetaDataResultSet.hxx> +#include <FDatabaseMetaDataResultSet.hxx> +#include <com/sun/star/sdbc/DataType.hpp> +#include <com/sun/star/sdbc/ResultSetType.hpp> +#include <com/sun/star/sdbc/ResultSetConcurrency.hpp> +#include <com/sun/star/sdbc/TransactionIsolation.hpp> +#include <TPrivilegesResultSet.hxx> +#include <rtl/ustrbuf.hxx> +#include <sal/log.hxx> +#include <o3tl/string_view.hxx> + +using namespace connectivity::odbc; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; + +ODatabaseMetaData::ODatabaseMetaData(const SQLHANDLE _pHandle,OConnection* _pCon) + : ::connectivity::ODatabaseMetaDataBase(_pCon,_pCon->getConnectionInfo()) + ,m_aConnectionHandle(_pHandle) + ,m_pConnection(_pCon) + ,m_bUseCatalog(true) +{ + OSL_ENSURE(m_pConnection,"ODatabaseMetaData::ODatabaseMetaData: No connection set!"); + if(!m_pConnection->isCatalogUsed()) + { + osl_atomic_increment( &m_refCount ); + try + { + m_bUseCatalog = !(usesLocalFiles() || usesLocalFilePerTable()); + } + catch(SQLException& ) + { // doesn't matter here + } + osl_atomic_decrement( &m_refCount ); + } +} + +ODatabaseMetaData::~ODatabaseMetaData() +{ +} + +Reference< XResultSet > ODatabaseMetaData::impl_getTypeInfo_throw( ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openTypeInfo(); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eTypeInfo); + } + + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getCatalogs( ) +{ + Reference< XResultSet > xRef; + if(!m_bUseCatalog) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eCatalogs); + } + else + { + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openCatalogs(); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eCatalogs); + } + } + + return xRef; +} + +OUString ODatabaseMetaData::impl_getCatalogSeparator_throw( ) +{ + OUString aVal; + if ( m_bUseCatalog ) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_NAME_SEPARATOR,aVal,*this,m_pConnection->getTextEncoding()); + + return aVal; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getSchemas( ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openSchemas(); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eSchemas); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getColumnPrivileges( + const Any& catalog, const OUString& schema, const OUString& table, + const OUString& columnNamePattern ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openColumnPrivileges(m_bUseCatalog ? catalog : Any(),schema,table,columnNamePattern); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eColumnPrivileges); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getColumns( + const Any& catalog, const OUString& schemaPattern, const OUString& tableNamePattern, + const OUString& columnNamePattern ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openColumns(m_bUseCatalog ? catalog : Any(),schemaPattern,tableNamePattern,columnNamePattern); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eColumns); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTables( + const Any& catalog, const OUString& schemaPattern, + const OUString& tableNamePattern, const Sequence< OUString >& types ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openTables(m_bUseCatalog ? catalog : Any(),schemaPattern,tableNamePattern,types); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eTables); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getProcedureColumns( + const Any& catalog, const OUString& schemaPattern, + const OUString& procedureNamePattern, const OUString& columnNamePattern ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openProcedureColumns(m_bUseCatalog ? catalog : Any(),schemaPattern,procedureNamePattern,columnNamePattern); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eProcedureColumns); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getProcedures( + const Any& catalog, const OUString& schemaPattern, + const OUString& procedureNamePattern ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openProcedures(m_bUseCatalog ? catalog : Any(),schemaPattern,procedureNamePattern); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eProcedures); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getVersionColumns( + const Any& catalog, const OUString& schema, const OUString& table ) +{ + Reference< XResultSet > xRef; + bool bSuccess = false; + try + { + if ( !m_pConnection->preventGetVersionColumns() ) + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openVersionColumns(m_bUseCatalog ? catalog : Any(),schema,table); + bSuccess = true; + } + } + catch(SQLException&) + { + } + + if ( !bSuccess ) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eVersionColumns); + } + + return xRef; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxBinaryLiteralLength( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_BINARY_LITERAL_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxRowSize( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_ROW_SIZE,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxCatalogNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_CATALOG_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxCharLiteralLength( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_CHAR_LITERAL_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_COLUMN_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInIndex( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_COLUMNS_IN_INDEX,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxCursorNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_CURSOR_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxConnections( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_DRIVER_CONNECTIONS/*SQL_ACTIVE_CONNECTIONS*/,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInTable( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_COLUMNS_IN_TABLE,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxStatementLength( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_STATEMENT_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxTableNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_TABLE_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Int32 ODatabaseMetaData::impl_getMaxTablesInSelect_throw( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_TABLES_IN_SELECT,nValue,*this); + return nValue; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getExportedKeys( + const Any& catalog, const OUString& schema, const OUString& table ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openExportedKeys(m_bUseCatalog ? catalog : Any(),schema,table); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eExportedKeys); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getImportedKeys( + const Any& catalog, const OUString& schema, const OUString& table ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openImportedKeys(m_bUseCatalog ? catalog : Any(),schema,table); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eImportedKeys); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getPrimaryKeys( + const Any& catalog, const OUString& schema, const OUString& table ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openPrimaryKeys(m_bUseCatalog ? catalog : Any(),schema,table); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::ePrimaryKeys); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getIndexInfo( + const Any& catalog, const OUString& schema, const OUString& table, + sal_Bool unique, sal_Bool approximate ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openIndexInfo(m_bUseCatalog ? catalog : Any(),schema,table,unique,approximate); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eIndexInfo); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getBestRowIdentifier( + const Any& catalog, const OUString& schema, const OUString& table, sal_Int32 scope, + sal_Bool nullable ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openBestRowIdentifier(m_bUseCatalog ? catalog : Any(),schema,table,scope,nullable); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eBestRowIdentifier); + } + return xRef; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTablePrivileges( + const Any& catalog, const OUString& schemaPattern, const OUString& tableNamePattern ) +{ + if ( m_pConnection->isIgnoreDriverPrivilegesEnabled() ) + { + return new OResultSetPrivileges(this,catalog,schemaPattern,tableNamePattern); + } + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + pResult->openTablePrivileges(m_bUseCatalog ? catalog : Any(),schemaPattern,tableNamePattern); + return pResult; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getCrossReference( + const Any& primaryCatalog, const OUString& primarySchema, + const OUString& primaryTable, const Any& foreignCatalog, + const OUString& foreignSchema, const OUString& foreignTable ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openForeignKeys(m_bUseCatalog ? primaryCatalog : Any(),primarySchema.toChar() == '%' ? &primarySchema : nullptr,&primaryTable, + m_bUseCatalog ? foreignCatalog : Any(), foreignSchema.toChar() == '%' ? &foreignSchema : nullptr,&foreignTable); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eCrossReference); + } + return xRef; +} + +sal_Bool SAL_CALL ODatabaseMetaData::doesMaxRowSizeIncludeBlobs( ) +{ + OUString aVal; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_ROW_SIZE_INCLUDES_LONG,aVal,*this,m_pConnection->getTextEncoding()); + return aVal.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesLowerCaseQuotedIdentifiers( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_QUOTED_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_LOWER; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesLowerCaseIdentifiers( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_LOWER; +} + +bool ODatabaseMetaData::impl_storesMixedCaseQuotedIdentifiers_throw( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_QUOTED_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_MIXED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesMixedCaseIdentifiers( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_MIXED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesUpperCaseQuotedIdentifiers( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_QUOTED_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_UPPER; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesUpperCaseIdentifiers( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_UPPER; +} + +bool ODatabaseMetaData::impl_supportsAlterTableWithAddColumn_throw( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ALTER_TABLE,nValue,*this); + return (nValue & SQL_AT_ADD_COLUMN) == SQL_AT_ADD_COLUMN; +} + +bool ODatabaseMetaData::impl_supportsAlterTableWithDropColumn_throw( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ALTER_TABLE,nValue,*this); + return ((nValue & SQL_AT_DROP_COLUMN) == SQL_AT_DROP_COLUMN) || + ((nValue & SQL_AT_DROP_COLUMN_CASCADE) == SQL_AT_DROP_COLUMN_CASCADE) || + ((nValue & SQL_AT_DROP_COLUMN_RESTRICT) == SQL_AT_DROP_COLUMN_RESTRICT); +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxIndexLength( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_INDEX_SIZE,nValue,*this); + return nValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsNonNullableColumns( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_NON_NULLABLE_COLUMNS,nValue,*this); + return nValue == SQL_NNC_NON_NULL; +} + +OUString SAL_CALL ODatabaseMetaData::getCatalogTerm( ) +{ + OUString aVal; + if(m_bUseCatalog) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_TERM,aVal,*this,m_pConnection->getTextEncoding()); + return aVal; +} + +OUString ODatabaseMetaData::impl_getIdentifierQuoteString_throw( ) +{ + OUString aVal; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_IDENTIFIER_QUOTE_CHAR,aVal,*this,m_pConnection->getTextEncoding()); + return aVal; +} + +OUString SAL_CALL ODatabaseMetaData::getExtraNameCharacters( ) +{ + OUString aVal; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SPECIAL_CHARACTERS,aVal,*this,m_pConnection->getTextEncoding()); + return aVal; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsDifferentTableCorrelationNames( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + return nValue != SQL_CN_NONE; +} + +bool ODatabaseMetaData::impl_isCatalogAtStart_throw( ) +{ + SQLUSMALLINT nValue=0; + if ( m_bUseCatalog ) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_LOCATION,nValue,*this); + return nValue == SQL_CL_START; +} + +sal_Bool SAL_CALL ODatabaseMetaData::dataDefinitionIgnoredInTransactions( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TXN_CAPABLE,nValue,*this); + return nValue == SQL_TC_DDL_IGNORE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::dataDefinitionCausesTransactionCommit( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TXN_CAPABLE,nValue,*this); + return nValue == SQL_TC_DDL_COMMIT; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsDataManipulationTransactionsOnly( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TXN_CAPABLE,nValue,*this); + return nValue == SQL_TC_DML; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsDataDefinitionAndDataManipulationTransactions( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TXN_CAPABLE,nValue,*this); + return nValue == SQL_TC_ALL; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsPositionedDelete( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DYNAMIC_CURSOR_ATTRIBUTES1,nValue,*this); + return (nValue & SQL_CA1_POS_DELETE) == SQL_CA1_POS_DELETE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsPositionedUpdate( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DYNAMIC_CURSOR_ATTRIBUTES1,nValue,*this); + return (nValue & SQL_CA1_POS_UPDATE) == SQL_CA1_POS_UPDATE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenStatementsAcrossRollback( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CURSOR_ROLLBACK_BEHAVIOR,nValue,*this); + return nValue == SQL_CB_PRESERVE || nValue == SQL_CB_CLOSE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenStatementsAcrossCommit( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CURSOR_COMMIT_BEHAVIOR,nValue,*this); + return nValue == SQL_CB_PRESERVE || nValue == SQL_CB_CLOSE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenCursorsAcrossCommit( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CURSOR_COMMIT_BEHAVIOR,nValue,*this); + return nValue == SQL_CB_PRESERVE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenCursorsAcrossRollback( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CURSOR_ROLLBACK_BEHAVIOR,nValue,*this); + return nValue == SQL_CB_PRESERVE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTransactionIsolationLevel( sal_Int32 level ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TXN_ISOLATION_OPTION,nValue,*this); + return (nValue & static_cast<SQLUINTEGER>(level)) == static_cast<SQLUINTEGER>(level); +} + +bool ODatabaseMetaData::impl_supportsSchemasInDataManipulation_throw( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SCHEMA_USAGE,nValue,*this); + return (nValue & SQL_SU_DML_STATEMENTS) == SQL_SU_DML_STATEMENTS; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsANSI92FullSQL( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SQL_CONFORMANCE,nValue,*this); + return static_cast<bool>(nValue & SQL_SC_SQL92_FULL); +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsANSI92EntryLevelSQL( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SQL_CONFORMANCE,nValue,*this); + return static_cast<bool>(nValue &SQL_SC_SQL92_ENTRY); +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsIntegrityEnhancementFacility( ) +{ + OUString aStr; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_INTEGRITY,aStr,*this,m_pConnection->getTextEncoding()); + return aStr.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInIndexDefinitions( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SCHEMA_USAGE,nValue,*this); + return (nValue & SQL_SU_INDEX_DEFINITION) == SQL_SU_INDEX_DEFINITION; +} + +bool ODatabaseMetaData::impl_supportsSchemasInTableDefinitions_throw( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SCHEMA_USAGE,nValue,*this); + return (nValue & SQL_SU_TABLE_DEFINITION) == SQL_SU_TABLE_DEFINITION; +} + +bool ODatabaseMetaData::impl_supportsCatalogsInTableDefinitions_throw( ) +{ + SQLUINTEGER nValue=0; + if(m_bUseCatalog) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_USAGE,nValue,*this); + return (nValue & SQL_CU_TABLE_DEFINITION) == SQL_CU_TABLE_DEFINITION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInIndexDefinitions( ) +{ + SQLUINTEGER nValue=0; + if(m_bUseCatalog) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_USAGE,nValue,*this); + return (nValue & SQL_CU_INDEX_DEFINITION) == SQL_CU_INDEX_DEFINITION; +} + +bool ODatabaseMetaData::impl_supportsCatalogsInDataManipulation_throw( ) +{ + SQLUINTEGER nValue=0; + if(m_bUseCatalog) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_USAGE,nValue,*this); + return (nValue & SQL_CU_DML_STATEMENTS) == SQL_CU_DML_STATEMENTS; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOuterJoins( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_OJ_CAPABILITIES,nValue,*this); + return ((nValue & (SQL_OJ_FULL|SQL_OJ_LEFT|SQL_OJ_RIGHT|SQL_OJ_NESTED|SQL_OJ_NOT_ORDERED|SQL_OJ_ALL_COMPARISON_OPS|SQL_OJ_INNER)) != 0); +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTableTypes( ) +{ + Reference< XResultSet > xRef; + try + { + rtl::Reference<ODatabaseMetaDataResultSet> pResult = new ODatabaseMetaDataResultSet(m_pConnection); + xRef = pResult; + pResult->openTablesTypes(); + } + catch(SQLException&) + { + xRef = new ::connectivity::ODatabaseMetaDataResultSet(::connectivity::ODatabaseMetaDataResultSet::eTableTypes); + } + return xRef; +} + +sal_Int32 ODatabaseMetaData::impl_getMaxStatements_throw( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_CONCURRENT_ACTIVITIES,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxProcedureNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_PROCEDURE_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxSchemaNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_SCHEMA_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTransactions( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TXN_CAPABLE,nValue,*this); + return nValue != SQL_TC_NONE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::allProceduresAreCallable( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ACCESSIBLE_PROCEDURES,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsStoredProcedures( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_PROCEDURES,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSelectForUpdate( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DYNAMIC_CURSOR_ATTRIBUTES1,nValue,*this); + return (nValue & SQL_CA1_POSITIONED_UPDATE) == SQL_CA1_POSITIONED_UPDATE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::allTablesAreSelectable( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ACCESSIBLE_TABLES,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::isReadOnly( ) +{ + return m_pConnection->isReadOnly(); +} + +sal_Bool SAL_CALL ODatabaseMetaData::usesLocalFiles( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_FILE_USAGE,nValue,*this); + return nValue == SQL_FILE_CATALOG; +} + +sal_Bool SAL_CALL ODatabaseMetaData::usesLocalFilePerTable( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_FILE_USAGE,nValue,*this); + return nValue == SQL_FILE_TABLE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTypeConversion( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_FUNCTIONS,nValue,*this); + return (nValue & SQL_FN_CVT_CONVERT) == SQL_FN_CVT_CONVERT; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullPlusNonNullIsNull( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONCAT_NULL_BEHAVIOR,nValue,*this); + return nValue == SQL_CB_NULL; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsColumnAliasing( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_COLUMN_ALIAS,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTableCorrelationNames( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + return nValue != SQL_CN_NONE; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsConvert( sal_Int32 fromType, sal_Int32 toType ) +{ + if(fromType == toType) + return true; + + SQLUINTEGER nValue=0; + switch(fromType) + { + case DataType::BIT: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_BIT,nValue,*this); + break; + case DataType::TINYINT: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_TINYINT,nValue,*this); + break; + case DataType::SMALLINT: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_SMALLINT,nValue,*this); + break; + case DataType::INTEGER: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_INTEGER,nValue,*this); + break; + case DataType::BIGINT: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_BIGINT,nValue,*this); + break; + case DataType::FLOAT: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_FLOAT,nValue,*this); + break; + case DataType::REAL: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_REAL,nValue,*this); + break; + case DataType::DOUBLE: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_DOUBLE,nValue,*this); + break; + case DataType::NUMERIC: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_NUMERIC,nValue,*this); + break; + case DataType::DECIMAL: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_DECIMAL,nValue,*this); + break; + case DataType::CHAR: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_CHAR,nValue,*this); + break; + case DataType::VARCHAR: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_VARCHAR,nValue,*this); + break; + case DataType::LONGVARCHAR: + case DataType::CLOB: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_LONGVARCHAR,nValue,*this); + break; + case DataType::DATE: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_DATE,nValue,*this); + break; + case DataType::TIME: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_TIME,nValue,*this); + break; + case DataType::TIMESTAMP: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_TIMESTAMP,nValue,*this); + break; + case DataType::BINARY: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_BINARY,nValue,*this); + break; + case DataType::VARBINARY: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_VARBINARY,nValue,*this); + break; + case DataType::LONGVARBINARY: + case DataType::BLOB: + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CONVERT_LONGVARBINARY,nValue,*this); + break; + case DataType::SQLNULL: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + case DataType::OTHER: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + case DataType::OBJECT: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + case DataType::DISTINCT: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + case DataType::STRUCT: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + case DataType::ARRAY: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + case DataType::REF: + // OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CORRELATION_NAME,nValue,*this); + break; + } + bool bConvert = false; + switch(toType) + { + case DataType::BIT: + bConvert = (nValue & SQL_CVT_BIT) == SQL_CVT_BIT; + break; + case DataType::TINYINT: + bConvert = (nValue & SQL_CVT_TINYINT) == SQL_CVT_TINYINT; + break; + case DataType::SMALLINT: + bConvert = (nValue & SQL_CVT_SMALLINT) == SQL_CVT_SMALLINT; + break; + case DataType::INTEGER: + bConvert = (nValue & SQL_CVT_INTEGER) == SQL_CVT_INTEGER; + break; + case DataType::BIGINT: + bConvert = (nValue & SQL_CVT_BIGINT) == SQL_CVT_BIGINT; + break; + case DataType::FLOAT: + bConvert = (nValue & SQL_CVT_FLOAT) == SQL_CVT_FLOAT; + break; + case DataType::REAL: + bConvert = (nValue & SQL_CVT_REAL) == SQL_CVT_REAL; + break; + case DataType::DOUBLE: + bConvert = (nValue & SQL_CVT_DOUBLE) == SQL_CVT_DOUBLE; + break; + case DataType::NUMERIC: + bConvert = (nValue & SQL_CVT_NUMERIC) == SQL_CVT_NUMERIC; + break; + case DataType::DECIMAL: + bConvert = (nValue & SQL_CVT_DECIMAL) == SQL_CVT_DECIMAL; + break; + case DataType::CHAR: + bConvert = (nValue & SQL_CVT_CHAR) == SQL_CVT_CHAR; + break; + case DataType::VARCHAR: + bConvert = (nValue & SQL_CVT_VARCHAR) == SQL_CVT_VARCHAR; + break; + case DataType::LONGVARCHAR: + case DataType::CLOB: + bConvert = (nValue & SQL_CVT_LONGVARCHAR) == SQL_CVT_LONGVARCHAR; + break; + case DataType::DATE: + bConvert = (nValue & SQL_CVT_DATE) == SQL_CVT_DATE; + break; + case DataType::TIME: + bConvert = (nValue & SQL_CVT_TIME) == SQL_CVT_TIME; + break; + case DataType::TIMESTAMP: + bConvert = (nValue & SQL_CVT_TIMESTAMP) == SQL_CVT_TIMESTAMP; + break; + case DataType::BINARY: + bConvert = (nValue & SQL_CVT_BINARY) == SQL_CVT_BINARY; + break; + case DataType::VARBINARY: + bConvert = (nValue & SQL_CVT_VARBINARY) == SQL_CVT_VARBINARY; + break; + case DataType::LONGVARBINARY: + case DataType::BLOB: + bConvert = (nValue & SQL_CVT_LONGVARBINARY) == SQL_CVT_LONGVARBINARY; + break; + } + + return bConvert; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsExpressionsInOrderBy( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_EXPRESSIONS_IN_ORDERBY,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsGroupBy( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_GROUP_BY,nValue,*this); + return nValue != SQL_GB_NOT_SUPPORTED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsGroupByBeyondSelect( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_GROUP_BY,nValue,*this); + return nValue != SQL_GB_GROUP_BY_CONTAINS_SELECT; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsGroupByUnrelated( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_GROUP_BY,nValue,*this); + return nValue == SQL_GB_NO_RELATION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMultipleTransactions( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MULTIPLE_ACTIVE_TXN,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMultipleResultSets( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MULT_RESULT_SETS,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsLikeEscapeClause( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_LIKE_ESCAPE_CLAUSE,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'Y'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOrderByUnrelated( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ORDER_BY_COLUMNS_IN_SELECT,aValue,*this,m_pConnection->getTextEncoding()); + return aValue.toChar() == 'N'; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsUnion( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_UNION,nValue,*this); + return (nValue & SQL_U_UNION) == SQL_U_UNION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsUnionAll( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_UNION,nValue,*this); + return (nValue & SQL_U_UNION_ALL) == SQL_U_UNION_ALL; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMixedCaseIdentifiers( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_MIXED; +} + +bool ODatabaseMetaData::impl_supportsMixedCaseQuotedIdentifiers_throw( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_QUOTED_IDENTIFIER_CASE,nValue,*this); + return nValue == SQL_IC_MIXED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedAtEnd( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_NULL_COLLATION,nValue,*this); + return nValue == SQL_NC_END; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedAtStart( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_NULL_COLLATION,nValue,*this); + return nValue == SQL_NC_START; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedHigh( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_NULL_COLLATION,nValue,*this); + return nValue == SQL_NC_HIGH; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedLow( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_NULL_COLLATION,nValue,*this); + return nValue == SQL_NC_LOW; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInProcedureCalls( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SCHEMA_USAGE,nValue,*this); + return (nValue & SQL_SU_PROCEDURE_INVOCATION) == SQL_SU_PROCEDURE_INVOCATION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInPrivilegeDefinitions( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SCHEMA_USAGE,nValue,*this); + return (nValue & SQL_SU_PRIVILEGE_DEFINITION) == SQL_SU_PRIVILEGE_DEFINITION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInProcedureCalls( ) +{ + SQLUINTEGER nValue=0; + if(m_bUseCatalog) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_USAGE,nValue,*this); + return (nValue & SQL_CU_PROCEDURE_INVOCATION) == SQL_CU_PROCEDURE_INVOCATION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInPrivilegeDefinitions( ) +{ + SQLUINTEGER nValue=0; + if(m_bUseCatalog) + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CATALOG_USAGE,nValue,*this); + return (nValue & SQL_CU_PRIVILEGE_DEFINITION) == SQL_CU_PRIVILEGE_DEFINITION; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCorrelatedSubqueries( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SUBQUERIES,nValue,*this); + return (nValue & SQL_SQ_CORRELATED_SUBQUERIES) == SQL_SQ_CORRELATED_SUBQUERIES; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInComparisons( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SUBQUERIES,nValue,*this); + return (nValue & SQL_SQ_COMPARISON) == SQL_SQ_COMPARISON; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInExists( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SUBQUERIES,nValue,*this); + return (nValue & SQL_SQ_EXISTS) == SQL_SQ_EXISTS; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInIns( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SUBQUERIES,nValue,*this); + return (nValue & SQL_SQ_IN) == SQL_SQ_IN; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInQuantifieds( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SUBQUERIES,nValue,*this); + return (nValue & SQL_SQ_QUANTIFIED) == SQL_SQ_QUANTIFIED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsANSI92IntermediateSQL( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SQL_CONFORMANCE,nValue,*this); + return static_cast<bool>(nValue & SQL_SC_SQL92_INTERMEDIATE); +} + +OUString ODatabaseMetaData::getURLImpl() +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DATA_SOURCE_NAME,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getURL( ) +{ + OUString aValue = m_pConnection->getURL(); + if ( aValue.isEmpty() ) + { + aValue = "sdbc:odbc:" + getURLImpl(); + } + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getUserName( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_USER_NAME,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getDriverName( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DRIVER_NAME,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getDriverVersion() +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DRIVER_ODBC_VER,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getDatabaseProductVersion( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DRIVER_VER,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getDatabaseProductName( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DBMS_NAME,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getProcedureTerm( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_PROCEDURE_TERM,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getSchemaTerm( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SCHEMA_TERM,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getDriverMajorVersion( ) try +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DRIVER_VER,aValue,*this,m_pConnection->getTextEncoding()); + return o3tl::toInt32(aValue.subView(0,aValue.indexOf('.'))); +} +catch (const SQLException &) +{ + return 0; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getDefaultTransactionIsolation( ) +{ + SQLUINTEGER nValue; + sal_Int32 nValueTranslated; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DEFAULT_TXN_ISOLATION,nValue,*this); + switch(nValue) + { + case SQL_TXN_READ_UNCOMMITTED: + nValueTranslated = css::sdbc::TransactionIsolation::READ_UNCOMMITTED; + break; + case SQL_TXN_READ_COMMITTED: + nValueTranslated = css::sdbc::TransactionIsolation::READ_COMMITTED; + break; + case SQL_TXN_REPEATABLE_READ: + nValueTranslated = css::sdbc::TransactionIsolation::REPEATABLE_READ; + break; + case SQL_TXN_SERIALIZABLE: + nValueTranslated = css::sdbc::TransactionIsolation::SERIALIZABLE; + break; + default: + nValueTranslated = 0; + } + return nValueTranslated; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getDriverMinorVersion( ) try +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_DRIVER_VER,aValue,*this,m_pConnection->getTextEncoding()); + return o3tl::toInt32(aValue.subView(0,aValue.lastIndexOf('.'))); +} +catch (const SQLException &) +{ + return 0; +} + +OUString SAL_CALL ODatabaseMetaData::getSQLKeywords( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_KEYWORDS,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getSearchStringEscape( ) +{ + OUString aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SEARCH_PATTERN_ESCAPE,aValue,*this,m_pConnection->getTextEncoding()); + return aValue; +} + +OUString SAL_CALL ODatabaseMetaData::getStringFunctions( ) +{ + SQLUINTEGER nValue; + OUStringBuffer aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_STRING_FUNCTIONS,nValue,*this); + if(nValue & SQL_FN_STR_ASCII) + aValue.append("ASCII,"); + if(nValue & SQL_FN_STR_BIT_LENGTH) + aValue.append("BIT_LENGTH,"); + if(nValue & SQL_FN_STR_CHAR) + aValue.append("CHAR,"); + if(nValue & SQL_FN_STR_CHAR_LENGTH) + aValue.append("CHAR_LENGTH,"); + if(nValue & SQL_FN_STR_CHARACTER_LENGTH) + aValue.append("CHARACTER_LENGTH,"); + if(nValue & SQL_FN_STR_CONCAT) + aValue.append("CONCAT,"); + if(nValue & SQL_FN_STR_DIFFERENCE) + aValue.append("DIFFERENCE,"); + if(nValue & SQL_FN_STR_INSERT) + aValue.append("INSERT,"); + if(nValue & SQL_FN_STR_LCASE) + aValue.append("LCASE,"); + if(nValue & SQL_FN_STR_LEFT) + aValue.append("LEFT,"); + if(nValue & SQL_FN_STR_LENGTH) + aValue.append("LENGTH,"); + if(nValue & SQL_FN_STR_LOCATE) + aValue.append("LOCATE,"); + if(nValue & SQL_FN_STR_LOCATE_2) + aValue.append("LOCATE_2,"); + if(nValue & SQL_FN_STR_LTRIM) + aValue.append("LTRIM,"); + if(nValue & SQL_FN_STR_OCTET_LENGTH) + aValue.append("OCTET_LENGTH,"); + if(nValue & SQL_FN_STR_POSITION) + aValue.append("POSITION,"); + if(nValue & SQL_FN_STR_REPEAT) + aValue.append("REPEAT,"); + if(nValue & SQL_FN_STR_REPLACE) + aValue.append("REPLACE,"); + if(nValue & SQL_FN_STR_RIGHT) + aValue.append("RIGHT,"); + if(nValue & SQL_FN_STR_RTRIM) + aValue.append("RTRIM,"); + if(nValue & SQL_FN_STR_SOUNDEX) + aValue.append("SOUNDEX,"); + if(nValue & SQL_FN_STR_SPACE) + aValue.append("SPACE,"); + if(nValue & SQL_FN_STR_SUBSTRING) + aValue.append("SUBSTRING,"); + if(nValue & SQL_FN_STR_UCASE) + aValue.append("UCASE,"); + + + if ( !aValue.isEmpty() ) + aValue.setLength(aValue.getLength()-1); + + return aValue.makeStringAndClear(); +} + +OUString SAL_CALL ODatabaseMetaData::getTimeDateFunctions( ) +{ + SQLUINTEGER nValue; + OUStringBuffer aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_TIMEDATE_FUNCTIONS,nValue,*this); + + if(nValue & SQL_FN_TD_CURRENT_DATE) + aValue.append("CURRENT_DATE,"); + if(nValue & SQL_FN_TD_CURRENT_TIME) + aValue.append("CURRENT_TIME,"); + if(nValue & SQL_FN_TD_CURRENT_TIMESTAMP) + aValue.append("CURRENT_TIMESTAMP,"); + if(nValue & SQL_FN_TD_CURDATE) + aValue.append("CURDATE,"); + if(nValue & SQL_FN_TD_CURTIME) + aValue.append("CURTIME,"); + if(nValue & SQL_FN_TD_DAYNAME) + aValue.append("DAYNAME,"); + if(nValue & SQL_FN_TD_DAYOFMONTH) + aValue.append("DAYOFMONTH,"); + if(nValue & SQL_FN_TD_DAYOFWEEK) + aValue.append("DAYOFWEEK,"); + if(nValue & SQL_FN_TD_DAYOFYEAR) + aValue.append("DAYOFYEAR,"); + if(nValue & SQL_FN_TD_EXTRACT) + aValue.append("EXTRACT,"); + if(nValue & SQL_FN_TD_HOUR) + aValue.append("HOUR,"); + if(nValue & SQL_FN_TD_MINUTE) + aValue.append("MINUTE,"); + if(nValue & SQL_FN_TD_MONTH) + aValue.append("MONTH,"); + if(nValue & SQL_FN_TD_MONTHNAME) + aValue.append("MONTHNAME,"); + if(nValue & SQL_FN_TD_NOW) + aValue.append("NOW,"); + if(nValue & SQL_FN_TD_QUARTER) + aValue.append("QUARTER,"); + if(nValue & SQL_FN_TD_SECOND) + aValue.append("SECOND,"); + if(nValue & SQL_FN_TD_TIMESTAMPADD) + aValue.append("TIMESTAMPADD,"); + if(nValue & SQL_FN_TD_TIMESTAMPDIFF) + aValue.append("TIMESTAMPDIFF,"); + if(nValue & SQL_FN_TD_WEEK) + aValue.append("WEEK,"); + if(nValue & SQL_FN_TD_YEAR) + aValue.append("YEAR,"); + + if ( !aValue.isEmpty() ) + aValue.setLength(aValue.getLength()-1); + + return aValue.makeStringAndClear(); +} + +OUString SAL_CALL ODatabaseMetaData::getSystemFunctions( ) +{ + SQLUINTEGER nValue; + OUStringBuffer aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_SYSTEM_FUNCTIONS,nValue,*this); + + if(nValue & SQL_FN_SYS_DBNAME) + aValue.append("DBNAME,"); + if(nValue & SQL_FN_SYS_IFNULL) + aValue.append("IFNULL,"); + if(nValue & SQL_FN_SYS_USERNAME) + aValue.append("USERNAME,"); + + if ( !aValue.isEmpty() ) + aValue.setLength(aValue.getLength()-1); + + return aValue.makeStringAndClear(); +} + +OUString SAL_CALL ODatabaseMetaData::getNumericFunctions( ) +{ + SQLUINTEGER nValue; + OUStringBuffer aValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_NUMERIC_FUNCTIONS,nValue,*this); + + if(nValue & SQL_FN_NUM_ABS) + aValue.append("ABS,"); + if(nValue & SQL_FN_NUM_ACOS) + aValue.append("ACOS,"); + if(nValue & SQL_FN_NUM_ASIN) + aValue.append("ASIN,"); + if(nValue & SQL_FN_NUM_ATAN) + aValue.append("ATAN,"); + if(nValue & SQL_FN_NUM_ATAN2) + aValue.append("ATAN2,"); + if(nValue & SQL_FN_NUM_CEILING) + aValue.append("CEILING,"); + if(nValue & SQL_FN_NUM_COS) + aValue.append("COS,"); + if(nValue & SQL_FN_NUM_COT) + aValue.append("COT,"); + if(nValue & SQL_FN_NUM_DEGREES) + aValue.append("DEGREES,"); + if(nValue & SQL_FN_NUM_EXP) + aValue.append("EXP,"); + if(nValue & SQL_FN_NUM_FLOOR) + aValue.append("FLOOR,"); + if(nValue & SQL_FN_NUM_LOG) + aValue.append("LOGF,"); + if(nValue & SQL_FN_NUM_LOG10) + aValue.append("LOG10,"); + if(nValue & SQL_FN_NUM_MOD) + aValue.append("MOD,"); + if(nValue & SQL_FN_NUM_PI) + aValue.append("PI,"); + if(nValue & SQL_FN_NUM_POWER) + aValue.append("POWER,"); + if(nValue & SQL_FN_NUM_RADIANS) + aValue.append("RADIANS,"); + if(nValue & SQL_FN_NUM_RAND) + aValue.append("RAND,"); + if(nValue & SQL_FN_NUM_ROUND) + aValue.append("ROUND,"); + if(nValue & SQL_FN_NUM_SIGN) + aValue.append("SIGN,"); + if(nValue & SQL_FN_NUM_SIN) + aValue.append("SIN,"); + if(nValue & SQL_FN_NUM_SQRT) + aValue.append("SQRT,"); + if(nValue & SQL_FN_NUM_TAN) + aValue.append("TAN,"); + if(nValue & SQL_FN_NUM_TRUNCATE) + aValue.append("TRUNCATE,"); + + if ( !aValue.isEmpty() ) + aValue.setLength(aValue.getLength()-1); + + return aValue.makeStringAndClear(); +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsExtendedSQLGrammar( ) +{ + SQLUINTEGER nValue; + // SQL_ODBC_SQL_CONFORMANCE is deprecated in ODBC 3.x, but there does not seem te be any equivalent. + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ODBC_SQL_CONFORMANCE,nValue,*this); + SAL_WARN_IF(! (nValue == SQL_OSC_MINIMUM || nValue == SQL_OSC_CORE || nValue == SQL_OSC_EXTENDED), + "connectivity.odbc", + "SQL_ODBC_SQL_CONFORMANCE is neither MINIMAL nor CORE nor EXTENDED"); + return nValue == SQL_OSC_EXTENDED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCoreSQLGrammar( ) +{ + SQLUINTEGER nValue; + // SQL_ODBC_SQL_CONFORMANCE is deprecated in ODBC 3.x, but there does not seem te be any equivalent. + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ODBC_SQL_CONFORMANCE,nValue,*this); + SAL_WARN_IF(! (nValue == SQL_OSC_MINIMUM || nValue == SQL_OSC_CORE || nValue == SQL_OSC_EXTENDED), + "connectivity.odbc", + "SQL_ODBC_SQL_CONFORMANCE is neither MINIMAL nor CORE nor EXTENDED"); + return nValue == SQL_OSC_CORE || nValue == SQL_OSC_EXTENDED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMinimumSQLGrammar( ) +{ + SQLUINTEGER nValue; + // SQL_ODBC_SQL_CONFORMANCE is deprecated in ODBC 3.x, but there does not seem te be any equivalent. + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_ODBC_SQL_CONFORMANCE,nValue,*this); + SAL_WARN_IF(! (nValue == SQL_OSC_MINIMUM || nValue == SQL_OSC_CORE || nValue == SQL_OSC_EXTENDED), + "connectivity.odbc", + "SQL_ODBC_SQL_CONFORMANCE is neither MINIMAL nor CORE nor EXTENDED"); + return nValue == SQL_OSC_MINIMUM || nValue == SQL_OSC_CORE || nValue == SQL_OSC_EXTENDED; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsFullOuterJoins( ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_OJ_CAPABILITIES,nValue,*this); + return (nValue & SQL_OJ_FULL) == SQL_OJ_FULL; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsLimitedOuterJoins( ) +{ + return supportsFullOuterJoins( ); +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInGroupBy( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_COLUMNS_IN_GROUP_BY,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInOrderBy( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_COLUMNS_IN_ORDER_BY,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInSelect( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_COLUMNS_IN_SELECT,nValue,*this); + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxUserNameLength( ) +{ + SQLUSMALLINT nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_MAX_USER_NAME_LEN,nValue,*this); + return nValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsResultSetType( sal_Int32 setType ) +{ + SQLUINTEGER nValue; + OTools::GetInfo(m_pConnection,m_aConnectionHandle,SQL_CURSOR_SENSITIVITY,nValue,*this); + return (nValue & static_cast<SQLUINTEGER>(setType)) == static_cast<SQLUINTEGER>(setType); +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsResultSetConcurrency( sal_Int32 setType, sal_Int32 concurrency ) +{ + SQLUINTEGER nValue; + SQLUSMALLINT nAskFor( SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 ); + switch(setType) + { + default: + case ResultSetType::FORWARD_ONLY: + nAskFor = SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_INSENSITIVE: + nAskFor = SQL_STATIC_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_SENSITIVE: + nAskFor = SQL_DYNAMIC_CURSOR_ATTRIBUTES2; + break; + } + + OTools::GetInfo(m_pConnection,m_aConnectionHandle,nAskFor,nValue,*this); + bool bRet = false; + switch(concurrency) + { + case ResultSetConcurrency::READ_ONLY: + bRet = (nValue & SQL_CA2_READ_ONLY_CONCURRENCY) == SQL_CA2_READ_ONLY_CONCURRENCY; + break; + case ResultSetConcurrency::UPDATABLE: + bRet = (nValue & SQL_CA2_OPT_VALUES_CONCURRENCY) == SQL_CA2_OPT_VALUES_CONCURRENCY; + break; + } + return bRet; +} + +sal_Bool SAL_CALL ODatabaseMetaData::ownUpdatesAreVisible( sal_Int32 setType ) +{ + SQLUINTEGER nValue; + SQLUSMALLINT nAskFor( SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 ); + switch(setType) + { + default: + case ResultSetType::FORWARD_ONLY: + nAskFor = SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_INSENSITIVE: + nAskFor = SQL_STATIC_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_SENSITIVE: + nAskFor = SQL_DYNAMIC_CURSOR_ATTRIBUTES2; + break; + } + + OTools::GetInfo(m_pConnection,m_aConnectionHandle,nAskFor,nValue,*this); + return (nValue & SQL_CA2_SENSITIVITY_UPDATES) == SQL_CA2_SENSITIVITY_UPDATES; +} + +sal_Bool SAL_CALL ODatabaseMetaData::ownDeletesAreVisible( sal_Int32 setType ) +{ + SQLUINTEGER nValue; + SQLUSMALLINT nAskFor( SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 ); + switch(setType) + { + default: + case ResultSetType::FORWARD_ONLY: + nAskFor = SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_INSENSITIVE: + nAskFor = SQL_STATIC_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_SENSITIVE: + nAskFor = SQL_DYNAMIC_CURSOR_ATTRIBUTES2; + break; + } + + OTools::GetInfo(m_pConnection,m_aConnectionHandle,nAskFor,nValue,*this); + return (nValue & SQL_CA2_SENSITIVITY_DELETIONS) != SQL_CA2_SENSITIVITY_DELETIONS; +} + +sal_Bool SAL_CALL ODatabaseMetaData::ownInsertsAreVisible( sal_Int32 setType ) +{ + SQLUINTEGER nValue; + SQLUSMALLINT nAskFor( SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 ); + switch(setType) + { + default: + case ResultSetType::FORWARD_ONLY: + nAskFor = SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_INSENSITIVE: + nAskFor = SQL_STATIC_CURSOR_ATTRIBUTES2; + break; + case ResultSetType::SCROLL_SENSITIVE: + nAskFor = SQL_DYNAMIC_CURSOR_ATTRIBUTES2; + break; + } + + OTools::GetInfo(m_pConnection,m_aConnectionHandle,nAskFor,nValue,*this); + return (nValue & SQL_CA2_SENSITIVITY_ADDITIONS) == SQL_CA2_SENSITIVITY_ADDITIONS; +} + +sal_Bool SAL_CALL ODatabaseMetaData::othersUpdatesAreVisible( sal_Int32 setType ) +{ + return ownUpdatesAreVisible(setType); +} + +sal_Bool SAL_CALL ODatabaseMetaData::othersDeletesAreVisible( sal_Int32 setType ) +{ + return ownDeletesAreVisible(setType); +} + +sal_Bool SAL_CALL ODatabaseMetaData::othersInsertsAreVisible( sal_Int32 setType ) +{ + return ownInsertsAreVisible(setType); +} + +sal_Bool SAL_CALL ODatabaseMetaData::updatesAreDetected( sal_Int32 /*setType*/ ) +{ + return false; +} + +sal_Bool SAL_CALL ODatabaseMetaData::deletesAreDetected( sal_Int32 /*setType*/ ) +{ + return false; +} + +sal_Bool SAL_CALL ODatabaseMetaData::insertsAreDetected( sal_Int32 /*setType*/ ) +{ + return false; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsBatchUpdates( ) +{ + return false; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getUDTs( const Any& /*catalog*/, const OUString& /*schemaPattern*/, const OUString& /*typeNamePattern*/, const Sequence< sal_Int32 >& /*types*/ ) +{ + return nullptr; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/ODatabaseMetaDataResultSet.cxx b/connectivity/source/drivers/odbc/ODatabaseMetaDataResultSet.cxx new file mode 100644 index 000000000..5fbe8bf8f --- /dev/null +++ b/connectivity/source/drivers/odbc/ODatabaseMetaDataResultSet.cxx @@ -0,0 +1,1330 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <TConnection.hxx> + +#include <odbc/ODatabaseMetaDataResultSet.hxx> +#include <com/sun/star/sdbc/DataType.hpp> +#include <comphelper/property.hxx> +#include <cppuhelper/typeprovider.hxx> +#include <comphelper/sequence.hxx> +#include <odbc/OResultSetMetaData.hxx> +#include <odbc/OTools.hxx> +#include <comphelper/types.hxx> +#include <connectivity/dbexception.hxx> + +using namespace ::comphelper; + + +using namespace connectivity::odbc; +using namespace cppu; + +using namespace ::com::sun::star::lang; +using namespace com::sun::star::uno; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::util; + + +ODatabaseMetaDataResultSet::ODatabaseMetaDataResultSet(OConnection* _pConnection) + :ODatabaseMetaDataResultSet_BASE(m_aMutex) + ,OPropertySetHelper(ODatabaseMetaDataResultSet_BASE::rBHelper) + + ,m_aStatementHandle(_pConnection->createStatementHandle()) + ,m_pConnection(_pConnection) + ,m_nTextEncoding(_pConnection->getTextEncoding()) + ,m_nRowPos(-1) + ,m_nDriverColumnCount(0) + ,m_nCurrentFetchState(0) + ,m_bWasNull(true) + ,m_bEOF(false) +{ + OSL_ENSURE(m_pConnection.is(),"ODatabaseMetaDataResultSet::ODatabaseMetaDataResultSet: No parent set!"); + if( SQL_NULL_HANDLE == m_aStatementHandle ) + throw RuntimeException(); + + osl_atomic_increment( &m_refCount ); + m_pRowStatusArray.reset( new SQLUSMALLINT[1] ); // the default value + osl_atomic_decrement( &m_refCount ); +} + + +ODatabaseMetaDataResultSet::~ODatabaseMetaDataResultSet() +{ + OSL_ENSURE(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed,"Object wasn't disposed!"); + if(!ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed) + { + osl_atomic_increment( &m_refCount ); + dispose(); + } +} + +void ODatabaseMetaDataResultSet::disposing() +{ + OPropertySetHelper::disposing(); + + ::osl::MutexGuard aGuard(m_aMutex); + + m_pConnection->freeStatementHandle(m_aStatementHandle); + + m_aStatement.clear(); + m_xMetaData.clear(); + m_pConnection.clear(); +} + +Any SAL_CALL ODatabaseMetaDataResultSet::queryInterface( const Type & rType ) +{ + Any aRet = OPropertySetHelper::queryInterface(rType); + return aRet.hasValue() ? aRet : ODatabaseMetaDataResultSet_BASE::queryInterface(rType); +} + +Reference< XPropertySetInfo > SAL_CALL ODatabaseMetaDataResultSet::getPropertySetInfo( ) +{ + return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); +} + +void SAL_CALL ODatabaseMetaDataResultSet::acquire() noexcept +{ + ODatabaseMetaDataResultSet_BASE::acquire(); +} + +void SAL_CALL ODatabaseMetaDataResultSet::release() noexcept +{ + ODatabaseMetaDataResultSet_BASE::release(); +} + +Sequence< Type > SAL_CALL ODatabaseMetaDataResultSet::getTypes( ) +{ + ::cppu::OTypeCollection aTypes( cppu::UnoType<XMultiPropertySet>::get(), + cppu::UnoType<XFastPropertySet>::get(), + cppu::UnoType<XPropertySet>::get()); + + return ::comphelper::concatSequences(aTypes.getTypes(),ODatabaseMetaDataResultSet_BASE::getTypes()); +} + +sal_Int32 ODatabaseMetaDataResultSet::mapColumn (sal_Int32 column) +{ + sal_Int32 map = column; + + if (!m_aColMapping.empty()) + { + // Validate column number + map = m_aColMapping[column]; + } + + return map; +} + + +sal_Int32 SAL_CALL ODatabaseMetaDataResultSet::findColumn( const OUString& columnName ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + Reference< XResultSetMetaData > xMeta = getMetaData(); + sal_Int32 nLen = xMeta->getColumnCount(); + sal_Int32 i = 1; + for(;i<=nLen;++i) + { + if(xMeta->isCaseSensitive(i) ? columnName == xMeta->getColumnName(i) : + columnName.equalsIgnoreAsciiCase(xMeta->getColumnName(i))) + return i; + } + + ::dbtools::throwInvalidColumnException( columnName, *this ); + assert(false); + return 0; // Never reached +} + +template < typename T, SQLSMALLINT sqlTypeId > T ODatabaseMetaDataResultSet::getInteger ( sal_Int32 columnIndex ) +{ + ::cppu::OBroadcastHelper& rBHelper(ODatabaseMetaDataResultSet_BASE::rBHelper); + checkDisposed(rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + columnIndex = mapColumn(columnIndex); + T nVal = 0; + if(columnIndex <= m_nDriverColumnCount) + { + getValue<T>(m_pConnection.get(), m_aStatementHandle, columnIndex, sqlTypeId, m_bWasNull, **this, nVal); + + if ( !m_aValueRange.empty() ) + { + auto aValueRangeIter = m_aValueRange.find(columnIndex); + if ( aValueRangeIter != m_aValueRange.end() ) + return static_cast<T>(aValueRangeIter->second[nVal]); + } + } + else + m_bWasNull = true; + return nVal; +} + + +Reference< css::io::XInputStream > SAL_CALL ODatabaseMetaDataResultSet::getBinaryStream( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getBinaryStream", *this ); + return nullptr; +} + +Reference< css::io::XInputStream > SAL_CALL ODatabaseMetaDataResultSet::getCharacterStream( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getCharacterStream", *this ); + return nullptr; +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::getBoolean( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + columnIndex = mapColumn(columnIndex); + + bool bRet = false; + if(columnIndex <= m_nDriverColumnCount) + { + sal_Int32 nType = getMetaData()->getColumnType(columnIndex); + switch(nType) + { + case DataType::BIT: + { + sal_Int8 nValue = 0; + OTools::getValue(m_pConnection.get(),m_aStatementHandle,columnIndex,SQL_C_BIT,m_bWasNull,**this,&nValue,sizeof nValue); + bRet = nValue != 0; + } + break; + default: + bRet = getInt(columnIndex) != 0; + } + } + return bRet; +} + + +sal_Int8 SAL_CALL ODatabaseMetaDataResultSet::getByte( sal_Int32 columnIndex ) +{ + return getInteger<sal_Int8, SQL_C_STINYINT>( columnIndex ); +} + + +Sequence< sal_Int8 > SAL_CALL ODatabaseMetaDataResultSet::getBytes( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + if(columnIndex <= m_nDriverColumnCount) + { + sal_Int32 nType = getMetaData()->getColumnType(columnIndex); + switch(nType) + { + case DataType::CHAR: + case DataType::VARCHAR: + case DataType::LONGVARCHAR: + { + OUString const & aRet = OTools::getStringValue(m_pConnection.get(),m_aStatementHandle,columnIndex,SQL_C_BINARY,m_bWasNull,**this,m_nTextEncoding); + return Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(aRet.getStr()),sizeof(sal_Unicode)*aRet.getLength()); + } + } + return OTools::getBytesValue(m_pConnection.get(),m_aStatementHandle,columnIndex,SQL_C_BINARY,m_bWasNull,**this); + } + else + m_bWasNull = true; + return Sequence<sal_Int8>(); +} + + +css::util::Date SAL_CALL ODatabaseMetaDataResultSet::getDate( sal_Int32 columnIndex ) +{ + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + if(columnIndex <= m_nDriverColumnCount) + { + DATE_STRUCT aDate; + aDate.day = 0; + aDate.month = 0; + aDate.year = 0; + OTools::getValue(m_pConnection.get(),m_aStatementHandle,columnIndex,m_pConnection->useOldDateFormat() ? SQL_C_DATE : SQL_C_TYPE_DATE,m_bWasNull,**this,&aDate,sizeof aDate); + return Date(aDate.day,aDate.month,aDate.year); + } + else + m_bWasNull = true; + return Date(); +} + + +double SAL_CALL ODatabaseMetaDataResultSet::getDouble( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + double nValue(0.0); + if(columnIndex <= m_nDriverColumnCount) + OTools::getValue(m_pConnection.get(),m_aStatementHandle,columnIndex,SQL_C_DOUBLE,m_bWasNull,**this,&nValue,sizeof nValue); + else + m_bWasNull = true; + return nValue; +} + + +float SAL_CALL ODatabaseMetaDataResultSet::getFloat( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + float nVal(0); + if(columnIndex <= m_nDriverColumnCount) + OTools::getValue(m_pConnection.get(),m_aStatementHandle,columnIndex,SQL_C_FLOAT,m_bWasNull,**this,&nVal,sizeof nVal); + else + m_bWasNull = true; + return nVal; +} + + +sal_Int32 SAL_CALL ODatabaseMetaDataResultSet::getInt( sal_Int32 columnIndex ) +{ + return getInteger<sal_Int32, SQL_C_SLONG>( columnIndex ); +} + + +sal_Int32 SAL_CALL ODatabaseMetaDataResultSet::getRow( ) +{ + return 0; +} + + +sal_Int64 SAL_CALL ODatabaseMetaDataResultSet::getLong( sal_Int32 columnIndex ) +{ + return getInteger<sal_Int64, SQL_C_SBIGINT>( columnIndex ); +} + + +Reference< XResultSetMetaData > SAL_CALL ODatabaseMetaDataResultSet::getMetaData( ) +{ + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + if (!m_xMetaData.is()) + m_xMetaData = new OResultSetMetaData(m_pConnection.get(),m_aStatementHandle); + return m_xMetaData; +} + +Reference< XArray > SAL_CALL ODatabaseMetaDataResultSet::getArray( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getArray", *this ); + return nullptr; +} + +Reference< XClob > SAL_CALL ODatabaseMetaDataResultSet::getClob( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getClob", *this ); + return nullptr; +} + +Reference< XBlob > SAL_CALL ODatabaseMetaDataResultSet::getBlob( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getBlob", *this ); + return nullptr; +} + + +Reference< XRef > SAL_CALL ODatabaseMetaDataResultSet::getRef( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getRef", *this ); + return nullptr; +} + + +Any SAL_CALL ODatabaseMetaDataResultSet::getObject( sal_Int32 /*columnIndex*/, const Reference< css::container::XNameAccess >& /*typeMap*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getObject", *this ); + return Any(); +} + + +sal_Int16 SAL_CALL ODatabaseMetaDataResultSet::getShort( sal_Int32 columnIndex ) +{ + return getInteger<sal_Int16, SQL_C_SSHORT>( columnIndex ); +} + + +OUString SAL_CALL ODatabaseMetaDataResultSet::getString( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + OUString aVal; + if(columnIndex <= m_nDriverColumnCount) + aVal = OTools::getStringValue(m_pConnection.get(),m_aStatementHandle,columnIndex,impl_getColumnType_nothrow(columnIndex),m_bWasNull,**this,m_nTextEncoding); + else + m_bWasNull = true; + + return aVal; +} + + +css::util::Time SAL_CALL ODatabaseMetaDataResultSet::getTime( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + TIME_STRUCT aTime={0,0,0}; + if(columnIndex <= m_nDriverColumnCount) + OTools::getValue(m_pConnection.get(),m_aStatementHandle,columnIndex,m_pConnection->useOldDateFormat() ? SQL_C_TIME : SQL_C_TYPE_TIME,m_bWasNull,**this,&aTime,sizeof aTime); + else + m_bWasNull = true; + return Time(0, aTime.second,aTime.minute,aTime.hour, false); +} + + +css::util::DateTime SAL_CALL ODatabaseMetaDataResultSet::getTimestamp( sal_Int32 columnIndex ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + columnIndex = mapColumn(columnIndex); + TIMESTAMP_STRUCT aTime={0,0,0,0,0,0,0}; + if(columnIndex <= m_nDriverColumnCount) + OTools::getValue(m_pConnection.get(),m_aStatementHandle,columnIndex,m_pConnection->useOldDateFormat() ? SQL_C_TIMESTAMP : SQL_C_TYPE_TIMESTAMP, m_bWasNull, **this, &aTime, sizeof aTime); + else + m_bWasNull = true; + return DateTime(aTime.fraction, aTime.second, aTime.minute, aTime.hour, + aTime.day, aTime.month, aTime.year, false); +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::isAfterLast( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_nCurrentFetchState == SQL_NO_DATA; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::isFirst( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_nRowPos == 1; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::isLast( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_bEOF && m_nCurrentFetchState != SQL_NO_DATA; +} + +void SAL_CALL ODatabaseMetaDataResultSet::beforeFirst( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + if(first()) + previous(); + m_nCurrentFetchState = SQL_SUCCESS; +} + +void SAL_CALL ODatabaseMetaDataResultSet::afterLast( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + if(last()) + next(); +} + + +void SAL_CALL ODatabaseMetaDataResultSet::close( ) +{ + { + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + } + dispose(); +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::first( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + m_bEOF = false; + + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_FIRST,0); + OTools::ThrowException(m_pConnection.get(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + bool bRet = ( m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO ); + if( bRet ) + m_nRowPos = 1; + return bRet; +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::last( ) +{ + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed ); + ::osl::MutexGuard aGuard( m_aMutex ); + + + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_LAST,0); + OTools::ThrowException(m_pConnection.get(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + // here I know definitely that I stand on the last record + bool bRet = ( m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO ); + if( bRet ) + m_bEOF = true; + return bRet; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::absolute( sal_Int32 row ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + m_bEOF = false; + + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_ABSOLUTE,row); + OTools::ThrowException(m_pConnection.get(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + bool bRet = m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; + if(bRet) + m_nRowPos = row; + return bRet; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::relative( sal_Int32 row ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + m_bEOF = false; + + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_RELATIVE,row); + OTools::ThrowException(m_pConnection.get(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + bool bRet = m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; + if(bRet) + m_nRowPos += row; + return bRet; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::previous( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + m_bEOF = false; + + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_PRIOR,0); + OTools::ThrowException(m_pConnection.get(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + bool bRet = m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; + if(bRet) + --m_nRowPos; + else if ( m_nCurrentFetchState == SQL_NO_DATA ) + m_nRowPos = 0; + return bRet; +} + +Reference< XInterface > SAL_CALL ODatabaseMetaDataResultSet::getStatement( ) +{ + return nullptr; +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::rowDeleted( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_pRowStatusArray[0] == SQL_ROW_DELETED; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::rowInserted( ) +{ + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_pRowStatusArray[0] == SQL_ROW_ADDED; +} + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::rowUpdated( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_pRowStatusArray[0] == SQL_ROW_UPDATED; +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::isBeforeFirst( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_nRowPos == 0; +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::next( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + m_bEOF = false; + + SQLRETURN nOldFetchStatus = m_nCurrentFetchState; + // m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_NEXT,0); + m_nCurrentFetchState = N3SQLFetch(m_aStatementHandle); + OTools::ThrowException(m_pConnection.get(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + bool bRet = m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; + if(bRet || ( m_nCurrentFetchState == SQL_NO_DATA && nOldFetchStatus != SQL_NO_DATA ) ) + ++m_nRowPos; + return bRet; +} + + +sal_Bool SAL_CALL ODatabaseMetaDataResultSet::wasNull( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + return m_bWasNull; +} + +void SAL_CALL ODatabaseMetaDataResultSet::refreshRow( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + +} + + +void SAL_CALL ODatabaseMetaDataResultSet::cancel( ) +{ + + checkDisposed(ODatabaseMetaDataResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + + N3SQLCancel(m_aStatementHandle); +} + +void SAL_CALL ODatabaseMetaDataResultSet::clearWarnings( ) +{ +} + +Any SAL_CALL ODatabaseMetaDataResultSet::getWarnings( ) +{ + return Any(); +} + +sal_Int32 ODatabaseMetaDataResultSet::getFetchSize() +{ + return 1; +} + +OUString ODatabaseMetaDataResultSet::getCursorName() +{ + return OUString(); +} + + +::cppu::IPropertyArrayHelper* ODatabaseMetaDataResultSet::createArrayHelper( ) const +{ + + return new ::cppu::OPropertyArrayHelper + { + { + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME), + PROPERTY_ID_CURSORNAME, + cppu::UnoType<OUString>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION), + PROPERTY_ID_FETCHDIRECTION, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE), + PROPERTY_ID_FETCHSIZE, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY), + PROPERTY_ID_RESULTSETCONCURRENCY, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE), + PROPERTY_ID_RESULTSETTYPE, + cppu::UnoType<sal_Int32>::get(), + 0 + } + } + }; +} + +::cppu::IPropertyArrayHelper & ODatabaseMetaDataResultSet::getInfoHelper() +{ + return *getArrayHelper(); +} + +sal_Bool ODatabaseMetaDataResultSet::convertFastPropertyValue( + Any & rConvertedValue, + Any & rOldValue, + sal_Int32 nHandle, + const Any& rValue ) +{ + switch(nHandle) + { + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + throw css::lang::IllegalArgumentException(); + case PROPERTY_ID_FETCHDIRECTION: + return ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchDirection()); + case PROPERTY_ID_FETCHSIZE: + return ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchSize()); + default: + ; + } + return false; +} + +void ODatabaseMetaDataResultSet::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& /*rValue*/ ) +{ + switch(nHandle) + { + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + case PROPERTY_ID_FETCHDIRECTION: + case PROPERTY_ID_FETCHSIZE: + throw Exception("cannot set prop " + OUString::number(nHandle), nullptr); + default: + OSL_FAIL("setFastPropertyValue_NoBroadcast: Illegal handle value!"); + } +} + +void ODatabaseMetaDataResultSet::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const +{ + switch(nHandle) + { + case PROPERTY_ID_CURSORNAME: + rValue <<= getCursorName(); + break; + case PROPERTY_ID_RESULTSETCONCURRENCY: + rValue <<= sal_Int32(css::sdbc::ResultSetConcurrency::READ_ONLY); + break; + case PROPERTY_ID_RESULTSETTYPE: + rValue <<= sal_Int32(css::sdbc::ResultSetType::FORWARD_ONLY); + break; + case PROPERTY_ID_FETCHDIRECTION: + rValue <<= getFetchDirection(); + break; + case PROPERTY_ID_FETCHSIZE: + rValue <<= getFetchSize(); + break; + } +} + +void ODatabaseMetaDataResultSet::openTypeInfo() +{ + ::std::map<sal_Int32,sal_Int32> aMap; + aMap[SQL_BIT] = DataType::BIT; + aMap[SQL_TINYINT] = DataType::TINYINT; + aMap[SQL_SMALLINT] = DataType::SMALLINT; + aMap[SQL_INTEGER] = DataType::INTEGER; + aMap[SQL_FLOAT] = DataType::FLOAT; + aMap[SQL_REAL] = DataType::REAL; + aMap[SQL_DOUBLE] = DataType::DOUBLE; + aMap[SQL_BIGINT] = DataType::BIGINT; + + aMap[SQL_CHAR] = DataType::CHAR; + aMap[SQL_WCHAR] = DataType::CHAR; + aMap[SQL_VARCHAR] = DataType::VARCHAR; + aMap[SQL_WVARCHAR] = DataType::VARCHAR; + aMap[SQL_LONGVARCHAR] = DataType::LONGVARCHAR; + aMap[SQL_WLONGVARCHAR] = DataType::LONGVARCHAR; + + aMap[SQL_TYPE_DATE] = DataType::DATE; + aMap[SQL_DATE] = DataType::DATE; + aMap[SQL_TYPE_TIME] = DataType::TIME; + aMap[SQL_TIME] = DataType::TIME; + aMap[SQL_TYPE_TIMESTAMP] = DataType::TIMESTAMP; + aMap[SQL_TIMESTAMP] = DataType::TIMESTAMP; + + aMap[SQL_DECIMAL] = DataType::DECIMAL; + aMap[SQL_NUMERIC] = DataType::NUMERIC; + + aMap[SQL_BINARY] = DataType::BINARY; + aMap[SQL_VARBINARY] = DataType::VARBINARY; + aMap[SQL_LONGVARBINARY] = DataType::LONGVARBINARY; + + aMap[SQL_GUID] = DataType::VARBINARY; + + + m_aValueRange[2] = aMap; + + OTools::ThrowException(m_pConnection.get(),N3SQLGetTypeInfo(m_aStatementHandle, SQL_ALL_TYPES),m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openTables(const Any& catalog, const OUString& schemaPattern, + std::u16string_view tableNamePattern, + const Sequence< OUString >& types ) +{ + OString aPKQ,aPKO,aPKN,aCOL; + const OUString *pSchemaPat = nullptr; + + if(schemaPattern != "%") + pSchemaPat = &schemaPattern; + else + pSchemaPat = nullptr; + + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schemaPattern,m_nTextEncoding); + aPKN = OUStringToOString(tableNamePattern,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(); + + + const char *pCOL = nullptr; + const char* const pComma = ","; + const OUString* pBegin = types.getConstArray(); + const OUString* pEnd = pBegin + types.getLength(); + for(;pBegin != pEnd;++pBegin) + { + aCOL += OUStringToOString(*pBegin,m_nTextEncoding) + pComma; + } + if ( !aCOL.isEmpty() ) + { + aCOL = aCOL.replaceAt(aCOL.getLength()-1,1,pComma); + pCOL = aCOL.getStr(); + } + else + pCOL = SQL_ALL_TABLE_TYPES; + + SQLRETURN nRetcode = N3SQLTables(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pCOL)), pCOL ? SQL_NTS : 0); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); + +} + +void ODatabaseMetaDataResultSet::openTablesTypes( ) +{ + SQLRETURN nRetcode = N3SQLTables(m_aStatementHandle, + nullptr,0, + nullptr,0, + nullptr,0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(SQL_ALL_TABLE_TYPES)),SQL_NTS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + m_aColMapping.clear(); + m_aColMapping.push_back(-1); + m_aColMapping.push_back(4); + m_xMetaData = new OResultSetMetaData(m_pConnection.get(),m_aStatementHandle,std::vector(m_aColMapping)); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openCatalogs() +{ + SQLRETURN nRetcode = N3SQLTables(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(SQL_ALL_CATALOGS)),SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>("")),SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>("")),SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>("")),SQL_NTS); + + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + m_aColMapping.clear(); + m_aColMapping.push_back(-1); + m_aColMapping.push_back(1); + m_xMetaData = new OResultSetMetaData(m_pConnection.get(),m_aStatementHandle,std::vector(m_aColMapping)); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openSchemas() +{ + SQLRETURN nRetcode = N3SQLTables(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>("")),SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(SQL_ALL_SCHEMAS)),SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>("")),SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>("")),SQL_NTS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + m_aColMapping.clear(); + m_aColMapping.push_back(-1); + m_aColMapping.push_back(2); + m_xMetaData = new OResultSetMetaData(m_pConnection.get(),m_aStatementHandle,std::vector(m_aColMapping)); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openColumnPrivileges( const Any& catalog, const OUString& schema, + std::u16string_view table, + std::u16string_view columnNamePattern ) +{ + const OUString *pSchemaPat = nullptr; + + if(schema != "%") + pSchemaPat = &schema; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN,aCOL; + + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schema,m_nTextEncoding); + aPKN = OUStringToOString(table,m_nTextEncoding); + aCOL = OUStringToOString(columnNamePattern,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(), + *pCOL = aCOL.getStr(); + + + SQLRETURN nRetcode = N3SQLColumnPrivileges(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pCOL)), SQL_NTS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openColumns( const Any& catalog, const OUString& schemaPattern, + std::u16string_view tableNamePattern, std::u16string_view columnNamePattern ) +{ + const OUString *pSchemaPat = nullptr; + + if(schemaPattern != "%") + pSchemaPat = &schemaPattern; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN,aCOL; + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schemaPattern,m_nTextEncoding); + aPKN = OUStringToOString(tableNamePattern,m_nTextEncoding); + aCOL = OUStringToOString(columnNamePattern,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(), + *pCOL = aCOL.getStr(); + + + SQLRETURN nRetcode = N3SQLColumns(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pCOL)), SQL_NTS); + + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + ::std::map<sal_Int32,sal_Int32> aMap; + aMap[SQL_BIT] = DataType::BIT; + aMap[SQL_TINYINT] = DataType::TINYINT; + aMap[SQL_SMALLINT] = DataType::SMALLINT; + aMap[SQL_INTEGER] = DataType::INTEGER; + aMap[SQL_FLOAT] = DataType::FLOAT; + aMap[SQL_REAL] = DataType::REAL; + aMap[SQL_DOUBLE] = DataType::DOUBLE; + aMap[SQL_BIGINT] = DataType::BIGINT; + + aMap[SQL_CHAR] = DataType::CHAR; + aMap[SQL_WCHAR] = DataType::CHAR; + aMap[SQL_VARCHAR] = DataType::VARCHAR; + aMap[SQL_WVARCHAR] = DataType::VARCHAR; + aMap[SQL_LONGVARCHAR] = DataType::LONGVARCHAR; + aMap[SQL_WLONGVARCHAR] = DataType::LONGVARCHAR; + + aMap[SQL_TYPE_DATE] = DataType::DATE; + aMap[SQL_DATE] = DataType::DATE; + aMap[SQL_TYPE_TIME] = DataType::TIME; + aMap[SQL_TIME] = DataType::TIME; + aMap[SQL_TYPE_TIMESTAMP] = DataType::TIMESTAMP; + aMap[SQL_TIMESTAMP] = DataType::TIMESTAMP; + + aMap[SQL_DECIMAL] = DataType::DECIMAL; + aMap[SQL_NUMERIC] = DataType::NUMERIC; + + aMap[SQL_BINARY] = DataType::BINARY; + aMap[SQL_VARBINARY] = DataType::VARBINARY; + aMap[SQL_LONGVARBINARY] = DataType::LONGVARBINARY; + + aMap[SQL_GUID] = DataType::VARBINARY; + + m_aValueRange[5] = aMap; + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openProcedureColumns( const Any& catalog, const OUString& schemaPattern, + std::u16string_view procedureNamePattern,std::u16string_view columnNamePattern ) +{ + const OUString *pSchemaPat = nullptr; + + if(schemaPattern != "%") + pSchemaPat = &schemaPattern; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN,aCOL; + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schemaPattern,m_nTextEncoding); + aPKN = OUStringToOString(procedureNamePattern,m_nTextEncoding); + aCOL = OUStringToOString(columnNamePattern,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(), + *pCOL = aCOL.getStr(); + + + SQLRETURN nRetcode = N3SQLProcedureColumns(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pCOL)), SQL_NTS); + + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openProcedures(const Any& catalog, const OUString& schemaPattern, + std::u16string_view procedureNamePattern) +{ + const OUString *pSchemaPat = nullptr; + + if(schemaPattern != "%") + pSchemaPat = &schemaPattern; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN; + + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schemaPattern,m_nTextEncoding); + aPKN = OUStringToOString(procedureNamePattern,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(); + + + SQLRETURN nRetcode = N3SQLProcedures(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openSpecialColumns(bool _bRowVer,const Any& catalog, const OUString& schema, + std::u16string_view table,sal_Int32 scope, bool nullable ) +{ + // Some ODBC drivers really don't like getting an empty string as tableName + // E.g. psqlodbc up to at least version 09.01.0100 segfaults + if (table.empty()) + { + static constexpr OUStringLiteral errMsg + = u"ODBC: Trying to get special columns of empty table name"; + static constexpr OUStringLiteral SQLState = u"HY009"; + throw SQLException( errMsg, *this, SQLState, -1, Any() ); + } + + const OUString *pSchemaPat = nullptr; + + if(schema != "%") + pSchemaPat = &schema; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN; + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schema,m_nTextEncoding); + aPKN = OUStringToOString(table,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(); + + + SQLRETURN nRetcode = N3SQLSpecialColumns(m_aStatementHandle,_bRowVer ? SQL_ROWVER : SQL_BEST_ROWID, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS, + static_cast<SQLSMALLINT>(scope), + nullable ? SQL_NULLABLE : SQL_NO_NULLS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openVersionColumns(const Any& catalog, const OUString& schema, + std::u16string_view table) +{ + openSpecialColumns(true,catalog,schema,table,SQL_SCOPE_TRANSACTION,false); +} + +void ODatabaseMetaDataResultSet::openBestRowIdentifier( const Any& catalog, const OUString& schema, + std::u16string_view table,sal_Int32 scope,bool nullable ) +{ + openSpecialColumns(false,catalog,schema,table,scope,nullable); +} + +void ODatabaseMetaDataResultSet::openForeignKeys( const Any& catalog, const OUString* schema, + const OUString* table, + const Any& catalog2, const OUString* schema2, + const OUString* table2) +{ + OString aPKQ, aPKO, aPKN, aFKQ, aFKO, aFKN; + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + if ( catalog2.hasValue() ) + aFKQ = OUStringToOString(comphelper::getString(catalog2),m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr; + const char *pPKO = nullptr; + if (schema && !schema->isEmpty()) + { + aPKO = OUStringToOString(*schema,m_nTextEncoding); + pPKO = aPKO.getStr(); + } + const char *pPKN = nullptr; + if (table) + { + aPKN = OUStringToOString(*table,m_nTextEncoding); + pPKN = aPKN.getStr(); + } + const char *pFKQ = catalog2.hasValue() && !aFKQ.isEmpty() ? aFKQ.getStr() : nullptr; + const char *pFKO = nullptr; + if (schema2 && !schema2->isEmpty()) + { + aFKO = OUStringToOString(*schema2,m_nTextEncoding); + pFKO = aFKO.getStr(); + } + const char *pFKN = nullptr; + if (table2) + { + aFKN = OUStringToOString(*table2,m_nTextEncoding); + pFKN = aFKN.getStr(); + } + + SQLRETURN nRetcode = N3SQLForeignKeys(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), pPKN ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pFKQ)), (catalog2.hasValue() && !aFKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pFKO)), pFKO ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pFKN)), SQL_NTS + ); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openImportedKeys(const Any& catalog, const OUString& schema, + const OUString& table) +{ + + openForeignKeys(Any(),nullptr,nullptr,catalog, schema == "%" ? &schema : nullptr, &table); +} + +void ODatabaseMetaDataResultSet::openExportedKeys(const Any& catalog, const OUString& schema, + const OUString& table) +{ + openForeignKeys(catalog, schema == "%" ? &schema : nullptr, &table,Any(),nullptr,nullptr); +} + +void ODatabaseMetaDataResultSet::openPrimaryKeys(const Any& catalog, const OUString& schema, + std::u16string_view table) +{ + const OUString *pSchemaPat = nullptr; + + if(schema != "%") + pSchemaPat = &schema; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN; + + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schema,m_nTextEncoding); + aPKN = OUStringToOString(table,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(); + + + SQLRETURN nRetcode = N3SQLPrimaryKeys(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openTablePrivileges(const Any& catalog, const OUString& schemaPattern, + std::u16string_view tableNamePattern) +{ + const OUString *pSchemaPat = nullptr; + + if(schemaPattern != "%") + pSchemaPat = &schemaPattern; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN; + + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schemaPattern,m_nTextEncoding); + aPKN = OUStringToOString(tableNamePattern,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(); + + SQLRETURN nRetcode = N3SQLTablePrivileges(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::openIndexInfo( const Any& catalog, const OUString& schema, + std::u16string_view table, bool unique, bool approximate ) +{ + const OUString *pSchemaPat = nullptr; + + if(schema != "%") + pSchemaPat = &schema; + else + pSchemaPat = nullptr; + + OString aPKQ,aPKO,aPKN; + + if ( catalog.hasValue() ) + aPKQ = OUStringToOString(comphelper::getString(catalog),m_nTextEncoding); + aPKO = OUStringToOString(schema,m_nTextEncoding); + aPKN = OUStringToOString(table,m_nTextEncoding); + + const char *pPKQ = catalog.hasValue() && !aPKQ.isEmpty() ? aPKQ.getStr() : nullptr, + *pPKO = pSchemaPat && !pSchemaPat->isEmpty() && !aPKO.isEmpty() ? aPKO.getStr() : nullptr, + *pPKN = aPKN.getStr(); + + SQLRETURN nRetcode = N3SQLStatistics(m_aStatementHandle, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKQ)), (catalog.hasValue() && !aPKQ.isEmpty()) ? SQL_NTS : 0, + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKO)), pPKO ? SQL_NTS : 0 , + reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(pPKN)), SQL_NTS, + unique ? SQL_INDEX_UNIQUE : SQL_INDEX_ALL, + approximate ? 1 : 0); + OTools::ThrowException(m_pConnection.get(),nRetcode,m_aStatementHandle,SQL_HANDLE_STMT,*this); + checkColumnCount(); +} + +void ODatabaseMetaDataResultSet::checkColumnCount() +{ + sal_Int16 nNumResultCols=0; + OTools::ThrowException(m_pConnection.get(),N3SQLNumResultCols(m_aStatementHandle,&nNumResultCols),m_aStatementHandle,SQL_HANDLE_STMT,*this); + m_nDriverColumnCount = nNumResultCols; +} + + +SWORD ODatabaseMetaDataResultSet::impl_getColumnType_nothrow(sal_Int32 columnIndex) +{ + std::map<sal_Int32,SWORD>::iterator aFind = m_aODBCColumnTypes.find(columnIndex); + if ( aFind == m_aODBCColumnTypes.end() ) + aFind = m_aODBCColumnTypes.emplace( + columnIndex, + OResultSetMetaData::getColumnODBCType(m_pConnection.get(),m_aStatementHandle,*this,columnIndex) + ).first; + return aFind->second; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/ODriver.cxx b/connectivity/source/drivers/odbc/ODriver.cxx new file mode 100644 index 000000000..df7b3fd20 --- /dev/null +++ b/connectivity/source/drivers/odbc/ODriver.cxx @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/ODriver.hxx> +#include <odbc/OConnection.hxx> +#include <odbc/OTools.hxx> +#include <connectivity/dbexception.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <strings.hrc> +#include <resource/sharedresources.hxx> + +using namespace connectivity::odbc; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; + +ODBCDriver::ODBCDriver(const css::uno::Reference< css::uno::XComponentContext >& _rxContext) + :ODriver_BASE(m_aMutex) + ,m_xContext(_rxContext) + ,m_pDriverHandle(SQL_NULL_HANDLE) +{ +} + +void ODBCDriver::disposing() +{ + ::osl::MutexGuard aGuard(m_aMutex); + + + for (auto const& connection : m_xConnections) + { + Reference< XComponent > xComp(connection.get(), UNO_QUERY); + if (xComp.is()) + xComp->dispose(); + } + m_xConnections.clear(); + + ODriver_BASE::disposing(); +} + +// static ServiceInfo + +OUString ODBCDriver::getImplementationName( ) +{ + return "com.sun.star.comp.sdbc.ODBCDriver"; + // this name is referenced in the configuration and in the odbc.xml + // Please take care when changing it. +} + + +Sequence< OUString > ODBCDriver::getSupportedServiceNames( ) +{ + return { "com.sun.star.sdbc.Driver" }; +} + + +sal_Bool SAL_CALL ODBCDriver::supportsService( const OUString& _rServiceName ) +{ + return cppu::supportsService(this, _rServiceName); +} + + +Reference< XConnection > SAL_CALL ODBCDriver::connect( const OUString& url, const Sequence< PropertyValue >& info ) +{ + if ( ! acceptsURL(url) ) + return nullptr; + + if(!m_pDriverHandle) + { + OUString aPath; + if(!EnvironmentHandle(aPath)) + throw SQLException(aPath,*this,OUString(),1000,Any()); + } + rtl::Reference<OConnection> pCon = new OConnection(m_pDriverHandle,this); + pCon->Construct(url,info); + m_xConnections.push_back(WeakReferenceHelper(*pCon)); + + return pCon; +} + +sal_Bool SAL_CALL ODBCDriver::acceptsURL( const OUString& url ) +{ + return url.startsWith("sdbc:odbc:"); +} + +Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const OUString& url, const Sequence< PropertyValue >& /*info*/ ) +{ + if ( acceptsURL(url) ) + { + Sequence< OUString > aBooleanValues{ "false", "true" }; + + return + { + { + "CharSet", + "CharSet of the database.", + false, + {}, + {} + }, + { + "UseCatalog", + "Use catalog for file-based databases.", + false, + "false", + aBooleanValues + }, + { + "SystemDriverSettings", + "Driver settings.", + false, + {}, + {} + }, + { + "ParameterNameSubstitution", + "Change named parameters with '?'.", + false, + "false", + aBooleanValues + }, + { + "IgnoreDriverPrivileges", + "Ignore the privileges from the database driver.", + false, + "false", + aBooleanValues + }, + { + "IsAutoRetrievingEnabled", + "Retrieve generated values.", + false, + "false", + aBooleanValues + }, + { + "AutoRetrievingStatement", + "Auto-increment statement.", + false, + {}, + {} + }, + { + "GenerateASBeforeCorrelationName", + "Generate AS before table correlation names.", + false, + "false", + aBooleanValues + }, + { + "EscapeDateTime", + "Escape date time format.", + false, + "true", + aBooleanValues + } + }; + } + ::connectivity::SharedResources aResources; + const OUString sMessage = aResources.getResourceString(STR_URI_SYNTAX_ERROR); + ::dbtools::throwGenericSQLException(sMessage ,*this); + return Sequence< DriverPropertyInfo >(); +} + +sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) +{ + return 1; +} + +sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) +{ + return 0; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/OFunctions.cxx b/connectivity/source/drivers/odbc/OFunctions.cxx new file mode 100644 index 000000000..951eb8b36 --- /dev/null +++ b/connectivity/source/drivers/odbc/OFunctions.cxx @@ -0,0 +1,245 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/OFunctions.hxx> + +// Implib definitions for ODBC-DLL/shared library: + +namespace connectivity +{ + T3SQLAllocHandle pODBC3SQLAllocHandle; +T3SQLConnect pODBC3SQLConnect; +T3SQLDriverConnect pODBC3SQLDriverConnect; +T3SQLBrowseConnect pODBC3SQLBrowseConnect; +T3SQLDataSources pODBC3SQLDataSources; +T3SQLDrivers pODBC3SQLDrivers; +T3SQLGetInfo pODBC3SQLGetInfo; +T3SQLGetFunctions pODBC3SQLGetFunctions; +T3SQLGetTypeInfo pODBC3SQLGetTypeInfo; +T3SQLSetConnectAttr pODBC3SQLSetConnectAttr; +T3SQLGetConnectAttr pODBC3SQLGetConnectAttr; +T3SQLSetEnvAttr pODBC3SQLSetEnvAttr; +T3SQLGetEnvAttr pODBC3SQLGetEnvAttr; +T3SQLSetStmtAttr pODBC3SQLSetStmtAttr; +T3SQLGetStmtAttr pODBC3SQLGetStmtAttr; +T3SQLPrepare pODBC3SQLPrepare; +T3SQLBindParameter pODBC3SQLBindParameter; +T3SQLSetCursorName pODBC3SQLSetCursorName; +T3SQLExecute pODBC3SQLExecute; +T3SQLExecDirect pODBC3SQLExecDirect; +T3SQLDescribeParam pODBC3SQLDescribeParam; +T3SQLNumParams pODBC3SQLNumParams; +T3SQLParamData pODBC3SQLParamData; +T3SQLPutData pODBC3SQLPutData; +T3SQLRowCount pODBC3SQLRowCount; +T3SQLNumResultCols pODBC3SQLNumResultCols; +T3SQLDescribeCol pODBC3SQLDescribeCol; +T3SQLColAttribute pODBC3SQLColAttribute; +T3SQLBindCol pODBC3SQLBindCol; +T3SQLFetch pODBC3SQLFetch; +T3SQLFetchScroll pODBC3SQLFetchScroll; +T3SQLGetData pODBC3SQLGetData; +T3SQLSetPos pODBC3SQLSetPos; +T3SQLBulkOperations pODBC3SQLBulkOperations; +T3SQLMoreResults pODBC3SQLMoreResults; +T3SQLGetDiagRec pODBC3SQLGetDiagRec; +T3SQLColumnPrivileges pODBC3SQLColumnPrivileges; +T3SQLColumns pODBC3SQLColumns; +T3SQLForeignKeys pODBC3SQLForeignKeys; +T3SQLPrimaryKeys pODBC3SQLPrimaryKeys; +T3SQLProcedureColumns pODBC3SQLProcedureColumns; +T3SQLProcedures pODBC3SQLProcedures; +T3SQLSpecialColumns pODBC3SQLSpecialColumns; +T3SQLStatistics pODBC3SQLStatistics; +T3SQLTablePrivileges pODBC3SQLTablePrivileges; +T3SQLTables pODBC3SQLTables; +T3SQLFreeStmt pODBC3SQLFreeStmt; +T3SQLCloseCursor pODBC3SQLCloseCursor; +T3SQLCancel pODBC3SQLCancel; +T3SQLEndTran pODBC3SQLEndTran; +T3SQLDisconnect pODBC3SQLDisconnect; +T3SQLFreeHandle pODBC3SQLFreeHandle; +T3SQLGetCursorName pODBC3SQLGetCursorName; +T3SQLNativeSql pODBC3SQLNativeSql; + +static bool LoadFunctions(oslModule pODBCso); + +// Take care of Dynamically loading of the DLL/shared lib and Addresses: +// Returns sal_True at success +bool LoadLibrary_ODBC3(OUString &_rPath) +{ + static bool bLoaded = false; + static oslModule pODBCso = nullptr; + + if (bLoaded) + return true; +#ifdef DISABLE_DYNLOADING + (void)_rPath; +#else +#ifdef _WIN32 + _rPath = "ODBC32.DLL"; +#endif +#ifdef UNX + #ifdef MACOSX + _rPath = "libiodbc.dylib"; + #else + _rPath = "libodbc.so.2"; + pODBCso = osl_loadModule( _rPath.pData,SAL_LOADMODULE_NOW ); + if ( !pODBCso ) + { + _rPath = "libodbc.so.1"; + pODBCso = osl_loadModule( _rPath.pData,SAL_LOADMODULE_NOW ); + } + if ( !pODBCso ) + _rPath = "libodbc.so"; + + #endif /* MACOSX */ +#endif + + if ( !pODBCso ) + pODBCso = osl_loadModule( _rPath.pData,SAL_LOADMODULE_NOW ); +#endif // DISABLE_DYNLOADING + if( !pODBCso) + return false; + + bLoaded = LoadFunctions(pODBCso); + return bLoaded; +} + + +bool LoadFunctions(oslModule pODBCso) +{ + + if( ( pODBC3SQLAllocHandle = reinterpret_cast<T3SQLAllocHandle>(osl_getFunctionSymbol(pODBCso, OUString("SQLAllocHandle").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLConnect = reinterpret_cast<T3SQLConnect>(osl_getFunctionSymbol(pODBCso, OUString("SQLConnect").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLDriverConnect = reinterpret_cast<T3SQLDriverConnect>(osl_getFunctionSymbol(pODBCso, OUString("SQLDriverConnect").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLBrowseConnect = reinterpret_cast<T3SQLBrowseConnect>(osl_getFunctionSymbol(pODBCso, OUString("SQLBrowseConnect").pData ))) == nullptr ) + return false; + if(( pODBC3SQLDataSources = reinterpret_cast<T3SQLDataSources>(osl_getFunctionSymbol(pODBCso, OUString("SQLDataSources").pData ))) == nullptr ) + return false; + if(( pODBC3SQLDrivers = reinterpret_cast<T3SQLDrivers>(osl_getFunctionSymbol(pODBCso, OUString("SQLDrivers").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetInfo = reinterpret_cast<T3SQLGetInfo>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetInfo").pData ))) == nullptr ) + return false; + if(( pODBC3SQLGetFunctions = reinterpret_cast<T3SQLGetFunctions>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetFunctions").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetTypeInfo = reinterpret_cast<T3SQLGetTypeInfo>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetTypeInfo").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLSetConnectAttr = reinterpret_cast<T3SQLSetConnectAttr>(osl_getFunctionSymbol(pODBCso, OUString("SQLSetConnectAttr").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetConnectAttr = reinterpret_cast<T3SQLGetConnectAttr>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetConnectAttr").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLSetEnvAttr = reinterpret_cast<T3SQLSetEnvAttr>(osl_getFunctionSymbol(pODBCso, OUString("SQLSetEnvAttr").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetEnvAttr = reinterpret_cast<T3SQLGetEnvAttr>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetEnvAttr").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLSetStmtAttr = reinterpret_cast<T3SQLSetStmtAttr>(osl_getFunctionSymbol(pODBCso, OUString("SQLSetStmtAttr").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetStmtAttr = reinterpret_cast<T3SQLGetStmtAttr>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetStmtAttr").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLPrepare = reinterpret_cast<T3SQLPrepare>(osl_getFunctionSymbol(pODBCso, OUString("SQLPrepare").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLBindParameter = reinterpret_cast<T3SQLBindParameter>(osl_getFunctionSymbol(pODBCso, OUString("SQLBindParameter").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLSetCursorName = reinterpret_cast<T3SQLSetCursorName>(osl_getFunctionSymbol(pODBCso, OUString("SQLSetCursorName").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLExecute = reinterpret_cast<T3SQLExecute>(osl_getFunctionSymbol(pODBCso, OUString("SQLExecute").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLExecDirect = reinterpret_cast<T3SQLExecDirect>(osl_getFunctionSymbol(pODBCso, OUString("SQLExecDirect").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLDescribeParam = reinterpret_cast<T3SQLDescribeParam>(osl_getFunctionSymbol(pODBCso, OUString("SQLDescribeParam").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLNumParams = reinterpret_cast<T3SQLNumParams>(osl_getFunctionSymbol(pODBCso, OUString("SQLNumParams").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLParamData = reinterpret_cast<T3SQLParamData>(osl_getFunctionSymbol(pODBCso, OUString("SQLParamData").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLPutData = reinterpret_cast<T3SQLPutData>(osl_getFunctionSymbol(pODBCso, OUString("SQLPutData").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLRowCount = reinterpret_cast<T3SQLRowCount>(osl_getFunctionSymbol(pODBCso, OUString("SQLRowCount").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLNumResultCols = reinterpret_cast<T3SQLNumResultCols>(osl_getFunctionSymbol(pODBCso, OUString("SQLNumResultCols").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLDescribeCol = reinterpret_cast<T3SQLDescribeCol>(osl_getFunctionSymbol(pODBCso, OUString("SQLDescribeCol").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLColAttribute = reinterpret_cast<T3SQLColAttribute>(osl_getFunctionSymbol(pODBCso, OUString("SQLColAttribute").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLBindCol = reinterpret_cast<T3SQLBindCol>(osl_getFunctionSymbol(pODBCso, OUString("SQLBindCol").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLFetch = reinterpret_cast<T3SQLFetch>(osl_getFunctionSymbol(pODBCso, OUString("SQLFetch").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLFetchScroll = reinterpret_cast<T3SQLFetchScroll>(osl_getFunctionSymbol(pODBCso, OUString("SQLFetchScroll").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetData = reinterpret_cast<T3SQLGetData>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetData").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLSetPos = reinterpret_cast<T3SQLSetPos>(osl_getFunctionSymbol(pODBCso, OUString("SQLSetPos").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLBulkOperations = reinterpret_cast<T3SQLBulkOperations>(osl_getFunctionSymbol(pODBCso, OUString("SQLBulkOperations").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLMoreResults = reinterpret_cast<T3SQLMoreResults>(osl_getFunctionSymbol(pODBCso, OUString("SQLMoreResults").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetDiagRec = reinterpret_cast<T3SQLGetDiagRec>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetDiagRec").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLColumnPrivileges = reinterpret_cast<T3SQLColumnPrivileges>(osl_getFunctionSymbol(pODBCso, OUString("SQLColumnPrivileges").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLColumns = reinterpret_cast<T3SQLColumns>(osl_getFunctionSymbol(pODBCso, OUString("SQLColumns").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLForeignKeys = reinterpret_cast<T3SQLForeignKeys>(osl_getFunctionSymbol(pODBCso, OUString("SQLForeignKeys").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLPrimaryKeys = reinterpret_cast<T3SQLPrimaryKeys>(osl_getFunctionSymbol(pODBCso, OUString("SQLPrimaryKeys").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLProcedureColumns = reinterpret_cast<T3SQLProcedureColumns>(osl_getFunctionSymbol(pODBCso, OUString("SQLProcedureColumns").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLProcedures = reinterpret_cast<T3SQLProcedures>(osl_getFunctionSymbol(pODBCso, OUString("SQLProcedures").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLSpecialColumns = reinterpret_cast<T3SQLSpecialColumns>(osl_getFunctionSymbol(pODBCso, OUString("SQLSpecialColumns").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLStatistics = reinterpret_cast<T3SQLStatistics>(osl_getFunctionSymbol(pODBCso, OUString("SQLStatistics").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLTablePrivileges = reinterpret_cast<T3SQLTablePrivileges>(osl_getFunctionSymbol(pODBCso, OUString("SQLTablePrivileges").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLTables = reinterpret_cast<T3SQLTables>(osl_getFunctionSymbol(pODBCso, OUString("SQLTables").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLFreeStmt = reinterpret_cast<T3SQLFreeStmt>(osl_getFunctionSymbol(pODBCso, OUString("SQLFreeStmt").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLCloseCursor = reinterpret_cast<T3SQLCloseCursor>(osl_getFunctionSymbol(pODBCso, OUString("SQLCloseCursor").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLCancel = reinterpret_cast<T3SQLCancel>(osl_getFunctionSymbol(pODBCso, OUString("SQLCancel").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLEndTran = reinterpret_cast<T3SQLEndTran>(osl_getFunctionSymbol(pODBCso, OUString("SQLEndTran").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLDisconnect = reinterpret_cast<T3SQLDisconnect>(osl_getFunctionSymbol(pODBCso, OUString("SQLDisconnect").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLFreeHandle = reinterpret_cast<T3SQLFreeHandle>(osl_getFunctionSymbol(pODBCso, OUString("SQLFreeHandle").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLGetCursorName = reinterpret_cast<T3SQLGetCursorName>(osl_getFunctionSymbol(pODBCso, OUString("SQLGetCursorName").pData ))) == nullptr ) + return false; + if( ( pODBC3SQLNativeSql = reinterpret_cast<T3SQLNativeSql>(osl_getFunctionSymbol(pODBCso, OUString("SQLNativeSql").pData ))) == nullptr ) + return false; + + return true; +} + + +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/OPreparedStatement.cxx b/connectivity/source/drivers/odbc/OPreparedStatement.cxx new file mode 100644 index 000000000..d5852c9ea --- /dev/null +++ b/connectivity/source/drivers/odbc/OPreparedStatement.cxx @@ -0,0 +1,924 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include <string.h> +#include <osl/diagnose.h> +#include <odbc/OPreparedStatement.hxx> +#include <odbc/OBoundParam.hxx> +#include <com/sun/star/io/IOException.hpp> +#include <com/sun/star/sdbc/DataType.hpp> +#include <odbc/OTools.hxx> +#include <odbc/OResultSet.hxx> +#include <odbc/OResultSetMetaData.hxx> +#include <comphelper/sequence.hxx> +#include <connectivity/dbtools.hxx> +#include <comphelper/types.hxx> +#include <connectivity/FValue.hxx> +#include <strings.hrc> +#include <memory> +#include <type_traits> + +using namespace ::comphelper; +using namespace connectivity; +using namespace connectivity::odbc; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::sdbcx; +using namespace com::sun::star::container; +using namespace com::sun::star::io; +using namespace com::sun::star::util; + +IMPLEMENT_SERVICE_INFO(OPreparedStatement,"com.sun.star.sdbcx.OPreparedStatement","com.sun.star.sdbc.PreparedStatement"); + +namespace +{ + // for now, never use wchar, + // but most of code is prepared to handle it + // in case we make this configurable + const bool bUseWChar = false; +} + +OPreparedStatement::OPreparedStatement( OConnection* _pConnection,const OUString& sql) + :OStatement_BASE2(_pConnection) + ,numParams(0) + ,m_bPrepared(false) +{ + m_sSqlStatement = sql; +} + +OPreparedStatement::~OPreparedStatement() +{ +} + +void SAL_CALL OPreparedStatement::acquire() noexcept +{ + OStatement_BASE2::acquire(); +} + +void SAL_CALL OPreparedStatement::release() noexcept +{ + OStatement_BASE2::release(); +} + +Any SAL_CALL OPreparedStatement::queryInterface( const Type & rType ) +{ + Any aRet = OStatement_BASE2::queryInterface(rType); + return aRet.hasValue() ? aRet : OPreparedStatement_BASE::queryInterface(rType); +} + +css::uno::Sequence< css::uno::Type > SAL_CALL OPreparedStatement::getTypes( ) +{ + return ::comphelper::concatSequences(OPreparedStatement_BASE::getTypes(),OStatement_BASE2::getTypes()); +} + + +Reference< XResultSetMetaData > SAL_CALL OPreparedStatement::getMetaData( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + prepareStatement(); + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + if(!m_xMetaData.is()) + m_xMetaData = new OResultSetMetaData(getOwnConnection(),m_aStatementHandle); + return m_xMetaData; +} + + +void SAL_CALL OPreparedStatement::close( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + // Close/clear our result set + clearMyResultSet (); + + // Reset last warning message + + try { + clearWarnings (); + OStatement_BASE2::close(); + FreeParams(); + } + catch (SQLException &) { + // If we get an error, ignore + } + + // Remove this Statement object from the Connection object's + // list +} + + +sal_Bool SAL_CALL OPreparedStatement::execute( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + // Reset warnings + + clearWarnings (); + + // Reset the statement handle, warning and saved Resultset + + reset(); + + // Call SQLExecute + prepareStatement(); + + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + try + { + SQLRETURN nReturn = N3SQLExecute(m_aStatementHandle); + + OTools::ThrowException(m_pConnection.get(),nReturn,m_aStatementHandle,SQL_HANDLE_STMT,*this); + bool needData = nReturn == SQL_NEED_DATA; + + // Now loop while more data is needed (i.e. a data-at- + // execution parameter was given). For each parameter + // that needs data, put the data from the input stream. + + while (needData) { + + // Get the parameter number that requires data + + sal_Int32* paramIndex = nullptr; + N3SQLParamData(m_aStatementHandle, reinterpret_cast<SQLPOINTER*>(¶mIndex)); + + // If the parameter index is -1, there is no + // more data required + + if ( !paramIndex || ( *paramIndex == -1 ) ) + needData = false; + else + { + // Now we have the proper parameter + // index, get the data from the input + // stream and do a SQLPutData + putParamData (*paramIndex); + } + } + + } + catch (const SQLWarning&) + { + } + + // Now determine if there is a result set associated with + // the SQL statement that was executed. Get the column + // count, and if it is not zero, there is a result set. + + + return getColumnCount() > 0; +} + + +sal_Int32 SAL_CALL OPreparedStatement::executeUpdate( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + sal_Int32 numRows = -1; + + prepareStatement(); + // Execute the statement. If execute returns sal_False, a + // row count exists. + + if (!execute()) + numRows = getUpdateCount (); + else + { + // No update count was produced (a ResultSet was). Raise + // an exception + m_pConnection->throwGenericSQLException(STR_NO_ROWCOUNT,*this); + } + return numRows; +} + + +void SAL_CALL OPreparedStatement::setString( sal_Int32 parameterIndex, const OUString& x ) +{ + setParameter(parameterIndex, DataType::CHAR, invalid_scale, x); +} + + +Reference< XConnection > SAL_CALL OPreparedStatement::getConnection( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + return m_pConnection; +} + + +Reference< XResultSet > SAL_CALL OPreparedStatement::executeQuery( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + Reference< XResultSet > rs; + + prepareStatement(); + + if (execute()) + rs = getResultSet(false); + else + { + // No ResultSet was produced. Raise an exception + m_pConnection->throwGenericSQLException(STR_NO_RESULTSET,*this); + } + return rs; +} + + +void SAL_CALL OPreparedStatement::setBoolean( sal_Int32 parameterIndex, sal_Bool x ) +{ + // Set the parameter as if it were an integer + setInt (parameterIndex, x ? 1 : 0 ); +} + +// The MutexGuard must _already_ be taken! +void OPreparedStatement::setParameterPre(sal_Int32 parameterIndex) +{ + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + prepareStatement(); + checkParameterIndex(parameterIndex); + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); +} + + +template <typename T> void OPreparedStatement::setScalarParameter(const sal_Int32 parameterIndex, const sal_Int32 i_nType, const SQLULEN i_nColSize, const T i_Value) +{ + setScalarParameter(parameterIndex, i_nType, i_nColSize, invalid_scale, i_Value); +} + + +template <typename T> void OPreparedStatement::setScalarParameter(const sal_Int32 parameterIndex, const sal_Int32 i_nType, const SQLULEN i_nColSize, sal_Int32 i_nScale, const T i_Value) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + setParameterPre(parameterIndex); + + typedef typename std::remove_reference<T>::type TnoRef; + + TnoRef *bindBuf = static_cast< TnoRef* >( allocBindBuf(parameterIndex, sizeof(i_Value)) ); + *bindBuf = i_Value; + + setParameter(parameterIndex, i_nType, i_nColSize, i_nScale, bindBuf, sizeof(i_Value), sizeof(i_Value)); +} + + +void OPreparedStatement::setParameter(const sal_Int32 parameterIndex, const sal_Int32 _nType, const sal_Int16 _nScale, const OUString &_sData) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + setParameterPre(parameterIndex); + + assert (_nType == DataType::VARCHAR || _nType == DataType::CHAR || _nType == DataType::DECIMAL || _nType == DataType::NUMERIC); + + sal_Int32 nCharLen; + sal_Int32 nByteLen; + void *pData; + if (bUseWChar) + { + /* + * On Windows, wchar is 16 bits (UTF-16 encoding), the ODBC "W" variants functions take UTF-16 encoded strings + * and character lengths are number of UTF-16 codepoints. + * Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms716246%28v=vs.85%29.aspx + * ODBC Programmer's reference > Developing Applications > Programming Considerations > Unicode > Unicode Function Arguments + * http://support.microsoft.com/kb/294169 + * + * UnixODBC can be configured at compile-time so that the "W" variants expect + * UTF-16 or UTF-32 encoded strings, and character lengths are number of codepoints. + * However, UTF-16 is the default, what all/most distributions do + * and the established API that most drivers implement. + * As wchar is often 32 bits, this differs from C-style strings of wchar! + * + * On MacOS X, the "W" variants use wchar_t, which is UCS4 + * + * Our internal OUString storage is always UTF-16, so no conversion to do here. + */ + static_assert(sizeof (SQLWCHAR) == 2 || sizeof (SQLWCHAR) == 4, "must be 2 or 4"); + if (sizeof (SQLWCHAR) == 2) + { + nCharLen = _sData.getLength(); + nByteLen = 2 * nCharLen; + pData = allocBindBuf(parameterIndex, nByteLen); + memcpy(pData, _sData.getStr(), nByteLen); + } + else + { + pData = allocBindBuf(parameterIndex, _sData.getLength() * 4); + sal_uInt32* pCursor = static_cast<sal_uInt32*>(pData); + nCharLen = 0; + for (sal_Int32 i = 0; i != _sData.getLength();) + { + *pCursor++ = _sData.iterateCodePoints(&i); + nCharLen += 1; + } + nByteLen = 4 * nCharLen; + } + } + else + { + assert(getOwnConnection()->getTextEncoding() != RTL_TEXTENCODING_UCS2 && + getOwnConnection()->getTextEncoding() != RTL_TEXTENCODING_UCS4); + OString sOData( + OUStringToOString(_sData, getOwnConnection()->getTextEncoding())); + nCharLen = nByteLen = sOData.getLength(); + pData = allocBindBuf(parameterIndex, nByteLen); + memcpy(pData, sOData.getStr(), nByteLen); + } + + setParameter( parameterIndex, _nType, nCharLen, _nScale, pData, nByteLen, nByteLen ); +} + +void OPreparedStatement::setParameter(const sal_Int32 parameterIndex, const sal_Int32 _nType, const Sequence< sal_Int8 > &x) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + setParameterPre(parameterIndex); + + assert(_nType == DataType::BINARY || _nType == DataType::VARBINARY); + + // don't copy the sequence, just point the ODBC directly at the sequence's storage array + // Why BINARY/Sequence is treated differently than strings (which are copied), I'm not sure + OSL_VERIFY(allocBindBuf(parameterIndex, 0) == nullptr); + boundParams[parameterIndex-1].setSequence(x); // this ensures that the sequence stays alive + + setParameter( parameterIndex, _nType, x.getLength(), invalid_scale, x.getConstArray(), x.getLength(), x.getLength() ); +} + +void OPreparedStatement::setParameter(const sal_Int32 parameterIndex, const sal_Int32 _nType, const SQLULEN _nColumnSize, const sal_Int32 _nScale, const void* const _pData, const SQLULEN _nDataLen, const SQLLEN _nDataAllocLen) +{ + SQLSMALLINT fCType, fSqlType; + OTools::getBindTypes(bUseWChar, m_pConnection->useOldDateFormat(), OTools::jdbcTypeToOdbc(_nType), fCType, fSqlType); + + SQLLEN& rDataLen = boundParams[parameterIndex-1].getBindLengthBuffer(); + rDataLen = _nDataLen; + + SQLRETURN nRetcode; + nRetcode = (*reinterpret_cast<T3SQLBindParameter>(m_pConnection->getOdbcFunction(ODBC3SQLFunctionId::BindParameter)))( + m_aStatementHandle, + // checkParameterIndex guarantees this is safe + static_cast<SQLUSMALLINT>(parameterIndex), + SQL_PARAM_INPUT, + fCType, + fSqlType, + _nColumnSize, + _nScale, + // we trust the ODBC driver not to touch it because SQL_PARAM_INPUT + const_cast<void*>(_pData), + _nDataAllocLen, + &rDataLen); + + OTools::ThrowException(m_pConnection.get(), nRetcode, m_aStatementHandle, SQL_HANDLE_STMT, *this); +} + +void SAL_CALL OPreparedStatement::setByte( const sal_Int32 parameterIndex, const sal_Int8 x ) +{ + setScalarParameter(parameterIndex, DataType::TINYINT, 3, 0, x); +} + +void SAL_CALL OPreparedStatement::setDate( sal_Int32 parameterIndex, const Date& aData ) +{ + DATE_STRUCT x(OTools::DateToOdbcDate(aData)); + setScalarParameter<DATE_STRUCT&>(parameterIndex, DataType::DATE, 10, x); +} + +void SAL_CALL OPreparedStatement::setTime( sal_Int32 parameterIndex, const css::util::Time& aVal ) +{ + SQLULEN nColSize; + if(aVal.NanoSeconds == 0) + nColSize = 8; + else if(aVal.NanoSeconds % 100000000 == 0) + nColSize = 10; + else if(aVal.NanoSeconds % 10000000 == 0) + nColSize = 11; + else if(aVal.NanoSeconds % 1000000 == 0) + nColSize = 12; + else if(aVal.NanoSeconds % 100000 == 0) + nColSize = 13; + else if(aVal.NanoSeconds % 10000 == 0) + nColSize = 14; + else if(aVal.NanoSeconds % 1000 == 0) + nColSize = 15; + else if(aVal.NanoSeconds % 100 == 0) + nColSize = 16; + else if(aVal.NanoSeconds % 10 == 0) + nColSize = 17; + else + nColSize = 18; + TIME_STRUCT x(OTools::TimeToOdbcTime(aVal)); + setScalarParameter<TIME_STRUCT&>(parameterIndex, DataType::TIME, nColSize, (nColSize == 8)? 0 : nColSize-9, x); +} + + +void SAL_CALL OPreparedStatement::setTimestamp( sal_Int32 parameterIndex, const DateTime& aVal ) +{ + SQLULEN nColSize; + if(aVal.NanoSeconds == 0) + { + if (aVal.Seconds == 0) + nColSize=16; + else + nColSize=19; + } + else if(aVal.NanoSeconds % 100000000 == 0) + nColSize = 21; + else if(aVal.NanoSeconds % 10000000 == 0) + nColSize = 22; + else if(aVal.NanoSeconds % 1000000 == 0) + nColSize = 23; + else if(aVal.NanoSeconds % 100000 == 0) + nColSize = 24; + else if(aVal.NanoSeconds % 10000 == 0) + nColSize = 25; + else if(aVal.NanoSeconds % 1000 == 0) + nColSize = 26; + else if(aVal.NanoSeconds % 100 == 0) + nColSize = 27; + else if(aVal.NanoSeconds % 10 == 0) + nColSize = 28; + else + nColSize = 29; + + TIMESTAMP_STRUCT x(OTools::DateTimeToTimestamp(aVal)); + setScalarParameter<TIMESTAMP_STRUCT&>(parameterIndex, DataType::TIMESTAMP, nColSize, (nColSize <= 19)? 0 : nColSize-20, x); +} + + +void SAL_CALL OPreparedStatement::setDouble( sal_Int32 parameterIndex, double x ) +{ + setScalarParameter(parameterIndex, DataType::DOUBLE, 15, x); +} + + +void SAL_CALL OPreparedStatement::setFloat( sal_Int32 parameterIndex, float x ) +{ + setScalarParameter(parameterIndex, DataType::FLOAT, 15, x); +} + + +void SAL_CALL OPreparedStatement::setInt( sal_Int32 parameterIndex, sal_Int32 x ) +{ + setScalarParameter(parameterIndex, DataType::INTEGER, 10, 0, x); +} + + +void SAL_CALL OPreparedStatement::setLong( sal_Int32 parameterIndex, sal_Int64 x ) +{ + try + { + setScalarParameter(parameterIndex, DataType::BIGINT, 19, 0, x); + } + catch(SQLException&) + { + setString(parameterIndex, ORowSetValue(x).getString()); + } +} + + +void SAL_CALL OPreparedStatement::setNull( sal_Int32 parameterIndex, const sal_Int32 _nType ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + setParameterPre(parameterIndex); + + OSL_VERIFY(allocBindBuf(parameterIndex, 0) == nullptr); + SQLLEN * const lenBuf = getLengthBuf (parameterIndex); + *lenBuf = SQL_NULL_DATA; + + + SQLSMALLINT fCType; + SQLSMALLINT fSqlType; + + OTools::getBindTypes( bUseWChar, + m_pConnection->useOldDateFormat(), + OTools::jdbcTypeToOdbc(_nType), + fCType, + fSqlType); + + SQLRETURN nReturn = N3SQLBindParameter( m_aStatementHandle, + static_cast<SQLUSMALLINT>(parameterIndex), + SQL_PARAM_INPUT, + fCType, + fSqlType, + 0, + 0, + nullptr, + 0, + lenBuf + ); + OTools::ThrowException(m_pConnection.get(),nReturn,m_aStatementHandle,SQL_HANDLE_STMT,*this); +} + + +void SAL_CALL OPreparedStatement::setClob( sal_Int32 parameterIndex, const Reference< XClob >& x ) +{ + if ( x.is() ) + setStream(parameterIndex, x->getCharacterStream(), x->length(), DataType::LONGVARCHAR); +} + + +void SAL_CALL OPreparedStatement::setBlob( sal_Int32 parameterIndex, const Reference< XBlob >& x ) +{ + if ( x.is() ) + setStream(parameterIndex, x->getBinaryStream(), x->length(), DataType::LONGVARBINARY); +} + + +void SAL_CALL OPreparedStatement::setArray( sal_Int32 /*parameterIndex*/, const Reference< XArray >& /*x*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XParameters::setArray", *this ); +} + + +void SAL_CALL OPreparedStatement::setRef( sal_Int32 /*parameterIndex*/, const Reference< XRef >& /*x*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XParameters::setRef", *this ); +} + +void SAL_CALL OPreparedStatement::setObjectWithInfo( sal_Int32 parameterIndex, const Any& x, sal_Int32 sqlType, sal_Int32 scale ) +{ + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + prepareStatement(); + // For each known SQL Type, call the appropriate + // set routine + + switch (sqlType) + { + case DataType::CHAR: + case DataType::VARCHAR: + case DataType::LONGVARCHAR: + if(x.hasValue()) + { + OUString sStr; + x >>= sStr; + setParameter(parameterIndex, sqlType, scale, sStr); + } + else + setNull(parameterIndex,sqlType); + break; + case DataType::DECIMAL: + case DataType::NUMERIC: + if(x.hasValue()) + { + ORowSetValue aValue; + aValue.fill(x); + setParameter(parameterIndex, sqlType, scale, aValue.getString()); + } + else + setNull(parameterIndex,sqlType); + break; + default: + ::dbtools::setObjectWithInfo(this,parameterIndex,x,sqlType,scale); + } +} + + +void SAL_CALL OPreparedStatement::setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const OUString& /*typeName*/ ) +{ + setNull(parameterIndex,sqlType); +} + + +void SAL_CALL OPreparedStatement::setObject( sal_Int32 parameterIndex, const Any& x ) +{ + if (!::dbtools::implSetObject(this, parameterIndex, x)) + { // there is no other setXXX call which can handle the value in x + throw SQLException(); + } +} + + +void SAL_CALL OPreparedStatement::setShort( sal_Int32 parameterIndex, sal_Int16 x ) +{ + setScalarParameter(parameterIndex, DataType::SMALLINT, 5, 0, x); +} + + +void SAL_CALL OPreparedStatement::setBytes( sal_Int32 parameterIndex, const Sequence< sal_Int8 >& x ) +{ + setParameter(parameterIndex, DataType::BINARY, x); +} + + +void SAL_CALL OPreparedStatement::setCharacterStream( sal_Int32 parameterIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length ) +{ + // LEM: It is quite unclear to me what the interface here is. + // The XInputStream provides *bytes*, not characters. + setStream(parameterIndex, x, length, DataType::LONGVARCHAR); +} + + +void SAL_CALL OPreparedStatement::setBinaryStream( sal_Int32 parameterIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length ) +{ + setStream(parameterIndex, x, length, DataType::LONGVARBINARY); +} + + +void SAL_CALL OPreparedStatement::clearParameters( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + prepareStatement(); + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + N3SQLFreeStmt (m_aStatementHandle, SQL_RESET_PARAMS); + N3SQLFreeStmt (m_aStatementHandle, SQL_UNBIND); +} + +void SAL_CALL OPreparedStatement::clearBatch( ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XPreparedBatchExecution::clearBatch", *this ); + // clearParameters( ); + // m_aBatchVector.erase(); +} + + +void SAL_CALL OPreparedStatement::addBatch( ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XPreparedBatchExecution::addBatch", *this ); +} + + +Sequence< sal_Int32 > SAL_CALL OPreparedStatement::executeBatch( ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XPreparedBatchExecution::executeBatch", *this ); + // not reached, but keep -Werror happy + return Sequence< sal_Int32 > (); +} + + +// methods + + +// initBoundParam +// Initialize the bound parameter objects + + +void OPreparedStatement::initBoundParam () +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + // Get the number of parameters + numParams = 0; + N3SQLNumParams (m_aStatementHandle,&numParams); + + // There are parameter markers, allocate the bound + // parameter objects + + if (numParams > 0) + { + boundParams.reset(new OBoundParam[numParams]); + } +} + + +// allocBindBuf +// Allocate storage for the permanent data buffer for the bound +// parameter. + + +void* OPreparedStatement::allocBindBuf( sal_Int32 index,sal_Int32 bufLen) +{ + void* b = nullptr; + + // Sanity check the parameter number + + if ((index >= 1) && (index <= numParams)) + { + b = boundParams[index - 1].allocBindDataBuffer(bufLen); + } + + return b; +} + + +// getLengthBuf +// Gets the length buffer for the given parameter index + + +SQLLEN* OPreparedStatement::getLengthBuf (sal_Int32 index) +{ + SQLLEN* b = nullptr; + + // Sanity check the parameter number + + if ((index >= 1) && + (index <= numParams)) + { + b = &boundParams[index - 1].getBindLengthBuffer (); + } + + return b; +} + + +// putParamData +// Puts parameter data from a previously bound input stream. The +// input stream was bound using SQL_LEN_DATA_AT_EXEC. +void OPreparedStatement::putParamData (sal_Int32 index) +{ + // Sanity check the parameter index + if ((index < 1) || + (index > numParams)) + { + return; + } + + // We'll transfer up to MAX_PUT_DATA_LENGTH at a time + Sequence< sal_Int8 > buf( MAX_PUT_DATA_LENGTH ); + + // Get the information about the input stream + + Reference< XInputStream> inputStream = boundParams[index - 1].getInputStream (); + if ( !inputStream.is() ) + { + ::connectivity::SharedResources aResources; + const OUString sError( aResources.getResourceString(STR_NO_INPUTSTREAM)); + throw SQLException (sError, *this,OUString(),0,Any()); + } + + sal_Int32 maxBytesLeft = boundParams[index - 1].getInputStreamLen (); + + // Loop while more data from the input stream + sal_Int32 haveRead = 0; + try + { + + do + { + sal_Int32 toReadThisRound = std::min( MAX_PUT_DATA_LENGTH, maxBytesLeft ); + + // Read some data from the input stream + haveRead = inputStream->readBytes( buf, toReadThisRound ); + OSL_ENSURE( haveRead == buf.getLength(), "OPreparedStatement::putParamData: inconsistency!" ); + + if ( !haveRead ) + // no more data in the stream - the given stream length was a maximum which could not be + // fulfilled by the stream + break; + + // Put the data + OSL_ENSURE( m_aStatementHandle, "OPreparedStatement::putParamData: StatementHandle is null!" ); + N3SQLPutData ( m_aStatementHandle, buf.getArray(), buf.getLength() ); + + // decrement the number of bytes still needed + maxBytesLeft -= haveRead; + } + while ( maxBytesLeft > 0 ); + } + catch (const IOException& ex) + { + + // If an I/O exception was generated, turn + // it into a SQLException + + throw SQLException(ex.Message,*this,OUString(),0,Any()); + } +} + +// setStream +// Sets an input stream as a parameter, using the given SQL type +void OPreparedStatement::setStream( + sal_Int32 ParameterIndex, + const Reference< XInputStream>& x, + SQLLEN length, + sal_Int32 _nType) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + prepareStatement(); + + checkParameterIndex(ParameterIndex); + // Get the buffer needed for the length + + SQLLEN * const lenBuf = getLengthBuf(ParameterIndex); + + // Allocate a new buffer for the parameter data. This buffer + // will be returned by SQLParamData (it is set to the parameter + // number, a sal_Int32) + + sal_Int32* dataBuf = static_cast<sal_Int32*>( allocBindBuf(ParameterIndex, sizeof(ParameterIndex)) ); + *dataBuf = ParameterIndex; + + // Bind the parameter with SQL_LEN_DATA_AT_EXEC + *lenBuf = SQL_LEN_DATA_AT_EXEC (length); + + SQLSMALLINT fCType, fSqlType; + OTools::getBindTypes(bUseWChar, m_pConnection->useOldDateFormat(), OTools::jdbcTypeToOdbc(_nType), fCType, fSqlType); + + + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + N3SQLBindParameter(m_aStatementHandle, + static_cast<SQLUSMALLINT>(ParameterIndex), + SQL_PARAM_INPUT, + fCType, + fSqlType, + length, + invalid_scale, + dataBuf, + sizeof(ParameterIndex), + lenBuf); + + // Save the input stream + boundParams[ParameterIndex - 1].setInputStream (x, length); +} + + +void OPreparedStatement::FreeParams() +{ + numParams = 0; + boundParams.reset(); +} + +void OPreparedStatement::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) +{ + try + { + switch(nHandle) + { + case PROPERTY_ID_RESULTSETCONCURRENCY: + if(!isPrepared()) + setResultSetConcurrency(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_RESULTSETTYPE: + if(!isPrepared()) + setResultSetType(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_FETCHDIRECTION: + if(!isPrepared()) + setFetchDirection(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_USEBOOKMARKS: + if(!isPrepared()) + setUsingBookmarks(comphelper::getBOOL(rValue)); + break; + default: + OStatement_Base::setFastPropertyValue_NoBroadcast(nHandle,rValue); + } + } + catch(const SQLException&) + { + // throw Exception(e.Message,*this); + } +} + +void OPreparedStatement::prepareStatement() +{ + if(!isPrepared()) + { + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + OString aSql(OUStringToOString(m_sSqlStatement,getOwnConnection()->getTextEncoding())); + SQLRETURN nReturn = N3SQLPrepare(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(aSql.getStr())), aSql.getLength()); + OTools::ThrowException(m_pConnection.get(),nReturn,m_aStatementHandle,SQL_HANDLE_STMT,*this); + m_bPrepared = true; + initBoundParam(); + } +} + +void OPreparedStatement::checkParameterIndex(sal_Int32 _parameterIndex) +{ + if( _parameterIndex > numParams || + _parameterIndex < 1 || + _parameterIndex > std::numeric_limits<SQLUSMALLINT>::max() ) + { + ::connectivity::SharedResources aResources; + const OUString sError( aResources.getResourceStringWithSubstitution(STR_WRONG_PARAM_INDEX, + "$pos$", OUString::number(_parameterIndex), + "$count$", OUString::number(numParams) + )); + SQLException aNext(sError,*this, OUString(),0,Any()); + + ::dbtools::throwInvalidIndexException(*this,Any(aNext)); + } +} + +rtl::Reference<OResultSet> OPreparedStatement::createResultSet() +{ + rtl::Reference<OResultSet> pReturn = new OResultSet(m_aStatementHandle,this); + pReturn->setMetaData(getMetaData()); + return pReturn; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/ORealDriver.cxx b/connectivity/source/drivers/odbc/ORealDriver.cxx new file mode 100644 index 000000000..28c054b45 --- /dev/null +++ b/connectivity/source/drivers/odbc/ORealDriver.cxx @@ -0,0 +1,291 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/ODriver.hxx> +#include <odbc/OTools.hxx> +#include <odbc/OFunctions.hxx> + +namespace connectivity::odbc +{ + namespace { + + class ORealOdbcDriver : public ODBCDriver + { + protected: + virtual oslGenericFunction getOdbcFunction(ODBC3SQLFunctionId _nIndex) const override; + virtual SQLHANDLE EnvironmentHandle(OUString &_rPath) override; + public: + explicit ORealOdbcDriver(const css::uno::Reference< css::uno::XComponentContext >& _rxContext) : ODBCDriver(_rxContext) {} + }; + + } + +oslGenericFunction ORealOdbcDriver::getOdbcFunction(ODBC3SQLFunctionId _nIndex) const +{ + oslGenericFunction pFunction = nullptr; + switch(_nIndex) + { + case ODBC3SQLFunctionId::AllocHandle: + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLAllocHandle); + break; + case ODBC3SQLFunctionId::Connect: + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLConnect); + break; + case ODBC3SQLFunctionId::DriverConnect: + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLDriverConnect); + break; + case ODBC3SQLFunctionId::BrowseConnect: + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLBrowseConnect); + break; + case ODBC3SQLFunctionId::DataSources: + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLDataSources); + break; + case ODBC3SQLFunctionId::Drivers: + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLDrivers); + break; + case ODBC3SQLFunctionId::GetInfo: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetInfo); + break; + case ODBC3SQLFunctionId::GetFunctions: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetFunctions); + break; + case ODBC3SQLFunctionId::GetTypeInfo: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetTypeInfo); + break; + case ODBC3SQLFunctionId::SetConnectAttr: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLSetConnectAttr); + break; + case ODBC3SQLFunctionId::GetConnectAttr: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetConnectAttr); + break; + case ODBC3SQLFunctionId::SetEnvAttr: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLSetEnvAttr); + break; + case ODBC3SQLFunctionId::GetEnvAttr: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetEnvAttr); + break; + case ODBC3SQLFunctionId::SetStmtAttr: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLSetStmtAttr); + break; + case ODBC3SQLFunctionId::GetStmtAttr: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetStmtAttr); + break; + case ODBC3SQLFunctionId::Prepare: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLPrepare); + break; + case ODBC3SQLFunctionId::BindParameter: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLBindParameter); + break; + case ODBC3SQLFunctionId::SetCursorName: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLSetCursorName); + break; + case ODBC3SQLFunctionId::Execute: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLExecute); + break; + case ODBC3SQLFunctionId::ExecDirect: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLExecDirect); + break; + case ODBC3SQLFunctionId::DescribeParam: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLDescribeParam); + break; + case ODBC3SQLFunctionId::NumParams: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLNumParams); + break; + case ODBC3SQLFunctionId::ParamData: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLParamData); + break; + case ODBC3SQLFunctionId::PutData: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLPutData); + break; + case ODBC3SQLFunctionId::RowCount: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLRowCount); + break; + case ODBC3SQLFunctionId::NumResultCols: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLNumResultCols); + break; + case ODBC3SQLFunctionId::DescribeCol: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLDescribeCol); + break; + case ODBC3SQLFunctionId::ColAttribute: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLColAttribute); + break; + case ODBC3SQLFunctionId::BindCol: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLBindCol); + break; + case ODBC3SQLFunctionId::Fetch: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLFetch); + break; + case ODBC3SQLFunctionId::FetchScroll: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLFetchScroll); + break; + case ODBC3SQLFunctionId::GetData: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetData); + break; + case ODBC3SQLFunctionId::SetPos: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLSetPos); + break; + case ODBC3SQLFunctionId::BulkOperations: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLBulkOperations); + break; + case ODBC3SQLFunctionId::MoreResults: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLMoreResults); + break; + case ODBC3SQLFunctionId::GetDiagRec: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetDiagRec); + break; + case ODBC3SQLFunctionId::ColumnPrivileges: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLColumnPrivileges); + break; + case ODBC3SQLFunctionId::Columns: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLColumns); + break; + case ODBC3SQLFunctionId::ForeignKeys: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLForeignKeys); + break; + case ODBC3SQLFunctionId::PrimaryKeys: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLPrimaryKeys); + break; + case ODBC3SQLFunctionId::ProcedureColumns: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLProcedureColumns); + break; + case ODBC3SQLFunctionId::Procedures: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLProcedures); + break; + case ODBC3SQLFunctionId::SpecialColumns: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLSpecialColumns); + break; + case ODBC3SQLFunctionId::Statistics: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLStatistics); + break; + case ODBC3SQLFunctionId::TablePrivileges: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLTablePrivileges); + break; + case ODBC3SQLFunctionId::Tables: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLTables); + break; + case ODBC3SQLFunctionId::FreeStmt: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLFreeStmt); + break; + case ODBC3SQLFunctionId::CloseCursor: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLCloseCursor); + break; + case ODBC3SQLFunctionId::Cancel: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLCancel); + break; + case ODBC3SQLFunctionId::EndTran: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLEndTran); + break; + case ODBC3SQLFunctionId::Disconnect: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLDisconnect); + break; + case ODBC3SQLFunctionId::FreeHandle: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLFreeHandle); + break; + case ODBC3SQLFunctionId::GetCursorName: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLGetCursorName); + break; + case ODBC3SQLFunctionId::NativeSql: + + pFunction = reinterpret_cast<oslGenericFunction>(pODBC3SQLNativeSql); + break; + default: + OSL_FAIL("Function unknown!"); + } + return pFunction; +} + + +// ODBC Environment (common for all Connections): +SQLHANDLE ORealOdbcDriver::EnvironmentHandle(OUString &_rPath) +{ + // Is (for this instance) already an Environment made? + if (!m_pDriverHandle) + { + SQLHANDLE h = SQL_NULL_HANDLE; + // allocate Environment + + // load ODBC-DLL now: + if (!LoadLibrary_ODBC3(_rPath) || N3SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&h) != SQL_SUCCESS) + return SQL_NULL_HANDLE; + + // Save in global Structure + m_pDriverHandle = h; + N3SQLSetEnvAttr(h, SQL_ATTR_ODBC_VERSION, reinterpret_cast<SQLPOINTER>(SQL_OV_ODBC3), SQL_IS_UINTEGER); + //N3SQLSetEnvAttr(h, SQL_ATTR_CONNECTION_POOLING,(SQLPOINTER) SQL_CP_ONE_PER_HENV, SQL_IS_INTEGER); + } + + return m_pDriverHandle; +} + +} + +extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface* +connectivity_odbc_ORealOdbcDriver_get_implementation( + css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const&) +{ + return cppu::acquire(new connectivity::odbc::ORealOdbcDriver(context)); +} +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/OResultSet.cxx b/connectivity/source/drivers/odbc/OResultSet.cxx new file mode 100644 index 000000000..9e68cd176 --- /dev/null +++ b/connectivity/source/drivers/odbc/OResultSet.cxx @@ -0,0 +1,1847 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/OResultSet.hxx> +#include <odbc/OTools.hxx> +#include <odbc/OResultSetMetaData.hxx> +#include <com/sun/star/sdbc/DataType.hpp> +#include <com/sun/star/beans/PropertyAttribute.hpp> +#include <com/sun/star/beans/PropertyVetoException.hpp> +#include <com/sun/star/sdbcx/CompareBookmark.hpp> +#include <com/sun/star/sdbc/ResultSetConcurrency.hpp> +#include <com/sun/star/sdbc/ResultSetType.hpp> +#include <comphelper/property.hxx> +#include <comphelper/sequence.hxx> +#include <cppuhelper/typeprovider.hxx> +#include <cppuhelper/supportsservice.hxx> +#include <comphelper/types.hxx> +#include <connectivity/dbtools.hxx> +#include <connectivity/dbexception.hxx> +#include <o3tl/safeint.hxx> +#include <sal/log.hxx> + +using namespace ::comphelper; +using namespace connectivity; +using namespace connectivity::odbc; +using namespace cppu; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::sdbcx; +using namespace com::sun::star::container; +using namespace com::sun::star::io; +using namespace com::sun::star::util; + +#define ODBC_SQL_NOT_DEFINED 99UL +static_assert(ODBC_SQL_NOT_DEFINED != SQL_UB_OFF, "ODBC_SQL_NOT_DEFINED must be unique"); +static_assert(ODBC_SQL_NOT_DEFINED != SQL_UB_ON, "ODBC_SQL_NOT_DEFINED must be unique"); +static_assert(ODBC_SQL_NOT_DEFINED != SQL_UB_FIXED, "ODBC_SQL_NOT_DEFINED must be unique"); +static_assert(ODBC_SQL_NOT_DEFINED != SQL_UB_VARIABLE, "ODBC_SQL_NOT_DEFINED must be unique"); + +namespace +{ + const SQLLEN nMaxBookmarkLen = 20; +} + + +// IMPLEMENT_SERVICE_INFO(OResultSet,"com.sun.star.sdbcx.OResultSet","com.sun.star.sdbc.ResultSet"); +OUString SAL_CALL OResultSet::getImplementationName( ) +{ + return "com.sun.star.sdbcx.odbc.ResultSet"; +} + + Sequence< OUString > SAL_CALL OResultSet::getSupportedServiceNames( ) +{ + return { "com.sun.star.sdbc.ResultSet", "com.sun.star.sdbcx.ResultSet" }; +} + +sal_Bool SAL_CALL OResultSet::supportsService( const OUString& _rServiceName ) +{ + return cppu::supportsService(this, _rServiceName); +} + + +OResultSet::OResultSet(SQLHANDLE _pStatementHandle ,OStatement_Base* pStmt) : OResultSet_BASE(m_aMutex) + ,OPropertySetHelper(OResultSet_BASE::rBHelper) + ,m_bFetchDataInOrder(true) + ,m_aStatementHandle(_pStatementHandle) + ,m_aConnectionHandle(pStmt->getConnectionHandle()) + ,m_pStatement(pStmt) + ,m_xStatement(*pStmt) + ,m_nTextEncoding(pStmt->getOwnConnection()->getTextEncoding()) + ,m_nRowPos(0) + ,m_nUseBookmarks(ODBC_SQL_NOT_DEFINED) + ,m_nCurrentFetchState(0) + ,m_bWasNull(true) + ,m_bEOF(true) + ,m_bRowInserted(false) + ,m_bRowDeleted(false) + ,m_bUseFetchScroll(false) +{ + osl_atomic_increment( &m_refCount ); + try + { + m_pRowStatusArray.reset( new SQLUSMALLINT[1] ); // the default value + setStmtOption<SQLUSMALLINT*, SQL_IS_POINTER>(SQL_ATTR_ROW_STATUS_PTR, m_pRowStatusArray.get()); + } + catch(const Exception&) + { // we don't want our result destroy here + } + + try + { + SQLULEN nCurType = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE); + SQLUINTEGER nValueLen = m_pStatement->getCursorProperties(nCurType,false); + if( (nValueLen & SQL_CA2_SENSITIVITY_DELETIONS) != SQL_CA2_SENSITIVITY_DELETIONS || + (nValueLen & SQL_CA2_CRC_EXACT) != SQL_CA2_CRC_EXACT) + m_pSkipDeletedSet.reset( new OSkipDeletedSet(this) ); + } + catch(const Exception&) + { // we don't want our result destroy here + } + try + { + SQLUINTEGER nValueLen = 0; + // Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms715441%28v=vs.85%29.aspx + // LibreOffice ODBC binds columns only on update, so we don't care about SQL_GD_ANY_COLUMN / SQL_GD_BOUND + // TODO: maybe a problem if a column is updated, then an earlier column fetched? + // an updated column is bound... + // TODO: aren't we assuming SQL_GD_OUTPUT_PARAMS? + // If yes, we should at least OSL_ENSURE it, + // even better throw an exception any OUT parameter registration if !SQL_GD_OUTPUT_PARAMS. + // If !SQL_GD_ANY_ORDER, cache the whole row so that callers can access columns in any order. + // In other words, isolate them from ODBC restrictions. + // TODO: we assume SQL_GD_BLOCK, unless fetchSize is 1 + OTools::GetInfo(m_pStatement->getOwnConnection(),m_aConnectionHandle,SQL_GETDATA_EXTENSIONS,nValueLen,nullptr); + m_bFetchDataInOrder = ((SQL_GD_ANY_ORDER & nValueLen) != SQL_GD_ANY_ORDER); + } + catch(const Exception&) + { + m_bFetchDataInOrder = true; + } + try + { + // TODO: this does *not* do what it appears. + // We use SQLFetchScroll unconditionally in several places + // the *only* difference this makes is whether ::next() uses SQLFetchScroll or SQLFetch + // so this test seems pointless + if ( getOdbcFunction(ODBC3SQLFunctionId::GetFunctions) ) + { + SQLUSMALLINT nSupported = 0; + m_bUseFetchScroll = ( N3SQLGetFunctions(m_aConnectionHandle,SQL_API_SQLFETCHSCROLL,&nSupported) == SQL_SUCCESS && nSupported == 1 ); + } + } + catch(const Exception&) + { + m_bUseFetchScroll = false; + } + + osl_atomic_decrement( &m_refCount ); +} + +OResultSet::~OResultSet() +{ +} + +void OResultSet::construct() +{ + osl_atomic_increment( &m_refCount ); + allocBuffer(); + osl_atomic_decrement( &m_refCount ); +} + +void OResultSet::disposing() +{ + N3SQLCloseCursor(m_aStatementHandle); + OPropertySetHelper::disposing(); + + ::osl::MutexGuard aGuard(m_aMutex); + releaseBuffer(); + + setStmtOption<SQLUSMALLINT*, SQL_IS_POINTER>(SQL_ATTR_ROW_STATUS_PTR, nullptr); + m_xStatement.clear(); + m_xMetaData.clear(); +} + +SQLRETURN OResultSet::unbind(bool _bUnbindHandle) +{ + SQLRETURN nRet = 0; + if ( _bUnbindHandle ) + nRet = N3SQLFreeStmt(m_aStatementHandle,SQL_UNBIND); + + if ( !m_aBindVector.empty() ) + { + for(auto& [rPtrAddr, rType] : m_aBindVector) + { + switch (rType) + { + case DataType::CHAR: + case DataType::VARCHAR: + delete static_cast< OString* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::BIGINT: + delete static_cast< sal_Int64* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::DECIMAL: + case DataType::NUMERIC: + delete static_cast< OString* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::REAL: + case DataType::DOUBLE: + delete static_cast< double* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::LONGVARCHAR: + case DataType::CLOB: + delete [] static_cast< char* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::LONGVARBINARY: + case DataType::BLOB: + delete [] static_cast< char* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::DATE: + delete static_cast< DATE_STRUCT* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::TIME: + delete static_cast< TIME_STRUCT* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::TIMESTAMP: + delete static_cast< TIMESTAMP_STRUCT* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::BIT: + case DataType::TINYINT: + delete static_cast< sal_Int8* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::SMALLINT: + delete static_cast< sal_Int16* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::INTEGER: + delete static_cast< sal_Int32* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::FLOAT: + delete static_cast< float* >(reinterpret_cast< void * >(rPtrAddr)); + break; + case DataType::BINARY: + case DataType::VARBINARY: + delete static_cast< sal_Int8* >(reinterpret_cast< void * >(rPtrAddr)); + break; + } + } + m_aBindVector.clear(); + } + return nRet; +} + +TVoidPtr OResultSet::allocBindColumn(sal_Int32 _nType,sal_Int32 _nColumnIndex) +{ + TVoidPtr aPair; + switch (_nType) + { + case DataType::CHAR: + case DataType::VARCHAR: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new OString()),_nType); + break; + case DataType::BIGINT: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new sal_Int64(0)),_nType); + break; + case DataType::DECIMAL: + case DataType::NUMERIC: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new OString()),_nType); + break; + case DataType::REAL: + case DataType::DOUBLE: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new double(0.0)),_nType); + break; + case DataType::LONGVARCHAR: + case DataType::CLOB: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new char[2]),_nType); // only for finding + break; + case DataType::LONGVARBINARY: + case DataType::BLOB: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new char[2]),_nType); // only for finding + break; + case DataType::DATE: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new DATE_STRUCT),_nType); + break; + case DataType::TIME: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new TIME_STRUCT),_nType); + break; + case DataType::TIMESTAMP: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new TIMESTAMP_STRUCT),_nType); + break; + case DataType::BIT: + case DataType::TINYINT: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new sal_Int8(0)),_nType); + break; + case DataType::SMALLINT: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new sal_Int16(0)),_nType); + break; + case DataType::INTEGER: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new sal_Int32(0)),_nType); + break; + case DataType::FLOAT: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new float(0)),_nType); + break; + case DataType::BINARY: + case DataType::VARBINARY: + aPair = TVoidPtr(reinterpret_cast< sal_Int64 >(new sal_Int8[m_aRow[_nColumnIndex].getSequence().getLength()]),_nType); + break; + default: + SAL_WARN( "connectivity.odbc", "Unknown type"); + aPair = TVoidPtr(0,_nType); + } + return aPair; +} + +void OResultSet::allocBuffer() +{ + Reference< XResultSetMetaData > xMeta = getMetaData(); + sal_Int32 nLen = xMeta->getColumnCount(); + + m_aBindVector.reserve(nLen); + m_aRow.resize(nLen+1); + + m_aRow[0].setTypeKind(DataType::VARBINARY); + m_aRow[0].setBound( false ); + + for(sal_Int32 i = 1;i<=nLen;++i) + { + sal_Int32 nType = xMeta->getColumnType(i); + m_aRow[i].setTypeKind( nType ); + m_aRow[i].setBound( false ); + } + m_aLengthVector.resize(nLen + 1); +} + +void OResultSet::releaseBuffer() +{ + unbind(false); + m_aLengthVector.clear(); +} + +Any SAL_CALL OResultSet::queryInterface( const Type & rType ) +{ + Any aRet = OPropertySetHelper::queryInterface(rType); + return aRet.hasValue() ? aRet : OResultSet_BASE::queryInterface(rType); +} + + Sequence< Type > SAL_CALL OResultSet::getTypes( ) +{ + OTypeCollection aTypes( cppu::UnoType<css::beans::XMultiPropertySet>::get(), + cppu::UnoType<css::beans::XFastPropertySet>::get(), + cppu::UnoType<css::beans::XPropertySet>::get()); + + return ::comphelper::concatSequences(aTypes.getTypes(),OResultSet_BASE::getTypes()); +} + + +sal_Int32 SAL_CALL OResultSet::findColumn( const OUString& columnName ) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + ::osl::MutexGuard aGuard( m_aMutex ); + + Reference< XResultSetMetaData > xMeta = getMetaData(); + sal_Int32 nLen = xMeta->getColumnCount(); + sal_Int32 i = 1; + for(;i<=nLen;++i) + { + if(xMeta->isCaseSensitive(i) ? columnName == xMeta->getColumnName(i) : + columnName.equalsIgnoreAsciiCase(xMeta->getColumnName(i))) + return i; + } + + ::dbtools::throwInvalidColumnException( columnName, *this ); + assert(false); + return 0; // Never reached +} + +void OResultSet::ensureCacheForColumn(sal_Int32 columnIndex) +{ + SAL_INFO( "connectivity.odbc", "odbc lionel@mamane.lu OResultSet::ensureCacheForColumn" ); + + assert(columnIndex >= 0); + + const TDataRow::size_type oldCacheSize = m_aRow.size(); + const TDataRow::size_type uColumnIndex = static_cast<TDataRow::size_type>(columnIndex); + + if (oldCacheSize > uColumnIndex) + // nothing to do + return; + + m_aRow.resize(columnIndex + 1); + TDataRow::iterator i (m_aRow.begin() + oldCacheSize); + const TDataRow::const_iterator end(m_aRow.end()); + for (; i != end; ++i) + { + i->setBound(false); + } +} +void OResultSet::invalidateCache() +{ + for(auto& rItem : m_aRow) + { + rItem.setBound(false); + } +} + +Reference< XInputStream > SAL_CALL OResultSet::getBinaryStream( sal_Int32 /*columnIndex*/ ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getBinaryStream", *this ); + + return nullptr; +} + +Reference< XInputStream > SAL_CALL OResultSet::getCharacterStream( sal_Int32 /*columnIndex*/ ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getBinaryStream", *this ); + + return nullptr; +} + +template < typename T > T OResultSet::impl_getValue( const sal_Int32 _nColumnIndex, SQLSMALLINT nType ) +{ + T val; + + OTools::getValue(m_pStatement->getOwnConnection(), m_aStatementHandle, _nColumnIndex, nType, m_bWasNull, **this, &val, sizeof(val)); + + return val; +} + +// this function exists for the implicit conversion to sal_Bool (compared to a direct call to impl_getValue) +bool OResultSet::impl_getBoolean( sal_Int32 columnIndex ) +{ + return impl_getValue<sal_Int8>(columnIndex, SQL_C_BIT); +} + +template < typename T > T OResultSet::getValue( sal_Int32 columnIndex ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + fillColumn(columnIndex); + m_bWasNull = m_aRow[columnIndex].isNull(); + auto const & row = m_aRow[columnIndex]; + if constexpr ( std::is_same_v<css::util::Time, T> ) + return row.getTime(); + else if constexpr ( std::is_same_v<css::util::DateTime, T> ) + return row.getDateTime(); + else if constexpr ( std::is_same_v<css::util::Date, T> ) + return row.getDate(); + else if constexpr ( std::is_same_v<OUString, T> ) + return row.getString(); + else if constexpr ( std::is_same_v<sal_Int64, T> ) + return row.getLong(); + else if constexpr ( std::is_same_v<sal_Int32, T> ) + return row.getInt32(); + else if constexpr ( std::is_same_v<sal_Int16, T> ) + return row.getInt16(); + else if constexpr ( std::is_same_v<sal_Int8, T> ) + return row.getInt8(); + else if constexpr ( std::is_same_v<float, T> ) + return row.getFloat(); + else if constexpr ( std::is_same_v<double, T> ) + return row.getDouble(); + else if constexpr ( std::is_same_v<bool, T> ) + return row.getBool(); + else + return row; +} + +sal_Bool SAL_CALL OResultSet::getBoolean( sal_Int32 columnIndex ) +{ + return getValue<bool>( columnIndex ); +} + +sal_Int8 SAL_CALL OResultSet::getByte( sal_Int32 columnIndex ) +{ + return getValue<sal_Int8>( columnIndex ); +} + + +Sequence< sal_Int8 > SAL_CALL OResultSet::getBytes( sal_Int32 columnIndex ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + fillColumn(columnIndex); + m_bWasNull = m_aRow[columnIndex].isNull(); + + Sequence< sal_Int8 > nRet; + switch(m_aRow[columnIndex].getTypeKind()) + { + case DataType::BINARY: + case DataType::VARBINARY: + case DataType::LONGVARBINARY: + nRet = m_aRow[columnIndex].getSequence(); + break; + default: + { + OUString const & sRet = m_aRow[columnIndex].getString(); + nRet = Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(sRet.getStr()),sizeof(sal_Unicode)*sRet.getLength()); + } + } + return nRet; +} +Sequence< sal_Int8 > OResultSet::impl_getBytes( sal_Int32 columnIndex ) +{ + const SWORD nColumnType = impl_getColumnType_nothrow(columnIndex); + + switch(nColumnType) + { + case SQL_WVARCHAR: + case SQL_WCHAR: + case SQL_WLONGVARCHAR: + case SQL_VARCHAR: + case SQL_CHAR: + case SQL_LONGVARCHAR: + { + OUString const & aRet = OTools::getStringValue(m_pStatement->getOwnConnection(),m_aStatementHandle,columnIndex,nColumnType,m_bWasNull,**this,m_nTextEncoding); + return Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(aRet.getStr()),sizeof(sal_Unicode)*aRet.getLength()); + } + default: + return OTools::getBytesValue(m_pStatement->getOwnConnection(),m_aStatementHandle,columnIndex,SQL_C_BINARY,m_bWasNull,**this); + } +} + +Date OResultSet::impl_getDate( sal_Int32 columnIndex ) +{ + DATE_STRUCT aDate = impl_getValue< DATE_STRUCT> ( columnIndex, + m_pStatement->getOwnConnection()->useOldDateFormat() ? SQL_C_DATE : SQL_C_TYPE_DATE ); + + return Date(aDate.day, aDate.month, aDate.year); +} + +Date SAL_CALL OResultSet::getDate( sal_Int32 columnIndex ) +{ + return getValue<Date>( columnIndex ); +} + + +double SAL_CALL OResultSet::getDouble( sal_Int32 columnIndex ) +{ + return getValue<double>( columnIndex ); +} + + +float SAL_CALL OResultSet::getFloat( sal_Int32 columnIndex ) +{ + return getValue<float>( columnIndex ); +} + +sal_Int16 SAL_CALL OResultSet::getShort( sal_Int32 columnIndex ) +{ + return getValue<sal_Int16>( columnIndex ); +} + +sal_Int32 SAL_CALL OResultSet::getInt( sal_Int32 columnIndex ) +{ + return getValue<sal_Int32>( columnIndex ); +} + +sal_Int64 SAL_CALL OResultSet::getLong( sal_Int32 columnIndex ) +{ + return getValue<sal_Int64>( columnIndex ); +} +sal_Int64 OResultSet::impl_getLong( sal_Int32 columnIndex ) +{ + try + { + return impl_getValue<sal_Int64>(columnIndex, SQL_C_SBIGINT); + } + catch(const SQLException&) + { + return getString(columnIndex).toInt64(); + } +} + +sal_Int32 SAL_CALL OResultSet::getRow( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return m_pSkipDeletedSet ? m_pSkipDeletedSet->getMappedPosition(getDriverPos()) : getDriverPos(); +} + +Reference< XResultSetMetaData > SAL_CALL OResultSet::getMetaData( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + if(!m_xMetaData.is()) + m_xMetaData = new OResultSetMetaData(m_pStatement->getOwnConnection(),m_aStatementHandle); + return m_xMetaData; +} + +Reference< XArray > SAL_CALL OResultSet::getArray( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getArray", *this ); + return nullptr; +} + + +Reference< XClob > SAL_CALL OResultSet::getClob( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getClob", *this ); + return nullptr; +} + +Reference< XBlob > SAL_CALL OResultSet::getBlob( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getBlob", *this ); + return nullptr; +} + + +Reference< XRef > SAL_CALL OResultSet::getRef( sal_Int32 /*columnIndex*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRow::getRef", *this ); + return nullptr; +} + + +Any SAL_CALL OResultSet::getObject( sal_Int32 columnIndex, const Reference< css::container::XNameAccess >& /*typeMap*/ ) +{ + return getValue<ORowSetValue>( columnIndex ).makeAny(); +} + +OUString OResultSet::impl_getString( sal_Int32 columnIndex ) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + const SWORD nColumnType = impl_getColumnType_nothrow(columnIndex); + return OTools::getStringValue(m_pStatement->getOwnConnection(),m_aStatementHandle,columnIndex,nColumnType,m_bWasNull,**this,m_nTextEncoding); +} +OUString OResultSet::getString( sal_Int32 columnIndex ) +{ + return getValue<OUString>( columnIndex ); +} + +Time OResultSet::impl_getTime( sal_Int32 columnIndex ) +{ + TIME_STRUCT aTime = impl_getValue< TIME_STRUCT > ( columnIndex, + m_pStatement->getOwnConnection()->useOldDateFormat() ? SQL_C_TIME : SQL_C_TYPE_TIME ); + + return Time(0, aTime.second,aTime.minute,aTime.hour, false); +} +Time SAL_CALL OResultSet::getTime( sal_Int32 columnIndex ) +{ + return getValue<Time>( columnIndex ); +} + +DateTime OResultSet::impl_getTimestamp( sal_Int32 columnIndex ) +{ + TIMESTAMP_STRUCT aTime = impl_getValue< TIMESTAMP_STRUCT > ( columnIndex, + m_pStatement->getOwnConnection()->useOldDateFormat() ? SQL_C_TIMESTAMP : SQL_C_TYPE_TIMESTAMP ); + + return DateTime(aTime.fraction, + aTime.second, + aTime.minute, + aTime.hour, + aTime.day, + aTime.month, + aTime.year, + false); +} +DateTime SAL_CALL OResultSet::getTimestamp( sal_Int32 columnIndex ) +{ + return getValue<DateTime>( columnIndex ); +} + +sal_Bool SAL_CALL OResultSet::isBeforeFirst( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + return m_nRowPos == 0; +} + +sal_Bool SAL_CALL OResultSet::isAfterLast( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return m_nRowPos != 0 && m_nCurrentFetchState == SQL_NO_DATA; +} + +sal_Bool SAL_CALL OResultSet::isFirst( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return m_nRowPos == 1; +} + +sal_Bool SAL_CALL OResultSet::isLast( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return m_bEOF && m_nCurrentFetchState != SQL_NO_DATA; +} + +void SAL_CALL OResultSet::beforeFirst( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + if(first()) + previous(); + m_nCurrentFetchState = SQL_SUCCESS; +} + +void SAL_CALL OResultSet::afterLast( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + if(last()) + next(); + m_bEOF = true; +} + + +void SAL_CALL OResultSet::close( ) +{ + { + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + } + dispose(); +} + + +sal_Bool SAL_CALL OResultSet::first( ) +{ + return moveImpl(IResultSetHelper::FIRST,0); +} + + +sal_Bool SAL_CALL OResultSet::last( ) +{ + return moveImpl(IResultSetHelper::LAST,0); +} + +sal_Bool SAL_CALL OResultSet::absolute( sal_Int32 row ) +{ + return moveImpl(IResultSetHelper::ABSOLUTE1,row); +} + +sal_Bool SAL_CALL OResultSet::relative( sal_Int32 row ) +{ + return moveImpl(IResultSetHelper::RELATIVE1,row); +} + +sal_Bool SAL_CALL OResultSet::previous( ) +{ + return moveImpl(IResultSetHelper::PRIOR,0); +} + +Reference< XInterface > SAL_CALL OResultSet::getStatement( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + return m_xStatement; +} + + +sal_Bool SAL_CALL OResultSet::rowDeleted() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + bool bRet = m_bRowDeleted; + m_bRowDeleted = false; + + return bRet; +} + +sal_Bool SAL_CALL OResultSet::rowInserted( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + bool bInserted = m_bRowInserted; + m_bRowInserted = false; + + return bInserted; +} + +sal_Bool SAL_CALL OResultSet::rowUpdated( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return m_pRowStatusArray[0] == SQL_ROW_UPDATED; +} + + +sal_Bool SAL_CALL OResultSet::next( ) +{ + return moveImpl(IResultSetHelper::NEXT,1); +} + + +sal_Bool SAL_CALL OResultSet::wasNull( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return m_bWasNull; +} + + +void SAL_CALL OResultSet::cancel( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + N3SQLCancel(m_aStatementHandle); +} + +void SAL_CALL OResultSet::clearWarnings( ) +{ +} + +Any SAL_CALL OResultSet::getWarnings( ) +{ + return Any(); +} + +void SAL_CALL OResultSet::insertRow( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + SQLLEN nRealLen = 0; + Sequence<sal_Int8> aBookmark(nMaxBookmarkLen); + static_assert(o3tl::make_unsigned(nMaxBookmarkLen) >= sizeof(SQLLEN), "must be larger"); + + SQLRETURN nRet = N3SQLBindCol(m_aStatementHandle, + 0, + SQL_C_VARBOOKMARK, + aBookmark.getArray(), + nMaxBookmarkLen, + &nRealLen + ); + + bool bPositionByBookmark = ( nullptr != getOdbcFunction( ODBC3SQLFunctionId::BulkOperations ) ); + if ( bPositionByBookmark ) + { + nRet = N3SQLBulkOperations( m_aStatementHandle, SQL_ADD ); + fillNeededData( nRet ); + } + else + { + if(isBeforeFirst()) + next(); // must be done + nRet = N3SQLSetPos( m_aStatementHandle, 1, SQL_ADD, SQL_LOCK_NO_CHANGE ); + fillNeededData( nRet ); + } + aBookmark.realloc(nRealLen); + try + { + OTools::ThrowException(m_pStatement->getOwnConnection(),nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + } + catch(const SQLException&) + { + nRet = unbind(); + throw; + } + + nRet = unbind(); + OTools::ThrowException(m_pStatement->getOwnConnection(),nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + if ( bPositionByBookmark ) + { + setStmtOption<SQLLEN*, SQL_IS_POINTER>(SQL_ATTR_FETCH_BOOKMARK_PTR, reinterpret_cast<SQLLEN*>(aBookmark.getArray())); + + nRet = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_BOOKMARK,0); + } + else + nRet = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_RELATIVE,0); // OJ 06.03.2004 + // sometimes we got an error but we are not interested in anymore #106047# OJ + // OTools::ThrowException(m_pStatement->getOwnConnection(),nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + if(m_pSkipDeletedSet) + { + if(moveToBookmark(Any(aBookmark))) + { + sal_Int32 nRowPos = getDriverPos(); + if ( -1 == m_nRowPos ) + { + nRowPos = m_aPosToBookmarks.size() + 1; + } + if ( nRowPos == m_nRowPos ) + ++nRowPos; + m_nRowPos = nRowPos; + m_pSkipDeletedSet->insertNewPosition(nRowPos); + m_aPosToBookmarks[aBookmark] = nRowPos; + } + } + m_bRowInserted = true; + +} + +void SAL_CALL OResultSet::updateRow( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + SQLRETURN nRet; + + try + { + bool bPositionByBookmark = ( nullptr != getOdbcFunction( ODBC3SQLFunctionId::BulkOperations ) ); + if ( bPositionByBookmark ) + { + getBookmark(); + assert(m_aRow[0].isBound()); + Sequence<sal_Int8> aBookmark(m_aRow[0].getSequence()); + SQLLEN nRealLen = aBookmark.getLength(); + nRet = N3SQLBindCol(m_aStatementHandle, + 0, + SQL_C_VARBOOKMARK, + aBookmark.getArray(), + aBookmark.getLength(), + &nRealLen + ); + OTools::ThrowException(m_pStatement->getOwnConnection(),nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + nRet = N3SQLBulkOperations(m_aStatementHandle, SQL_UPDATE_BY_BOOKMARK); + fillNeededData(nRet); + // the driver should not have touched this + // (neither the contents of aBookmark FWIW) + assert(nRealLen == aBookmark.getLength()); + } + else + { + nRet = N3SQLSetPos(m_aStatementHandle,1,SQL_UPDATE,SQL_LOCK_NO_CHANGE); + fillNeededData(nRet); + } + OTools::ThrowException(m_pStatement->getOwnConnection(),nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + // unbind all columns so we can fetch all columns again with SQLGetData + // (and also so that our buffers don't clobber anything, and + // so that a subsequent fetch does not overwrite m_aRow[0]) + invalidateCache(); + nRet = unbind(); + OSL_ENSURE(nRet == SQL_SUCCESS,"ODBC insert could not unbind the columns after success"); + } + catch(...) + { + // unbind all columns so that a subsequent fetch does not overwrite m_aRow[0] + nRet = unbind(); + OSL_ENSURE(nRet == SQL_SUCCESS,"ODBC insert could not unbind the columns after failure"); + throw; + } +} + +void SAL_CALL OResultSet::deleteRow( ) +{ + SQLRETURN nRet = SQL_SUCCESS; + sal_Int32 nPos = getDriverPos(); + nRet = N3SQLSetPos(m_aStatementHandle,1,SQL_DELETE,SQL_LOCK_NO_CHANGE); + OTools::ThrowException(m_pStatement->getOwnConnection(),nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + m_bRowDeleted = ( m_pRowStatusArray[0] == SQL_ROW_DELETED ); + if ( m_bRowDeleted ) + { + TBookmarkPosMap::iterator aIter = std::find_if(m_aPosToBookmarks.begin(), m_aPosToBookmarks.end(), + [&nPos](const TBookmarkPosMap::value_type& rEntry) { return rEntry.second == nPos; }); + if (aIter != m_aPosToBookmarks.end()) + m_aPosToBookmarks.erase(aIter); + } + if ( m_pSkipDeletedSet ) + m_pSkipDeletedSet->deletePosition(nPos); +} + + +void SAL_CALL OResultSet::cancelRowUpdates( ) +{ +} + + +void SAL_CALL OResultSet::moveToInsertRow( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + invalidateCache(); + // first unbound all columns + OSL_VERIFY( unbind() == SQL_SUCCESS ); + // SQLRETURN nRet = N3SQLSetStmtAttr(m_aStatementHandle,SQL_ATTR_ROW_ARRAY_SIZE ,(SQLPOINTER)1,SQL_IS_INTEGER); +} + + +void SAL_CALL OResultSet::moveToCurrentRow( ) +{ + invalidateCache(); +} + +void OResultSet::updateValue(sal_Int32 columnIndex, SQLSMALLINT _nType, void const * _pValue) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + m_aBindVector.push_back(allocBindColumn(OTools::MapOdbcType2Jdbc(_nType),columnIndex)); + void* pData = reinterpret_cast<void*>(m_aBindVector.rbegin()->first); + OSL_ENSURE(pData != nullptr,"Data for update is NULL!"); + OTools::bindValue( m_pStatement->getOwnConnection(), + m_aStatementHandle, + columnIndex, + _nType, + 0, + _pValue, + pData, + &m_aLengthVector[columnIndex], + **this, + m_nTextEncoding, + m_pStatement->getOwnConnection()->useOldDateFormat()); +} + +void SAL_CALL OResultSet::updateNull( sal_Int32 columnIndex ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + m_aBindVector.push_back(allocBindColumn(DataType::CHAR,columnIndex)); + void* pData = reinterpret_cast<void*>(m_aBindVector.rbegin()->first); + OTools::bindValue(m_pStatement->getOwnConnection(),m_aStatementHandle,columnIndex,SQL_CHAR,0,nullptr,pData,&m_aLengthVector[columnIndex],**this,m_nTextEncoding,m_pStatement->getOwnConnection()->useOldDateFormat()); +} + + +void SAL_CALL OResultSet::updateBoolean( sal_Int32 columnIndex, sal_Bool x ) +{ + updateValue(columnIndex,SQL_BIT,&x); +} + +void SAL_CALL OResultSet::updateByte( sal_Int32 columnIndex, sal_Int8 x ) +{ + updateValue(columnIndex,SQL_CHAR,&x); +} + + +void SAL_CALL OResultSet::updateShort( sal_Int32 columnIndex, sal_Int16 x ) +{ + updateValue(columnIndex,SQL_TINYINT,&x); +} + +void SAL_CALL OResultSet::updateInt( sal_Int32 columnIndex, sal_Int32 x ) +{ + updateValue(columnIndex,SQL_INTEGER,&x); +} + +void SAL_CALL OResultSet::updateLong( sal_Int32 /*columnIndex*/, sal_Int64 /*x*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRowUpdate::updateLong", *this ); +} + +void SAL_CALL OResultSet::updateFloat( sal_Int32 columnIndex, float x ) +{ + updateValue(columnIndex,SQL_REAL,&x); +} + + +void SAL_CALL OResultSet::updateDouble( sal_Int32 columnIndex, double x ) +{ + updateValue(columnIndex,SQL_DOUBLE,&x); +} + +void SAL_CALL OResultSet::updateString( sal_Int32 columnIndex, const OUString& x ) +{ + sal_Int32 nType = m_aRow[columnIndex].getTypeKind(); + SQLSMALLINT nOdbcType = OTools::jdbcTypeToOdbc(nType); + m_aRow[columnIndex] = x; + m_aRow[columnIndex].setTypeKind(nType); // OJ: otherwise longvarchar will be recognized by fillNeededData + m_aRow[columnIndex].setBound(true); + updateValue(columnIndex,nOdbcType, &x); +} + +void SAL_CALL OResultSet::updateBytes( sal_Int32 columnIndex, const Sequence< sal_Int8 >& x ) +{ + sal_Int32 nType = m_aRow[columnIndex].getTypeKind(); + SQLSMALLINT nOdbcType = OTools::jdbcTypeToOdbc(nType); + m_aRow[columnIndex] = x; + m_aRow[columnIndex].setTypeKind(nType); // OJ: otherwise longvarbinary will be recognized by fillNeededData + m_aRow[columnIndex].setBound(true); + updateValue(columnIndex,nOdbcType, &x); +} + +void SAL_CALL OResultSet::updateDate( sal_Int32 columnIndex, const Date& x ) +{ + DATE_STRUCT aVal = OTools::DateToOdbcDate(x); + updateValue(columnIndex,SQL_DATE,&aVal); +} + + +void SAL_CALL OResultSet::updateTime( sal_Int32 columnIndex, const css::util::Time& x ) +{ + TIME_STRUCT aVal = OTools::TimeToOdbcTime(x); + updateValue(columnIndex,SQL_TIME,&aVal); +} + + +void SAL_CALL OResultSet::updateTimestamp( sal_Int32 columnIndex, const DateTime& x ) +{ + TIMESTAMP_STRUCT aVal = OTools::DateTimeToTimestamp(x); + updateValue(columnIndex,SQL_TIMESTAMP,&aVal); +} + + +void SAL_CALL OResultSet::updateBinaryStream( sal_Int32 columnIndex, const Reference< XInputStream >& x, sal_Int32 length ) +{ + if(!x.is()) + ::dbtools::throwFunctionSequenceException(*this); + + Sequence<sal_Int8> aSeq; + x->readBytes(aSeq,length); + updateBytes(columnIndex,aSeq); +} + +void SAL_CALL OResultSet::updateCharacterStream( sal_Int32 columnIndex, const Reference< XInputStream >& x, sal_Int32 length ) +{ + updateBinaryStream(columnIndex,x,length); +} + +void SAL_CALL OResultSet::refreshRow( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + // SQLRETURN nRet = N3SQLSetPos(m_aStatementHandle,1,SQL_REFRESH,SQL_LOCK_NO_CHANGE); + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_RELATIVE,0); + OTools::ThrowException(m_pStatement->getOwnConnection(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); +} + +void SAL_CALL OResultSet::updateObject( sal_Int32 columnIndex, const Any& x ) +{ + if (!::dbtools::implUpdateObject(this, columnIndex, x)) + throw SQLException(); +} + + +void SAL_CALL OResultSet::updateNumericObject( sal_Int32 columnIndex, const Any& x, sal_Int32 /*scale*/ ) +{ + if (!::dbtools::implUpdateObject(this, columnIndex, x)) + throw SQLException(); +} + +// XRowLocate +Any SAL_CALL OResultSet::getBookmark( ) +{ + fillColumn(0); + if(m_aRow[0].isNull()) + throw SQLException(); + return m_aRow[0].makeAny(); +} +Sequence<sal_Int8> OResultSet::impl_getBookmark( ) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + TBookmarkPosMap::const_iterator aFind = std::find_if(m_aPosToBookmarks.begin(),m_aPosToBookmarks.end(), + [this] (const TBookmarkPosMap::value_type& bookmarkPos) { + return bookmarkPos.second == m_nRowPos; + }); + + if ( aFind == m_aPosToBookmarks.end() ) + { + if ( m_nUseBookmarks == ODBC_SQL_NOT_DEFINED ) + { + m_nUseBookmarks = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS); + } + if(m_nUseBookmarks == SQL_UB_OFF) + throw SQLException(); + + Sequence<sal_Int8> bookmark = OTools::getBytesValue(m_pStatement->getOwnConnection(),m_aStatementHandle,0,SQL_C_VARBOOKMARK,m_bWasNull,**this); + m_aPosToBookmarks[bookmark] = m_nRowPos; + OSL_ENSURE(bookmark.hasElements(),"Invalid bookmark from length 0!"); + return bookmark; + } + else + { + return aFind->first; + } +} + +sal_Bool SAL_CALL OResultSet::moveToBookmark( const Any& bookmark ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + invalidateCache(); + Sequence<sal_Int8> aBookmark; + bookmark >>= aBookmark; + OSL_ENSURE(aBookmark.hasElements(),"Invalid bookmark from length 0!"); + if(aBookmark.hasElements()) + { + SQLRETURN nReturn = setStmtOption<SQLLEN*, SQL_IS_POINTER>(SQL_ATTR_FETCH_BOOKMARK_PTR, reinterpret_cast<SQLLEN*>(aBookmark.getArray())); + + if ( SQL_INVALID_HANDLE != nReturn && SQL_ERROR != nReturn ) + { + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_BOOKMARK,0); + OTools::ThrowException(m_pStatement->getOwnConnection(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + TBookmarkPosMap::const_iterator aFind = m_aPosToBookmarks.find(aBookmark); + if(aFind != m_aPosToBookmarks.end()) + m_nRowPos = aFind->second; + else + m_nRowPos = -1; + return m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; + } + } + return false; +} + +sal_Bool SAL_CALL OResultSet::moveRelativeToBookmark( const Any& bookmark, sal_Int32 rows ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + invalidateCache(); + Sequence<sal_Int8> aBookmark; + bookmark >>= aBookmark; + setStmtOption<SQLLEN*, SQL_IS_POINTER>(SQL_ATTR_FETCH_BOOKMARK_PTR, reinterpret_cast<SQLLEN*>(aBookmark.getArray())); + + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,SQL_FETCH_BOOKMARK,rows); + OTools::ThrowException(m_pStatement->getOwnConnection(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + return m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; +} + +sal_Int32 SAL_CALL OResultSet::compareBookmarks( const Any& lhs, const Any& rhs ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return (lhs == rhs) ? CompareBookmark::EQUAL : CompareBookmark::NOT_EQUAL; +} + +sal_Bool SAL_CALL OResultSet::hasOrderedBookmarks( ) +{ + return false; +} + +sal_Int32 SAL_CALL OResultSet::hashBookmark( const Any& /*bookmark*/ ) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "XRowLocate::hashBookmark", *this ); + return 0; +} + +// XDeleteRows +Sequence< sal_Int32 > SAL_CALL OResultSet::deleteRows( const Sequence< Any >& rows ) +{ + Sequence< sal_Int32 > aRet(rows.getLength()); + sal_Int32 *pRet = aRet.getArray(); + + const Any *pBegin = rows.getConstArray(); + const Any *pEnd = pBegin + rows.getLength(); + + for(;pBegin != pEnd;++pBegin,++pRet) + { + try + { + if(moveToBookmark(*pBegin)) + { + deleteRow(); + *pRet = 1; + } + } + catch(const SQLException&) + { + *pRet = 0; + } + } + return aRet; +} + +template < typename T, SQLINTEGER BufferLength > T OResultSet::getStmtOption (SQLINTEGER fOption) const +{ + T result (0); + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + N3SQLGetStmtAttr(m_aStatementHandle, fOption, &result, BufferLength, nullptr); + return result; +} +template < typename T, SQLINTEGER BufferLength > SQLRETURN OResultSet::setStmtOption (SQLINTEGER fOption, T value) const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLPOINTER sv = reinterpret_cast<SQLPOINTER>(value); + return N3SQLSetStmtAttr(m_aStatementHandle, fOption, sv, BufferLength); +} + +sal_Int32 OResultSet::getResultSetConcurrency() const +{ + sal_uInt32 nValue = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY); + if(SQL_CONCUR_READ_ONLY == nValue) + nValue = ResultSetConcurrency::READ_ONLY; + else + nValue = ResultSetConcurrency::UPDATABLE; + + return nValue; +} + +sal_Int32 OResultSet::getResultSetType() const +{ + sal_uInt32 nValue = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SENSITIVITY); + if(SQL_SENSITIVE == nValue) + nValue = ResultSetType::SCROLL_SENSITIVE; + else if(SQL_INSENSITIVE == nValue) + nValue = ResultSetType::SCROLL_INSENSITIVE; + else + { + SQLULEN nCurType = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE); + if(SQL_CURSOR_KEYSET_DRIVEN == nCurType) + nValue = ResultSetType::SCROLL_SENSITIVE; + else if(SQL_CURSOR_STATIC == nCurType) + nValue = ResultSetType::SCROLL_INSENSITIVE; + else if(SQL_CURSOR_FORWARD_ONLY == nCurType) + nValue = ResultSetType::FORWARD_ONLY; + else if(SQL_CURSOR_DYNAMIC == nCurType) + nValue = ResultSetType::SCROLL_SENSITIVE; + } + return nValue; +} + +sal_Int32 OResultSet::getFetchSize() const +{ + return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_ARRAY_SIZE); +} + +OUString OResultSet::getCursorName() const +{ + SQLCHAR pName[258]; + SQLSMALLINT nRealLen = 0; + N3SQLGetCursorName(m_aStatementHandle,pName,256,&nRealLen); + return OUString::createFromAscii(reinterpret_cast<char*>(pName)); +} + +bool OResultSet::isBookmarkable() const +{ + if(!m_aConnectionHandle) + return false; + + const SQLULEN nCursorType = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE); + + sal_Int32 nAttr = 0; + try + { + switch(nCursorType) + { + case SQL_CURSOR_FORWARD_ONLY: + return false; + case SQL_CURSOR_STATIC: + OTools::GetInfo(m_pStatement->getOwnConnection(),m_aConnectionHandle,SQL_STATIC_CURSOR_ATTRIBUTES1,nAttr,nullptr); + break; + case SQL_CURSOR_KEYSET_DRIVEN: + OTools::GetInfo(m_pStatement->getOwnConnection(),m_aConnectionHandle,SQL_KEYSET_CURSOR_ATTRIBUTES1,nAttr,nullptr); + break; + case SQL_CURSOR_DYNAMIC: + OTools::GetInfo(m_pStatement->getOwnConnection(),m_aConnectionHandle,SQL_DYNAMIC_CURSOR_ATTRIBUTES1,nAttr,nullptr); + break; + } + } + catch(const Exception&) + { + return false; + } + + if ( m_nUseBookmarks == ODBC_SQL_NOT_DEFINED ) + { + m_nUseBookmarks = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS); + } + + return (m_nUseBookmarks != SQL_UB_OFF) && (nAttr & SQL_CA1_BOOKMARK) == SQL_CA1_BOOKMARK; +} + +void OResultSet::setFetchDirection(sal_Int32 _par0) +{ + ::dbtools::throwFunctionNotSupportedSQLException( "setFetchDirection", *this ); + + OSL_ENSURE(_par0>0,"Illegal fetch direction!"); + if ( _par0 > 0 ) + { + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, _par0); + } +} + +void OResultSet::setFetchSize(sal_Int32 _par0) +{ + OSL_ENSURE(_par0>0,"Illegal fetch size!"); + if ( _par0 != 1 ) + { + throw css::beans::PropertyVetoException("SDBC/ODBC layer not prepared for fetchSize > 1", *this); + } + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_ARRAY_SIZE, _par0); + m_pRowStatusArray.reset( new SQLUSMALLINT[_par0] ); + setStmtOption<SQLUSMALLINT*, SQL_IS_POINTER>(SQL_ATTR_ROW_STATUS_PTR, m_pRowStatusArray.get()); +} + +IPropertyArrayHelper* OResultSet::createArrayHelper( ) const +{ + return new OPropertyArrayHelper + { + { + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME), + PROPERTY_ID_CURSORNAME, + cppu::UnoType<OUString>::get(), + PropertyAttribute::READONLY + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION), + PROPERTY_ID_FETCHDIRECTION, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE), + PROPERTY_ID_FETCHSIZE, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE), + PROPERTY_ID_ISBOOKMARKABLE, + cppu::UnoType<bool>::get(), + PropertyAttribute::READONLY + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY), + PROPERTY_ID_RESULTSETCONCURRENCY, + cppu::UnoType<sal_Int32>::get(), + PropertyAttribute::READONLY + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE), + PROPERTY_ID_RESULTSETTYPE, + cppu::UnoType<sal_Int32>::get(), + PropertyAttribute::READONLY + } + } + }; +} + +IPropertyArrayHelper & OResultSet::getInfoHelper() +{ + return *getArrayHelper(); +} + +sal_Bool OResultSet::convertFastPropertyValue( + Any & rConvertedValue, + Any & rOldValue, + sal_Int32 nHandle, + const Any& rValue ) +{ + switch(nHandle) + { + case PROPERTY_ID_ISBOOKMARKABLE: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + throw css::lang::IllegalArgumentException(); + case PROPERTY_ID_FETCHDIRECTION: + return ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchDirection()); + case PROPERTY_ID_FETCHSIZE: + return ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchSize()); + default: + ; + } + return false; +} + +void OResultSet::setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const Any& rValue + ) +{ + switch(nHandle) + { + case PROPERTY_ID_ISBOOKMARKABLE: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + throw Exception("cannot set prop " + OUString::number(nHandle), nullptr); + case PROPERTY_ID_FETCHDIRECTION: + setFetchDirection(getINT32(rValue)); + break; + case PROPERTY_ID_FETCHSIZE: + setFetchSize(getINT32(rValue)); + break; + default: + ; + } +} + +void OResultSet::getFastPropertyValue( + Any& rValue, + sal_Int32 nHandle + ) const +{ + switch(nHandle) + { + case PROPERTY_ID_ISBOOKMARKABLE: + rValue <<= isBookmarkable(); + break; + case PROPERTY_ID_CURSORNAME: + rValue <<= getCursorName(); + break; + case PROPERTY_ID_RESULTSETCONCURRENCY: + rValue <<= getResultSetConcurrency(); + break; + case PROPERTY_ID_RESULTSETTYPE: + rValue <<= getResultSetType(); + break; + case PROPERTY_ID_FETCHDIRECTION: + rValue <<= getFetchDirection(); + break; + case PROPERTY_ID_FETCHSIZE: + rValue <<= getFetchSize(); + break; + } +} + +void OResultSet::fillColumn(const sal_Int32 _nColumn) +{ + ensureCacheForColumn(_nColumn); + + if (m_aRow[_nColumn].isBound()) + return; + + sal_Int32 curCol; + if(m_bFetchDataInOrder) + { + // m_aRow necessarily has a prefix of bound values, then all unbound values + // EXCEPT for column 0 + // so use binary search to find the earliest unbound value before or at _nColumn + sal_Int32 lower=0; + sal_Int32 upper=_nColumn; + + while (lower < upper) + { + const sal_Int32 middle=(upper-lower)/2 + lower; + if(m_aRow[middle].isBound()) + { + lower=middle+1; + } + else + { + upper=middle; + } + } + + curCol = upper; + } + else + { + curCol = _nColumn; + } + + TDataRow::iterator pColumn = m_aRow.begin() + curCol; + const TDataRow::const_iterator pColumnEnd = m_aRow.begin() + _nColumn + 1; + + if(curCol==0) + { + try + { + *pColumn=impl_getBookmark(); + } + catch (SQLException &) + { + pColumn->setNull(); + } + pColumn->setBound(true); + ++curCol; + ++pColumn; + } + + for (; pColumn != pColumnEnd; ++curCol, ++pColumn) + { + const sal_Int32 nType = pColumn->getTypeKind(); + switch (nType) + { + case DataType::CHAR: + case DataType::VARCHAR: + case DataType::DECIMAL: + case DataType::NUMERIC: + case DataType::LONGVARCHAR: + case DataType::CLOB: + *pColumn=impl_getString(curCol); + break; + case DataType::FLOAT: + *pColumn = impl_getValue<float>(curCol, SQL_C_FLOAT); + break; + case DataType::REAL: + case DataType::DOUBLE: + *pColumn = impl_getValue<double>(curCol, SQL_C_DOUBLE); + break; + case DataType::BINARY: + case DataType::VARBINARY: + case DataType::LONGVARBINARY: + case DataType::BLOB: + *pColumn = impl_getBytes(curCol); + break; + case DataType::DATE: + *pColumn = impl_getDate(curCol); + break; + case DataType::TIME: + *pColumn = impl_getTime(curCol); + break; + case DataType::TIMESTAMP: + *pColumn = impl_getTimestamp(curCol); + break; + case DataType::BIT: + *pColumn = impl_getBoolean(curCol); + break; + case DataType::TINYINT: + *pColumn = impl_getValue<sal_Int8>(curCol, SQL_C_TINYINT); + break; + case DataType::SMALLINT: + *pColumn = impl_getValue<sal_Int16>(curCol, SQL_C_SHORT); + break; + case DataType::INTEGER: + *pColumn = impl_getValue<sal_Int32>(curCol, SQL_C_LONG); + break; + case DataType::BIGINT: + *pColumn = impl_getLong(curCol); + break; + default: + SAL_WARN( "connectivity.odbc","Unknown DataType"); + } + + if ( m_bWasNull ) + pColumn->setNull(); + pColumn->setBound(true); + if(nType != pColumn->getTypeKind()) + { + pColumn->setTypeKind(nType); + } + } +} + +void SAL_CALL OResultSet::acquire() noexcept +{ + OResultSet_BASE::acquire(); +} + +void SAL_CALL OResultSet::release() noexcept +{ + OResultSet_BASE::release(); +} + +css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL OResultSet::getPropertySetInfo( ) +{ + return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); +} + +bool OResultSet::move(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, bool /*_bRetrieveData*/) +{ + SQLSMALLINT nFetchOrientation = SQL_FETCH_NEXT; + switch(_eCursorPosition) + { + case IResultSetHelper::NEXT: + nFetchOrientation = SQL_FETCH_NEXT; + break; + case IResultSetHelper::PRIOR: + nFetchOrientation = SQL_FETCH_PRIOR; + break; + case IResultSetHelper::FIRST: + nFetchOrientation = SQL_FETCH_FIRST; + break; + case IResultSetHelper::LAST: + nFetchOrientation = SQL_FETCH_LAST; + break; + case IResultSetHelper::RELATIVE1: + nFetchOrientation = SQL_FETCH_RELATIVE; + break; + case IResultSetHelper::ABSOLUTE1: + nFetchOrientation = SQL_FETCH_ABSOLUTE; + break; + case IResultSetHelper::BOOKMARK: // special case here because we are only called with position numbers + { + TBookmarkPosMap::const_iterator aIter = std::find_if(m_aPosToBookmarks.begin(), m_aPosToBookmarks.end(), + [&_nOffset](const TBookmarkPosMap::value_type& rEntry) { return rEntry.second == _nOffset; }); + if (aIter != m_aPosToBookmarks.end()) + return moveToBookmark(Any(aIter->first)); + SAL_WARN( "connectivity.odbc", "Bookmark not found!"); + } + return false; + } + + m_bEOF = false; + invalidateCache(); + + SQLRETURN nOldFetchStatus = m_nCurrentFetchState; + // TODO FIXME: both of these will misbehave for + // _eCursorPosition == IResultSetHelper::NEXT/PREVIOUS + // when fetchSize > 1 + if ( !m_bUseFetchScroll && _eCursorPosition == IResultSetHelper::NEXT ) + m_nCurrentFetchState = N3SQLFetch(m_aStatementHandle); + else + m_nCurrentFetchState = N3SQLFetchScroll(m_aStatementHandle,nFetchOrientation,_nOffset); + + SAL_INFO( + "connectivity.odbc", + "move(" << nFetchOrientation << "," << _nOffset << "), FetchState = " + << m_nCurrentFetchState); + OTools::ThrowException(m_pStatement->getOwnConnection(),m_nCurrentFetchState,m_aStatementHandle,SQL_HANDLE_STMT,*this); + + const bool bSuccess = m_nCurrentFetchState == SQL_SUCCESS || m_nCurrentFetchState == SQL_SUCCESS_WITH_INFO; + if ( bSuccess ) + { + switch(_eCursorPosition) + { + case IResultSetHelper::NEXT: + ++m_nRowPos; + break; + case IResultSetHelper::PRIOR: + --m_nRowPos; + break; + case IResultSetHelper::FIRST: + m_nRowPos = 1; + break; + case IResultSetHelper::LAST: + m_bEOF = true; + break; + case IResultSetHelper::RELATIVE1: + m_nRowPos += _nOffset; + break; + case IResultSetHelper::ABSOLUTE1: + case IResultSetHelper::BOOKMARK: // special case here because we are only called with position numbers + m_nRowPos = _nOffset; + break; + } // switch(_eCursorPosition) + if ( m_nUseBookmarks == ODBC_SQL_NOT_DEFINED ) + { + m_nUseBookmarks = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS); + } + if ( m_nUseBookmarks == SQL_UB_OFF ) + { + m_aRow[0].setNull(); + } + else + { + ensureCacheForColumn(0); + Sequence<sal_Int8> bookmark = OTools::getBytesValue(m_pStatement->getOwnConnection(),m_aStatementHandle,0,SQL_C_VARBOOKMARK,m_bWasNull,**this); + m_aPosToBookmarks[bookmark] = m_nRowPos; + OSL_ENSURE(bookmark.hasElements(),"Invalid bookmark from length 0!"); + m_aRow[0] = bookmark; + } + m_aRow[0].setBound(true); + } + else if ( IResultSetHelper::PRIOR == _eCursorPosition && m_nCurrentFetchState == SQL_NO_DATA ) + // we went beforeFirst + m_nRowPos = 0; + else if(IResultSetHelper::NEXT == _eCursorPosition && m_nCurrentFetchState == SQL_NO_DATA && nOldFetchStatus != SQL_NO_DATA) + // we went afterLast + ++m_nRowPos; + + return bSuccess; +} + +sal_Int32 OResultSet::getDriverPos() const +{ + sal_Int32 nValue = getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_NUMBER); + SAL_INFO( + "connectivity.odbc", + "RowNum = " << nValue << ", RowPos = " << m_nRowPos); + return nValue ? nValue : m_nRowPos; +} + +bool OResultSet::isRowDeleted() const +{ + return m_pRowStatusArray[0] == SQL_ROW_DELETED; +} + +bool OResultSet::moveImpl(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + return (m_pSkipDeletedSet != nullptr) + ? m_pSkipDeletedSet->skipDeleted(_eCursorPosition,_nOffset,true/*_bRetrieveData*/) + : move(_eCursorPosition,_nOffset,true/*_bRetrieveData*/); +} + +void OResultSet::fillNeededData(SQLRETURN _nRet) +{ + SQLRETURN nRet = _nRet; + if( nRet != SQL_NEED_DATA) + return; + + void* pColumnIndex = nullptr; + nRet = N3SQLParamData(m_aStatementHandle,&pColumnIndex); + + do + { + if (nRet != SQL_SUCCESS && nRet != SQL_SUCCESS_WITH_INFO && nRet != SQL_NEED_DATA) + break; + + sal_IntPtr nColumnIndex ( reinterpret_cast<sal_IntPtr>(pColumnIndex)); + Sequence< sal_Int8 > aSeq; + switch(m_aRow[nColumnIndex].getTypeKind()) + { + case DataType::BINARY: + case DataType::VARBINARY: + case DataType::LONGVARBINARY: + case DataType::BLOB: + aSeq = m_aRow[nColumnIndex].getSequence(); + N3SQLPutData (m_aStatementHandle, aSeq.getArray(), aSeq.getLength()); + break; + case SQL_WLONGVARCHAR: + { + OUString const & sRet = m_aRow[nColumnIndex].getString(); + N3SQLPutData (m_aStatementHandle, static_cast<SQLPOINTER>(const_cast<sal_Unicode *>(sRet.getStr())), sizeof(sal_Unicode)*sRet.getLength()); + break; + } + case DataType::LONGVARCHAR: + case DataType::CLOB: + { + OUString sRet = m_aRow[nColumnIndex].getString(); + OString aString(OUStringToOString(sRet,m_nTextEncoding)); + N3SQLPutData (m_aStatementHandle, static_cast<SQLPOINTER>(const_cast<char *>(aString.getStr())), aString.getLength()); + break; + } + default: + SAL_WARN( "connectivity.odbc", "Not supported at the moment!"); + } + nRet = N3SQLParamData(m_aStatementHandle,&pColumnIndex); + } + while (nRet == SQL_NEED_DATA); +} + +SWORD OResultSet::impl_getColumnType_nothrow(sal_Int32 columnIndex) +{ + std::map<sal_Int32,SWORD>::const_iterator aFind = m_aODBCColumnTypes.find(columnIndex); + if ( aFind == m_aODBCColumnTypes.end() ) + aFind = m_aODBCColumnTypes.emplace( + columnIndex, + OResultSetMetaData::getColumnODBCType(m_pStatement->getOwnConnection(),m_aStatementHandle,*this,columnIndex) + ).first; + return aFind->second; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/OResultSetMetaData.cxx b/connectivity/source/drivers/odbc/OResultSetMetaData.cxx new file mode 100644 index 000000000..21b95c6a7 --- /dev/null +++ b/connectivity/source/drivers/odbc/OResultSetMetaData.cxx @@ -0,0 +1,291 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/OResultSetMetaData.hxx> +#include <odbc/OTools.hxx> + +using namespace connectivity::odbc; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::sdbc; + + +OResultSetMetaData::~OResultSetMetaData() +{ +} + +OUString OResultSetMetaData::getCharColAttrib(sal_Int32 _column,sal_Int32 ident) +{ + sal_Int32 column = _column; + if(_column <static_cast<sal_Int32>(m_vMapping.size())) // use mapping + column = m_vMapping[_column]; + + SQLSMALLINT BUFFER_LEN = 128; + std::unique_ptr<char[]> pName(new char[BUFFER_LEN+1]); + SQLSMALLINT nRealLen=0; + SQLRETURN nRet = N3SQLColAttribute(m_aStatementHandle, + static_cast<SQLUSMALLINT>(column), + static_cast<SQLUSMALLINT>(ident), + static_cast<SQLPOINTER>(pName.get()), + BUFFER_LEN, + &nRealLen, + nullptr + ); + OUString sValue; + if ( nRet == SQL_SUCCESS ) + { + if ( nRealLen < 0 ) + nRealLen = BUFFER_LEN; + sValue = OUString(pName.get(),nRealLen,m_pConnection->getTextEncoding()); + } + pName.reset(); + OTools::ThrowException(m_pConnection,nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + if(nRealLen > BUFFER_LEN) + { + pName.reset(new char[nRealLen+1]); + nRet = N3SQLColAttribute(m_aStatementHandle, + static_cast<SQLUSMALLINT>(column), + static_cast<SQLUSMALLINT>(ident), + static_cast<SQLPOINTER>(pName.get()), + nRealLen, + &nRealLen, + nullptr + ); + if ( nRet == SQL_SUCCESS && nRealLen > 0) + sValue = OUString(pName.get(),nRealLen,m_pConnection->getTextEncoding()); + OTools::ThrowException(m_pConnection,nRet,m_aStatementHandle,SQL_HANDLE_STMT,*this); + } + + return sValue; +} + +SQLLEN OResultSetMetaData::getNumColAttrib(OConnection const * _pConnection + ,SQLHANDLE _aStatementHandle + ,const css::uno::Reference< css::uno::XInterface >& _xInterface + ,sal_Int32 _column + ,sal_Int32 _ident) +{ + SQLLEN nValue=0; + OTools::ThrowException(_pConnection,(*reinterpret_cast<T3SQLColAttribute>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::ColAttribute)))(_aStatementHandle, + static_cast<SQLUSMALLINT>(_column), + static_cast<SQLUSMALLINT>(_ident), + nullptr, + 0, + nullptr, + &nValue),_aStatementHandle,SQL_HANDLE_STMT,_xInterface); + return nValue; +} + +sal_Int32 OResultSetMetaData::getNumColAttrib(sal_Int32 _column,sal_Int32 ident) +{ + sal_Int32 column = _column; + if(_column < static_cast<sal_Int32>(m_vMapping.size())) // use mapping + column = m_vMapping[_column]; + + return getNumColAttrib(m_pConnection,m_aStatementHandle,*this,column,ident); +} + +sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_DISPLAY_SIZE); +} + +SQLSMALLINT OResultSetMetaData::getColumnODBCType(OConnection const * _pConnection + ,SQLHANDLE _aStatementHandle + ,const css::uno::Reference< css::uno::XInterface >& _xInterface + ,sal_Int32 column) +{ + SQLSMALLINT nType = 0; + try + { + nType = static_cast<SQLSMALLINT>(getNumColAttrib(_pConnection,_aStatementHandle,_xInterface,column,SQL_DESC_CONCISE_TYPE)); + if(nType == SQL_UNKNOWN_TYPE) + nType = static_cast<SQLSMALLINT>(getNumColAttrib(_pConnection,_aStatementHandle,_xInterface,column, SQL_DESC_TYPE)); + } + catch(SQLException& ) // in this case we have an odbc 2.0 driver + { + nType = static_cast<SQLSMALLINT>(getNumColAttrib(_pConnection,_aStatementHandle,_xInterface,column,SQL_DESC_CONCISE_TYPE )); + } + + return nType; +} + +sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) +{ + std::map<sal_Int32,sal_Int32>::iterator aFind = m_aColumnTypes.find(column); + if ( aFind == m_aColumnTypes.end() ) + { + sal_Int32 nType = 0; + if(!m_bUseODBC2Types) + { + try + { + nType = getNumColAttrib(column,SQL_DESC_CONCISE_TYPE); + if(nType == SQL_UNKNOWN_TYPE) + nType = getNumColAttrib(column, SQL_DESC_TYPE); + nType = OTools::MapOdbcType2Jdbc(nType); + } + catch(SQLException& ) // in this case we have an odbc 2.0 driver + { + m_bUseODBC2Types = true; + nType = OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_CONCISE_TYPE )); + } + } + else + nType = OTools::MapOdbcType2Jdbc(getNumColAttrib(column,SQL_DESC_CONCISE_TYPE )); + aFind = m_aColumnTypes.emplace(column,nType).first; + } + + + return aFind->second; +} + + +sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount( ) +{ + if(m_nColCount != -1) + return m_nColCount; + sal_Int16 nNumResultCols=0; + OTools::ThrowException(m_pConnection,N3SQLNumResultCols(m_aStatementHandle,&nNumResultCols),m_aStatementHandle,SQL_HANDLE_STMT,*this); + m_nColCount = nNumResultCols; + return m_nColCount; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_CASE_SENSITIVE) == SQL_TRUE; +} + + +OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 column ) +{ + return getCharColAttrib(column,SQL_DESC_SCHEMA_NAME); +} + + +OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) +{ + return getCharColAttrib(column,SQL_DESC_NAME); +} + +OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) +{ + return getCharColAttrib(column,SQL_DESC_TABLE_NAME); +} + +OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 column ) +{ + return getCharColAttrib(column,SQL_DESC_CATALOG_NAME); +} + +OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 column ) +{ + return getCharColAttrib(column,SQL_DESC_TYPE_NAME); +} + +OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) +{ + return getCharColAttrib(column,SQL_DESC_LABEL); +} + +OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 /*column*/ ) +{ + return OUString(); +} + + +sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_FIXED_PREC_SCALE) == SQL_TRUE; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_AUTO_UNIQUE_VALUE) == SQL_TRUE; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_UNSIGNED) == SQL_FALSE; +} + +sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) +{ + sal_Int32 nType = 0; + try + { + nType = getNumColAttrib(column,SQL_DESC_PRECISION); + } + catch(const SQLException& ) // in this case we have an odbc 2.0 driver + { + m_bUseODBC2Types = true; + nType = getNumColAttrib(column,SQL_COLUMN_PRECISION ); + } + return nType; +} + +sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) +{ + sal_Int32 nType = 0; + try + { + nType = getNumColAttrib(column,SQL_DESC_SCALE); + } + catch(const SQLException& ) // in this case we have an odbc 2.0 driver + { + m_bUseODBC2Types = true; + nType = getNumColAttrib(column,SQL_COLUMN_SCALE ); + } + return nType; +} + + +sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_NULLABLE); +} + + +sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_SEARCHABLE) != SQL_PRED_NONE; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_READONLY; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE; +} + +sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) +{ + return getNumColAttrib(column,SQL_DESC_UPDATABLE) == SQL_ATTR_WRITE; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/OStatement.cxx b/connectivity/source/drivers/odbc/OStatement.cxx new file mode 100644 index 000000000..da50e01f1 --- /dev/null +++ b/connectivity/source/drivers/odbc/OStatement.cxx @@ -0,0 +1,1140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include <osl/diagnose.h> +#include <odbc/OStatement.hxx> +#include <odbc/OConnection.hxx> +#include <odbc/OResultSet.hxx> +#include <comphelper/property.hxx> +#include <odbc/OTools.hxx> +#include <com/sun/star/sdbc/ResultSetConcurrency.hpp> +#include <com/sun/star/sdbc/ResultSetType.hpp> +#include <com/sun/star/sdbc/FetchDirection.hpp> +#include <com/sun/star/lang/DisposedException.hpp> +#include <comphelper/sequence.hxx> +#include <cppuhelper/typeprovider.hxx> +#include <cppuhelper/queryinterface.hxx> +#include <comphelper/types.hxx> +#include <rtl/strbuf.hxx> +#include <algorithm> +#include <strings.hrc> +#include <connectivity/dbexception.hxx> + +using namespace ::comphelper; + +#define THROW_SQL(x) \ + OTools::ThrowException(m_pConnection.get(),x,m_aStatementHandle,SQL_HANDLE_STMT,*this) + + +using namespace connectivity::odbc; + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::sdbcx; +using namespace com::sun::star::container; +using namespace com::sun::star::io; +using namespace com::sun::star::util; + +OStatement_Base::OStatement_Base(OConnection* _pConnection ) + :OStatement_BASE(m_aMutex) + ,OPropertySetHelper(OStatement_BASE::rBHelper) + ,m_pConnection(_pConnection) + ,m_aStatementHandle(SQL_NULL_HANDLE) + ,m_pRowStatusArray(nullptr) +{ + osl_atomic_increment( &m_refCount ); + m_aStatementHandle = m_pConnection->createStatementHandle(); + + //setMaxFieldSize(0); + // Don't do this. By ODBC spec, "0" is the default for the SQL_ATTR_MAX_LENGTH attribute. We once introduced + // this line since a PostgreSQL ODBC driver had a default other than 0. However, current drivers (at least 8.3 + // and later) have a proper default of 0, so there should be no need anymore. + // On the other hand, the NotesSQL driver (IBM's ODBC driver for the Lotus Notes series) wrongly interprets + // "0" as "0", whereas the ODBC spec says it should in fact mean "unlimited". + // So, removing this line seems to be the best option for now. + // If we ever again encounter an ODBC driver which needs this option, then we should introduce a data source + // setting for it, instead of unconditionally doing it. + + osl_atomic_decrement( &m_refCount ); +} + +OStatement_Base::~OStatement_Base() +{ + OSL_ENSURE(!m_aStatementHandle,"Sohould ne null here!"); +} + +void OStatement_Base::disposeResultSet() +{ + // free the cursor if alive + Reference< XComponent > xComp(m_xResultSet.get(), UNO_QUERY); + if (xComp.is()) + xComp->dispose(); + m_xResultSet.clear(); +} + +void SAL_CALL OStatement_Base::disposing() +{ + ::osl::MutexGuard aGuard(m_aMutex); + + disposeResultSet(); + ::comphelper::disposeComponent(m_xGeneratedStatement); + + OSL_ENSURE(m_aStatementHandle,"OStatement_BASE2::disposing: StatementHandle is null!"); + if (m_pConnection.is()) + { + m_pConnection->freeStatementHandle(m_aStatementHandle); + m_pConnection.clear(); + } + OSL_ENSURE(!m_aStatementHandle,"Sohould ne null here!"); + + OStatement_BASE::disposing(); +} + +void OStatement_BASE2::disposing() +{ + ::osl::MutexGuard aGuard1(m_aMutex); + OStatement_Base::disposing(); +} + +Any SAL_CALL OStatement_Base::queryInterface( const Type & rType ) +{ + if ( m_pConnection.is() && !m_pConnection->isAutoRetrievingEnabled() && rType == cppu::UnoType<XGeneratedResultSet>::get()) + return Any(); + Any aRet = OStatement_BASE::queryInterface(rType); + return aRet.hasValue() ? aRet : OPropertySetHelper::queryInterface(rType); +} + +Sequence< Type > SAL_CALL OStatement_Base::getTypes( ) +{ + ::cppu::OTypeCollection aTypes( cppu::UnoType<XMultiPropertySet>::get(), + cppu::UnoType<XFastPropertySet>::get(), + cppu::UnoType<XPropertySet>::get()); + Sequence< Type > aOldTypes = OStatement_BASE::getTypes(); + if ( m_pConnection.is() && !m_pConnection->isAutoRetrievingEnabled() ) + { + auto [begin, end] = asNonConstRange(aOldTypes); + auto newEnd = std::remove(begin, end, + cppu::UnoType<XGeneratedResultSet>::get()); + aOldTypes.realloc(std::distance(begin, newEnd)); + } + + return ::comphelper::concatSequences(aTypes.getTypes(),aOldTypes); +} + +Reference< XResultSet > SAL_CALL OStatement_Base::getGeneratedValues( ) +{ + OSL_ENSURE( m_pConnection.is() && m_pConnection->isAutoRetrievingEnabled(),"Illegal call here. isAutoRetrievingEnabled is false!"); + Reference< XResultSet > xRes; + if ( m_pConnection.is() ) + { + OUString sStmt = m_pConnection->getTransformedGeneratedStatement(m_sSqlStatement); + if ( !sStmt.isEmpty() ) + { + ::comphelper::disposeComponent(m_xGeneratedStatement); + m_xGeneratedStatement = m_pConnection->createStatement(); + xRes = m_xGeneratedStatement->executeQuery(sStmt); + } + } + return xRes; +} + +void SAL_CALL OStatement_Base::cancel( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + N3SQLCancel(m_aStatementHandle); +} + + +void SAL_CALL OStatement_Base::close( ) +{ + { + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + } + dispose(); +} + + +void SAL_CALL OStatement::clearBatch( ) +{ + +} + +void OStatement_Base::reset() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + clearWarnings (); + + if (m_xResultSet.get().is()) + { + clearMyResultSet(); + } + if(m_aStatementHandle) + { + THROW_SQL(N3SQLFreeStmt(m_aStatementHandle, SQL_CLOSE)); + } +} + +// clearMyResultSet +// If a ResultSet was created for this Statement, close it +void OStatement_Base::clearMyResultSet() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + try + { + Reference<XCloseable> xCloseable( + m_xResultSet.get(), css::uno::UNO_QUERY); + if ( xCloseable.is() ) + xCloseable->close(); + } + catch( const DisposedException& ) { } + + m_xResultSet.clear(); +} + +SQLLEN OStatement_Base::getRowCount() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + SQLLEN numRows = 0; + + try { + THROW_SQL(N3SQLRowCount(m_aStatementHandle,&numRows)); + } + catch (const SQLException&) + { + } + return numRows; +} + +// lockIfNecessary +// If the given SQL statement contains a 'FOR UPDATE' clause, change +// the concurrency to lock so that the row can then be updated. Returns +// true if the concurrency has been changed +bool OStatement_Base::lockIfNecessary (const OUString& sql) +{ + bool rc = false; + + // First, convert the statement to upper case + + OUString sqlStatement = sql.toAsciiUpperCase (); + + // Now, look for the FOR UPDATE keywords. If there is any extra white + // space between the FOR and UPDATE, this will fail. + + sal_Int32 index = sqlStatement.indexOf(" FOR UPDATE"); + + // We found it. Change our concurrency level to ensure that the + // row can be updated. + + if (index > 0) + { + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + try + { + THROW_SQL((setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY, SQL_CONCUR_LOCK))); + } + catch (const SQLWarning& warn) + { + // Catch any warnings and place on the warning stack + setWarning (warn); + } + rc = true; + } + + return rc; +} + +// setWarning +// Sets the warning + + +void OStatement_Base::setWarning (const SQLWarning &ex) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + m_aLastWarning = ex; +} + + +// getColumnCount +// Return the number of columns in the ResultSet +sal_Int32 OStatement_Base::getColumnCount() +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + sal_Int16 numCols = 0; + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + + try { + THROW_SQL(N3SQLNumResultCols(m_aStatementHandle,&numCols)); + } + catch (const SQLException&) + { + } + return numCols; +} + + +sal_Bool SAL_CALL OStatement_Base::execute( const OUString& sql ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + m_sSqlStatement = sql; + + + OString aSql(OUStringToOString(sql,getOwnConnection()->getTextEncoding())); + + bool hasResultSet = false; + + // Reset the statement handle and warning + + reset(); + + // Check for a 'FOR UPDATE' statement. If present, change + // the concurrency to lock + + lockIfNecessary (sql); + + // Call SQLExecDirect + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + + try { + THROW_SQL(N3SQLExecDirect(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(aSql.getStr())), aSql.getLength())); + } + catch (const SQLWarning&) { + + //TODO: Save pointer to warning and save with ResultSet + // object once it is created. + } + + // Now determine if there is a result set associated with + // the SQL statement that was executed. Get the column + // count, and if it is not zero, there is a result set. + + if (getColumnCount () > 0) + { + hasResultSet = true; + } + + return hasResultSet; +} + +// getResultSet +// getResultSet returns the current result as a ResultSet. It +// returns NULL if the current result is not a ResultSet. + +Reference< XResultSet > OStatement_Base::getResultSet(bool checkCount) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + if (m_xResultSet.get().is()) // if resultset already retrieved, + { + // throw exception to avoid sequence error + ::dbtools::throwFunctionSequenceException(*this); + } + + rtl::Reference<OResultSet> pRs; + sal_Int32 numCols = 1; + + // If we already know we have result columns, checkCount + // is false. This is an optimization to prevent unneeded + // calls to getColumnCount + + if (checkCount) + numCols = getColumnCount (); + + // Only return a result set if there are result columns + + if (numCols > 0) + { + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + pRs = createResultSet(); + pRs->construct(); + + // Save a copy of our last result set + // Changed to save copy at getResultSet. + //m_xResultSet = rs; + } + else + clearMyResultSet (); + + return pRs; +} + +// getStmtOption +// Invoke SQLGetStmtOption with the given option. + + +template < typename T, SQLINTEGER BufferLength > T OStatement_Base::getStmtOption (SQLINTEGER fOption) const +{ + T result (0); + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + N3SQLGetStmtAttr(m_aStatementHandle, fOption, &result, BufferLength, nullptr); + return result; +} +template < typename T, SQLINTEGER BufferLength > SQLRETURN OStatement_Base::setStmtOption (SQLINTEGER fOption, T value) const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLPOINTER sv = reinterpret_cast<SQLPOINTER>(value); + return N3SQLSetStmtAttr(m_aStatementHandle, fOption, sv, BufferLength); +} + + +Reference< XResultSet > SAL_CALL OStatement_Base::executeQuery( const OUString& sql ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + Reference< XResultSet > xRS; + + // Execute the statement. If execute returns true, a result + // set exists. + + if (execute (sql)) + { + xRS = getResultSet (false); + m_xResultSet = xRS; + } + else + { + // No ResultSet was produced. Raise an exception + m_pConnection->throwGenericSQLException(STR_NO_RESULTSET,*this); + } + return xRS; +} + + +Reference< XConnection > SAL_CALL OStatement_Base::getConnection( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + return m_pConnection; +} + + +Any SAL_CALL OStatement::queryInterface( const Type & rType ) +{ + Any aRet = ::cppu::queryInterface(rType,static_cast< XBatchExecution*> (this)); + return aRet.hasValue() ? aRet : OStatement_Base::queryInterface(rType); +} + + +void SAL_CALL OStatement::addBatch( const OUString& sql ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + m_aBatchVector.push_back(sql); +} + +Sequence< sal_Int32 > SAL_CALL OStatement::executeBatch( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + OStringBuffer aBatchSql; + sal_Int32 nLen = m_aBatchVector.size(); + + for (auto const& elem : m_aBatchVector) + { + aBatchSql.append(OUStringToOString(elem,getOwnConnection()->getTextEncoding())); + aBatchSql.append(";"); + } + + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + auto s = aBatchSql.makeStringAndClear(); + THROW_SQL(N3SQLExecDirect(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(s.getStr())), s.getLength())); + + Sequence< sal_Int32 > aRet(nLen); + sal_Int32* pArray = aRet.getArray(); + for(sal_Int32 j=0;j<nLen;++j) + { + SQLRETURN nError = N3SQLMoreResults(m_aStatementHandle); + if(nError == SQL_SUCCESS) + { + SQLLEN nRowCount=0; + N3SQLRowCount(m_aStatementHandle,&nRowCount); + pArray[j] = nRowCount; + } + } + return aRet; +} + + +sal_Int32 SAL_CALL OStatement_Base::executeUpdate( const OUString& sql ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + sal_Int32 numRows = -1; + + // Execute the statement. If execute returns false, a + // row count exists. + + if (!execute (sql)) { + numRows = getUpdateCount(); + } + else { + + // No update count was produced (a ResultSet was). Raise + // an exception + + ::connectivity::SharedResources aResources; + const OUString sError( aResources.getResourceString(STR_NO_ROWCOUNT)); + throw SQLException (sError, *this,OUString(),0,Any()); + } + return numRows; + +} + + +Reference< XResultSet > SAL_CALL OStatement_Base::getResultSet( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + m_xResultSet = getResultSet(true); + return m_xResultSet; +} + + +sal_Int32 SAL_CALL OStatement_Base::getUpdateCount( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + sal_Int32 rowCount = -1; + + // Only return a row count for SQL statements that did not + // return a result set. + + if (getColumnCount () == 0) + rowCount = getRowCount (); + + return rowCount; +} + + +sal_Bool SAL_CALL OStatement_Base::getMoreResults( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + SQLWarning warning; + bool hasResultSet = false; + + // clear previous warnings + + clearWarnings (); + + // Call SQLMoreResults + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + + try { + hasResultSet = N3SQLMoreResults(m_aStatementHandle) == SQL_SUCCESS; + } + catch (const SQLWarning &ex) { + + // Save pointer to warning and save with ResultSet + // object once it is created. + + warning = ex; + } + + // There are more results (it may not be a result set, though) + + if (hasResultSet) + { + + // Now determine if there is a result set associated + // with the SQL statement that was executed. Get the + // column count, and if it is zero, there is not a + // result set. + + if (getColumnCount () == 0) + hasResultSet = false; + } + + // Set the warning for the statement, if one was generated + + setWarning (warning); + + // Return the result set indicator + + return hasResultSet; +} + + +Any SAL_CALL OStatement_Base::getWarnings( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + return Any(m_aLastWarning); +} + + +void SAL_CALL OStatement_Base::clearWarnings( ) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + m_aLastWarning = SQLWarning(); +} + + +sal_Int64 OStatement_Base::getQueryTimeOut() const +{ + return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_QUERY_TIMEOUT); +} + +sal_Int64 OStatement_Base::getMaxRows() const +{ + return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_ROWS); +} + +sal_Int32 OStatement_Base::getResultSetConcurrency() const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLULEN nValue (getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY)); + if(nValue == SQL_CONCUR_READ_ONLY) + nValue = ResultSetConcurrency::READ_ONLY; + else + nValue = ResultSetConcurrency::UPDATABLE; + return nValue; +} + +sal_Int32 OStatement_Base::getResultSetType() const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLULEN nValue (getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE)); + switch(nValue) + { + case SQL_CURSOR_FORWARD_ONLY: + nValue = ResultSetType::FORWARD_ONLY; + break; + case SQL_CURSOR_KEYSET_DRIVEN: + case SQL_CURSOR_STATIC: + nValue = ResultSetType::SCROLL_INSENSITIVE; + break; + case SQL_CURSOR_DYNAMIC: + nValue = ResultSetType::SCROLL_SENSITIVE; + break; + default: + OSL_FAIL("Unknown ODBC Cursor Type"); + } + + return nValue; +} + +sal_Int32 OStatement_Base::getFetchDirection() const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLULEN nValue (getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SCROLLABLE)); + switch(nValue) + { + case SQL_SCROLLABLE: + nValue = FetchDirection::REVERSE; + break; + default: + nValue = FetchDirection::FORWARD; + break; + } + + return nValue; +} + +sal_Int32 OStatement_Base::getFetchSize() const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_ARRAY_SIZE); +} + +sal_Int64 OStatement_Base::getMaxFieldSize() const +{ + return getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_LENGTH); +} + +OUString OStatement_Base::getCursorName() const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLCHAR pName[258]; + SQLSMALLINT nRealLen = 0; + N3SQLGetCursorName(m_aStatementHandle,pName,256,&nRealLen); + return OUString::createFromAscii(reinterpret_cast<char*>(pName)); +} + +void OStatement_Base::setQueryTimeOut(sal_Int64 seconds) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_QUERY_TIMEOUT,seconds); +} + +void OStatement_Base::setMaxRows(sal_Int64 _par0) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_ROWS, _par0); +} + +void OStatement_Base::setResultSetConcurrency(sal_Int32 _par0) +{ + SQLULEN nSet; + if(_par0 == ResultSetConcurrency::READ_ONLY) + nSet = SQL_CONCUR_READ_ONLY; + else + nSet = SQL_CONCUR_VALUES; + + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CONCURRENCY, nSet); +} + +void OStatement_Base::setResultSetType(sal_Int32 _par0) +{ + + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_BIND_TYPE, SQL_BIND_BY_COLUMN); + + bool bUseBookmark = isUsingBookmarks(); + SQLULEN nSet( SQL_UNSPECIFIED ); + switch(_par0) + { + case ResultSetType::FORWARD_ONLY: + nSet = SQL_UNSPECIFIED; + break; + case ResultSetType::SCROLL_INSENSITIVE: + nSet = SQL_INSENSITIVE; + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_KEYSET_DRIVEN); + break; + case ResultSetType::SCROLL_SENSITIVE: + if(bUseBookmark) + { + SQLUINTEGER nCurProp = getCursorProperties(SQL_CURSOR_DYNAMIC,true); + if((nCurProp & SQL_CA1_BOOKMARK) != SQL_CA1_BOOKMARK) // check if bookmark for this type isn't supported + { // we have to test the next one + nCurProp = getCursorProperties(SQL_CURSOR_KEYSET_DRIVEN,true); + bool bNotBookmarks = ((nCurProp & SQL_CA1_BOOKMARK) != SQL_CA1_BOOKMARK); + nCurProp = getCursorProperties(SQL_CURSOR_KEYSET_DRIVEN,false); + nSet = SQL_CURSOR_KEYSET_DRIVEN; + if( bNotBookmarks || + ((nCurProp & SQL_CA2_SENSITIVITY_DELETIONS) != SQL_CA2_SENSITIVITY_DELETIONS) || + ((nCurProp & SQL_CA2_SENSITIVITY_ADDITIONS) != SQL_CA2_SENSITIVITY_ADDITIONS)) + { + // bookmarks for keyset isn't supported so reset bookmark setting + setUsingBookmarks(false); + nSet = SQL_CURSOR_DYNAMIC; + } + } + else + nSet = SQL_CURSOR_DYNAMIC; + } + else + nSet = SQL_CURSOR_DYNAMIC; + if( setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, nSet) != SQL_SUCCESS ) + { + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_KEYSET_DRIVEN); + } + nSet = SQL_SENSITIVE; + break; + default: + OSL_FAIL( "OStatement_Base::setResultSetType: invalid result set type!" ); + break; + } + + + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SENSITIVITY, nSet); +} + +void OStatement_Base::setEscapeProcessing( const bool _bEscapeProc ) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLULEN nEscapeProc( _bEscapeProc ? SQL_NOSCAN_OFF : SQL_NOSCAN_ON ); + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_NOSCAN, nEscapeProc); +} + + +void OStatement_Base::setFetchDirection(sal_Int32 _par0) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + if(_par0 == FetchDirection::FORWARD) + { + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SCROLLABLE, SQL_NONSCROLLABLE); + } + else if(_par0 == FetchDirection::REVERSE) + { + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_CURSOR_SCROLLABLE, SQL_SCROLLABLE); + } +} + +void OStatement_Base::setFetchSize(sal_Int32 _par0) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + OSL_ENSURE(_par0>0,"Illegal fetch size!"); + if ( _par0 > 0 ) + { + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_ROW_ARRAY_SIZE, _par0); + + delete[] m_pRowStatusArray; + m_pRowStatusArray = new SQLUSMALLINT[_par0]; + setStmtOption<SQLUSMALLINT*, SQL_IS_POINTER>(SQL_ATTR_ROW_STATUS_PTR, m_pRowStatusArray); + } +} + +void OStatement_Base::setMaxFieldSize(sal_Int64 _par0) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_MAX_LENGTH, _par0); +} + +void OStatement_Base::setCursorName(std::u16string_view _par0) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + OString aName(OUStringToOString(_par0,getOwnConnection()->getTextEncoding())); + N3SQLSetCursorName(m_aStatementHandle, reinterpret_cast<SDB_ODBC_CHAR *>(const_cast<char *>(aName.getStr())), static_cast<SQLSMALLINT>(aName.getLength())); +} + +bool OStatement_Base::isUsingBookmarks() const +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + return SQL_UB_OFF != getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS); +} + +bool OStatement_Base::getEscapeProcessing() const +{ + OSL_ENSURE( m_aStatementHandle, "StatementHandle is null!" ); + return SQL_NOSCAN_OFF == getStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS); +} + +void OStatement_Base::setUsingBookmarks(bool _bUseBookmark) +{ + OSL_ENSURE(m_aStatementHandle,"StatementHandle is null!"); + SQLULEN nValue = _bUseBookmark ? SQL_UB_VARIABLE : SQL_UB_OFF; + setStmtOption<SQLULEN, SQL_IS_UINTEGER>(SQL_ATTR_USE_BOOKMARKS, nValue); +} + +::cppu::IPropertyArrayHelper* OStatement_Base::createArrayHelper( ) const +{ + return new ::cppu::OPropertyArrayHelper + { + { + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME), + PROPERTY_ID_CURSORNAME, + cppu::UnoType<OUString>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ESCAPEPROCESSING), + PROPERTY_ID_ESCAPEPROCESSING, + cppu::UnoType<bool>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION), + PROPERTY_ID_FETCHDIRECTION, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE), + PROPERTY_ID_FETCHSIZE, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_MAXFIELDSIZE), + PROPERTY_ID_MAXFIELDSIZE, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_MAXROWS), + PROPERTY_ID_MAXROWS, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_QUERYTIMEOUT), + PROPERTY_ID_QUERYTIMEOUT, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY), + PROPERTY_ID_RESULTSETCONCURRENCY, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE), + PROPERTY_ID_RESULTSETTYPE, + cppu::UnoType<sal_Int32>::get(), + 0 + }, + { + ::connectivity::OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_USEBOOKMARKS), + PROPERTY_ID_USEBOOKMARKS, + cppu::UnoType<bool>::get(), + 0 + } + } + }; +} + + +::cppu::IPropertyArrayHelper & OStatement_Base::getInfoHelper() +{ + return *getArrayHelper(); +} + +sal_Bool OStatement_Base::convertFastPropertyValue( + Any & rConvertedValue, + Any & rOldValue, + sal_Int32 nHandle, + const Any& rValue ) +{ + bool bConverted = false; + try + { + switch(nHandle) + { + case PROPERTY_ID_QUERYTIMEOUT: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getQueryTimeOut()); + break; + + case PROPERTY_ID_MAXFIELDSIZE: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getMaxFieldSize()); + break; + + case PROPERTY_ID_MAXROWS: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getMaxRows()); + break; + + case PROPERTY_ID_CURSORNAME: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getCursorName()); + break; + + case PROPERTY_ID_RESULTSETCONCURRENCY: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getResultSetConcurrency()); + break; + + case PROPERTY_ID_RESULTSETTYPE: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getResultSetType()); + break; + + case PROPERTY_ID_FETCHDIRECTION: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchDirection()); + break; + + case PROPERTY_ID_FETCHSIZE: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchSize()); + break; + + case PROPERTY_ID_USEBOOKMARKS: + bConverted = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, isUsingBookmarks()); + break; + + case PROPERTY_ID_ESCAPEPROCESSING: + bConverted = ::comphelper::tryPropertyValue( rConvertedValue, rOldValue, rValue, getEscapeProcessing() ); + break; + + } + } + catch(const SQLException&) + { + // throw Exception(e.Message,*this); + } + return bConverted; +} + +void OStatement_Base::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) +{ + try + { + switch(nHandle) + { + case PROPERTY_ID_QUERYTIMEOUT: + setQueryTimeOut(comphelper::getINT64(rValue)); + break; + case PROPERTY_ID_MAXFIELDSIZE: + setMaxFieldSize(comphelper::getINT64(rValue)); + break; + case PROPERTY_ID_MAXROWS: + setMaxRows(comphelper::getINT64(rValue)); + break; + case PROPERTY_ID_CURSORNAME: + setCursorName(comphelper::getString(rValue)); + break; + case PROPERTY_ID_RESULTSETCONCURRENCY: + setResultSetConcurrency(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_RESULTSETTYPE: + setResultSetType(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_FETCHDIRECTION: + setFetchDirection(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_FETCHSIZE: + setFetchSize(comphelper::getINT32(rValue)); + break; + case PROPERTY_ID_USEBOOKMARKS: + setUsingBookmarks(comphelper::getBOOL(rValue)); + break; + case PROPERTY_ID_ESCAPEPROCESSING: + setEscapeProcessing( ::comphelper::getBOOL( rValue ) ); + break; + default: + OSL_FAIL( "OStatement_Base::setFastPropertyValue_NoBroadcast: what property?" ); + break; + } + } + catch(const SQLException& ) + { + // throw Exception(e.Message,*this); + } +} + +void OStatement_Base::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const +{ + switch(nHandle) + { + case PROPERTY_ID_QUERYTIMEOUT: + rValue <<= getQueryTimeOut(); + break; + case PROPERTY_ID_MAXFIELDSIZE: + rValue <<= getMaxFieldSize(); + break; + case PROPERTY_ID_MAXROWS: + rValue <<= getMaxRows(); + break; + case PROPERTY_ID_CURSORNAME: + rValue <<= getCursorName(); + break; + case PROPERTY_ID_RESULTSETCONCURRENCY: + rValue <<= getResultSetConcurrency(); + break; + case PROPERTY_ID_RESULTSETTYPE: + rValue <<= getResultSetType(); + break; + case PROPERTY_ID_FETCHDIRECTION: + rValue <<= getFetchDirection(); + break; + case PROPERTY_ID_FETCHSIZE: + rValue <<= getFetchSize(); + break; + case PROPERTY_ID_USEBOOKMARKS: + rValue <<= isUsingBookmarks(); + break; + case PROPERTY_ID_ESCAPEPROCESSING: + rValue <<= getEscapeProcessing(); + break; + default: + OSL_FAIL( "OStatement_Base::getFastPropertyValue: what property?" ); + break; + } +} + +IMPLEMENT_SERVICE_INFO(OStatement,"com.sun.star.sdbcx.OStatement","com.sun.star.sdbc.Statement"); + +void SAL_CALL OStatement_Base::acquire() noexcept +{ + OStatement_BASE::acquire(); +} + +void SAL_CALL OStatement_Base::release() noexcept +{ + OStatement_BASE::release(); +} + +void SAL_CALL OStatement::acquire() noexcept +{ + OStatement_BASE2::acquire(); +} + +void SAL_CALL OStatement::release() noexcept +{ + OStatement_BASE2::release(); +} + +rtl::Reference<OResultSet> OStatement_Base::createResultSet() +{ + return new OResultSet(m_aStatementHandle,this); +} + +Reference< css::beans::XPropertySetInfo > SAL_CALL OStatement_Base::getPropertySetInfo( ) +{ + return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); +} + +SQLUINTEGER OStatement_Base::getCursorProperties(SQLINTEGER _nCursorType, bool bFirst) +{ + SQLUINTEGER nValueLen = 0; + try + { + SQLUSMALLINT nAskFor = SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2; + if(SQL_CURSOR_KEYSET_DRIVEN == _nCursorType) + nAskFor = bFirst ? SQL_KEYSET_CURSOR_ATTRIBUTES1 : SQL_KEYSET_CURSOR_ATTRIBUTES2; + else if(SQL_CURSOR_STATIC == _nCursorType) + nAskFor = bFirst ? SQL_STATIC_CURSOR_ATTRIBUTES1 : SQL_STATIC_CURSOR_ATTRIBUTES2; + else if(SQL_CURSOR_FORWARD_ONLY == _nCursorType) + nAskFor = bFirst ? SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 : SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2; + else if(SQL_CURSOR_DYNAMIC == _nCursorType) + nAskFor = bFirst ? SQL_DYNAMIC_CURSOR_ATTRIBUTES1 : SQL_DYNAMIC_CURSOR_ATTRIBUTES2; + + + OTools::GetInfo(getOwnConnection(),getConnectionHandle(),nAskFor,nValueLen,nullptr); + } + catch(const Exception&) + { // we don't want our result destroy here + nValueLen = 0; + } + return nValueLen; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/OTools.cxx b/connectivity/source/drivers/odbc/OTools.cxx new file mode 100644 index 000000000..4781415de --- /dev/null +++ b/connectivity/source/drivers/odbc/OTools.cxx @@ -0,0 +1,797 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <odbc/OTools.hxx> +#include <odbc/OFunctions.hxx> +#include <com/sun/star/sdbc/DataType.hpp> +#include <o3tl/safeint.hxx> +#include <osl/diagnose.h> +#include <osl/endian.h> +#include <odbc/OConnection.hxx> +#include <rtl/ustrbuf.hxx> +#include <sal/log.hxx> + +#include <string.h> + +using namespace connectivity::odbc; +using namespace com::sun::star::uno; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::util; + +namespace { +size_t sqlTypeLen ( SQLSMALLINT _nType ) +{ + switch (_nType) + { + case SQL_C_SSHORT: + case SQL_C_SHORT: + return sizeof(SQLSMALLINT); + case SQL_C_USHORT: + return sizeof(SQLUSMALLINT); + case SQL_C_SLONG: + case SQL_C_LONG: + return sizeof(SQLINTEGER); + case SQL_C_ULONG: + return sizeof(SQLUINTEGER); + case SQL_C_FLOAT: + return sizeof(SQLREAL); + case SQL_C_DOUBLE: + static_assert(sizeof(SQLDOUBLE) == sizeof(SQLFLOAT), "SQLDOUBLE/SQLFLOAT confusion"); + return sizeof(SQLDOUBLE); + case SQL_C_BIT: + return sizeof(SQLCHAR); + case SQL_C_STINYINT: + case SQL_C_TINYINT: + return sizeof(SQLSCHAR); + case SQL_C_UTINYINT: + return sizeof(SQLCHAR); + case SQL_C_SBIGINT: + return sizeof(SQLBIGINT); + case SQL_C_UBIGINT: + return sizeof(SQLUBIGINT); + /* UnixODBC gives this the same value as SQL_C_UBIGINT + case SQL_C_BOOKMARK: + return sizeof(BOOKMARK); */ + case SQL_C_TYPE_DATE: + case SQL_C_DATE: + return sizeof(SQL_DATE_STRUCT); + case SQL_C_TYPE_TIME: + case SQL_C_TIME: + return sizeof(SQL_TIME_STRUCT); + case SQL_C_TYPE_TIMESTAMP: + case SQL_C_TIMESTAMP: + return sizeof(SQL_TIMESTAMP_STRUCT); + case SQL_C_NUMERIC: + return sizeof(SQL_NUMERIC_STRUCT); + case SQL_C_GUID: + return sizeof(SQLGUID); + case SQL_C_INTERVAL_YEAR: + case SQL_C_INTERVAL_MONTH: + case SQL_C_INTERVAL_DAY: + case SQL_C_INTERVAL_HOUR: + case SQL_C_INTERVAL_MINUTE: + case SQL_C_INTERVAL_SECOND: + case SQL_C_INTERVAL_YEAR_TO_MONTH: + case SQL_C_INTERVAL_DAY_TO_HOUR: + case SQL_C_INTERVAL_DAY_TO_MINUTE: + case SQL_C_INTERVAL_DAY_TO_SECOND: + case SQL_C_INTERVAL_HOUR_TO_MINUTE: + case SQL_C_INTERVAL_HOUR_TO_SECOND: + case SQL_C_INTERVAL_MINUTE_TO_SECOND: + return sizeof(SQL_INTERVAL_STRUCT); + // ** Variable-sized datatypes -> cannot predict length + case SQL_C_CHAR: + case SQL_C_WCHAR: + case SQL_C_BINARY: + // UnixODBC gives this the same value as SQL_C_BINARY + //case SQL_C_VARBOOKMARK: + // Unknown datatype -> cannot predict length + default: + return static_cast<size_t>(-1); + } +} + +void appendSQLWCHARs(OUStringBuffer & s, SQLWCHAR const * d, sal_Int32 n) +{ + static_assert( + sizeof (SQLWCHAR) == sizeof (sal_Unicode) || sizeof (SQLWCHAR) == 4, + "bad SQLWCHAR"); + if (sizeof (SQLWCHAR) == sizeof (sal_Unicode)) { + s.append(reinterpret_cast<sal_Unicode const *>(d), n); + } else { + for (sal_Int32 i = 0; i != n; ++i) { + s.appendUtf32(d[i]); + } + } +} +} + + +void OTools::getValue( OConnection const * _pConnection, + SQLHANDLE _aStatementHandle, + sal_Int32 columnIndex, + SQLSMALLINT _nType, + bool &_bWasNull, + const css::uno::Reference< css::uno::XInterface >& _xInterface, + void* _pValue, + SQLLEN _nSize) +{ + const size_t properSize = sqlTypeLen(_nType); + if ( properSize == static_cast<size_t>(-1) ) + SAL_WARN( "connectivity.drivers", "connectivity::odbc::OTools::getValue: unknown SQL type - cannot check buffer size"); + else + { + OSL_ENSURE(static_cast<size_t>(_nSize) == properSize, "connectivity::odbc::OTools::getValue got wrongly sized memory region to write result to"); + if ( o3tl::make_unsigned(_nSize) > properSize ) + { + SAL_WARN( "connectivity.drivers", "memory region is too big - trying to fudge it"); + memset(_pValue, 0, _nSize); +#ifdef OSL_BIGENDIAN + // This is skewed in favour of integer types + _pValue = static_cast<char*>(_pValue) + _nSize - properSize; +#endif + } + } + OSL_ENSURE(o3tl::make_unsigned(_nSize) >= properSize, "memory region is too small"); + SQLLEN pcbValue = SQL_NULL_DATA; + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetData>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetData)))(_aStatementHandle, + static_cast<SQLUSMALLINT>(columnIndex), + _nType, + _pValue, + _nSize, + &pcbValue), + _aStatementHandle,SQL_HANDLE_STMT,_xInterface,false); + _bWasNull = pcbValue == SQL_NULL_DATA; +} + +void OTools::bindValue( OConnection const * _pConnection, + SQLHANDLE _aStatementHandle, + sal_Int32 columnIndex, + SQLSMALLINT _nType, + SQLSMALLINT _nMaxLen, + const void* _pValue, + void* _pData, + SQLLEN * const pLen, + const css::uno::Reference< css::uno::XInterface >& _xInterface, + rtl_TextEncoding _nTextEncoding, + bool _bUseOldTimeDate) +{ + SQLRETURN nRetcode; + SQLSMALLINT fSqlType; + SQLSMALLINT fCType; + + OTools::getBindTypes( false, + _bUseOldTimeDate, + _nType, + fCType, + fSqlType); + + if (columnIndex != 0 && !_pValue) + { + *pLen = SQL_NULL_DATA; + nRetcode = (*reinterpret_cast<T3SQLBindCol>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::BindCol)))(_aStatementHandle, + static_cast<SQLUSMALLINT>(columnIndex), + fCType, + _pData, + _nMaxLen, + pLen + ); + } + else + { + try + { + switch (_nType) + { + case SQL_CHAR: + case SQL_VARCHAR: + { + OString aString(OUStringToOString(*static_cast<OUString const *>(_pValue),_nTextEncoding)); + *pLen = SQL_NTS; + *static_cast<OString*>(_pData) = aString; + + // Pointer on Char* + _pData = const_cast<char *>(aString.getStr()); + } break; + case SQL_BIGINT: + *static_cast<sal_Int64*>(_pData) = *static_cast<sal_Int64 const *>(_pValue); + *pLen = sizeof(sal_Int64); + break; + case SQL_DECIMAL: + case SQL_NUMERIC: + { + OString aString = OString::number(*static_cast<double const *>(_pValue)); + *pLen = static_cast<SQLSMALLINT>(aString.getLength()); + *static_cast<OString*>(_pData) = aString; + // Pointer on Char* + _pData = const_cast<char *>(static_cast<OString*>(_pData)->getStr()); + } break; + case SQL_BIT: + case SQL_TINYINT: + *static_cast<sal_Int8*>(_pData) = *static_cast<sal_Int8 const *>(_pValue); + *pLen = sizeof(sal_Int8); + break; + + case SQL_SMALLINT: + *static_cast<sal_Int16*>(_pData) = *static_cast<sal_Int16 const *>(_pValue); + *pLen = sizeof(sal_Int16); + break; + case SQL_INTEGER: + *static_cast<sal_Int32*>(_pData) = *static_cast<sal_Int32 const *>(_pValue); + *pLen = sizeof(sal_Int32); + break; + case SQL_FLOAT: + *static_cast<float*>(_pData) = *static_cast<float const *>(_pValue); + *pLen = sizeof(float); + break; + case SQL_REAL: + case SQL_DOUBLE: + *static_cast<double*>(_pData) = *static_cast<double const *>(_pValue); + *pLen = sizeof(double); + break; + case SQL_BINARY: + case SQL_VARBINARY: + { + _pData = const_cast<sal_Int8 *>(static_cast<const css::uno::Sequence< sal_Int8 > *>(_pValue)->getConstArray()); + *pLen = static_cast<const css::uno::Sequence< sal_Int8 > *>(_pValue)->getLength(); + } break; + case SQL_LONGVARBINARY: + { + /* see https://msdn.microsoft.com/en-us/library/ms716238%28v=vs.85%29.aspx + * for an explanation of that apparently weird cast */ + _pData = reinterpret_cast<void*>(static_cast<uintptr_t>(columnIndex)); + sal_Int32 nLen = static_cast<const css::uno::Sequence< sal_Int8 > *>(_pValue)->getLength(); + *pLen = static_cast<SQLLEN>(SQL_LEN_DATA_AT_EXEC(nLen)); + } + break; + case SQL_LONGVARCHAR: + { + /* see https://msdn.microsoft.com/en-us/library/ms716238%28v=vs.85%29.aspx + * for an explanation of that apparently weird cast */ + _pData = reinterpret_cast<void*>(static_cast<uintptr_t>(columnIndex)); + sal_Int32 nLen = static_cast<OUString const *>(_pValue)->getLength(); + *pLen = static_cast<SQLLEN>(SQL_LEN_DATA_AT_EXEC(nLen)); + } break; + case SQL_DATE: + *pLen = sizeof(DATE_STRUCT); + *static_cast<DATE_STRUCT*>(_pData) = *static_cast<DATE_STRUCT const *>(_pValue); + break; + case SQL_TIME: + *pLen = sizeof(TIME_STRUCT); + *static_cast<TIME_STRUCT*>(_pData) = *static_cast<TIME_STRUCT const *>(_pValue); + break; + case SQL_TIMESTAMP: + *pLen = sizeof(TIMESTAMP_STRUCT); + *static_cast<TIMESTAMP_STRUCT*>(_pData) = *static_cast<TIMESTAMP_STRUCT const *>(_pValue); + break; + } + } + catch ( ... ) + { + } + + nRetcode = (*reinterpret_cast<T3SQLBindCol>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::BindCol)))(_aStatementHandle, + static_cast<SQLUSMALLINT>(columnIndex), + fCType, + _pData, + _nMaxLen, + pLen + ); + } + + OTools::ThrowException(_pConnection,nRetcode,_aStatementHandle,SQL_HANDLE_STMT,_xInterface); +} + +void OTools::ThrowException(const OConnection* _pConnection, + const SQLRETURN _rRetCode, + const SQLHANDLE _pContext, + const SQLSMALLINT _nHandleType, + const Reference< XInterface >& _xInterface, + const bool _bNoFound) +{ + switch(_rRetCode) + { + case SQL_NEED_DATA: + case SQL_STILL_EXECUTING: + case SQL_SUCCESS: + + case SQL_SUCCESS_WITH_INFO: + return; + case SQL_NO_DATA_FOUND: + if(_bNoFound) + return; // no need to throw an exception + break; + case SQL_ERROR: break; + + + case SQL_INVALID_HANDLE: SAL_WARN( "connectivity.drivers", "SdbODBC3_SetStatus: SQL_INVALID_HANDLE"); + throw SQLException(); + } + + // Additional Information on the latest ODBC-functioncall available + // SQLError provides this Information. + + SDB_ODBC_CHAR szSqlState[5]; + SQLINTEGER pfNativeError; + SDB_ODBC_CHAR szErrorMessage[SQL_MAX_MESSAGE_LENGTH]; + szErrorMessage[0] = '\0'; + SQLSMALLINT pcbErrorMsg = 0; + + // Information for latest operation: + // when hstmt != SQL_NULL_HSTMT is (Used from SetStatus in SdbCursor, SdbTable, ...), + // then the status of the latest statements will be fetched, without the Status of the last + // statements of this connection [what in this case will probably be the same, but the Reference + // Manual isn't totally clear in this...]. + // corresponding for hdbc. + SQLRETURN n = (*reinterpret_cast<T3SQLGetDiagRec>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetDiagRec)))(_nHandleType,_pContext,1, + szSqlState, + &pfNativeError, + szErrorMessage,sizeof szErrorMessage - 1,&pcbErrorMsg); + OSL_ENSURE(n != SQL_INVALID_HANDLE,"SdbODBC3_SetStatus: SQLError returned SQL_INVALID_HANDLE"); + OSL_ENSURE(n == SQL_SUCCESS || n == SQL_SUCCESS_WITH_INFO || n == SQL_NO_DATA_FOUND || n == SQL_ERROR,"SdbODBC3_SetStatus: SQLError failed"); + + rtl_TextEncoding _nTextEncoding = osl_getThreadTextEncoding(); + // For the Return Code of SQLError see ODBC 2.0 Programmer's Reference Page 287ff + throw SQLException( OUString(reinterpret_cast<char *>(szErrorMessage), pcbErrorMsg, _nTextEncoding), + _xInterface, + OUString(reinterpret_cast<char *>(szSqlState), 5, _nTextEncoding), + pfNativeError, + Any() + ); + +} + +Sequence<sal_Int8> OTools::getBytesValue(const OConnection* _pConnection, + const SQLHANDLE _aStatementHandle, + const sal_Int32 columnIndex, + const SQLSMALLINT _fSqlType, + bool &_bWasNull, + const Reference< XInterface >& _xInterface) +{ + sal_Int8 aCharArray[2048]; + // First try to fetch the data with the little Buffer: + const SQLLEN nMaxLen = sizeof aCharArray; + SQLLEN pcbValue = SQL_NO_TOTAL; + Sequence<sal_Int8> aData; + + OSL_ENSURE( _fSqlType != SQL_CHAR && _fSqlType != SQL_VARCHAR && _fSqlType != SQL_LONGVARCHAR && + _fSqlType != SQL_WCHAR && _fSqlType != SQL_WVARCHAR && _fSqlType != SQL_WLONGVARCHAR, + "connectivity::odbc::OTools::getBytesValue called with character _fSqlType"); + + while (pcbValue == SQL_NO_TOTAL || pcbValue > nMaxLen) + { + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetData>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetData)))( + _aStatementHandle, + static_cast<SQLUSMALLINT>(columnIndex), + _fSqlType, + static_cast<SQLPOINTER>(aCharArray), + nMaxLen, + &pcbValue), + _aStatementHandle,SQL_HANDLE_STMT,_xInterface); + + _bWasNull = pcbValue == SQL_NULL_DATA; + if(_bWasNull) + return Sequence<sal_Int8>(); + + SQLLEN nReadBytes; + // After the SQLGetData that wrote out to aCharArray the last byte of the data, + // pcbValue will not be SQL_NO_TOTAL -> we have a reliable count + if ( (pcbValue == SQL_NO_TOTAL) || (pcbValue >= nMaxLen) ) + { + // we filled the buffer + nReadBytes = nMaxLen; + } + else + { + nReadBytes = pcbValue; + } + const sal_Int32 nLen = aData.getLength(); + aData.realloc(nLen + nReadBytes); + memcpy(aData.getArray() + nLen, aCharArray, nReadBytes); + } + return aData; +} + +OUString OTools::getStringValue(OConnection const * _pConnection, + SQLHANDLE _aStatementHandle, + sal_Int32 columnIndex, + SQLSMALLINT _fSqlType, + bool &_bWasNull, + const Reference< XInterface >& _xInterface, + const rtl_TextEncoding _nTextEncoding) +{ + OUStringBuffer aData; + switch(_fSqlType) + { + case SQL_WVARCHAR: + case SQL_WCHAR: + case SQL_WLONGVARCHAR: + { + SQLWCHAR waCharArray[2048]; + static_assert(sizeof(waCharArray) % sizeof(SQLWCHAR) == 0, "must fit in evenly"); + static_assert(sizeof(SQLWCHAR) == 2 || sizeof(SQLWCHAR) == 4, "must be 2 or 4"); + // Size == number of bytes, Len == number of UTF-16 or UCS4 code units + const SQLLEN nMaxSize = sizeof(waCharArray); + const SQLLEN nMaxLen = sizeof(waCharArray) / sizeof(SQLWCHAR); + static_assert(nMaxLen * sizeof(SQLWCHAR) == nMaxSize, "sizes must match"); + + // read the unicode data + SQLLEN pcbValue = SQL_NO_TOTAL; + while ((pcbValue == SQL_NO_TOTAL ) || (pcbValue >= nMaxSize) ) + { + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetData>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetData)))( + _aStatementHandle, + static_cast<SQLUSMALLINT>(columnIndex), + SQL_C_WCHAR, + &waCharArray, + SQLLEN(nMaxLen)*sizeof(sal_Unicode), + &pcbValue), + _aStatementHandle,SQL_HANDLE_STMT,_xInterface); + _bWasNull = pcbValue == SQL_NULL_DATA; + if(_bWasNull) + return OUString(); + + SQLLEN nReadChars; + OSL_ENSURE( (pcbValue < 0) || (pcbValue % 2 == 0), + "ODBC: SQLGetData of SQL_C_WCHAR returned odd number of bytes"); + if ( (pcbValue == SQL_NO_TOTAL) || (pcbValue >= nMaxSize) ) + { + // we filled the buffer; remove the terminating null character + nReadChars = nMaxLen-1; + if ( waCharArray[nReadChars] != 0) + { + SAL_WARN( "connectivity.drivers", "Buggy ODBC driver? Did not null-terminate (variable length) data!"); + ++nReadChars; + } + } + else + { + nReadChars = pcbValue/sizeof(SQLWCHAR); + } + + appendSQLWCHARs(aData, waCharArray, nReadChars); + } + break; + } + default: + { + char aCharArray[2048]; + // read the unicode data + const SQLLEN nMaxLen = sizeof(aCharArray); + SQLLEN pcbValue = SQL_NO_TOTAL; + + while ((pcbValue == SQL_NO_TOTAL ) || (pcbValue >= nMaxLen) ) + { + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetData>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetData)))( + _aStatementHandle, + static_cast<SQLUSMALLINT>(columnIndex), + SQL_C_CHAR, + &aCharArray, + nMaxLen, + &pcbValue), + _aStatementHandle,SQL_HANDLE_STMT,_xInterface); + _bWasNull = pcbValue == SQL_NULL_DATA; + if(_bWasNull) + return OUString(); + + SQLLEN nReadChars; + if ( (pcbValue == SQL_NO_TOTAL) || (pcbValue >= nMaxLen) ) + { + // we filled the buffer; remove the terminating null character + nReadChars = nMaxLen-1; + if ( aCharArray[nReadChars] != 0) + { + SAL_WARN( "connectivity.drivers", "Buggy ODBC driver? Did not null-terminate (variable length) data!"); + ++nReadChars; + } + } + else + { + nReadChars = pcbValue; + } + + aData.append(OUString(aCharArray, nReadChars, _nTextEncoding)); + + } + break; + } + } + + return aData.makeStringAndClear(); +} + +void OTools::GetInfo(OConnection const * _pConnection, + SQLHANDLE _aConnectionHandle, + SQLUSMALLINT _nInfo, + OUString &_rValue, + const Reference< XInterface >& _xInterface, + rtl_TextEncoding _nTextEncoding) +{ + char aValue[512]; + SQLSMALLINT nValueLen=0; + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetInfo>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetInfo)))(_aConnectionHandle,_nInfo,aValue,(sizeof aValue)-1,&nValueLen), + _aConnectionHandle,SQL_HANDLE_DBC,_xInterface); + + _rValue = OUString(aValue,nValueLen,_nTextEncoding); +} + +void OTools::GetInfo(OConnection const * _pConnection, + SQLHANDLE _aConnectionHandle, + SQLUSMALLINT _nInfo, + sal_Int32 &_rValue, + const Reference< XInterface >& _xInterface) +{ + SQLSMALLINT nValueLen; + _rValue = 0; // in case the driver uses only 16 of the 32 bits (as it does, for example, for SQL_CATALOG_LOCATION) + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetInfo>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetInfo)))(_aConnectionHandle,_nInfo,&_rValue,sizeof _rValue,&nValueLen), + _aConnectionHandle,SQL_HANDLE_DBC,_xInterface); +} + +void OTools::GetInfo(OConnection const * _pConnection, + SQLHANDLE _aConnectionHandle, + SQLUSMALLINT _nInfo, + SQLUINTEGER &_rValue, + const Reference< XInterface >& _xInterface) +{ + SQLSMALLINT nValueLen; + _rValue = 0; // in case the driver uses only 16 of the 32 bits (as it does, for example, for SQL_CATALOG_LOCATION) + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetInfo>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetInfo)))(_aConnectionHandle,_nInfo,&_rValue,sizeof _rValue,&nValueLen), + _aConnectionHandle,SQL_HANDLE_DBC,_xInterface); +} + +void OTools::GetInfo(OConnection const * _pConnection, + SQLHANDLE _aConnectionHandle, + SQLUSMALLINT _nInfo, + SQLUSMALLINT &_rValue, + const Reference< XInterface >& _xInterface) +{ + SQLSMALLINT nValueLen; + _rValue = 0; // in case the driver uses only 16 of the 32 bits (as it does, for example, for SQL_CATALOG_LOCATION) + OTools::ThrowException(_pConnection, + (*reinterpret_cast<T3SQLGetInfo>(_pConnection->getOdbcFunction(ODBC3SQLFunctionId::GetInfo)))(_aConnectionHandle,_nInfo,&_rValue,sizeof _rValue,&nValueLen), + _aConnectionHandle,SQL_HANDLE_DBC,_xInterface); +} + +sal_Int32 OTools::MapOdbcType2Jdbc(SQLSMALLINT _nType) +{ + sal_Int32 nValue = DataType::VARCHAR; + switch(_nType) + { + case SQL_BIT: + nValue = DataType::BIT; + break; + case SQL_TINYINT: + nValue = DataType::TINYINT; + break; + case SQL_SMALLINT: + nValue = DataType::SMALLINT; + break; + case SQL_INTEGER: + nValue = DataType::INTEGER; + break; + case SQL_BIGINT: + nValue = DataType::BIGINT; + break; + case SQL_FLOAT: + nValue = DataType::FLOAT; + break; + case SQL_REAL: + nValue = DataType::REAL; + break; + case SQL_DOUBLE: + nValue = DataType::DOUBLE; + break; + case SQL_NUMERIC: + nValue = DataType::NUMERIC; + break; + case SQL_DECIMAL: + nValue = DataType::DECIMAL; + break; + case SQL_WCHAR: + case SQL_CHAR: + nValue = DataType::CHAR; + break; + case SQL_WVARCHAR: + case SQL_VARCHAR: + nValue = DataType::VARCHAR; + break; + case SQL_WLONGVARCHAR: + case SQL_LONGVARCHAR: + nValue = DataType::LONGVARCHAR; + break; + case SQL_TYPE_DATE: + case SQL_DATE: + nValue = DataType::DATE; + break; + case SQL_TYPE_TIME: + case SQL_TIME: + nValue = DataType::TIME; + break; + case SQL_TYPE_TIMESTAMP: + case SQL_TIMESTAMP: + nValue = DataType::TIMESTAMP; + break; + case SQL_BINARY: + nValue = DataType::BINARY; + break; + case SQL_VARBINARY: + case SQL_GUID: + nValue = DataType::VARBINARY; + break; + case SQL_LONGVARBINARY: + nValue = DataType::LONGVARBINARY; + break; + default: + OSL_FAIL("Invalid type"); + } + return nValue; +} + +// jdbcTypeToOdbc +// Convert the JDBC SQL type to the correct ODBC type + +SQLSMALLINT OTools::jdbcTypeToOdbc(sal_Int32 jdbcType) +{ + // For the most part, JDBC types match ODBC types. We'll + // just convert the ones that we know are different + + sal_Int32 odbcType = jdbcType; + + switch (jdbcType) + { + case DataType::DATE: + odbcType = SQL_DATE; + break; + case DataType::TIME: + odbcType = SQL_TIME; + break; + case DataType::TIMESTAMP: + odbcType = SQL_TIMESTAMP; + break; + // ODBC doesn't have any notion of CLOB or BLOB + case DataType::CLOB: + odbcType = SQL_LONGVARCHAR; + break; + case DataType::BLOB: + odbcType = SQL_LONGVARBINARY; + break; + } + + return odbcType; +} + +void OTools::getBindTypes(bool _bUseWChar, + bool _bUseOldTimeDate, + SQLSMALLINT _nOdbcType, + SQLSMALLINT& fCType, + SQLSMALLINT& fSqlType + ) +{ + switch(_nOdbcType) + { + case SQL_CHAR: if(_bUseWChar) + { + fCType = SQL_C_WCHAR; + fSqlType = SQL_WCHAR; + } + else + { + fCType = SQL_C_CHAR; + fSqlType = SQL_CHAR; + } + break; + case SQL_VARCHAR: if(_bUseWChar) + { + fCType = SQL_C_WCHAR; + fSqlType = SQL_WVARCHAR; + } + else + { + fCType = SQL_C_CHAR; + fSqlType = SQL_VARCHAR; + } + break; + case SQL_LONGVARCHAR: if(_bUseWChar) + { + fCType = SQL_C_WCHAR; + fSqlType = SQL_WLONGVARCHAR; + } + else + { + fCType = SQL_C_CHAR; + fSqlType = SQL_LONGVARCHAR; + } + break; + case SQL_DECIMAL: fCType = _bUseWChar ? SQL_C_WCHAR : SQL_C_CHAR; + fSqlType = SQL_DECIMAL; break; + case SQL_NUMERIC: fCType = _bUseWChar ? SQL_C_WCHAR : SQL_C_CHAR; + fSqlType = SQL_NUMERIC; break; + case SQL_BIT: fCType = SQL_C_TINYINT; + fSqlType = SQL_INTEGER; break; + case SQL_TINYINT: fCType = SQL_C_TINYINT; + fSqlType = SQL_TINYINT; break; + case SQL_SMALLINT: fCType = SQL_C_SHORT; + fSqlType = SQL_SMALLINT; break; + case SQL_INTEGER: fCType = SQL_C_LONG; + fSqlType = SQL_INTEGER; break; + case SQL_BIGINT: fCType = SQL_C_SBIGINT; + fSqlType = SQL_BIGINT; break; + case SQL_FLOAT: fCType = SQL_C_FLOAT; + fSqlType = SQL_FLOAT; break; + case SQL_REAL: fCType = SQL_C_DOUBLE; + fSqlType = SQL_REAL; break; + case SQL_DOUBLE: fCType = SQL_C_DOUBLE; + fSqlType = SQL_DOUBLE; break; + case SQL_BINARY: fCType = SQL_C_BINARY; + fSqlType = SQL_BINARY; break; + case SQL_VARBINARY: + fCType = SQL_C_BINARY; + fSqlType = SQL_VARBINARY; break; + case SQL_LONGVARBINARY: fCType = SQL_C_BINARY; + fSqlType = SQL_LONGVARBINARY; break; + case SQL_DATE: + if(_bUseOldTimeDate) + { + fCType = SQL_C_DATE; + fSqlType = SQL_DATE; + } + else + { + fCType = SQL_C_TYPE_DATE; + fSqlType = SQL_TYPE_DATE; + } + break; + case SQL_TIME: + if(_bUseOldTimeDate) + { + fCType = SQL_C_TIME; + fSqlType = SQL_TIME; + } + else + { + fCType = SQL_C_TYPE_TIME; + fSqlType = SQL_TYPE_TIME; + } + break; + case SQL_TIMESTAMP: + if(_bUseOldTimeDate) + { + fCType = SQL_C_TIMESTAMP; + fSqlType = SQL_TIMESTAMP; + } + else + { + fCType = SQL_C_TYPE_TIMESTAMP; + fSqlType = SQL_TYPE_TIMESTAMP; + } + break; + default: fCType = SQL_C_BINARY; + fSqlType = SQL_LONGVARBINARY; break; + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/connectivity/source/drivers/odbc/odbc.component b/connectivity/source/drivers/odbc/odbc.component new file mode 100644 index 000000000..4d3348378 --- /dev/null +++ b/connectivity/source/drivers/odbc/odbc.component @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + --> + +<component loader="com.sun.star.loader.SharedLibrary" environment="@CPPU_ENV@" + xmlns="http://openoffice.org/2010/uno-components"> + <implementation name="com.sun.star.comp.sdbc.ODBCDriver" + constructor="connectivity_odbc_ORealOdbcDriver_get_implementation"> + <service name="com.sun.star.sdbc.Driver"/> + </implementation> +</component> |