bump product version to 6.3.0.0.beta1
[LibreOffice.git] / connectivity / source / commontools / dbtools2.cxx
blobca91c1401749b11a069b97086a292e5cf17168ad
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <connectivity/dbtools.hxx>
21 #include <connectivity/dbconversion.hxx>
22 #include <connectivity/dbcharset.hxx>
23 #include <connectivity/SQLStatementHelper.hxx>
24 #include <unotools/confignode.hxx>
25 #include <resource/sharedresources.hxx>
26 #include <strings.hrc>
27 #include <com/sun/star/sdbc/SQLException.hpp>
28 #include <com/sun/star/sdbc/XConnection.hpp>
29 #include <com/sun/star/sdbc/ColumnValue.hpp>
30 #include <com/sun/star/sdbc/DataType.hpp>
31 #include <com/sun/star/sdbc/DriverManager.hpp>
32 #include <com/sun/star/sdbc/XRow.hpp>
33 #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
34 #include <com/sun/star/sdbcx/XKeysSupplier.hpp>
35 #include <com/sun/star/sdbc/XDriverAccess.hpp>
36 #include <com/sun/star/sdbcx/XDataDefinitionSupplier.hpp>
37 #include <com/sun/star/sdbcx/Privilege.hpp>
38 #include <com/sun/star/container/XIndexAccess.hpp>
39 #include <com/sun/star/container/XEnumerationAccess.hpp>
40 #include <com/sun/star/sdbc/KeyRule.hpp>
41 #include <com/sun/star/sdbcx/KeyType.hpp>
42 #include <TConnection.hxx>
43 #include <connectivity/sdbcx/VColumn.hxx>
44 #include <com/sun/star/frame/XModel.hpp>
45 #include <com/sun/star/container/XChild.hpp>
47 #include <comphelper/types.hxx>
48 #include <tools/diagnose_ex.h>
49 #include <unotools/sharedunocomponent.hxx>
50 #include <algorithm>
51 #include <string_view>
53 namespace dbtools
56 using namespace ::com::sun::star::uno;
57 using namespace ::com::sun::star::beans;
58 using namespace ::com::sun::star::sdb;
59 using namespace ::com::sun::star::sdbc;
60 using namespace ::com::sun::star::sdbcx;
61 using namespace ::com::sun::star::lang;
62 using namespace ::com::sun::star::container;
63 using namespace ::com::sun::star::frame;
64 using namespace connectivity;
65 using namespace comphelper;
67 OUString createStandardTypePart(const Reference< XPropertySet >& xColProp,const Reference< XConnection>& _xConnection,const OUString& _sCreatePattern)
70 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
72 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
74 OUString sTypeName;
75 sal_Int32 nDataType = 0;
76 sal_Int32 nPrecision = 0;
77 sal_Int32 nScale = 0;
79 nDataType = nPrecision = nScale = 0;
81 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_TYPENAME)) >>= sTypeName;
82 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_TYPE)) >>= nDataType;
83 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_PRECISION)) >>= nPrecision;
84 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
86 OUStringBuffer aSql;
88 // check if the user enter a specific string to create autoincrement values
89 OUString sAutoIncrementValue;
90 Reference<XPropertySetInfo> xPropInfo = xColProp->getPropertySetInfo();
91 if ( xPropInfo.is() && xPropInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION)) )
92 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION)) >>= sAutoIncrementValue;
93 // look if we have to use precisions
94 bool bUseLiteral = false;
95 OUString sPrefix,sPostfix,sCreateParams;
97 Reference<XResultSet> xRes = xMetaData->getTypeInfo();
98 if(xRes.is())
100 Reference<XRow> xRow(xRes,UNO_QUERY);
101 while(xRes->next())
103 OUString sTypeName2Cmp = xRow->getString(1);
104 sal_Int32 nType = xRow->getShort(2);
105 sPrefix = xRow->getString (4);
106 sPostfix = xRow->getString (5);
107 sCreateParams = xRow->getString(6);
108 // first identical type will be used if typename is empty
109 if ( sTypeName.isEmpty() && nType == nDataType )
110 sTypeName = sTypeName2Cmp;
112 if( sTypeName.equalsIgnoreAsciiCase(sTypeName2Cmp) && nType == nDataType && !sCreateParams.isEmpty() && !xRow->wasNull())
114 bUseLiteral = true;
115 break;
121 sal_Int32 nIndex = 0;
122 if ( !sAutoIncrementValue.isEmpty() && (nIndex = sTypeName.indexOf(sAutoIncrementValue)) != -1 )
124 sTypeName = sTypeName.replaceAt(nIndex,sTypeName.getLength() - nIndex,OUString());
127 if ( (nPrecision > 0 || nScale > 0) && bUseLiteral )
129 sal_Int32 nParenPos = sTypeName.indexOf('(');
130 if ( nParenPos == -1 )
132 aSql.append(sTypeName);
133 aSql.append("(");
135 else
137 aSql.append(std::u16string_view(sTypeName).substr(0, ++nParenPos));
140 if ( nPrecision > 0 && nDataType != DataType::TIMESTAMP )
142 aSql.append(nPrecision);
143 if ( (nScale > 0) || (!_sCreatePattern.isEmpty() && sCreateParams.indexOf(_sCreatePattern) != -1) )
144 aSql.append(",");
146 if ( (nScale > 0) || ( !_sCreatePattern.isEmpty() && sCreateParams.indexOf(_sCreatePattern) != -1 ) || nDataType == DataType::TIMESTAMP )
147 aSql.append(nScale);
149 if ( nParenPos == -1 )
150 aSql.append(")");
151 else
153 nParenPos = sTypeName.indexOf(')',nParenPos);
154 aSql.append(std::u16string_view(sTypeName).substr(nParenPos));
157 else
158 aSql.append(sTypeName); // simply add the type name
160 OUString aDefault = ::comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_DEFAULTVALUE)));
161 if ( !aDefault.isEmpty() )
163 aSql.append(" DEFAULT ");
164 aSql.append(sPrefix);
165 aSql.append(aDefault);
166 aSql.append(sPostfix);
167 } // if ( aDefault.getLength() )
169 return aSql.makeStringAndClear();
172 OUString createStandardColumnPart(const Reference< XPropertySet >& xColProp,const Reference< XConnection>& _xConnection,ISQLStatementHelper* _pHelper,const OUString& _sCreatePattern)
174 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
176 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
178 bool bIsAutoIncrement = false;
179 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bIsAutoIncrement;
181 const OUString sQuoteString = xMetaData->getIdentifierQuoteString();
182 OUStringBuffer aSql = ::dbtools::quoteName(sQuoteString,::comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))));
184 // check if the user enter a specific string to create autoincrement values
185 OUString sAutoIncrementValue;
186 Reference<XPropertySetInfo> xPropInfo = xColProp->getPropertySetInfo();
187 if ( xPropInfo.is() && xPropInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION)) )
188 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION)) >>= sAutoIncrementValue;
190 aSql.append(" ");
192 aSql.append(createStandardTypePart(xColProp, _xConnection, _sCreatePattern));
194 if(::comphelper::getINT32(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISNULLABLE))) == ColumnValue::NO_NULLS)
195 aSql.append(" NOT NULL");
197 if ( bIsAutoIncrement && !sAutoIncrementValue.isEmpty())
199 aSql.append(" ");
200 aSql.append(sAutoIncrementValue);
203 if ( _pHelper )
204 _pHelper->addComment(xColProp,aSql);
206 return aSql.makeStringAndClear();
210 OUString createStandardCreateStatement(const Reference< XPropertySet >& descriptor,const Reference< XConnection>& _xConnection,ISQLStatementHelper* _pHelper,const OUString& _sCreatePattern)
212 OUStringBuffer aSql("CREATE TABLE ");
213 OUString sCatalog,sSchema,sTable,sComposedName;
215 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
216 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
218 descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)) >>= sCatalog;
219 descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= sSchema;
220 descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= sTable;
222 sComposedName = ::dbtools::composeTableName( xMetaData, sCatalog, sSchema, sTable, true, ::dbtools::EComposeRule::InTableDefinitions );
223 if ( sComposedName.isEmpty() )
224 ::dbtools::throwFunctionSequenceException(_xConnection);
226 aSql.append(sComposedName);
227 aSql.append(" (");
229 // columns
230 Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY);
231 Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY);
232 // check if there are columns
233 if(!xColumns.is() || !xColumns->getCount())
234 ::dbtools::throwFunctionSequenceException(_xConnection);
236 Reference< XPropertySet > xColProp;
238 sal_Int32 nCount = xColumns->getCount();
239 for(sal_Int32 i=0;i<nCount;++i)
241 if ( (xColumns->getByIndex(i) >>= xColProp) && xColProp.is() )
243 aSql.append(createStandardColumnPart(xColProp,_xConnection,_pHelper,_sCreatePattern));
244 aSql.append(",");
247 return aSql.makeStringAndClear();
249 namespace
251 OUString generateColumnNames(const Reference<XIndexAccess>& _xColumns,const Reference<XDatabaseMetaData>& _xMetaData)
253 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
255 const OUString sQuote(_xMetaData->getIdentifierQuoteString());
256 OUStringBuffer sSql( " (" );
257 Reference< XPropertySet > xColProp;
259 sal_Int32 nColCount = _xColumns->getCount();
260 for(sal_Int32 i=0;i<nColCount;++i)
262 if ( (_xColumns->getByIndex(i) >>= xColProp) && xColProp.is() )
263 sSql.append( ::dbtools::quoteName(sQuote,::comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)))) )
264 .append(",");
267 if ( nColCount )
268 sSql[sSql.getLength()-1] = ')';
269 return sSql.makeStringAndClear();
273 OUString createStandardKeyStatement(const Reference< XPropertySet >& descriptor,const Reference< XConnection>& _xConnection)
275 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
276 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
278 OUStringBuffer aSql;
279 // keys
280 Reference<XKeysSupplier> xKeySup(descriptor,UNO_QUERY);
281 Reference<XIndexAccess> xKeys = xKeySup->getKeys();
282 if ( xKeys.is() )
284 Reference< XPropertySet > xColProp;
285 Reference<XIndexAccess> xColumns;
286 Reference<XColumnsSupplier> xColumnSup;
287 OUString sCatalog,sSchema,sTable,sComposedName;
288 bool bPKey = false;
289 for(sal_Int32 i=0;i<xKeys->getCount();++i)
291 if ( (xKeys->getByIndex(i) >>= xColProp) && xColProp.is() )
294 sal_Int32 nKeyType = ::comphelper::getINT32(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_TYPE)));
296 if ( nKeyType == KeyType::PRIMARY )
298 if(bPKey)
299 ::dbtools::throwFunctionSequenceException(_xConnection);
301 bPKey = true;
302 xColumnSup.set(xColProp,UNO_QUERY);
303 xColumns.set(xColumnSup->getColumns(),UNO_QUERY);
304 if(!xColumns.is() || !xColumns->getCount())
305 ::dbtools::throwFunctionSequenceException(_xConnection);
307 aSql.append(" PRIMARY KEY ");
308 aSql.append(generateColumnNames(xColumns,xMetaData));
310 else if(nKeyType == KeyType::UNIQUE)
312 xColumnSup.set(xColProp,UNO_QUERY);
313 xColumns.set(xColumnSup->getColumns(),UNO_QUERY);
314 if(!xColumns.is() || !xColumns->getCount())
315 ::dbtools::throwFunctionSequenceException(_xConnection);
317 aSql.append(" UNIQUE ");
318 aSql.append(generateColumnNames(xColumns,xMetaData));
320 else if(nKeyType == KeyType::FOREIGN)
322 sal_Int32 nDeleteRule = getINT32(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_DELETERULE)));
324 xColumnSup.set(xColProp,UNO_QUERY);
325 xColumns.set(xColumnSup->getColumns(),UNO_QUERY);
326 if(!xColumns.is() || !xColumns->getCount())
327 ::dbtools::throwFunctionSequenceException(_xConnection);
329 aSql.append(" FOREIGN KEY ");
330 OUString sRefTable = getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_REFERENCEDTABLE)));
331 ::dbtools::qualifiedNameComponents(xMetaData,
332 sRefTable,
333 sCatalog,
334 sSchema,
335 sTable,
336 ::dbtools::EComposeRule::InDataManipulation);
337 sComposedName = ::dbtools::composeTableName( xMetaData, sCatalog, sSchema, sTable, true, ::dbtools::EComposeRule::InTableDefinitions );
340 if ( sComposedName.isEmpty() )
341 ::dbtools::throwFunctionSequenceException(_xConnection);
343 aSql.append(generateColumnNames(xColumns,xMetaData));
345 switch(nDeleteRule)
347 case KeyRule::CASCADE:
348 aSql.append(" ON DELETE CASCADE ");
349 break;
350 case KeyRule::RESTRICT:
351 aSql.append(" ON DELETE RESTRICT ");
352 break;
353 case KeyRule::SET_NULL:
354 aSql.append(" ON DELETE SET NULL ");
355 break;
356 case KeyRule::SET_DEFAULT:
357 aSql.append(" ON DELETE SET DEFAULT ");
358 break;
359 default:
367 if ( !aSql.isEmpty() )
369 if ( aSql[aSql.getLength() - 1] == ',' )
370 aSql[aSql.getLength() - 1] = ')';
371 else
372 aSql.append(")");
375 return aSql.makeStringAndClear();
379 OUString createSqlCreateTableStatement( const Reference< XPropertySet >& descriptor,
380 const Reference< XConnection>& _xConnection)
382 OUString aSql = ::dbtools::createStandardCreateStatement(descriptor,_xConnection,nullptr,OUString());
383 const OUString sKeyStmt = ::dbtools::createStandardKeyStatement(descriptor,_xConnection);
384 if ( !sKeyStmt.isEmpty() )
385 aSql += sKeyStmt;
386 else
388 if ( aSql.endsWith(",") )
389 aSql = aSql.replaceAt(aSql.getLength()-1, 1, ")");
390 else
391 aSql += ")";
393 return aSql;
395 namespace
397 Reference<XPropertySet> lcl_createSDBCXColumn(const Reference<XNameAccess>& _xPrimaryKeyColumns,
398 const Reference<XConnection>& _xConnection,
399 const Any& _aCatalog,
400 const OUString& _aSchema,
401 const OUString& _aTable,
402 const OUString& _rQueryName,
403 const OUString& _rName,
404 bool _bCase,
405 bool _bQueryForInfo,
406 bool _bIsAutoIncrement,
407 bool _bIsCurrency,
408 sal_Int32 _nDataType)
410 Reference<XPropertySet> xProp;
411 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
412 Reference< XResultSet > xResult = xMetaData->getColumns(_aCatalog, _aSchema, _aTable, _rQueryName);
413 OUString sCatalog;
414 _aCatalog >>= sCatalog;
416 if ( xResult.is() )
418 UStringMixEqual aMixCompare(_bCase);
419 Reference< XRow > xRow(xResult,UNO_QUERY);
420 while( xResult->next() )
422 if ( aMixCompare(xRow->getString(4),_rName) )
424 sal_Int32 nField5 = xRow->getInt(5);
425 OUString aField6 = xRow->getString(6);
426 sal_Int32 nField7 = xRow->getInt(7)
427 , nField9 = xRow->getInt(9)
428 , nField11= xRow->getInt(11);
429 OUString sField12 = xRow->getString(12),
430 sField13 = xRow->getString(13);
431 ::comphelper::disposeComponent(xRow);
433 bool bAutoIncrement = _bIsAutoIncrement
434 ,bIsCurrency = _bIsCurrency;
435 if ( _bQueryForInfo )
437 const OUString sQuote = xMetaData->getIdentifierQuoteString();
438 OUString sQuotedName = ::dbtools::quoteName(sQuote,_rName);
439 OUString sComposedName = composeTableNameForSelect(_xConnection, getString( _aCatalog ), _aSchema, _aTable );
441 ColumnInformationMap aInfo(_bCase);
442 collectColumnInformation(_xConnection,sComposedName,sQuotedName,aInfo);
443 ColumnInformationMap::const_iterator aIter = aInfo.begin();
444 if ( aIter != aInfo.end() )
446 bAutoIncrement = aIter->second.first.first;
447 bIsCurrency = aIter->second.first.second;
448 if ( DataType::OTHER == nField5 )
449 nField5 = aIter->second.second;
452 else if ( DataType::OTHER == nField5 )
453 nField5 = _nDataType;
455 if ( nField11 != ColumnValue::NO_NULLS )
459 if ( _xPrimaryKeyColumns.is() )
461 if ( _xPrimaryKeyColumns->hasByName(_rName) )
462 nField11 = ColumnValue::NO_NULLS;
465 else
467 Reference< XResultSet > xPKeys = xMetaData->getPrimaryKeys( _aCatalog, _aSchema, _aTable );
468 Reference< XRow > xPKeyRow( xPKeys, UNO_QUERY_THROW );
469 while( xPKeys->next() ) // there can be only one primary key
471 OUString sKeyColumn = xPKeyRow->getString(4);
472 if ( aMixCompare(_rName,sKeyColumn) )
474 nField11 = ColumnValue::NO_NULLS;
475 break;
480 catch(SQLException&)
482 OSL_FAIL( "lcl_createSDBCXColumn: caught an exception!" );
486 connectivity::sdbcx::OColumn* pRet = new connectivity::sdbcx::OColumn(_rName,
487 aField6,
488 sField13,
489 sField12,
490 nField11,
491 nField7,
492 nField9,
493 nField5,
494 bAutoIncrement,
495 false,
496 bIsCurrency,
497 _bCase,
498 sCatalog,
499 _aSchema,
500 _aTable);
502 xProp = pRet;
503 break;
508 return xProp;
511 Reference< XModel> lcl_getXModel(const Reference< XInterface>& _xIface)
513 Reference< XInterface > xParent = _xIface;
514 Reference< XModel > xModel(xParent,UNO_QUERY);
515 while( xParent.is() && !xModel.is() )
517 Reference<XChild> xChild(xParent,UNO_QUERY);
518 xParent.set(xChild.is() ? xChild->getParent() : Reference< XInterface >(),UNO_QUERY);
519 xModel.set(xParent,UNO_QUERY);
521 return xModel;
525 Reference<XPropertySet> createSDBCXColumn(const Reference<XPropertySet>& _xTable,
526 const Reference<XConnection>& _xConnection,
527 const OUString& _rName,
528 bool _bCase,
529 bool _bQueryForInfo,
530 bool _bIsAutoIncrement,
531 bool _bIsCurrency,
532 sal_Int32 _nDataType)
534 Reference<XPropertySet> xProp;
535 OSL_ENSURE(_xTable.is(),"Table is NULL!");
536 if ( !_xTable.is() )
537 return xProp;
539 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
540 Any aCatalog = _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME));
541 OUString sCatalog;
542 aCatalog >>= sCatalog;
544 OUString aSchema, aTable;
545 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= aSchema;
546 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= aTable;
548 Reference<XNameAccess> xPrimaryKeyColumns = getPrimaryKeyColumns_throw(_xTable);
550 xProp = lcl_createSDBCXColumn(xPrimaryKeyColumns,_xConnection,aCatalog, aSchema, aTable, _rName,_rName,_bCase,_bQueryForInfo,_bIsAutoIncrement,_bIsCurrency,_nDataType);
551 if ( !xProp.is() )
553 xProp = lcl_createSDBCXColumn(xPrimaryKeyColumns,_xConnection,aCatalog, aSchema, aTable, "%",_rName,_bCase,_bQueryForInfo,_bIsAutoIncrement,_bIsCurrency,_nDataType);
554 if ( !xProp.is() )
555 xProp = new connectivity::sdbcx::OColumn(_rName,
556 OUString(),OUString(),OUString(),
557 ColumnValue::NULLABLE_UNKNOWN,
560 DataType::VARCHAR,
561 _bIsAutoIncrement,
562 false,
563 _bIsCurrency,
564 _bCase,
565 sCatalog,
566 aSchema,
567 aTable);
571 return xProp;
575 bool getBooleanDataSourceSetting( const Reference< XConnection >& _rxConnection, const sal_Char* _pAsciiSettingName )
577 bool bValue( false );
580 Reference< XPropertySet> xDataSourceProperties( findDataSource( _rxConnection ), UNO_QUERY );
581 OSL_ENSURE( xDataSourceProperties.is(), "::dbtools::getBooleanDataSourceSetting: somebody is using this with a non-SDB-level connection!" );
582 if ( xDataSourceProperties.is() )
584 Reference< XPropertySet > xSettings(
585 xDataSourceProperties->getPropertyValue("Settings"),
586 UNO_QUERY_THROW
588 OSL_VERIFY( xSettings->getPropertyValue( OUString::createFromAscii( _pAsciiSettingName ) ) >>= bValue );
591 catch( const Exception& )
593 DBG_UNHANDLED_EXCEPTION("connectivity.commontools");
595 return bValue;
598 bool getDataSourceSetting( const Reference< XInterface >& _xChild, const OUString& _sAsciiSettingsName,
599 Any& /* [out] */ _rSettingsValue )
601 bool bIsPresent = false;
604 const Reference< XPropertySet> xDataSourceProperties( findDataSource( _xChild ), UNO_QUERY );
605 if ( !xDataSourceProperties.is() )
606 return false;
608 const Reference< XPropertySet > xSettings(
609 xDataSourceProperties->getPropertyValue("Settings"),
610 UNO_QUERY_THROW
613 _rSettingsValue = xSettings->getPropertyValue( _sAsciiSettingsName );
614 bIsPresent = true;
616 catch( const Exception& )
618 bIsPresent = false;
620 return bIsPresent;
623 bool getDataSourceSetting( const Reference< XInterface >& _rxDataSource, const sal_Char* _pAsciiSettingsName,
624 Any& /* [out] */ _rSettingsValue )
626 OUString sAsciiSettingsName = OUString::createFromAscii(_pAsciiSettingsName);
627 return getDataSourceSetting( _rxDataSource, sAsciiSettingsName,_rSettingsValue );
630 bool isDataSourcePropertyEnabled(const Reference<XInterface>& _xProp, const OUString& _sProperty, bool _bDefault)
632 bool bEnabled = _bDefault;
635 Reference< XPropertySet> xProp(findDataSource(_xProp),UNO_QUERY);
636 if ( xProp.is() )
638 Sequence< PropertyValue > aInfo;
639 xProp->getPropertyValue("Info") >>= aInfo;
640 const PropertyValue* pValue =std::find_if(aInfo.begin(),
641 aInfo.end(),
642 [&_sProperty](const PropertyValue& lhs)
643 { return lhs.Name == _sProperty; });
644 if ( pValue != aInfo.end() )
645 pValue->Value >>= bEnabled;
648 catch(SQLException&)
650 DBG_UNHANDLED_EXCEPTION("connectivity.commontools");
652 return bEnabled;
655 Reference< XTablesSupplier> getDataDefinitionByURLAndConnection(
656 const OUString& _rsUrl,
657 const Reference< XConnection>& _xConnection,
658 const Reference< XComponentContext >& _rxContext)
660 Reference< XTablesSupplier> xTablesSup;
663 Reference< XDriverManager2 > xManager = DriverManager::create( _rxContext );
664 Reference< XDataDefinitionSupplier > xSupp( xManager->getDriverByURL( _rsUrl ), UNO_QUERY );
666 if ( xSupp.is() )
668 xTablesSup = xSupp->getDataDefinitionByConnection( _xConnection );
669 OSL_ENSURE(xTablesSup.is(),"No table supplier!");
672 catch( const Exception& )
674 DBG_UNHANDLED_EXCEPTION("connectivity.commontools");
676 return xTablesSup;
680 sal_Int32 getTablePrivileges(const Reference< XDatabaseMetaData>& _xMetaData,
681 const OUString& _sCatalog,
682 const OUString& _sSchema,
683 const OUString& _sTable)
685 OSL_ENSURE(_xMetaData.is(),"Invalid metadata!");
686 sal_Int32 nPrivileges = 0;
689 Any aVal;
690 if(!_sCatalog.isEmpty())
691 aVal <<= _sCatalog;
692 Reference< XResultSet > xPrivileges = _xMetaData->getTablePrivileges(aVal, _sSchema, _sTable);
693 Reference< XRow > xCurrentRow(xPrivileges, UNO_QUERY);
695 const OUString sUserWorkingFor = _xMetaData->getUserName();
696 static const char sSELECT[] = "SELECT";
697 static const char sINSERT[] = "INSERT";
698 static const char sUPDATE[] = "UPDATE";
699 static const char sDELETE[] = "DELETE";
700 static const char sREAD[] = "READ";
701 static const char sCREATE[] = "CREATE";
702 static const char sALTER[] = "ALTER";
703 static const char sREFERENCE[] = "REFERENCE";
704 static const char sDROP[] = "DROP";
706 if ( xCurrentRow.is() )
708 // after creation the set is positioned before the first record, per definition
709 OUString sPrivilege, sGrantee;
710 while ( xPrivileges->next() )
712 sGrantee = xCurrentRow->getString(5);
713 sPrivilege = xCurrentRow->getString(6);
715 if (!sUserWorkingFor.equalsIgnoreAsciiCase(sGrantee))
716 continue;
718 if (sPrivilege.equalsIgnoreAsciiCase(sSELECT))
719 nPrivileges |= Privilege::SELECT;
720 else if (sPrivilege.equalsIgnoreAsciiCase(sINSERT))
721 nPrivileges |= Privilege::INSERT;
722 else if (sPrivilege.equalsIgnoreAsciiCase(sUPDATE))
723 nPrivileges |= Privilege::UPDATE;
724 else if (sPrivilege.equalsIgnoreAsciiCase(sDELETE))
725 nPrivileges |= Privilege::DELETE;
726 else if (sPrivilege.equalsIgnoreAsciiCase(sREAD))
727 nPrivileges |= Privilege::READ;
728 else if (sPrivilege.equalsIgnoreAsciiCase(sCREATE))
729 nPrivileges |= Privilege::CREATE;
730 else if (sPrivilege.equalsIgnoreAsciiCase(sALTER))
731 nPrivileges |= Privilege::ALTER;
732 else if (sPrivilege.equalsIgnoreAsciiCase(sREFERENCE))
733 nPrivileges |= Privilege::REFERENCE;
734 else if (sPrivilege.equalsIgnoreAsciiCase(sDROP))
735 nPrivileges |= Privilege::DROP;
738 disposeComponent(xPrivileges);
740 // Some drivers put a table privilege as soon as any column has the privilege,
741 // some drivers only if all columns have the privilege.
742 // To unify the situation, collect column privileges here, too.
743 Reference< XResultSet > xColumnPrivileges = _xMetaData->getColumnPrivileges(aVal, _sSchema, _sTable, "%");
744 Reference< XRow > xColumnCurrentRow(xColumnPrivileges, UNO_QUERY);
745 if ( xColumnCurrentRow.is() )
747 // after creation the set is positioned before the first record, per definition
748 OUString sPrivilege, sGrantee;
749 while ( xColumnPrivileges->next() )
751 sGrantee = xColumnCurrentRow->getString(6);
752 sPrivilege = xColumnCurrentRow->getString(7);
754 if (!sUserWorkingFor.equalsIgnoreAsciiCase(sGrantee))
755 continue;
757 if (sPrivilege.equalsIgnoreAsciiCase(sSELECT))
758 nPrivileges |= Privilege::SELECT;
759 else if (sPrivilege.equalsIgnoreAsciiCase(sINSERT))
760 nPrivileges |= Privilege::INSERT;
761 else if (sPrivilege.equalsIgnoreAsciiCase(sUPDATE))
762 nPrivileges |= Privilege::UPDATE;
763 else if (sPrivilege.equalsIgnoreAsciiCase(sDELETE))
764 nPrivileges |= Privilege::DELETE;
765 else if (sPrivilege.equalsIgnoreAsciiCase(sREAD))
766 nPrivileges |= Privilege::READ;
767 else if (sPrivilege.equalsIgnoreAsciiCase(sCREATE))
768 nPrivileges |= Privilege::CREATE;
769 else if (sPrivilege.equalsIgnoreAsciiCase(sALTER))
770 nPrivileges |= Privilege::ALTER;
771 else if (sPrivilege.equalsIgnoreAsciiCase(sREFERENCE))
772 nPrivileges |= Privilege::REFERENCE;
773 else if (sPrivilege.equalsIgnoreAsciiCase(sDROP))
774 nPrivileges |= Privilege::DROP;
777 disposeComponent(xColumnPrivileges);
779 catch(const SQLException& e)
781 // some drivers don't support any privileges so we assume that we are allowed to do all we want :-)
782 if(e.SQLState == "IM001")
783 nPrivileges |= Privilege::DROP |
784 Privilege::REFERENCE |
785 Privilege::ALTER |
786 Privilege::CREATE |
787 Privilege::READ |
788 Privilege::DELETE |
789 Privilege::UPDATE |
790 Privilege::INSERT |
791 Privilege::SELECT;
792 else
793 OSL_FAIL("Could not collect the privileges !");
795 return nPrivileges;
798 // we need some more information about the column
799 void collectColumnInformation(const Reference< XConnection>& _xConnection,
800 const OUString& _sComposedName,
801 const OUString& _rName,
802 ColumnInformationMap& _rInfo)
804 OUString sSelect = "SELECT " + _rName +
805 " FROM " + _sComposedName +
806 " WHERE 0 = 1";
810 ::utl::SharedUNOComponent< XStatement > xStmt( _xConnection->createStatement() );
811 Reference< XPropertySet > xStatementProps( xStmt, UNO_QUERY_THROW );
812 xStatementProps->setPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ), makeAny( false ) );
813 Reference< XResultSet > xResult( xStmt->executeQuery( sSelect ), UNO_SET_THROW );
814 Reference< XResultSetMetaDataSupplier > xSuppMeta( xResult, UNO_QUERY_THROW );
815 Reference< XResultSetMetaData > xMeta( xSuppMeta->getMetaData(), UNO_SET_THROW );
817 sal_Int32 nCount = xMeta->getColumnCount();
818 OSL_ENSURE( nCount != 0, "::dbtools::collectColumnInformation: result set has empty (column-less) meta data!" );
819 for (sal_Int32 i=1; i <= nCount ; ++i)
821 _rInfo.emplace( xMeta->getColumnName(i),
822 ColumnInformation(TBoolPair(xMeta->isAutoIncrement(i),xMeta->isCurrency(i)),xMeta->getColumnType(i)));
825 catch( const Exception& )
827 DBG_UNHANDLED_EXCEPTION("connectivity.commontools");
832 bool isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent, Reference< XConnection >& _rxActualConnection )
834 bool bIsEmbedded = false;
837 Reference< XModel > xModel = lcl_getXModel( _rxComponent );
839 if ( xModel.is() )
841 Sequence< PropertyValue > aArgs = xModel->getArgs();
842 const PropertyValue* pIter = aArgs.getConstArray();
843 const PropertyValue* pEnd = pIter + aArgs.getLength();
844 for(;pIter != pEnd;++pIter)
846 if ( pIter->Name == "ComponentData" )
848 Sequence<PropertyValue> aDocumentContext;
849 pIter->Value >>= aDocumentContext;
850 const PropertyValue* pContextIter = aDocumentContext.getConstArray();
851 const PropertyValue* pContextEnd = pContextIter + aDocumentContext.getLength();
852 for(;pContextIter != pContextEnd;++pContextIter)
854 if ( pContextIter->Name == "ActiveConnection"
855 && ( pContextIter->Value >>= _rxActualConnection )
858 bIsEmbedded = true;
859 break;
862 break;
867 catch(Exception&)
869 // not interested in
871 return bIsEmbedded;
874 namespace
876 OUString lcl_getEncodingName( rtl_TextEncoding _eEncoding )
878 OUString sEncodingName;
880 OCharsetMap aCharsets;
881 OCharsetMap::CharsetIterator aEncodingPos = aCharsets.find( _eEncoding );
882 OSL_ENSURE( aEncodingPos != aCharsets.end(), "lcl_getEncodingName: *which* encoding?" );
883 if ( aEncodingPos != aCharsets.end() )
884 sEncodingName = (*aEncodingPos).getIanaName();
886 return sEncodingName;
891 sal_Int32 DBTypeConversion::convertUnicodeString( const OUString& _rSource, OString& _rDest, rtl_TextEncoding _eEncoding )
893 if ( !rtl_convertUStringToString( &_rDest.pData, _rSource.getStr(), _rSource.getLength(),
894 _eEncoding,
895 RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |
896 RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |
897 RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 )
900 SharedResources aResources;
901 OUString sMessage = aResources.getResourceStringWithSubstitution( STR_CANNOT_CONVERT_STRING,
902 "$string$", _rSource,
903 "$charset$", lcl_getEncodingName( _eEncoding )
906 throw SQLException(
907 sMessage,
908 nullptr,
909 "22018",
910 22018,
911 Any()
915 return _rDest.getLength();
919 sal_Int32 DBTypeConversion::convertUnicodeStringToLength( const OUString& _rSource, OString& _rDest,
920 sal_Int32 _nMaxLen, rtl_TextEncoding _eEncoding )
922 sal_Int32 nLen = convertUnicodeString( _rSource, _rDest, _eEncoding );
923 if ( nLen > _nMaxLen )
925 SharedResources aResources;
926 OUString sMessage = aResources.getResourceStringWithSubstitution( STR_STRING_LENGTH_EXCEEDED,
927 "$string$", _rSource,
928 "$maxlen$", OUString::number( _nMaxLen ),
929 "$charset$", lcl_getEncodingName( _eEncoding )
932 throw SQLException(
933 sMessage,
934 nullptr,
935 "22001",
936 22001,
937 Any()
941 return nLen;
943 static OUString lcl_getReportEngines()
945 return OUString("org.openoffice.Office.DataAccess/ReportEngines");
948 static OUString lcl_getDefaultReportEngine()
950 return OUString("DefaultReportEngine");
953 static OUString lcl_getReportEngineNames()
955 return OUString("ReportEngineNames");
958 OUString getDefaultReportEngineServiceName(const Reference< XComponentContext >& _rxORB)
960 ::utl::OConfigurationTreeRoot aReportEngines = ::utl::OConfigurationTreeRoot::createWithComponentContext(
961 _rxORB, lcl_getReportEngines(), -1, ::utl::OConfigurationTreeRoot::CM_READONLY);
963 if ( aReportEngines.isValid() )
965 OUString sDefaultReportEngineName;
966 aReportEngines.getNodeValue(lcl_getDefaultReportEngine()) >>= sDefaultReportEngineName;
967 if ( !sDefaultReportEngineName.isEmpty() )
969 ::utl::OConfigurationNode aReportEngineNames = aReportEngines.openNode(lcl_getReportEngineNames());
970 if ( aReportEngineNames.isValid() )
972 ::utl::OConfigurationNode aReportEngine = aReportEngineNames.openNode(sDefaultReportEngineName);
973 if ( aReportEngine.isValid() )
975 OUString sRet;
976 aReportEngine.getNodeValue("ServiceName") >>= sRet;
977 return sRet;
981 else
982 return OUString("org.libreoffice.report.pentaho.SOReportJobFactory");
984 else
985 return OUString("org.libreoffice.report.pentaho.SOReportJobFactory");
986 return OUString();
989 bool isAggregateColumn(const Reference< XSingleSelectQueryComposer > &_xParser, const Reference< XPropertySet > &_xField)
991 OUString sName;
992 _xField->getPropertyValue("Name") >>= sName;
993 Reference< XColumnsSupplier > xColumnsSupplier(_xParser, UNO_QUERY);
994 Reference< css::container::XNameAccess > xCols;
995 if (xColumnsSupplier.is())
996 xCols = xColumnsSupplier->getColumns();
998 return isAggregateColumn(xCols, sName);
1001 bool isAggregateColumn(const Reference< XNameAccess > &_xColumns, const OUString &_sName)
1003 if ( _xColumns.is() && _xColumns->hasByName(_sName) )
1005 Reference<XPropertySet> xProp(_xColumns->getByName(_sName),UNO_QUERY);
1006 assert(xProp.is());
1007 return isAggregateColumn( xProp );
1009 return false;
1012 bool isAggregateColumn( const Reference< XPropertySet > &_xColumn )
1014 bool bAgg(false);
1016 static const char sAgg[] = "AggregateFunction";
1017 if ( _xColumn->getPropertySetInfo()->hasPropertyByName(sAgg) )
1018 _xColumn->getPropertyValue(sAgg) >>= bAgg;
1020 return bAgg;
1024 } // namespace dbtools
1027 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */