1 /**************************************************************
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 *************************************************************/
21
22
23
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_dbtools.hxx"
26 #include "connectivity/dbtools.hxx"
27 #include "connectivity/dbconversion.hxx"
28 #include "connectivity/dbcharset.hxx"
29 #include "connectivity/SQLStatementHelper.hxx"
30 #include <unotools/confignode.hxx>
31 #include "resource/sharedresources.hxx"
32 #include "resource/common_res.hrc"
33 #include <com/sun/star/sdbc/XConnection.hpp>
34 #include <com/sun/star/sdbc/ColumnValue.hpp>
35 #include <com/sun/star/sdbc/DataType.hpp>
36 #include <com/sun/star/sdbc/XRow.hpp>
37 #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
38 #include <com/sun/star/sdbcx/XKeysSupplier.hpp>
39 #include <com/sun/star/sdbc/XDriverAccess.hpp>
40 #include <com/sun/star/sdbcx/XDataDefinitionSupplier.hpp>
41 #include <com/sun/star/sdbcx/Privilege.hpp>
42 #include <com/sun/star/container/XIndexAccess.hpp>
43 #include <com/sun/star/container/XEnumerationAccess.hpp>
44 #include <com/sun/star/sdbc/KeyRule.hpp>
45 #include <com/sun/star/sdbcx/KeyType.hpp>
46 #include "TConnection.hxx"
47 #include "connectivity/sdbcx/VColumn.hxx"
48 #include <com/sun/star/frame/XModel.hpp>
49 #include <com/sun/star/container/XChild.hpp>
50
51 #include <tools/diagnose_ex.h>
52 #include <unotools/sharedunocomponent.hxx>
53 #include <comphelper/configurationhelper.hxx>
54 #include <functional>
55
56 //.........................................................................
57 namespace dbtools
58 {
59 //.........................................................................
60 using namespace ::com::sun::star::uno;
61 using namespace ::com::sun::star::beans;
62 using namespace ::com::sun::star::sdbc;
63 using namespace ::com::sun::star::sdbcx;
64 using namespace ::com::sun::star::lang;
65 using namespace ::com::sun::star::container;
66 using namespace ::com::sun::star::frame;
67 using namespace connectivity;
68 using namespace comphelper;
69
createStandardColumnPart(const Reference<XPropertySet> & xColProp,const Reference<XConnection> & _xConnection,ISQLStatementHelper * _pHelper,const::rtl::OUString & _sCreatePattern)70 ::rtl::OUString createStandardColumnPart(const Reference< XPropertySet >& xColProp,const Reference< XConnection>& _xConnection,ISQLStatementHelper* _pHelper,const ::rtl::OUString& _sCreatePattern)
71 {
72
73 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
74
75 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
76
77 ::rtl::OUString sTypeName;
78 sal_Int32 nDataType = 0;
79 sal_Int32 nPrecision = 0;
80 sal_Int32 nScale = 0;
81
82 const ::rtl::OUString sQuoteString = xMetaData->getIdentifierQuoteString();
83 ::rtl::OUStringBuffer aSql = ::dbtools::quoteName(sQuoteString,::comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))));
84
85 aSql.appendAscii(" ");
86
87 nDataType = nPrecision = nScale = 0;
88 sal_Bool bIsAutoIncrement = sal_False;
89 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_TYPENAME)) >>= sTypeName;
90 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_TYPE)) >>= nDataType;
91 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_PRECISION)) >>= nPrecision;
92 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
93 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bIsAutoIncrement;
94
95 // check if the user enter a specific string to create autoincrement values
96 ::rtl::OUString sAutoIncrementValue;
97 Reference<XPropertySetInfo> xPropInfo = xColProp->getPropertySetInfo();
98 if ( xPropInfo.is() && xPropInfo->hasPropertyByName(rPropMap.getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION)) )
99 xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION)) >>= sAutoIncrementValue;
100 // look if we have to use precisions
101 sal_Bool bUseLiteral = sal_False;
102 ::rtl::OUString sPreFix,sPostFix,sCreateParams;
103 {
104 Reference<XResultSet> xRes = xMetaData->getTypeInfo();
105 if(xRes.is())
106 {
107 Reference<XRow> xRow(xRes,UNO_QUERY);
108 while(xRes->next())
109 {
110 ::rtl::OUString sTypeName2Cmp = xRow->getString(1);
111 sal_Int32 nType = xRow->getShort(2);
112 sPreFix = xRow->getString (4);
113 sPostFix = xRow->getString (5);
114 sCreateParams = xRow->getString(6);
115 // first identical type will be used if typename is empty
116 if ( !sTypeName.getLength() && nType == nDataType )
117 sTypeName = sTypeName2Cmp;
118
119 if( sTypeName.equalsIgnoreAsciiCase(sTypeName2Cmp) && nType == nDataType && sCreateParams.getLength() && !xRow->wasNull())
120 {
121 bUseLiteral = sal_True;
122 break;
123 }
124 }
125 }
126 }
127
128 sal_Int32 nIndex = 0;
129 if ( sAutoIncrementValue.getLength() && (nIndex = sTypeName.indexOf(sAutoIncrementValue)) != -1 )
130 {
131 sTypeName = sTypeName.replaceAt(nIndex,sTypeName.getLength() - nIndex,::rtl::OUString());
132 }
133
134 if ( (nPrecision > 0 || nScale > 0) && bUseLiteral )
135 {
136 sal_Int32 nParenPos = sTypeName.indexOf('(');
137 if ( nParenPos == -1 )
138 {
139 aSql.append(sTypeName);
140 aSql.appendAscii("(");
141 }
142 else
143 {
144 aSql.append(sTypeName.copy(0,++nParenPos));
145 }
146
147 if ( nPrecision > 0 && nDataType != DataType::TIMESTAMP )
148 {
149 aSql.append(nPrecision);
150 if ( (nScale > 0) || (_sCreatePattern.getLength() && sCreateParams.indexOf(_sCreatePattern) != -1) )
151 aSql.appendAscii(",");
152 }
153 if ( (nScale > 0) || (_sCreatePattern.getLength() && sCreateParams.indexOf(_sCreatePattern) != -1 ) || nDataType == DataType::TIMESTAMP )
154 aSql.append(nScale);
155
156 if ( nParenPos == -1 )
157 aSql.appendAscii(")");
158 else
159 {
160 nParenPos = sTypeName.indexOf(')',nParenPos);
161 aSql.append(sTypeName.copy(nParenPos));
162 }
163 }
164 else
165 aSql.append(sTypeName); // simply add the type name
166
167 ::rtl::OUString aDefault = ::comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_DEFAULTVALUE)));
168 if ( aDefault.getLength() )
169 {
170 aSql.append(::rtl::OUString::createFromAscii(" DEFAULT "));
171 aSql.append(sPreFix);
172 aSql.append(aDefault);
173 aSql.append(sPostFix);
174 } // if ( aDefault.getLength() )
175
176 if(::comphelper::getINT32(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_ISNULLABLE))) == ColumnValue::NO_NULLS)
177 aSql.append(::rtl::OUString::createFromAscii(" NOT NULL"));
178
179 if ( bIsAutoIncrement && sAutoIncrementValue.getLength())
180 {
181 aSql.appendAscii(" ");
182 aSql.append(sAutoIncrementValue);
183 }
184
185 if ( _pHelper )
186 _pHelper->addComment(xColProp,aSql);
187
188 return aSql.makeStringAndClear();
189 }
190 // -----------------------------------------------------------------------------
191
createStandardCreateStatement(const Reference<XPropertySet> & descriptor,const Reference<XConnection> & _xConnection,ISQLStatementHelper * _pHelper,const::rtl::OUString & _sCreatePattern)192 ::rtl::OUString createStandardCreateStatement(const Reference< XPropertySet >& descriptor,const Reference< XConnection>& _xConnection,ISQLStatementHelper* _pHelper,const ::rtl::OUString& _sCreatePattern)
193 {
194 ::rtl::OUStringBuffer aSql = ::rtl::OUString::createFromAscii("CREATE TABLE ");
195 ::rtl::OUString sCatalog,sSchema,sTable,sComposedName;
196
197 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
198 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
199
200 descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME)) >>= sCatalog;
201 descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= sSchema;
202 descriptor->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= sTable;
203
204 sComposedName = ::dbtools::composeTableName( xMetaData, sCatalog, sSchema, sTable, sal_True, ::dbtools::eInTableDefinitions );
205 if ( !sComposedName.getLength() )
206 ::dbtools::throwFunctionSequenceException(_xConnection);
207
208 aSql.append(sComposedName);
209 aSql.append(::rtl::OUString::createFromAscii(" ("));
210
211 // columns
212 Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY);
213 Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY);
214 // check if there are columns
215 if(!xColumns.is() || !xColumns->getCount())
216 ::dbtools::throwFunctionSequenceException(_xConnection);
217
218 Reference< XPropertySet > xColProp;
219
220 sal_Int32 nCount = xColumns->getCount();
221 for(sal_Int32 i=0;i<nCount;++i)
222 {
223 if ( (xColumns->getByIndex(i) >>= xColProp) && xColProp.is() )
224 {
225 aSql.append(createStandardColumnPart(xColProp,_xConnection,_pHelper,_sCreatePattern));
226 aSql.appendAscii(",");
227 }
228 }
229 return aSql.makeStringAndClear();
230 }
231 namespace
232 {
generateColumnNames(const Reference<XIndexAccess> & _xColumns,const Reference<XDatabaseMetaData> & _xMetaData)233 ::rtl::OUString generateColumnNames(const Reference<XIndexAccess>& _xColumns,const Reference<XDatabaseMetaData>& _xMetaData)
234 {
235 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
236 static const ::rtl::OUString sComma(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(",")));
237
238 const ::rtl::OUString sQuote(_xMetaData->getIdentifierQuoteString());
239 ::rtl::OUString sSql = ::rtl::OUString::createFromAscii(" (");
240 Reference< XPropertySet > xColProp;
241
242 sal_Int32 nColCount = _xColumns->getCount();
243 for(sal_Int32 i=0;i<nColCount;++i)
244 {
245 if ( (_xColumns->getByIndex(i) >>= xColProp) && xColProp.is() )
246 sSql += ::dbtools::quoteName(sQuote,::comphelper::getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME))))
247 + sComma;
248 }
249
250 if ( nColCount )
251 sSql = sSql.replaceAt(sSql.getLength()-1,1,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(")")));
252 return sSql;
253 }
254 }
255 // -----------------------------------------------------------------------------
createStandardKeyStatement(const Reference<XPropertySet> & descriptor,const Reference<XConnection> & _xConnection)256 ::rtl::OUString createStandardKeyStatement(const Reference< XPropertySet >& descriptor,const Reference< XConnection>& _xConnection)
257 {
258 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
259 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
260
261 ::rtl::OUStringBuffer aSql;
262 // keys
263 Reference<XKeysSupplier> xKeySup(descriptor,UNO_QUERY);
264 Reference<XIndexAccess> xKeys = xKeySup->getKeys();
265 if ( xKeys.is() )
266 {
267 Reference< XPropertySet > xColProp;
268 Reference<XIndexAccess> xColumns;
269 Reference<XColumnsSupplier> xColumnSup;
270 ::rtl::OUString sCatalog,sSchema,sTable,sComposedName;
271 sal_Bool bPKey = sal_False;
272 for(sal_Int32 i=0;i<xKeys->getCount();++i)
273 {
274 if ( (xKeys->getByIndex(i) >>= xColProp) && xColProp.is() )
275 {
276
277 sal_Int32 nKeyType = ::comphelper::getINT32(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_TYPE)));
278
279 if ( nKeyType == KeyType::PRIMARY )
280 {
281 if(bPKey)
282 ::dbtools::throwFunctionSequenceException(_xConnection);
283
284 bPKey = sal_True;
285 xColumnSup = Reference<XColumnsSupplier>(xColProp,UNO_QUERY);
286 xColumns = Reference<XIndexAccess>(xColumnSup->getColumns(),UNO_QUERY);
287 if(!xColumns.is() || !xColumns->getCount())
288 ::dbtools::throwFunctionSequenceException(_xConnection);
289
290 const ::rtl::OUString sQuote = xMetaData->getIdentifierQuoteString();
291 aSql.append(::rtl::OUString::createFromAscii(" PRIMARY KEY "));
292 aSql.append(generateColumnNames(xColumns,xMetaData));
293 }
294 else if(nKeyType == KeyType::UNIQUE)
295 {
296 xColumnSup = Reference<XColumnsSupplier>(xColProp,UNO_QUERY);
297 xColumns = Reference<XIndexAccess>(xColumnSup->getColumns(),UNO_QUERY);
298 if(!xColumns.is() || !xColumns->getCount())
299 ::dbtools::throwFunctionSequenceException(_xConnection);
300
301 const ::rtl::OUString sQuote = xMetaData->getIdentifierQuoteString();
302 aSql.append(::rtl::OUString::createFromAscii(" UNIQUE "));
303 aSql.append(generateColumnNames(xColumns,xMetaData));
304 }
305 else if(nKeyType == KeyType::FOREIGN)
306 {
307 sal_Int32 nDeleteRule = getINT32(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_DELETERULE)));
308
309 xColumnSup = Reference<XColumnsSupplier>(xColProp,UNO_QUERY);
310 xColumns = Reference<XIndexAccess>(xColumnSup->getColumns(),UNO_QUERY);
311 if(!xColumns.is() || !xColumns->getCount())
312 ::dbtools::throwFunctionSequenceException(_xConnection);
313
314 aSql.append(::rtl::OUString::createFromAscii(" FOREIGN KEY "));
315 ::rtl::OUString sRefTable = getString(xColProp->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_REFERENCEDTABLE)));
316 ::dbtools::qualifiedNameComponents(xMetaData,
317 sRefTable,
318 sCatalog,
319 sSchema,
320 sTable,
321 ::dbtools::eInDataManipulation);
322 sComposedName = ::dbtools::composeTableName( xMetaData, sCatalog, sSchema, sTable, sal_True, ::dbtools::eInTableDefinitions );
323
324
325 if ( !sComposedName.getLength() )
326 ::dbtools::throwFunctionSequenceException(_xConnection);
327
328 aSql.append(generateColumnNames(xColumns,xMetaData));
329
330 switch(nDeleteRule)
331 {
332 case KeyRule::CASCADE:
333 aSql.append(::rtl::OUString::createFromAscii(" ON DELETE CASCADE "));
334 break;
335 case KeyRule::RESTRICT:
336 aSql.append(::rtl::OUString::createFromAscii(" ON DELETE RESTRICT "));
337 break;
338 case KeyRule::SET_NULL:
339 aSql.append(::rtl::OUString::createFromAscii(" ON DELETE SET NULL "));
340 break;
341 case KeyRule::SET_DEFAULT:
342 aSql.append(::rtl::OUString::createFromAscii(" ON DELETE SET DEFAULT "));
343 break;
344 default:
345 ;
346 }
347 }
348 }
349 }
350 }
351
352 if ( aSql.getLength() )
353 {
354 if ( aSql.charAt(aSql.getLength()-1) == ',' )
355 aSql.setCharAt(aSql.getLength()-1,')');
356 else
357 aSql.appendAscii(")");
358 }
359
360 return aSql.makeStringAndClear();
361
362 }
363 // -----------------------------------------------------------------------------
createSqlCreateTableStatement(const Reference<XPropertySet> & descriptor,const Reference<XConnection> & _xConnection,ISQLStatementHelper * _pHelper,const::rtl::OUString & _sCreatePattern)364 ::rtl::OUString createSqlCreateTableStatement( const Reference< XPropertySet >& descriptor,
365 const Reference< XConnection>& _xConnection,
366 ISQLStatementHelper* _pHelper,
367 const ::rtl::OUString& _sCreatePattern)
368 {
369 ::rtl::OUString aSql = ::dbtools::createStandardCreateStatement(descriptor,_xConnection,_pHelper,_sCreatePattern);
370 const ::rtl::OUString sKeyStmt = ::dbtools::createStandardKeyStatement(descriptor,_xConnection);
371 if ( sKeyStmt.getLength() )
372 aSql += sKeyStmt;
373 else
374 {
375 if ( aSql.lastIndexOf(',') == (aSql.getLength()-1) )
376 aSql = aSql.replaceAt(aSql.getLength()-1,1,::rtl::OUString::createFromAscii(")"));
377 else
378 aSql += ::rtl::OUString::createFromAscii(")");
379 }
380 return aSql;
381 }
382 namespace
383 {
lcl_createSDBCXColumn(const Reference<XNameAccess> & _xPrimaryKeyColumns,const Reference<XConnection> & _xConnection,const Any & _aCatalog,const::rtl::OUString & _aSchema,const::rtl::OUString & _aTable,const::rtl::OUString & _rQueryName,const::rtl::OUString & _rName,sal_Bool _bCase,sal_Bool _bQueryForInfo,sal_Bool _bIsAutoIncrement,sal_Bool _bIsCurrency,sal_Int32 _nDataType)384 Reference<XPropertySet> lcl_createSDBCXColumn(const Reference<XNameAccess>& _xPrimaryKeyColumns,
385 const Reference<XConnection>& _xConnection,
386 const Any& _aCatalog,
387 const ::rtl::OUString& _aSchema,
388 const ::rtl::OUString& _aTable,
389 const ::rtl::OUString& _rQueryName,
390 const ::rtl::OUString& _rName,
391 sal_Bool _bCase,
392 sal_Bool _bQueryForInfo,
393 sal_Bool _bIsAutoIncrement,
394 sal_Bool _bIsCurrency,
395 sal_Int32 _nDataType)
396 {
397 Reference<XPropertySet> xProp;
398 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
399 Reference< XResultSet > xResult = xMetaData->getColumns(_aCatalog, _aSchema, _aTable, _rQueryName);
400
401 if ( xResult.is() )
402 {
403 UStringMixEqual aMixCompare(_bCase);
404 Reference< XRow > xRow(xResult,UNO_QUERY);
405 while( xResult->next() )
406 {
407 if ( aMixCompare(xRow->getString(4),_rName) )
408 {
409 sal_Int32 nField5 = xRow->getInt(5);
410 ::rtl::OUString aField6 = xRow->getString(6);
411 sal_Int32 nField7 = xRow->getInt(7)
412 , nField9 = xRow->getInt(9)
413 , nField11= xRow->getInt(11);
414 ::rtl::OUString sField12 = xRow->getString(12),
415 sField13 = xRow->getString(13);
416 ::comphelper::disposeComponent(xRow);
417
418 sal_Bool bAutoIncrement = _bIsAutoIncrement
419 ,bIsCurrency = _bIsCurrency;
420 if ( _bQueryForInfo )
421 {
422 const ::rtl::OUString sQuote = xMetaData->getIdentifierQuoteString();
423 ::rtl::OUString sQuotedName = ::dbtools::quoteName(sQuote,_rName);
424 ::rtl::OUString sComposedName;
425 sComposedName = composeTableNameForSelect(_xConnection, getString( _aCatalog ), _aSchema, _aTable );
426
427 ColumnInformationMap aInfo(_bCase);
428 collectColumnInformation(_xConnection,sComposedName,sQuotedName,aInfo);
429 ColumnInformationMap::iterator aIter = aInfo.begin();
430 if ( aIter != aInfo.end() )
431 {
432 bAutoIncrement = aIter->second.first.first;
433 bIsCurrency = aIter->second.first.second;
434 if ( DataType::OTHER == nField5 )
435 nField5 = aIter->second.second;
436 }
437 }
438 else if ( DataType::OTHER == nField5 )
439 nField5 = _nDataType;
440
441 if ( nField11 != ColumnValue::NO_NULLS )
442 {
443 try
444 {
445 if ( _xPrimaryKeyColumns.is() )
446 {
447 if ( _xPrimaryKeyColumns->hasByName(_rName) )
448 nField11 = ColumnValue::NO_NULLS;
449
450 }
451 else
452 {
453 Reference< XResultSet > xPKeys = xMetaData->getPrimaryKeys( _aCatalog, _aSchema, _aTable );
454 Reference< XRow > xPKeyRow( xPKeys, UNO_QUERY_THROW );
455 while( xPKeys->next() ) // there can be only one primary key
456 {
457 ::rtl::OUString sKeyColumn = xPKeyRow->getString(4);
458 if ( aMixCompare(_rName,sKeyColumn) )
459 {
460 nField11 = ColumnValue::NO_NULLS;
461 break;
462 }
463 }
464 }
465 }
466 catch(SQLException&)
467 {
468 OSL_ENSURE( false, "lcl_createSDBCXColumn: caught an exception!" );
469 }
470 }
471
472 connectivity::sdbcx::OColumn* pRet = new connectivity::sdbcx::OColumn(_rName,
473 aField6,
474 sField13,
475 sField12,
476 nField11,
477 nField7,
478 nField9,
479 nField5,
480 bAutoIncrement,
481 sal_False,
482 bIsCurrency,
483 _bCase);
484
485 xProp = pRet;
486 break;
487 }
488 }
489 }
490
491 return xProp;
492 }
493 //------------------------------------------------------------------
lcl_getXModel(const Reference<XInterface> & _xIface)494 Reference< XModel> lcl_getXModel(const Reference< XInterface>& _xIface)
495 {
496 Reference< XInterface > xParent = _xIface;
497 Reference< XModel > xModel(xParent,UNO_QUERY);
498 while( xParent.is() && !xModel.is() )
499 {
500 Reference<XChild> xChild(xParent,UNO_QUERY);
501 xParent.set(xChild.is() ? xChild->getParent() : Reference< XInterface >(),UNO_QUERY);
502 xModel.set(xParent,UNO_QUERY);
503 }
504 return xModel;
505 }
506 }
507 // -----------------------------------------------------------------------------
createSDBCXColumn(const Reference<XPropertySet> & _xTable,const Reference<XConnection> & _xConnection,const::rtl::OUString & _rName,sal_Bool _bCase,sal_Bool _bQueryForInfo,sal_Bool _bIsAutoIncrement,sal_Bool _bIsCurrency,sal_Int32 _nDataType)508 Reference<XPropertySet> createSDBCXColumn(const Reference<XPropertySet>& _xTable,
509 const Reference<XConnection>& _xConnection,
510 const ::rtl::OUString& _rName,
511 sal_Bool _bCase,
512 sal_Bool _bQueryForInfo,
513 sal_Bool _bIsAutoIncrement,
514 sal_Bool _bIsCurrency,
515 sal_Int32 _nDataType)
516 {
517 Reference<XPropertySet> xProp;
518 OSL_ENSURE(_xTable.is(),"Table is NULL!");
519 if ( !_xTable.is() )
520 return xProp;
521
522 ::dbtools::OPropertyMap& rPropMap = OMetaConnection::getPropMap();
523 Reference<XDatabaseMetaData> xMetaData = _xConnection->getMetaData();
524 Any aCatalog;
525 aCatalog = _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_CATALOGNAME));
526
527 ::rtl::OUString aSchema, aTable;
528 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_SCHEMANAME)) >>= aSchema;
529 _xTable->getPropertyValue(rPropMap.getNameByIndex(PROPERTY_ID_NAME)) >>= aTable;
530
531 Reference<XNameAccess> xPrimaryKeyColumns = getPrimaryKeyColumns_throw(_xTable);
532
533 xProp = lcl_createSDBCXColumn(xPrimaryKeyColumns,_xConnection,aCatalog, aSchema, aTable, _rName,_rName,_bCase,_bQueryForInfo,_bIsAutoIncrement,_bIsCurrency,_nDataType);
534 if ( !xProp.is() )
535 {
536 xProp = lcl_createSDBCXColumn(xPrimaryKeyColumns,_xConnection,aCatalog, aSchema, aTable, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("%")),_rName,_bCase,_bQueryForInfo,_bIsAutoIncrement,_bIsCurrency,_nDataType);
537 if ( !xProp.is() )
538 xProp = new connectivity::sdbcx::OColumn(_rName,
539 ::rtl::OUString(),::rtl::OUString(),::rtl::OUString(),
540 ColumnValue::NULLABLE_UNKNOWN,
541 0,
542 0,
543 DataType::VARCHAR,
544 _bIsAutoIncrement,
545 sal_False,
546 _bIsCurrency,
547 _bCase);
548
549 }
550
551 return xProp;
552 }
553
554 // -----------------------------------------------------------------------------
getBooleanDataSourceSetting(const Reference<XConnection> & _rxConnection,const sal_Char * _pAsciiSettingName)555 bool getBooleanDataSourceSetting( const Reference< XConnection >& _rxConnection, const sal_Char* _pAsciiSettingName )
556 {
557 bool bValue( false );
558 try
559 {
560 Reference< XPropertySet> xDataSourceProperties( findDataSource( _rxConnection ), UNO_QUERY );
561 OSL_ENSURE( xDataSourceProperties.is(), "::dbtools::getBooleanDataSourceSetting: somebody is using this with a non-SDB-level connection!" );
562 if ( xDataSourceProperties.is() )
563 {
564 Reference< XPropertySet > xSettings(
565 xDataSourceProperties->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Settings") ) ),
566 UNO_QUERY_THROW
567 );
568 OSL_VERIFY( xSettings->getPropertyValue( ::rtl::OUString::createFromAscii( _pAsciiSettingName ) ) >>= bValue );
569 }
570 }
571 catch( const Exception& )
572 {
573 DBG_UNHANDLED_EXCEPTION();
574 }
575 return bValue;
576 }
577 // -------------------------------------------------------------------------
getDataSourceSetting(const Reference<XInterface> & _xChild,const::rtl::OUString & _sAsciiSettingsName,Any & _rSettingsValue)578 bool getDataSourceSetting( const Reference< XInterface >& _xChild, const ::rtl::OUString& _sAsciiSettingsName,
579 Any& /* [out] */ _rSettingsValue )
580 {
581 bool bIsPresent = false;
582 try
583 {
584 const Reference< XPropertySet> xDataSourceProperties( findDataSource( _xChild ), UNO_QUERY );
585 if ( !xDataSourceProperties.is() )
586 return false;
587
588 const Reference< XPropertySet > xSettings(
589 xDataSourceProperties->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Settings") ) ),
590 UNO_QUERY_THROW
591 );
592
593 _rSettingsValue = xSettings->getPropertyValue( _sAsciiSettingsName );
594 bIsPresent = true;
595 }
596 catch( const Exception& )
597 {
598 bIsPresent = false;
599 }
600 return bIsPresent;
601 }
602 // -------------------------------------------------------------------------
getDataSourceSetting(const Reference<XInterface> & _rxDataSource,const sal_Char * _pAsciiSettingsName,Any & _rSettingsValue)603 bool getDataSourceSetting( const Reference< XInterface >& _rxDataSource, const sal_Char* _pAsciiSettingsName,
604 Any& /* [out] */ _rSettingsValue )
605 {
606 ::rtl::OUString sAsciiSettingsName = ::rtl::OUString::createFromAscii(_pAsciiSettingsName);
607 return getDataSourceSetting( _rxDataSource, sAsciiSettingsName,_rSettingsValue );
608 }
609 // -----------------------------------------------------------------------------
isDataSourcePropertyEnabled(const Reference<XInterface> & _xProp,const::rtl::OUString & _sProperty,sal_Bool _bDefault)610 sal_Bool isDataSourcePropertyEnabled(const Reference<XInterface>& _xProp,const ::rtl::OUString& _sProperty,sal_Bool _bDefault)
611 {
612 sal_Bool bEnabled = _bDefault;
613 try
614 {
615 Reference< XPropertySet> xProp(findDataSource(_xProp),UNO_QUERY);
616 if ( xProp.is() )
617 {
618 Sequence< PropertyValue > aInfo;
619 xProp->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Info"))) >>= aInfo;
620 const PropertyValue* pValue =::std::find_if(aInfo.getConstArray(),
621 aInfo.getConstArray() + aInfo.getLength(),
622 ::std::bind(TPropertyValueEqualFunctor(), ::std::placeholders::_1,_sProperty));
623 if ( pValue && pValue != (aInfo.getConstArray() + aInfo.getLength()) )
624 pValue->Value >>= bEnabled;
625 }
626 }
627 catch(SQLException&)
628 {
629 DBG_UNHANDLED_EXCEPTION();
630 }
631 return bEnabled;
632 }
633 // -----------------------------------------------------------------------------
getDataDefinitionByURLAndConnection(const::rtl::OUString & _rsUrl,const Reference<XConnection> & _xConnection,const Reference<XMultiServiceFactory> & _rxFactory)634 Reference< XTablesSupplier> getDataDefinitionByURLAndConnection(
635 const ::rtl::OUString& _rsUrl,
636 const Reference< XConnection>& _xConnection,
637 const Reference< XMultiServiceFactory>& _rxFactory)
638 {
639 Reference< XTablesSupplier> xTablesSup;
640 try
641 {
642 Reference< XDriverAccess> xManager(
643 _rxFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.sdbc.DriverManager") ),
644 UNO_QUERY_THROW );
645 Reference< XDataDefinitionSupplier > xSupp( xManager->getDriverByURL( _rsUrl ), UNO_QUERY );
646
647 if ( xSupp.is() )
648 {
649 xTablesSup = xSupp->getDataDefinitionByConnection( _xConnection );
650 OSL_ENSURE(xTablesSup.is(),"No table supplier!");
651 }
652 }
653 catch( const Exception& )
654 {
655 DBG_UNHANDLED_EXCEPTION();
656 }
657 return xTablesSup;
658 }
659
660 // -----------------------------------------------------------------------------
getTablePrivileges(const Reference<XDatabaseMetaData> & _xMetaData,const::rtl::OUString & _sCatalog,const::rtl::OUString & _sSchema,const::rtl::OUString & _sTable)661 sal_Int32 getTablePrivileges(const Reference< XDatabaseMetaData>& _xMetaData,
662 const ::rtl::OUString& _sCatalog,
663 const ::rtl::OUString& _sSchema,
664 const ::rtl::OUString& _sTable)
665 {
666 OSL_ENSURE(_xMetaData.is(),"Invalid metadata!");
667 sal_Int32 nPrivileges = 0;
668 try
669 {
670 Any aVal;
671 if(_sCatalog.getLength())
672 aVal <<= _sCatalog;
673 Reference< XResultSet > xPrivileges = _xMetaData->getTablePrivileges(aVal, _sSchema, _sTable);
674 Reference< XRow > xCurrentRow(xPrivileges, UNO_QUERY);
675
676 if ( xCurrentRow.is() )
677 {
678 ::rtl::OUString sUserWorkingFor = _xMetaData->getUserName();
679 static const ::rtl::OUString sSELECT = ::rtl::OUString::createFromAscii("SELECT");
680 static const ::rtl::OUString sINSERT = ::rtl::OUString::createFromAscii("INSERT");
681 static const ::rtl::OUString sUPDATE = ::rtl::OUString::createFromAscii("UPDATE");
682 static const ::rtl::OUString sDELETE = ::rtl::OUString::createFromAscii("DELETE");
683 static const ::rtl::OUString sREAD = ::rtl::OUString::createFromAscii("READ");
684 static const ::rtl::OUString sCREATE = ::rtl::OUString::createFromAscii("CREATE");
685 static const ::rtl::OUString sALTER = ::rtl::OUString::createFromAscii("ALTER");
686 static const ::rtl::OUString sREFERENCE = ::rtl::OUString::createFromAscii("REFERENCE");
687 static const ::rtl::OUString sDROP = ::rtl::OUString::createFromAscii("DROP");
688 // after creation the set is positioned before the first record, per definitionem
689 #ifdef DBG_UTIL
690 Reference< XResultSetMetaDataSupplier > xSup(xPrivileges,UNO_QUERY);
691 if ( xSup.is() )
692 {
693 Reference< XResultSetMetaData > xRsMetaData = xSup->getMetaData();
694 if ( xRsMetaData.is() )
695 {
696 sal_Int32 nCount = xRsMetaData->getColumnCount();
697 for (sal_Int32 i=1; i<=nCount; ++i)
698 {
699 ::rtl::OUString sColumnName = xRsMetaData->getColumnName(i);
700 }
701 }
702 }
703 #endif
704
705 ::rtl::OUString sPrivilege, sGrantee;
706 while ( xPrivileges->next() )
707 {
708 #ifdef DBG_UTIL
709 ::rtl::OUString sCat, sSchema, sName, sGrantor, sGrantable;
710 sCat = xCurrentRow->getString(1);
711 sSchema = xCurrentRow->getString(2);
712 sName = xCurrentRow->getString(3);
713 sGrantor = xCurrentRow->getString(4);
714 #endif
715 sGrantee = xCurrentRow->getString(5);
716 sPrivilege = xCurrentRow->getString(6);
717 #ifdef DBG_UTIL
718 sGrantable = xCurrentRow->getString(7);
719 #endif
720
721 if (!sUserWorkingFor.equalsIgnoreAsciiCase(sGrantee))
722 continue;
723
724 if (sPrivilege.equalsIgnoreAsciiCase(sSELECT))
725 nPrivileges |= Privilege::SELECT;
726 else if (sPrivilege.equalsIgnoreAsciiCase(sINSERT))
727 nPrivileges |= Privilege::INSERT;
728 else if (sPrivilege.equalsIgnoreAsciiCase(sUPDATE))
729 nPrivileges |= Privilege::UPDATE;
730 else if (sPrivilege.equalsIgnoreAsciiCase(sDELETE))
731 nPrivileges |= Privilege::DELETE;
732 else if (sPrivilege.equalsIgnoreAsciiCase(sREAD))
733 nPrivileges |= Privilege::READ;
734 else if (sPrivilege.equalsIgnoreAsciiCase(sCREATE))
735 nPrivileges |= Privilege::CREATE;
736 else if (sPrivilege.equalsIgnoreAsciiCase(sALTER))
737 nPrivileges |= Privilege::ALTER;
738 else if (sPrivilege.equalsIgnoreAsciiCase(sREFERENCE))
739 nPrivileges |= Privilege::REFERENCE;
740 else if (sPrivilege.equalsIgnoreAsciiCase(sDROP))
741 nPrivileges |= Privilege::DROP;
742 }
743 }
744 disposeComponent(xPrivileges);
745 }
746 catch(const SQLException& e)
747 {
748 static ::rtl::OUString sNotSupportedState = ::rtl::OUString::createFromAscii("IM001");
749 // some drivers don't support any privileges so we assume that we are allowed to do all we want :-)
750 if(e.SQLState == sNotSupportedState)
751 nPrivileges |= Privilege::DROP |
752 Privilege::REFERENCE |
753 Privilege::ALTER |
754 Privilege::CREATE |
755 Privilege::READ |
756 Privilege::DELETE |
757 Privilege::UPDATE |
758 Privilege::INSERT |
759 Privilege::SELECT;
760 else
761 OSL_ENSURE(0,"Could not collect the privileges !");
762 }
763 return nPrivileges;
764 }
765 // -----------------------------------------------------------------------------
766 // we need some more information about the column
collectColumnInformation(const Reference<XConnection> & _xConnection,const::rtl::OUString & _sComposedName,const::rtl::OUString & _rName,ColumnInformationMap & _rInfo)767 void collectColumnInformation(const Reference< XConnection>& _xConnection,
768 const ::rtl::OUString& _sComposedName,
769 const ::rtl::OUString& _rName,
770 ColumnInformationMap& _rInfo)
771 {
772 static ::rtl::OUString STR_WHERE = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" WHERE "));
773
774 ::rtl::OUString sSelect = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SELECT "));
775 sSelect += _rName;
776 sSelect += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" FROM "));
777 sSelect += _sComposedName;
778 sSelect += STR_WHERE;
779 sSelect += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0 = 1"));
780
781 try
782 {
783 ::utl::SharedUNOComponent< XStatement > xStmt( _xConnection->createStatement() );
784 Reference< XPropertySet > xStatementProps( xStmt, UNO_QUERY_THROW );
785 xStatementProps->setPropertyValue( OMetaConnection::getPropMap().getNameByIndex( PROPERTY_ID_ESCAPEPROCESSING ), makeAny( (sal_Bool)sal_False ) );
786 Reference< XResultSet > xResult( xStmt->executeQuery( sSelect ), UNO_QUERY_THROW );
787 Reference< XResultSetMetaDataSupplier > xSuppMeta( xResult, UNO_QUERY_THROW );
788 Reference< XResultSetMetaData > xMeta( xSuppMeta->getMetaData(), UNO_QUERY_THROW );
789
790 sal_Int32 nCount = xMeta->getColumnCount();
791 OSL_ENSURE( nCount != 0, "::dbtools::collectColumnInformation: result set has empty (column-less) meta data!" );
792 for (sal_Int32 i=1; i <= nCount ; ++i)
793 {
794 _rInfo.insert(ColumnInformationMap::value_type(xMeta->getColumnName(i),
795 ColumnInformation(TBoolPair(xMeta->isAutoIncrement(i),xMeta->isCurrency(i)),xMeta->getColumnType(i))));
796 }
797 }
798 catch( const Exception& )
799 {
800 DBG_UNHANDLED_EXCEPTION();
801 }
802 }
803
804 // -----------------------------------------------------------------------------
isEmbeddedInDatabase(const Reference<XInterface> & _rxComponent,Reference<XConnection> & _rxActualConnection)805 bool isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent, Reference< XConnection >& _rxActualConnection )
806 {
807 bool bIsEmbedded = false;
808 try
809 {
810 Reference< XModel > xModel = lcl_getXModel( _rxComponent );
811
812 if ( xModel.is() )
813 {
814 Sequence< PropertyValue > aArgs = xModel->getArgs();
815 const PropertyValue* pIter = aArgs.getConstArray();
816 const PropertyValue* pEnd = pIter + aArgs.getLength();
817 for(;pIter != pEnd;++pIter)
818 {
819 if ( pIter->Name.equalsAscii("ComponentData") )
820 {
821 Sequence<PropertyValue> aDocumentContext;
822 pIter->Value >>= aDocumentContext;
823 const PropertyValue* pContextIter = aDocumentContext.getConstArray();
824 const PropertyValue* pContextEnd = pContextIter + aDocumentContext.getLength();
825 for(;pContextIter != pContextEnd;++pContextIter)
826 {
827 if ( pContextIter->Name.equalsAscii( "ActiveConnection" )
828 && ( pContextIter->Value >>= _rxActualConnection )
829 )
830 {
831 bIsEmbedded = true;
832 break;
833 }
834 }
835 break;
836 }
837 }
838 }
839 }
840 catch(Exception&)
841 {
842 // not intereseted in
843 }
844 return bIsEmbedded;
845 }
846 // -----------------------------------------------------------------------------
847 namespace
848 {
lcl_getEncodingName(rtl_TextEncoding _eEncoding)849 ::rtl::OUString lcl_getEncodingName( rtl_TextEncoding _eEncoding )
850 {
851 ::rtl::OUString sEncodingName;
852
853 OCharsetMap aCharsets;
854 OCharsetMap::CharsetIterator aEncodingPos = aCharsets.find( _eEncoding );
855 OSL_ENSURE( aEncodingPos != aCharsets.end(), "lcl_getEncodingName: *which* encoding?" );
856 if ( aEncodingPos != aCharsets.end() )
857 sEncodingName = (*aEncodingPos).getIanaName();
858
859 return sEncodingName;
860 }
861 }
862
863 // -----------------------------------------------------------------------------
convertUnicodeString(const::rtl::OUString & _rSource,::rtl::OString & _rDest,rtl_TextEncoding _eEncoding)864 sal_Int32 DBTypeConversion::convertUnicodeString( const ::rtl::OUString& _rSource, ::rtl::OString& _rDest, rtl_TextEncoding _eEncoding )
865 {
866 if ( !rtl_convertUStringToString( &_rDest.pData, _rSource.getStr(), _rSource.getLength(),
867 _eEncoding,
868 RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |
869 RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |
870 RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 |
871 RTL_UNICODETOTEXT_FLAGS_NOCOMPOSITE )
872 )
873 {
874 SharedResources aResources;
875 ::rtl::OUString sMessage = aResources.getResourceStringWithSubstitution( STR_CANNOT_CONVERT_STRING,
876 "$string$", _rSource,
877 "$charset$", lcl_getEncodingName( _eEncoding )
878 );
879
880 throw SQLException(
881 sMessage,
882 NULL,
883 ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "22018" ) ),
884 22018,
885 Any()
886 );
887 }
888
889 return _rDest.getLength();
890 }
891
892 // -----------------------------------------------------------------------------
convertUnicodeStringToLength(const::rtl::OUString & _rSource,::rtl::OString & _rDest,sal_Int32 _nMaxLen,rtl_TextEncoding _eEncoding)893 sal_Int32 DBTypeConversion::convertUnicodeStringToLength( const ::rtl::OUString& _rSource, ::rtl::OString& _rDest,
894 sal_Int32 _nMaxLen, rtl_TextEncoding _eEncoding )
895 {
896 sal_Int32 nLen = convertUnicodeString( _rSource, _rDest, _eEncoding );
897 if ( nLen > _nMaxLen )
898 {
899 SharedResources aResources;
900 ::rtl::OUString sMessage = aResources.getResourceStringWithSubstitution( STR_STRING_LENGTH_EXCEEDED,
901 "$string$", _rSource,
902 "$maxlen$", ::rtl::OUString::valueOf( _nMaxLen ),
903 "$charset$", lcl_getEncodingName( _eEncoding )
904 );
905
906 throw SQLException(
907 sMessage,
908 NULL,
909 ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "22001" ) ),
910 22001,
911 Any()
912 );
913 }
914
915 return nLen;
916 }
lcl_getReportEngines()917 ::rtl::OUString lcl_getReportEngines()
918 {
919 static ::rtl::OUString s_sNodeName(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Office.DataAccess/ReportEngines"));
920 return s_sNodeName;
921 }
922 // -----------------------------------------------------------------------------
lcl_getDefaultReportEngine()923 ::rtl::OUString lcl_getDefaultReportEngine()
924 {
925 static ::rtl::OUString s_sNodeName(RTL_CONSTASCII_USTRINGPARAM("DefaultReportEngine"));
926 return s_sNodeName;
927 }
928 // -----------------------------------------------------------------------------
lcl_getReportEngineNames()929 ::rtl::OUString lcl_getReportEngineNames()
930 {
931 static ::rtl::OUString s_sNodeName(RTL_CONSTASCII_USTRINGPARAM("ReportEngineNames"));
932 return s_sNodeName;
933 }
934 // -----------------------------------------------------------------------------
getDefaultReportEngineServiceName(const Reference<XMultiServiceFactory> & _rxORB)935 ::rtl::OUString getDefaultReportEngineServiceName(const Reference< XMultiServiceFactory >& _rxORB)
936 {
937 ::utl::OConfigurationTreeRoot aReportEngines = ::utl::OConfigurationTreeRoot::createWithServiceFactory(
938 _rxORB, lcl_getReportEngines(), -1, ::utl::OConfigurationTreeRoot::CM_READONLY);
939
940 if ( aReportEngines.isValid() )
941 {
942 ::rtl::OUString sDefaultReportEngineName;
943 aReportEngines.getNodeValue(lcl_getDefaultReportEngine()) >>= sDefaultReportEngineName;
944 if ( sDefaultReportEngineName.getLength() )
945 {
946 ::utl::OConfigurationNode aReportEngineNames = aReportEngines.openNode(lcl_getReportEngineNames());
947 if ( aReportEngineNames.isValid() )
948 {
949 ::utl::OConfigurationNode aReportEngine = aReportEngineNames.openNode(sDefaultReportEngineName);
950 if ( aReportEngine.isValid() )
951 {
952 ::rtl::OUString sRet;
953 const static ::rtl::OUString s_sService(RTL_CONSTASCII_USTRINGPARAM("ServiceName"));
954 aReportEngine.getNodeValue(s_sService) >>= sRet;
955 return sRet;
956 }
957 }
958 }
959 else
960 return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.pentaho.SOReportJobFactory"));
961 }
962 else
963 return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.pentaho.SOReportJobFactory"));
964 return ::rtl::OUString();
965 }
966 // -----------------------------------------------------------------------------
967 //.........................................................................
968 } // namespace dbtools
969 //.........................................................................
970