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_dbui.hxx"
26 
27 #include "dbu_misc.hrc"
28 #include "dbustrings.hrc"
29 #include "moduledbu.hxx"
30 #include "sqlmessage.hxx"
31 #include "UITools.hxx"
32 #include "WColumnSelect.hxx"
33 #include "WCopyTable.hxx"
34 #include "WCPage.hxx"
35 #include "WExtendPages.hxx"
36 #include "WizardPages.hrc"
37 #include "WNameMatch.hxx"
38 #include "WTypeSelect.hxx"
39 
40 /** === begin UNO includes === **/
41 #include <com/sun/star/sdb/application/CopyTableOperation.hpp>
42 #include <com/sun/star/sdb/SQLContext.hpp>
43 #include <com/sun/star/sdbc/ColumnValue.hpp>
44 #include <com/sun/star/sdbc/DataType.hpp>
45 #include <com/sun/star/sdbc/XResultSet.hpp>
46 #include <com/sun/star/sdbc/XRow.hpp>
47 #include <com/sun/star/sdbcx/KeyType.hpp>
48 #include <com/sun/star/sdbcx/XAppend.hpp>
49 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
50 #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
51 #include <com/sun/star/sdbcx/XKeysSupplier.hpp>
52 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
53 #include <com/sun/star/sdbcx/XViewsSupplier.hpp>
54 #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
55 /** === end UNO includes === **/
56 
57 #include <comphelper/extract.hxx>
58 #include <comphelper/types.hxx>
59 #include <comphelper/interaction.hxx>
60 #include <connectivity/dbtools.hxx>
61 #include <connectivity/dbmetadata.hxx>
62 #include <connectivity/dbexception.hxx>
63 
64 #include <rtl/logfile.hxx>
65 #include <rtl/ustrbuf.hxx>
66 #include <tools/debug.hxx>
67 #include <tools/diagnose_ex.h>
68 #include <vcl/lstbox.hxx>
69 #include <vcl/msgbox.hxx>
70 #include <vcl/waitobj.hxx>
71 
72 #include <functional>
73 
74 using namespace ::dbaui;
75 using namespace ::com::sun::star::uno;
76 using namespace ::com::sun::star::beans;
77 using namespace ::com::sun::star::container;
78 using namespace ::com::sun::star::util;
79 using namespace ::com::sun::star::sdb;
80 using namespace ::com::sun::star::sdbc;
81 using namespace ::com::sun::star::sdbcx;
82 using namespace ::com::sun::star::lang;
83 using namespace ::com::sun::star::task;
84 using namespace dbtools;
85 
86 namespace CopyTableOperation = ::com::sun::star::sdb::application::CopyTableOperation;
87 
88 #define MAX_PAGES	4	// max. Pages die angezeigt werden
89 
90 DBG_NAME(OCopyTableWizard)
91 namespace
92 {
93     //....................................................................
clearColumns(ODatabaseExport::TColumns & _rColumns,ODatabaseExport::TColumnVector & _rColumnsVec)94 	void clearColumns(ODatabaseExport::TColumns& _rColumns, ODatabaseExport::TColumnVector& _rColumnsVec)
95 	{
96 		ODatabaseExport::TColumns::iterator aIter = _rColumns.begin();
97 		ODatabaseExport::TColumns::iterator aEnd  = _rColumns.end();
98 
99 		for(;aIter != aEnd;++aIter)
100 			delete aIter->second;
101 
102 		_rColumnsVec.clear();
103 		_rColumns.clear();
104 	}
105 }
106 
107 //========================================================================
108 //= ICopyTableSourceObject
109 //========================================================================
110 //------------------------------------------------------------------------
~ICopyTableSourceObject()111 ICopyTableSourceObject::~ICopyTableSourceObject()
112 {
113 }
114 
115 //========================================================================
116 //= ObjectCopySource
117 //========================================================================
118 //------------------------------------------------------------------------
ObjectCopySource(const Reference<XConnection> & _rxConnection,const Reference<XPropertySet> & _rxObject)119 ObjectCopySource::ObjectCopySource( const Reference< XConnection >& _rxConnection, const Reference< XPropertySet >& _rxObject )
120     :m_xConnection( _rxConnection, UNO_SET_THROW )
121     ,m_xMetaData( _rxConnection->getMetaData(), UNO_SET_THROW )
122     ,m_xObject( _rxObject, UNO_SET_THROW )
123     ,m_xObjectPSI( _rxObject->getPropertySetInfo(), UNO_SET_THROW )
124     ,m_xObjectColumns( Reference< XColumnsSupplier >( _rxObject, UNO_QUERY_THROW )->getColumns(), UNO_SET_THROW )
125 {
126 }
127 
128 //------------------------------------------------------------------------
getQualifiedObjectName() const129 ::rtl::OUString ObjectCopySource::getQualifiedObjectName() const
130 {
131     ::rtl::OUString sName;
132 
133 	if ( !m_xObjectPSI->hasPropertyByName( PROPERTY_COMMAND ) )
134 		sName = ::dbtools::composeTableName( m_xMetaData, m_xObject, ::dbtools::eInDataManipulation, false, false, false );
135 	else
136 		m_xObject->getPropertyValue( PROPERTY_NAME ) >>= sName;
137     return sName;
138 }
139 
140 //------------------------------------------------------------------------
isView() const141 bool ObjectCopySource::isView() const
142 {
143 	bool bIsView = false;
144     try
145     {
146         if ( m_xObjectPSI->hasPropertyByName( PROPERTY_TYPE ) )
147         {
148             ::rtl::OUString sObjectType;
149             OSL_VERIFY( m_xObject->getPropertyValue( PROPERTY_TYPE ) >>= sObjectType );
150             bIsView = sObjectType.equalsAscii( "VIEW" );
151         }
152     }
153     catch( const Exception& )
154     {
155     	DBG_UNHANDLED_EXCEPTION();
156     }
157     return bIsView;
158 }
159 
160 //------------------------------------------------------------------------
copyUISettingsTo(const Reference<XPropertySet> & _rxObject) const161 void ObjectCopySource::copyUISettingsTo( const Reference< XPropertySet >& _rxObject ) const
162 {
163     const ::rtl::OUString aCopyProperties[] = {
164         PROPERTY_FONT, PROPERTY_ROW_HEIGHT, PROPERTY_TEXTCOLOR,PROPERTY_TEXTLINECOLOR,PROPERTY_TEXTEMPHASIS,PROPERTY_TEXTRELIEF
165     };
166     for ( size_t i=0; i < sizeof( aCopyProperties ) / sizeof( aCopyProperties[0] ); ++i )
167     {
168 		if ( m_xObjectPSI->hasPropertyByName( aCopyProperties[i] ) )
169 			_rxObject->setPropertyValue( aCopyProperties[i], m_xObject->getPropertyValue( aCopyProperties[i] ) );
170     }
171 }
172 //------------------------------------------------------------------------
copyFilterAndSortingTo(const Reference<XConnection> & _xConnection,const Reference<XPropertySet> & _rxObject) const173 void ObjectCopySource::copyFilterAndSortingTo( const Reference< XConnection >& _xConnection,const Reference< XPropertySet >& _rxObject ) const
174 {
175     ::std::pair< ::rtl::OUString, ::rtl::OUString > aProperties[] = {
176                  ::std::pair< ::rtl::OUString, ::rtl::OUString >(PROPERTY_FILTER,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" AND ")))
177                 ,::std::pair< ::rtl::OUString, ::rtl::OUString >(PROPERTY_ORDER,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ORDER BY ")))
178     };
179 
180     size_t i = 0;
181 
182     try
183     {
184         const String sSourceName = (::dbtools::composeTableNameForSelect(m_xConnection,m_xObject) + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".")));
185         const ::rtl::OUString sTargetName = ::dbtools::composeTableNameForSelect(_xConnection,_rxObject);
186         const String sTargetNameTemp = (sTargetName + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".")));
187 
188         ::rtl::OUString sStatement(RTL_CONSTASCII_USTRINGPARAM("SELECT * FROM "));
189         sStatement += sTargetName;
190         sStatement += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" WHERE 0=1"));
191 
192 
193         for ( i=0; i < sizeof( aProperties ) / sizeof( aProperties[0] ); ++i )
194         {
195 		    if ( m_xObjectPSI->hasPropertyByName( aProperties[i].first ) )
196             {
197                 ::rtl::OUString sFilter;
198                 m_xObject->getPropertyValue( aProperties[i].first ) >>= sFilter;
199                 if ( sFilter.getLength() )
200                 {
201                     sStatement += aProperties[i].second;
202                     String sReplace = sFilter;
203                     sReplace.SearchAndReplace(sSourceName,sTargetNameTemp);
204                     sFilter = sReplace;
205                     _rxObject->setPropertyValue( aProperties[i].first, makeAny(sFilter) );
206                     sStatement += sFilter;
207                 }
208             }
209         }
210 
211         _xConnection->createStatement()->executeQuery(sStatement);
212 
213 		if ( m_xObjectPSI->hasPropertyByName( PROPERTY_APPLYFILTER ) )
214 			_rxObject->setPropertyValue( PROPERTY_APPLYFILTER, m_xObject->getPropertyValue( PROPERTY_APPLYFILTER ) );
215     }
216     catch(Exception&)
217     {
218     }
219 }
220 //------------------------------------------------------------------------
getColumnNames() const221 Sequence< ::rtl::OUString > ObjectCopySource::getColumnNames() const
222 {
223     return m_xObjectColumns->getElementNames();
224 }
225 
226 //------------------------------------------------------------------------
getPrimaryKeyColumnNames() const227 Sequence< ::rtl::OUString > ObjectCopySource::getPrimaryKeyColumnNames() const
228 {
229     const Reference<XNameAccess> xPrimaryKeyColumns = getPrimaryKeyColumns_throw(m_xObject);
230     Sequence< ::rtl::OUString > aKeyColNames;
231     if ( xPrimaryKeyColumns.is() )
232         aKeyColNames = xPrimaryKeyColumns->getElementNames();
233     return aKeyColNames;
234 }
235 
236 //------------------------------------------------------------------------
createFieldDescription(const::rtl::OUString & _rColumnName) const237 OFieldDescription* ObjectCopySource::createFieldDescription( const ::rtl::OUString& _rColumnName ) const
238 {
239     Reference< XPropertySet > xColumn( m_xObjectColumns->getByName( _rColumnName ), UNO_QUERY_THROW );
240     return new OFieldDescription( xColumn );
241 }
242 //------------------------------------------------------------------------
getSelectStatement() const243 ::rtl::OUString ObjectCopySource::getSelectStatement() const
244 {
245     ::rtl::OUString sSelectStatement;
246     if ( m_xObjectPSI->hasPropertyByName( PROPERTY_COMMAND ) )
247     {   // query
248         OSL_VERIFY( m_xObject->getPropertyValue( PROPERTY_COMMAND ) >>= sSelectStatement );
249     }
250     else
251     {   // table
252         ::rtl::OUStringBuffer aSQL;
253         aSQL.appendAscii( "SELECT " );
254 
255         // we need to create the sql stmt with column names
256         // otherwise it is possible that names don't match
257         const ::rtl::OUString sQuote = m_xMetaData->getIdentifierQuoteString();
258 
259         Sequence< ::rtl::OUString > aColumnNames = getColumnNames();
260         const ::rtl::OUString* pColumnName = aColumnNames.getConstArray();
261         const ::rtl::OUString* pEnd = pColumnName + aColumnNames.getLength();
262         for ( ; pColumnName != pEnd; )
263         {
264             aSQL.append( ::dbtools::quoteName( sQuote, *pColumnName++ ) );
265 
266             if ( pColumnName == pEnd )
267                 aSQL.appendAscii( " " );
268             else
269                 aSQL.appendAscii( ", " );
270         }
271 
272         aSQL.appendAscii( "FROM " );
273         aSQL.append( ::dbtools::composeTableNameForSelect( m_xConnection, m_xObject ) );
274 
275         sSelectStatement = aSQL.makeStringAndClear();
276     }
277 
278     return sSelectStatement;
279 }
280 
281 //------------------------------------------------------------------------
getPreparedSelectStatement() const282 ::utl::SharedUNOComponent< XPreparedStatement > ObjectCopySource::getPreparedSelectStatement() const
283 {
284     ::utl::SharedUNOComponent< XPreparedStatement > xStatement(
285         m_xConnection->prepareStatement( getSelectStatement() ),
286         ::utl::SharedUNOComponent< XPreparedStatement >::TakeOwnership
287     );
288     return xStatement;
289 }
290 
291 //========================================================================
292 //= NamedTableCopySource
293 //========================================================================
294 //------------------------------------------------------------------------
NamedTableCopySource(const Reference<XConnection> & _rxConnection,const::rtl::OUString & _rTableName)295 NamedTableCopySource::NamedTableCopySource( const Reference< XConnection >& _rxConnection, const ::rtl::OUString& _rTableName )
296     :m_xConnection( _rxConnection, UNO_SET_THROW )
297     ,m_xMetaData( _rxConnection->getMetaData(), UNO_SET_THROW )
298     ,m_sTableName( _rTableName )
299     ,m_aColumnInfo()
300 {
301     ::dbtools::qualifiedNameComponents( m_xMetaData, m_sTableName, m_sTableCatalog, m_sTableSchema, m_sTableBareName, ::dbtools::eComplete );
302     impl_ensureColumnInfo_throw();
303 }
304 
305 //------------------------------------------------------------------------
getQualifiedObjectName() const306 ::rtl::OUString NamedTableCopySource::getQualifiedObjectName() const
307 {
308     return m_sTableName;
309 }
310 
311 //------------------------------------------------------------------------
isView() const312 bool NamedTableCopySource::isView() const
313 {
314     ::rtl::OUString sTableType;
315     try
316     {
317         Reference< XResultSet > xTableDesc( m_xMetaData->getTables( makeAny( m_sTableCatalog ), m_sTableSchema, m_sTableBareName,
318             Sequence< ::rtl::OUString >() ) );
319         Reference< XRow > xTableDescRow( xTableDesc, UNO_QUERY_THROW );
320         OSL_VERIFY( xTableDesc->next() );
321         sTableType = xTableDescRow->getString( 4 );
322         OSL_ENSURE( !xTableDescRow->wasNull(), "NamedTableCopySource::isView: invalid table type!" );
323     }
324     catch( const Exception& )
325     {
326 	    DBG_UNHANDLED_EXCEPTION();
327     }
328     return sTableType.equalsAscii( "VIEW" );
329 }
330 
331 //------------------------------------------------------------------------
copyUISettingsTo(const Reference<XPropertySet> &) const332 void NamedTableCopySource::copyUISettingsTo( const Reference< XPropertySet >& /*_rxObject*/ ) const
333 {
334     // not supported: we do not have UI settings to copy
335 }
336 // -----------------------------------------------------------------------------
copyFilterAndSortingTo(const Reference<XConnection> &,const Reference<XPropertySet> &) const337 void NamedTableCopySource::copyFilterAndSortingTo( const Reference< XConnection >& ,const Reference< XPropertySet >& /*_rxObject*/ ) const
338 {
339 }
340 //------------------------------------------------------------------------
impl_ensureColumnInfo_throw()341 void NamedTableCopySource::impl_ensureColumnInfo_throw()
342 {
343     if ( !m_aColumnInfo.empty() )
344         return;
345 
346     Reference< XResultSetMetaDataSupplier > xStatementMetaSupp( impl_ensureStatement_throw().getTyped(), UNO_QUERY_THROW );
347     Reference< XResultSetMetaData > xStatementMeta( xStatementMetaSupp->getMetaData(), UNO_SET_THROW );
348 
349     sal_Int32 nColCount( xStatementMeta->getColumnCount() );
350     for ( sal_Int32 i = 1; i <= nColCount; ++i )
351     {
352         OFieldDescription aDesc;
353 
354         aDesc.SetName(          xStatementMeta->getColumnName(      i ) );
355         aDesc.SetHelpText(      xStatementMeta->getColumnLabel(     i ) );
356         aDesc.SetTypeValue(     xStatementMeta->getColumnType(      i ) );
357         aDesc.SetTypeName(      xStatementMeta->getColumnTypeName(  i ) );
358         aDesc.SetPrecision(     xStatementMeta->getPrecision(       i ) );
359         aDesc.SetScale(         xStatementMeta->getScale(           i ) );
360         aDesc.SetIsNullable(    xStatementMeta->isNullable(         i ) );
361         aDesc.SetCurrency(      xStatementMeta->isCurrency(         i ) );
362         aDesc.SetAutoIncrement( xStatementMeta->isAutoIncrement(    i ) );
363 
364         m_aColumnInfo.push_back( aDesc );
365     }
366 }
367 
368 //------------------------------------------------------------------------
impl_ensureStatement_throw()369 ::utl::SharedUNOComponent< XPreparedStatement > NamedTableCopySource::impl_ensureStatement_throw()
370 {
371     if ( !m_xStatement.is() )
372         m_xStatement.set( m_xConnection->prepareStatement( getSelectStatement() ), UNO_SET_THROW );
373     return m_xStatement;
374 }
375 
376 //------------------------------------------------------------------------
getColumnNames() const377 Sequence< ::rtl::OUString > NamedTableCopySource::getColumnNames() const
378 {
379     Sequence< ::rtl::OUString > aNames( m_aColumnInfo.size() );
380     for (   ::std::vector< OFieldDescription >::const_iterator col = m_aColumnInfo.begin();
381             col != m_aColumnInfo.end();
382             ++col
383         )
384         aNames[ col - m_aColumnInfo.begin() ] = col->GetName();
385 
386     return aNames;
387 }
388 
389 //------------------------------------------------------------------------
getPrimaryKeyColumnNames() const390 Sequence< ::rtl::OUString > NamedTableCopySource::getPrimaryKeyColumnNames() const
391 {
392     Sequence< ::rtl::OUString > aPKColNames;
393 
394     try
395     {
396         Reference< XResultSet > xPKDesc( m_xMetaData->getPrimaryKeys( makeAny( m_sTableCatalog ), m_sTableSchema, m_sTableBareName ) );
397         Reference< XRow > xPKDescRow( xPKDesc, UNO_QUERY_THROW );
398         while ( xPKDesc->next() )
399         {
400             sal_Int32 len( aPKColNames.getLength() );
401             aPKColNames.realloc( len + 1 );
402             aPKColNames[ len ] = xPKDescRow->getString( 4 );    // COLUMN_NAME
403         }
404     }
405     catch( const Exception& )
406     {
407     	DBG_UNHANDLED_EXCEPTION();
408     }
409 
410     return aPKColNames;
411 }
412 
413 //------------------------------------------------------------------------
createFieldDescription(const::rtl::OUString & _rColumnName) const414 OFieldDescription* NamedTableCopySource::createFieldDescription( const ::rtl::OUString& _rColumnName ) const
415 {
416     for (   ::std::vector< OFieldDescription >::const_iterator col = m_aColumnInfo.begin();
417             col != m_aColumnInfo.end();
418             ++col
419         )
420         if ( col->GetName() == _rColumnName )
421             return new OFieldDescription( *col );
422 
423     return NULL;
424 }
425 //------------------------------------------------------------------------
getSelectStatement() const426 ::rtl::OUString NamedTableCopySource::getSelectStatement() const
427 {
428     ::rtl::OUStringBuffer aSQL;
429     aSQL.appendAscii( "SELECT * FROM " );
430 
431     aSQL.append( ::dbtools::composeTableNameForSelect( m_xConnection, m_sTableCatalog, m_sTableSchema, m_sTableBareName ) );
432 
433     return aSQL.makeStringAndClear();
434 }
435 
436 //------------------------------------------------------------------------
getPreparedSelectStatement() const437 ::utl::SharedUNOComponent< XPreparedStatement > NamedTableCopySource::getPreparedSelectStatement() const
438 {
439     return const_cast< NamedTableCopySource* >( this )->impl_ensureStatement_throw();
440 }
441 
442 // ========================================================
443 // DummyCopySource
444 // ========================================================
445 class DummyCopySource : public ICopyTableSourceObject
446 {
447 public:
DummyCopySource()448     DummyCopySource() { }
449 
450     static const DummyCopySource& Instance();
451 
452     // ICopyTableSourceObject overridables
453     virtual ::rtl::OUString     getQualifiedObjectName() const;
454     virtual bool                isView() const;
455     virtual void                copyUISettingsTo( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject ) const;
456     virtual void                copyFilterAndSortingTo(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject ) const;
457     virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
458                                 getColumnNames() const;
459     virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >
460                                 getPrimaryKeyColumnNames() const;
461     virtual OFieldDescription*  createFieldDescription( const ::rtl::OUString& _rColumnName ) const;
462     virtual ::rtl::OUString     getSelectStatement() const;
463     virtual ::utl::SharedUNOComponent< XPreparedStatement >
464                                 getPreparedSelectStatement() const;
465 };
466 
467 //------------------------------------------------------------------------
Instance()468 const DummyCopySource& DummyCopySource::Instance()
469 {
470     static DummyCopySource s_aTheInstance;
471     return s_aTheInstance;
472 }
473 
474 //------------------------------------------------------------------------
getQualifiedObjectName() const475 ::rtl::OUString DummyCopySource::getQualifiedObjectName() const
476 {
477     OSL_ENSURE( false, "DummyCopySource::getQualifiedObjectName: not to be called!" );
478     return ::rtl::OUString();
479 }
480 
481 //------------------------------------------------------------------------
isView() const482 bool DummyCopySource::isView() const
483 {
484     OSL_ENSURE( false, "DummyCopySource::isView: not to be called!" );
485     return false;
486 }
487 
488 //------------------------------------------------------------------------
copyUISettingsTo(const Reference<XPropertySet> &) const489 void DummyCopySource::copyUISettingsTo( const Reference< XPropertySet >& /*_rxObject*/ ) const
490 {
491     // no support
492 }
493 // -----------------------------------------------------------------------------
copyFilterAndSortingTo(const Reference<XConnection> &,const Reference<XPropertySet> &) const494 void DummyCopySource::copyFilterAndSortingTo( const Reference< XConnection >& ,const Reference< XPropertySet >& /*_rxObject*/ ) const
495 {
496 }
497 //------------------------------------------------------------------------
getColumnNames() const498 Sequence< ::rtl::OUString > DummyCopySource::getColumnNames() const
499 {
500     return Sequence< ::rtl::OUString >();
501 }
502 
503 //------------------------------------------------------------------------
getPrimaryKeyColumnNames() const504 Sequence< ::rtl::OUString > DummyCopySource::getPrimaryKeyColumnNames() const
505 {
506     OSL_ENSURE( false, "DummyCopySource::getPrimaryKeyColumnNames: not to be called!" );
507     return Sequence< ::rtl::OUString >();
508 }
509 
510 //------------------------------------------------------------------------
createFieldDescription(const::rtl::OUString &) const511 OFieldDescription* DummyCopySource::createFieldDescription( const ::rtl::OUString& /*_rColumnName*/ ) const
512 {
513     OSL_ENSURE( false, "DummyCopySource::createFieldDescription: not to be called!" );
514     return NULL;
515 }
516 //------------------------------------------------------------------------
getSelectStatement() const517 ::rtl::OUString DummyCopySource::getSelectStatement() const
518 {
519     OSL_ENSURE( false, "DummyCopySource::getSelectStatement: not to be called!" );
520     return ::rtl::OUString();
521 }
522 
523 //------------------------------------------------------------------------
getPreparedSelectStatement() const524 ::utl::SharedUNOComponent< XPreparedStatement > DummyCopySource::getPreparedSelectStatement() const
525 {
526     OSL_ENSURE( false, "DummyCopySource::getPreparedSelectStatement: not to be called!" );
527     return ::utl::SharedUNOComponent< XPreparedStatement >();
528 }
529 
530 //------------------------------------------------------------------------
531 namespace
532 {
lcl_canCreateViewFor_nothrow(const Reference<XConnection> & _rxConnection)533     bool lcl_canCreateViewFor_nothrow( const Reference< XConnection >& _rxConnection )
534     {
535 	    Reference< XViewsSupplier > xSup( _rxConnection, UNO_QUERY );
536 	    Reference< XDataDescriptorFactory > xViewFac;
537 	    if ( xSup.is() )
538 		    xViewFac.set( xSup->getViews(), UNO_QUERY );
539         return xViewFac.is();
540     }
541 
lcl_sameConnection_throw(const Reference<XConnection> & _rxLHS,const Reference<XConnection> & _rxRHS)542     bool lcl_sameConnection_throw( const Reference< XConnection >& _rxLHS, const Reference< XConnection >& _rxRHS )
543     {
544         Reference< XDatabaseMetaData > xMetaLHS( _rxLHS->getMetaData(), UNO_QUERY_THROW );
545         Reference< XDatabaseMetaData > xMetaRHS( _rxRHS->getMetaData(), UNO_QUERY_THROW );
546         return xMetaLHS->getURL().equals( xMetaRHS->getURL() );
547     }
548 }
549 
550 //========================================================================
551 //= OCopyTableWizard
552 //========================================================================
553 //------------------------------------------------------------------------
OCopyTableWizard(Window * pParent,const::rtl::OUString & _rDefaultName,sal_Int16 _nOperation,const ICopyTableSourceObject & _rSourceObject,const Reference<XConnection> & _xSourceConnection,const Reference<XConnection> & _xConnection,const Reference<XMultiServiceFactory> & _rxORB,const Reference<XInteractionHandler> & _xInteractionHandler)554 OCopyTableWizard::OCopyTableWizard( Window * pParent, const ::rtl::OUString& _rDefaultName, sal_Int16 _nOperation,
555         const ICopyTableSourceObject& _rSourceObject, const Reference< XConnection >& _xSourceConnection,
556         const Reference< XConnection >& _xConnection, const Reference< XMultiServiceFactory >& _rxORB,
557         const Reference< XInteractionHandler>&   _xInteractionHandler)
558 	: WizardDialog( pParent, ModuleRes(WIZ_RTFCOPYTABLE))
559     ,m_pbHelp( this , ModuleRes(PB_HELP))
560 	,m_pbCancel( this , ModuleRes(PB_CANCEL))
561 	,m_pbPrev( this , ModuleRes(PB_PREV))
562 	,m_pbNext( this , ModuleRes(PB_NEXT))
563 	,m_pbFinish( this , ModuleRes(PB_OK))
564 	,m_mNameMapping(_xConnection->getMetaData().is() && _xConnection->getMetaData()->supportsMixedCaseQuotedIdentifiers())
565     ,m_xDestConnection( _xConnection )
566 	,m_rSourceObject( _rSourceObject )
567     ,m_xFormatter( getNumberFormatter( _xConnection, _rxORB ) )
568 	,m_xFactory(_rxORB)
569     ,m_xInteractionHandler(_xInteractionHandler)
570 	,m_sTypeNames(ModuleRes(STR_TABLEDESIGN_DBFIELDTYPES))
571 	,m_nPageCount(0)
572 	,m_bDeleteSourceColumns(sal_True)
573     ,m_bInterConnectionCopy( _xSourceConnection != _xConnection )
574     ,m_sName( _rDefaultName )
575 	,m_nOperation( _nOperation )
576     ,m_ePressed( WIZARD_NONE )
577     ,m_bCreatePrimaryKeyColumn(sal_False)
578 {
579     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::OCopyTableWizard" );
580 	DBG_CTOR(OCopyTableWizard,NULL);
581 	construct();
582 
583     // extract table name
584     ::rtl::OUString sInitialTableName( _rDefaultName );
585 	try
586 	{
587         m_sSourceName = m_rSourceObject.getQualifiedObjectName();
588         OSL_ENSURE( m_sSourceName.getLength() > 0, "OCopyTableWizard::OCopyTableWizard: unable to retrieve the source object's name!" );
589 
590         if ( !sInitialTableName.getLength() )
591             sInitialTableName = m_sSourceName;
592 
593         if ( !m_sName.getLength() )
594         {
595 		    if ( _xSourceConnection == m_xDestConnection )
596 		    {
597 			    Reference< XTablesSupplier > xSup( m_xDestConnection, UNO_QUERY_THROW );
598 			    m_sName = ::dbtools::createUniqueName( xSup->getTables(), sInitialTableName, sal_False );
599 		    }
600 		    else
601 			    m_sName = sInitialTableName;
602         }
603 	}
604 	catch ( const Exception& )
605 	{
606         m_sName = sInitialTableName;
607 	}
608 
609 	::dbaui::fillTypeInfo( _xSourceConnection, m_sTypeNames, m_aTypeInfo, m_aTypeInfoIndex );
610 	::dbaui::fillTypeInfo( m_xDestConnection, m_sTypeNames, m_aDestTypeInfo, m_aDestTypeInfoIndex );
611     impl_loadSourceData();
612 
613     bool bAllowViews = true;
614     // if the source is a, don't allow creating views #100644# (oj)
615     // (fs: Hmm? A SELECT * FROM <view> would be created, where #100644# claims this is nonsense. Why?
616     if ( m_rSourceObject.isView() )
617         bAllowViews = false;
618     // no views if the target connection does not support creating them
619     if ( !lcl_canCreateViewFor_nothrow( m_xDestConnection ) )
620         bAllowViews = false;
621     // no views if we're copying to a different database
622     if ( !lcl_sameConnection_throw( _xSourceConnection, m_xDestConnection ) )
623         bAllowViews = false;
624 
625 	if ( m_bInterConnectionCopy )
626 	{
627 		Reference< XDatabaseMetaData > xSrcMeta = _xSourceConnection->getMetaData();
628 		::rtl::OUString sCatalog;
629 		::rtl::OUString sSchema;
630 		::rtl::OUString sTable;
631 		::dbtools::qualifiedNameComponents(	xSrcMeta,
632 											m_sName,
633 											sCatalog,
634 											sSchema,
635 											sTable,
636 											::dbtools::eInDataManipulation);
637 
638 		m_sName = ::dbtools::composeTableName(m_xDestConnection->getMetaData(),sCatalog,sSchema,sTable,sal_False,::dbtools::eInTableDefinitions);
639 	}
640 
641 	OCopyTable* pPage1( new OCopyTable( this ) );
642     pPage1->disallowUseHeaderLine();
643     if ( !bAllowViews )
644         pPage1->disallowViews();
645 	pPage1->setCreateStyleAction();
646 	AddWizardPage(pPage1);
647 
648     AddWizardPage( new OWizNameMatching( this ) );
649 	AddWizardPage( new OWizColumnSelect( this ) );
650 	AddWizardPage( new OWizNormalExtend( this ) );
651 	ActivatePage();
652 }
653 
654 // -----------------------------------------------------------------------------
OCopyTableWizard(Window * pParent,const::rtl::OUString & _rDefaultName,sal_Int16 _nOperation,const ODatabaseExport::TColumns & _rSourceColumns,const ODatabaseExport::TColumnVector & _rSourceColVec,const Reference<XConnection> & _xConnection,const Reference<XNumberFormatter> & _xFormatter,TypeSelectionPageFactory _pTypeSelectionPageFactory,SvStream & _rTypeSelectionPageArg,const Reference<XMultiServiceFactory> & _rM)655 OCopyTableWizard::OCopyTableWizard( Window* pParent, const ::rtl::OUString& _rDefaultName, sal_Int16 _nOperation,
656         const ODatabaseExport::TColumns& _rSourceColumns, const ODatabaseExport::TColumnVector& _rSourceColVec,
657         const Reference< XConnection >& _xConnection, const Reference< XNumberFormatter >&	_xFormatter,
658         TypeSelectionPageFactory _pTypeSelectionPageFactory, SvStream& _rTypeSelectionPageArg, const Reference< XMultiServiceFactory >& _rM )
659 	:WizardDialog( pParent, ModuleRes(WIZ_RTFCOPYTABLE))
660 	,m_vSourceColumns(_rSourceColumns)
661     ,m_pbHelp( this , ModuleRes(PB_HELP))
662 	,m_pbCancel( this , ModuleRes(PB_CANCEL))
663 	,m_pbPrev( this , ModuleRes(PB_PREV))
664 	,m_pbNext( this , ModuleRes(PB_NEXT))
665 	,m_pbFinish( this , ModuleRes(PB_OK))
666 	,m_mNameMapping(_xConnection->getMetaData().is() && _xConnection->getMetaData()->supportsMixedCaseQuotedIdentifiers())
667     ,m_xDestConnection( _xConnection )
668     ,m_rSourceObject( DummyCopySource::Instance() )
669 	,m_xFormatter(_xFormatter)
670 	,m_xFactory(_rM)
671 	,m_sTypeNames(ModuleRes(STR_TABLEDESIGN_DBFIELDTYPES))
672 	,m_nPageCount(0)
673 	,m_bDeleteSourceColumns(sal_False)
674     ,m_bInterConnectionCopy( false )
675 	,m_sName(_rDefaultName)
676     ,m_nOperation( _nOperation )
677     ,m_ePressed( WIZARD_NONE )
678 	,m_bCreatePrimaryKeyColumn(sal_False)
679 {
680     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::OCopyTableWizard" );
681 	DBG_CTOR(OCopyTableWizard,NULL);
682 	construct();
683     ODatabaseExport::TColumnVector::const_iterator aIter = _rSourceColVec.begin();
684     ODatabaseExport::TColumnVector::const_iterator aEnd = _rSourceColVec.end();
685     for (; aIter != aEnd ; ++aIter)
686     {
687         m_vSourceVec.push_back(m_vSourceColumns.find((*aIter)->first));
688     }
689 
690 	::dbaui::fillTypeInfo( _xConnection, m_sTypeNames, m_aTypeInfo, m_aTypeInfoIndex );
691 	::dbaui::fillTypeInfo( _xConnection, m_sTypeNames, m_aDestTypeInfo, m_aDestTypeInfoIndex );
692 
693     m_xInteractionHandler.set( m_xFactory->createInstance( SERVICE_TASK_INTERACTION_HANDLER ), UNO_QUERY);
694 
695     OCopyTable* pPage1( new OCopyTable( this ) );
696     pPage1->disallowViews();
697 	pPage1->setCreateStyleAction();
698     AddWizardPage( pPage1 );
699 
700     AddWizardPage( new OWizNameMatching( this ) );
701 	AddWizardPage( new OWizColumnSelect( this ) );
702     AddWizardPage( (*_pTypeSelectionPageFactory)( this, _rTypeSelectionPageArg ) );
703 
704     ActivatePage();
705 }
706 
707 // -----------------------------------------------------------------------------
construct()708 void OCopyTableWizard::construct()
709 {
710     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::construct" );
711     AddButton( &m_pbHelp, WIZARDDIALOG_BUTTON_STDOFFSET_X );
712 	AddButton( &m_pbCancel, WIZARDDIALOG_BUTTON_STDOFFSET_X );
713     AddButton( &m_pbPrev );
714 	AddButton( &m_pbNext, WIZARDDIALOG_BUTTON_STDOFFSET_X );
715 	AddButton( &m_pbFinish );
716 
717 	m_pbPrev.SetClickHdl( LINK( this, OCopyTableWizard, ImplPrevHdl ) );
718 	m_pbNext.SetClickHdl( LINK( this, OCopyTableWizard, ImplNextHdl ) );
719 	m_pbFinish.SetClickHdl( LINK( this, OCopyTableWizard, ImplOKHdl ) );
720 
721 	SetActivatePageHdl( LINK( this, OCopyTableWizard, ImplActivateHdl ) );
722 
723 	SetPrevButton( &m_pbPrev );
724 	SetNextButton( &m_pbNext );
725 
726 	ShowButtonFixedLine( sal_True );
727 
728 	m_pbNext.GrabFocus();
729 
730 	if (m_vDestColumns.size())
731 		// source is a html or rtf table
732 		m_pbNext.SetStyle(m_pbFinish.GetStyle() | WB_DEFBUTTON);
733 	else
734 		m_pbFinish.SetStyle(m_pbFinish.GetStyle() | WB_DEFBUTTON);
735 
736 	FreeResource();
737 
738 	m_pTypeInfo = TOTypeInfoSP(new OTypeInfo());
739 	m_pTypeInfo->aUIName = m_sTypeNames.GetToken(TYPE_OTHER);
740 	m_bAddPKFirstTime = sal_True;
741 }
742 //------------------------------------------------------------------------
~OCopyTableWizard()743 OCopyTableWizard::~OCopyTableWizard()
744 {
745 	DBG_DTOR(OCopyTableWizard,NULL);
746 	for ( ;; )
747     {
748         TabPage *pPage = GetPage(0);
749         if ( pPage == NULL )
750             break;
751 		RemovePage( pPage );
752 		delete pPage;
753 	}
754 
755 	if ( m_bDeleteSourceColumns )
756 		clearColumns(m_vSourceColumns,m_vSourceVec);
757 
758 	clearColumns(m_vDestColumns,m_aDestVec);
759 
760 	// clear the type information
761 	m_aTypeInfoIndex.clear();
762 	m_aTypeInfo.clear();
763 	m_aDestTypeInfoIndex.clear();
764 }
765 // -----------------------------------------------------------------------
IMPL_LINK(OCopyTableWizard,ImplPrevHdl,PushButton *,EMPTYARG)766 IMPL_LINK( OCopyTableWizard, ImplPrevHdl, PushButton*, EMPTYARG )
767 {
768 	m_ePressed = WIZARD_PREV;
769 	if ( GetCurLevel() )
770 	{
771 		if ( getOperation() != CopyTableOperation::AppendData )
772 		{
773 			if(GetCurLevel() == 2)
774 				ShowPage(GetCurLevel()-2);
775 			else
776 				ShowPrevPage();
777 		}
778 		else
779 			ShowPrevPage();
780 	}
781 	return 0;
782 }
783 
784 // -----------------------------------------------------------------------
785 
IMPL_LINK(OCopyTableWizard,ImplNextHdl,PushButton *,EMPTYARG)786 IMPL_LINK( OCopyTableWizard, ImplNextHdl, PushButton*, EMPTYARG )
787 {
788 	m_ePressed = WIZARD_NEXT;
789 	if ( GetCurLevel() < MAX_PAGES )
790 	{
791 		if ( getOperation() != CopyTableOperation::AppendData )
792 		{
793 			if(GetCurLevel() == 0)
794 				ShowPage(GetCurLevel()+2);
795 			else
796 				ShowNextPage();
797 		}
798 		else
799 			ShowNextPage();
800 	}
801 	return 0;
802 }
803 // -----------------------------------------------------------------------
CheckColumns(sal_Int32 & _rnBreakPos)804 sal_Bool OCopyTableWizard::CheckColumns(sal_Int32& _rnBreakPos)
805 {
806     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::CheckColumns" );
807 	sal_Bool bRet = sal_True;
808 	m_vColumnPos.clear();
809 	m_vColumnTypes.clear();
810 
811 	OSL_ENSURE( m_xDestConnection.is(), "OCopyTableWizard::CheckColumns: No connection!" );
812 	//////////////////////////////////////////////////////////////////////
813 	// Wenn Datenbank PrimaryKeys verarbeiten kann, PrimaryKey anlegen
814 	if ( m_xDestConnection.is() )
815 	{
816 		sal_Bool bPKeyAllowed = supportsPrimaryKey();
817 
818 		sal_Bool bContainsColumns = !m_vDestColumns.empty();
819 
820 		if ( bPKeyAllowed && shouldCreatePrimaryKey() )
821 		{
822 			// add extra column for the primary key
823 			TOTypeInfoSP pTypeInfo = queryPrimaryKeyType(m_aDestTypeInfo);
824 			if ( pTypeInfo.get() )
825 			{
826 				if ( m_bAddPKFirstTime )
827 				{
828 					OFieldDescription* pField = new OFieldDescription();
829 					pField->SetName(m_aKeyName);
830 					pField->FillFromTypeInfo(pTypeInfo,sal_True,sal_True);
831 					pField->SetPrimaryKey(sal_True);
832 					m_bAddPKFirstTime = sal_False;
833 					insertColumn(0,pField);
834 				}
835 				m_vColumnPos.push_back(ODatabaseExport::TPositions::value_type(1,1));
836 				m_vColumnTypes.push_back(pTypeInfo->nType);
837 			}
838 		}
839 
840 		if ( bContainsColumns )
841 		{	// we have dest columns so look for the matching column
842 			ODatabaseExport::TColumnVector::const_iterator aSrcIter = m_vSourceVec.begin();
843             ODatabaseExport::TColumnVector::const_iterator aSrcEnd = m_vSourceVec.end();
844 			for(;aSrcIter != aSrcEnd;++aSrcIter)
845 			{
846 				ODatabaseExport::TColumns::iterator aDestIter = m_vDestColumns.find(m_mNameMapping[(*aSrcIter)->first]);
847 
848 				if ( aDestIter != m_vDestColumns.end() )
849 				{
850 					ODatabaseExport::TColumnVector::const_iterator aFind = ::std::find(m_aDestVec.begin(),m_aDestVec.end(),aDestIter);
851 					sal_Int32 nPos = (aFind - m_aDestVec.begin())+1;
852 					m_vColumnPos.push_back(ODatabaseExport::TPositions::value_type(nPos,nPos));
853 					m_vColumnTypes.push_back((*aFind)->second->GetType());
854 				}
855 				else
856 				{
857 					m_vColumnPos.push_back( ODatabaseExport::TPositions::value_type( COLUMN_POSITION_NOT_FOUND, COLUMN_POSITION_NOT_FOUND ) );
858 					m_vColumnTypes.push_back(0);
859 				}
860 			}
861 		}
862 		else
863 		{
864             Reference< XDatabaseMetaData > xMetaData( m_xDestConnection->getMetaData() );
865 			::rtl::OUString sExtraChars = xMetaData->getExtraNameCharacters();
866 			sal_Int32 nMaxNameLen		= getMaxColumnNameLength();
867 
868 			ODatabaseExport::TColumnVector::const_iterator aSrcIter = m_vSourceVec.begin();
869             ODatabaseExport::TColumnVector::const_iterator aSrcEnd = m_vSourceVec.end();
870 			for(_rnBreakPos=0;aSrcIter != aSrcEnd && bRet ;++aSrcIter,++_rnBreakPos)
871 			{
872 				OFieldDescription* pField = new OFieldDescription(*(*aSrcIter)->second);
873 				pField->SetName(convertColumnName(TExportColumnFindFunctor(&m_vDestColumns),(*aSrcIter)->first,sExtraChars,nMaxNameLen));
874 				TOTypeInfoSP pType = convertType((*aSrcIter)->second->getSpecialTypeInfo(),bRet);
875 				pField->SetType(pType);
876 				if ( !bPKeyAllowed )
877 					pField->SetPrimaryKey(sal_False);
878 
879 				// now create a column
880 				insertColumn(m_vDestColumns.size(),pField);
881 				m_vColumnPos.push_back(ODatabaseExport::TPositions::value_type(m_vDestColumns.size(),m_vDestColumns.size()));
882 				m_vColumnTypes.push_back((*aSrcIter)->second->GetType());
883 			}
884 		}
885 	}
886 	return bRet;
887 }
888 // -----------------------------------------------------------------------
IMPL_LINK(OCopyTableWizard,ImplOKHdl,OKButton *,EMPTYARG)889 IMPL_LINK( OCopyTableWizard, ImplOKHdl, OKButton*, EMPTYARG )
890 {
891 	m_ePressed = WIZARD_FINISH;
892 	sal_Bool bFinish = DeactivatePage() != 0;
893 
894 	if(bFinish)
895 	{
896 		WaitObject aWait(this);
897 		switch(getOperation())
898 		{
899 			case CopyTableOperation::CopyDefinitionAndData:
900 			case CopyTableOperation::CopyDefinitionOnly:
901 			{
902 				sal_Bool bOnFirstPage = GetCurLevel() == 0;
903 				if ( bOnFirstPage )
904 				{
905 					// we came from the first page so we have to clear
906 					// all column information already collected
907 					clearDestColumns();
908 					m_mNameMapping.clear();
909 				}
910 				sal_Int32 nBreakPos = 0;
911 				sal_Bool bCheckOk = CheckColumns(nBreakPos);
912 				if ( bOnFirstPage && !bCheckOk )
913 				{
914 					showColumnTypeNotSupported(m_vSourceVec[nBreakPos-1]->first);
915 					OWizTypeSelect* pPage = static_cast<OWizTypeSelect*>(GetPage(3));
916 					if ( pPage )
917 					{
918                         m_mNameMapping.clear();
919 						pPage->setDisplayRow(nBreakPos);
920 						ShowPage(3);
921 						return 0;
922 					}
923 				}
924                 if ( m_xDestConnection.is() )
925 	            {
926                     if ( supportsPrimaryKey() )
927                     {
928                         ODatabaseExport::TColumns::iterator aFind = ::std::find_if(m_vDestColumns.begin(),m_vDestColumns.end()
929                             ,::std::compose1(::std::mem_fun(&OFieldDescription::IsPrimaryKey),::std::select2nd<ODatabaseExport::TColumns::value_type>()));
930                         if ( aFind == m_vDestColumns.end() && m_xInteractionHandler.is() )
931                         {
932 
933                             String sTitle(ModuleRes(STR_TABLEDESIGN_NO_PRIM_KEY_HEAD));
934 			                String sMsg(ModuleRes(STR_TABLEDESIGN_NO_PRIM_KEY));
935                             SQLContext aError;
936                             aError.Message = sMsg;
937                             ::rtl::Reference< ::comphelper::OInteractionRequest > xRequest( new ::comphelper::OInteractionRequest( makeAny( aError ) ) );
938                             ::rtl::Reference< ::comphelper::OInteractionApprove > xYes = new ::comphelper::OInteractionApprove;
939                             xRequest->addContinuation( xYes.get() );
940                             xRequest->addContinuation( new ::comphelper::OInteractionDisapprove );
941                             ::rtl::Reference< ::comphelper::OInteractionAbort > xAbort = new ::comphelper::OInteractionAbort;
942                             xRequest->addContinuation( xAbort.get() );
943 
944                             m_xInteractionHandler->handle( xRequest.get() );
945 
946                             if ( xYes->wasSelected() )
947                             {
948                                 OCopyTable* pPage = static_cast<OCopyTable*>(GetPage(0));
949                                 m_bCreatePrimaryKeyColumn = sal_True;
950                                 m_aKeyName = pPage->GetKeyName();
951                                 if ( !m_aKeyName.getLength() )
952                                     m_aKeyName = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ID" ) );
953                                 m_aKeyName = createUniqueName( m_aKeyName );
954                                 sal_Int32 nBreakPos2 = 0;
955 			                    CheckColumns(nBreakPos2);
956                             }
957                             else if ( xAbort->wasSelected() )
958                             {
959                                 ShowPage(3);
960                                 return 0;
961                             }
962                         }
963                     }
964                 }
965 				break;
966 			}
967 			case CopyTableOperation::AppendData:
968 			case CopyTableOperation::CreateAsView:
969 				break;
970 			default:
971 			{
972 				OSL_ENSURE(sal_False, "OCopyTableWizard::ImplOKHdl: invalid creation style!");
973 			}
974 		}
975 
976 		EndDialog(RET_OK);
977 	}
978 	return bFinish;
979 }
980 //------------------------------------------------------------------------
shouldCreatePrimaryKey() const981 sal_Bool OCopyTableWizard::shouldCreatePrimaryKey() const
982 {
983     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::shouldCreatePrimaryKey" );
984 	return m_bCreatePrimaryKeyColumn;
985 }
986 
987 // -----------------------------------------------------------------------
setCreatePrimaryKey(bool _bDoCreate,const::rtl::OUString & _rSuggestedName)988 void OCopyTableWizard::setCreatePrimaryKey( bool _bDoCreate, const ::rtl::OUString& _rSuggestedName )
989 {
990     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::setCreatePrimaryKey" );
991     m_bCreatePrimaryKeyColumn = _bDoCreate;
992     if ( _rSuggestedName.getLength() )
993         m_aKeyName = _rSuggestedName;
994 
995     OCopyTable* pSettingsPage = dynamic_cast< OCopyTable* >( GetPage( 0 ) );
996     OSL_ENSURE( pSettingsPage, "OCopyTableWizard::setCreatePrimaryKey: page should have been added in the ctor!" );
997     if ( pSettingsPage )
998         pSettingsPage->setCreatePrimaryKey( _bDoCreate, _rSuggestedName );
999 }
1000 
1001 // -----------------------------------------------------------------------
IMPL_LINK(OCopyTableWizard,ImplActivateHdl,WizardDialog *,EMPTYARG)1002 IMPL_LINK( OCopyTableWizard, ImplActivateHdl, WizardDialog*, EMPTYARG )
1003 {
1004 	OWizardPage* pCurrent = (OWizardPage*)GetPage(GetCurLevel());
1005 	if(pCurrent)
1006 	{
1007 		sal_Bool bFirstTime = pCurrent->IsFirstTime();
1008 		if(bFirstTime)
1009 			pCurrent->Reset();
1010 
1011 		CheckButtons();
1012 
1013 		SetText(pCurrent->GetTitle());
1014 
1015 		Invalidate();
1016 	}
1017 	return 0;
1018 }
1019 // -----------------------------------------------------------------------
CheckButtons()1020 void OCopyTableWizard::CheckButtons()
1021 {
1022     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::CheckButtons" );
1023 	if(GetCurLevel() == 0) // erste Seite hat kein PrevButton
1024 	{
1025 		if(m_nPageCount > 1)
1026 			m_pbNext.Enable(sal_True);
1027 		else
1028 			m_pbNext.Enable(sal_False);
1029 
1030 		m_pbPrev.Enable(sal_False);
1031 	}
1032 	else if(GetCurLevel() == m_nPageCount-1) // letzte Seite hat keinen Next Button
1033 	{
1034 		m_pbNext.Enable(sal_False);
1035 		m_pbPrev.Enable(sal_True);
1036 	}
1037 	else
1038 	{
1039 		m_pbPrev.Enable(sal_True);
1040 		// next has already his state
1041 	}
1042 }
1043 // -----------------------------------------------------------------------
EnableButton(Wizard_Button_Style eStyle,sal_Bool bEnable)1044 void OCopyTableWizard::EnableButton(Wizard_Button_Style eStyle,sal_Bool bEnable)
1045 {
1046     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::EnableButton" );
1047 //	CheckButtons();
1048 	Button* pButton;
1049 	if(eStyle == WIZARD_NEXT)
1050 		pButton = &m_pbNext;
1051 	else if(eStyle == WIZARD_PREV)
1052 		pButton = &m_pbPrev;
1053 	else
1054 		pButton = &m_pbFinish;
1055 	pButton->Enable(bEnable);
1056 
1057 }
1058 // -----------------------------------------------------------------------
DeactivatePage()1059 long OCopyTableWizard::DeactivatePage()
1060 {
1061     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::DeactivatePage" );
1062 	OWizardPage* pPage = (OWizardPage*)GetPage(GetCurLevel());
1063 	return pPage ? pPage->LeavePage() : sal_False;
1064 }
1065 // -----------------------------------------------------------------------
AddWizardPage(OWizardPage * pPage)1066 void OCopyTableWizard::AddWizardPage(OWizardPage* pPage)
1067 {
1068     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::AddWizardPage" );
1069 	AddPage(pPage);
1070 	++m_nPageCount;
1071 }
1072 // -----------------------------------------------------------------------------
insertColumn(sal_Int32 _nPos,OFieldDescription * _pField)1073 void OCopyTableWizard::insertColumn(sal_Int32 _nPos,OFieldDescription* _pField)
1074 {
1075     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::insertColumn" );
1076 	OSL_ENSURE(_pField,"FieldDescrioption is null!");
1077 	if ( _pField )
1078 	{
1079 		ODatabaseExport::TColumns::iterator aFind = m_vDestColumns.find(_pField->GetName());
1080 		if ( aFind != m_vDestColumns.end() )
1081 		{
1082 			delete aFind->second;
1083 			m_vDestColumns.erase(aFind);
1084 		}
1085 
1086 		m_aDestVec.insert(m_aDestVec.begin() + _nPos,
1087 			m_vDestColumns.insert(ODatabaseExport::TColumns::value_type(_pField->GetName(),_pField)).first);
1088         m_mNameMapping[_pField->GetName()] = _pField->GetName();
1089 	}
1090 }
1091 // -----------------------------------------------------------------------------
replaceColumn(sal_Int32 _nPos,OFieldDescription * _pField,const::rtl::OUString & _sOldName)1092 void OCopyTableWizard::replaceColumn(sal_Int32 _nPos,OFieldDescription* _pField,const ::rtl::OUString& _sOldName)
1093 {
1094     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::replaceColumn" );
1095 	OSL_ENSURE(_pField,"FieldDescrioption is null!");
1096 	if ( _pField )
1097 	{
1098 		m_vDestColumns.erase(_sOldName);
1099 		OSL_ENSURE( m_vDestColumns.find(_pField->GetName()) == m_vDestColumns.end(),"Column with that name already exist!");
1100 
1101 		m_aDestVec[_nPos] =
1102 			m_vDestColumns.insert(ODatabaseExport::TColumns::value_type(_pField->GetName(),_pField)).first;
1103 	}
1104 }
1105 // -----------------------------------------------------------------------------
impl_loadSourceData()1106 void OCopyTableWizard::impl_loadSourceData()
1107 {
1108     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::impl_loadSourceData" );
1109     loadData( m_rSourceObject, m_vSourceColumns, m_vSourceVec );
1110 }
1111 
1112 // -----------------------------------------------------------------------------
loadData(const ICopyTableSourceObject & _rSourceObject,ODatabaseExport::TColumns & _rColumns,ODatabaseExport::TColumnVector & _rColVector)1113 void OCopyTableWizard::loadData(  const ICopyTableSourceObject& _rSourceObject, ODatabaseExport::TColumns& _rColumns, ODatabaseExport::TColumnVector& _rColVector )
1114 {
1115     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::loadData" );
1116     ODatabaseExport::TColumns::iterator colEnd = _rColumns.end();
1117 	for ( ODatabaseExport::TColumns::iterator col = _rColumns.begin(); col != colEnd; ++col )
1118 		delete col->second;
1119 
1120 	_rColVector.clear();
1121 	_rColumns.clear();
1122 
1123 	OFieldDescription* pActFieldDescr = NULL;
1124 	String aType;
1125 	::rtl::OUString sCreateParam(RTL_CONSTASCII_USTRINGPARAM("x"));
1126 	//////////////////////////////////////////////////////////////////////
1127 	// ReadOnly-Flag
1128 	// Bei Drop darf keine Zeile editierbar sein.
1129 	// Bei Add duerfen nur die leeren Zeilen editierbar sein.
1130 	// Bei Add und Drop koennen alle Zeilen editiert werden.
1131 	Sequence< ::rtl::OUString > aColumns( _rSourceObject.getColumnNames() );
1132 	const ::rtl::OUString* pColumn      = aColumns.getConstArray();
1133 	const ::rtl::OUString* pColumnEnd   = pColumn + aColumns.getLength();
1134 
1135 	for ( ; pColumn != pColumnEnd; ++pColumn )
1136 	{
1137 		// get the properties of the column
1138 		pActFieldDescr = _rSourceObject.createFieldDescription( *pColumn );
1139         OSL_ENSURE( pActFieldDescr, "OCopyTableWizard::loadData: illegal field description!" );
1140         if ( !pActFieldDescr )
1141             continue;
1142 
1143 		sal_Int32 nType			  = pActFieldDescr->GetType();
1144 		sal_Int32 nScale		  = pActFieldDescr->GetScale();
1145 		sal_Int32 nPrecision	  = pActFieldDescr->GetPrecision();
1146 		sal_Bool bAutoIncrement   = pActFieldDescr->IsAutoIncrement();
1147 		::rtl::OUString sTypeName = pActFieldDescr->GetTypeName();
1148 
1149 		// search for type
1150 		sal_Bool bForce;
1151 		TOTypeInfoSP pTypeInfo = ::dbaui::getTypeInfoFromType(m_aTypeInfo,nType,sTypeName,sCreateParam,nPrecision,nScale,bAutoIncrement,bForce);
1152 		if ( !pTypeInfo.get() )
1153 			pTypeInfo = m_pTypeInfo;
1154 
1155 		pActFieldDescr->FillFromTypeInfo(pTypeInfo,sal_True,sal_False);
1156 		_rColVector.push_back(_rColumns.insert(ODatabaseExport::TColumns::value_type(pActFieldDescr->GetName(),pActFieldDescr)).first);
1157 	}
1158 
1159     // determine which coumns belong to the primary key
1160     Sequence< ::rtl::OUString > aPrimaryKeyColumns( _rSourceObject.getPrimaryKeyColumnNames() );
1161     const ::rtl::OUString* pKeyColName  = aPrimaryKeyColumns.getConstArray();
1162     const ::rtl::OUString* pKeyColEnd   = pKeyColName + aPrimaryKeyColumns.getLength();
1163 
1164     for( ; pKeyColName != pKeyColEnd; ++pKeyColName )
1165     {
1166         ODatabaseExport::TColumns::iterator keyPos = _rColumns.find( *pKeyColName );
1167         if ( keyPos != _rColumns.end() )
1168         {
1169             keyPos->second->SetPrimaryKey( sal_True );
1170             keyPos->second->SetIsNullable( ColumnValue::NO_NULLS );
1171         }
1172     }
1173 }
1174 // -----------------------------------------------------------------------------
clearDestColumns()1175 void OCopyTableWizard::clearDestColumns()
1176 {
1177     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::clearDestColumns" );
1178 	clearColumns(m_vDestColumns,m_aDestVec);
1179     m_bAddPKFirstTime = sal_True;
1180     m_mNameMapping.clear();
1181 }
1182 
1183 // -----------------------------------------------------------------------------
appendColumns(Reference<XColumnsSupplier> & _rxColSup,const ODatabaseExport::TColumnVector * _pVec,sal_Bool _bKeyColumns) const1184 void OCopyTableWizard::appendColumns( Reference<XColumnsSupplier>& _rxColSup, const ODatabaseExport::TColumnVector* _pVec, sal_Bool _bKeyColumns) const
1185 {
1186     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::appendColumns" );
1187 	// now append the columns
1188 	OSL_ENSURE(_rxColSup.is(),"No columns supplier");
1189 	if(!_rxColSup.is())
1190 		return;
1191 	Reference<XNameAccess> xColumns = _rxColSup->getColumns();
1192 	OSL_ENSURE(xColumns.is(),"No columns");
1193 	Reference<XDataDescriptorFactory> xColumnFactory(xColumns,UNO_QUERY);
1194 
1195 	Reference<XAppend> xAppend(xColumns,UNO_QUERY);
1196 	OSL_ENSURE(xAppend.is(),"No XAppend Interface!");
1197 
1198 	ODatabaseExport::TColumnVector::const_iterator aIter = _pVec->begin();
1199     ODatabaseExport::TColumnVector::const_iterator aEnd = _pVec->end();
1200 	for(;aIter != aEnd;++aIter)
1201 	{
1202 		OFieldDescription* pField = (*aIter)->second;
1203 		if(!pField)
1204 			continue;
1205 
1206 		Reference<XPropertySet> xColumn;
1207 		if(pField->IsPrimaryKey() || !_bKeyColumns)
1208 			xColumn = xColumnFactory->createDataDescriptor();
1209 		if(xColumn.is())
1210 		{
1211 			if(!_bKeyColumns)
1212 				dbaui::setColumnProperties(xColumn,pField);
1213 			else
1214 				xColumn->setPropertyValue(PROPERTY_NAME,makeAny(pField->GetName()));
1215 
1216 			xAppend->appendByDescriptor(xColumn);
1217 			xColumn = NULL;
1218 			// now only the settings are missing
1219 			if(xColumns->hasByName(pField->GetName()))
1220 			{
1221                 xColumn.set(xColumns->getByName(pField->GetName()),UNO_QUERY);
1222                 OSL_ENSURE(xColumn.is(),"OCopyTableWizard::appendColumns: Column is NULL!");
1223 				if ( xColumn.is() )
1224 					pField->copyColumnSettingsTo(xColumn);
1225 			}
1226 			else
1227 			{
1228 				OSL_ENSURE(sal_False, "OCopyTableWizard::appendColumns: invalid field name!");
1229 			}
1230 
1231 		}
1232 	}
1233 }
1234 // -----------------------------------------------------------------------------
appendKey(Reference<XKeysSupplier> & _rxSup,const ODatabaseExport::TColumnVector * _pVec) const1235 void OCopyTableWizard::appendKey( Reference<XKeysSupplier>& _rxSup, const ODatabaseExport::TColumnVector* _pVec) const
1236 {
1237     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::appendKey" );
1238 	if(!_rxSup.is())
1239 		return; // the database doesn't support keys
1240 	OSL_ENSURE(_rxSup.is(),"No XKeysSupplier!");
1241 	Reference<XDataDescriptorFactory> xKeyFactory(_rxSup->getKeys(),UNO_QUERY);
1242 	OSL_ENSURE(xKeyFactory.is(),"No XDataDescriptorFactory Interface!");
1243 	if ( !xKeyFactory.is() )
1244 		return;
1245 	Reference<XAppend> xAppend(xKeyFactory,UNO_QUERY);
1246 	OSL_ENSURE(xAppend.is(),"No XAppend Interface!");
1247 
1248 	Reference<XPropertySet> xKey = xKeyFactory->createDataDescriptor();
1249 	OSL_ENSURE(xKey.is(),"Key is null!");
1250 	xKey->setPropertyValue(PROPERTY_TYPE,makeAny(KeyType::PRIMARY));
1251 
1252 	Reference<XColumnsSupplier> xColSup(xKey,UNO_QUERY);
1253 	if(xColSup.is())
1254 	{
1255 		appendColumns(xColSup,_pVec,sal_True);
1256 		Reference<XNameAccess> xColumns = xColSup->getColumns();
1257 		if(xColumns.is() && xColumns->getElementNames().getLength())
1258 			xAppend->appendByDescriptor(xKey);
1259 	}
1260 
1261 }
1262 // -----------------------------------------------------------------------------
createView() const1263 Reference< XPropertySet > OCopyTableWizard::createView() const
1264 {
1265     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::createView" );
1266     ::rtl::OUString sCommand( m_rSourceObject.getSelectStatement() );
1267     OSL_ENSURE( sCommand.getLength(), "OCopyTableWizard::createView: no statement in the source object!" );
1268         // there are legitimate cases in which getSelectStatement does not provide a statement,
1269         // but in all those cases, this method here should never be called.
1270     return ::dbaui::createView( m_sName, m_xDestConnection, sCommand );
1271 }
1272 // -----------------------------------------------------------------------------
createTable()1273 Reference< XPropertySet > OCopyTableWizard::createTable()
1274 {
1275     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::createTable" );
1276     Reference< XPropertySet > xTable;
1277 
1278 	Reference<XTablesSupplier> xSup( m_xDestConnection, UNO_QUERY );
1279 	Reference< XNameAccess > xTables;
1280 	if(xSup.is())
1281 		xTables = xSup->getTables();
1282 	if ( getOperation() != CopyTableOperation::AppendData )
1283 	{
1284 		Reference<XDataDescriptorFactory> xFact(xTables,UNO_QUERY);
1285 		OSL_ENSURE(xFact.is(),"No XDataDescriptorFactory available!");
1286 		if(!xFact.is())
1287 			return NULL;
1288 
1289 		xTable = xFact->createDataDescriptor();
1290 		OSL_ENSURE(xTable.is(),"Could not create a new object!");
1291 		if(!xTable.is())
1292 			return NULL;
1293 
1294 		::rtl::OUString sCatalog,sSchema,sTable;
1295         Reference< XDatabaseMetaData> xMetaData = m_xDestConnection->getMetaData();
1296 		::dbtools::qualifiedNameComponents(xMetaData,
1297 											m_sName,
1298 											sCatalog,
1299 											sSchema,
1300 											sTable,
1301 											::dbtools::eInDataManipulation);
1302 
1303         if ( !sCatalog.getLength() && xMetaData->supportsCatalogsInTableDefinitions() )
1304         {
1305             sCatalog = m_xDestConnection->getCatalog();
1306         }
1307 
1308         if ( !sSchema.getLength() && xMetaData->supportsSchemasInTableDefinitions() )
1309         {
1310             sSchema = xMetaData->getUserName();
1311         }
1312 
1313 		xTable->setPropertyValue(PROPERTY_CATALOGNAME,makeAny(sCatalog));
1314 		xTable->setPropertyValue(PROPERTY_SCHEMANAME,makeAny(sSchema));
1315 		xTable->setPropertyValue(PROPERTY_NAME,makeAny(sTable));
1316 
1317 		Reference< XColumnsSupplier > xSuppDestinationColumns( xTable, UNO_QUERY );
1318 		// now append the columns
1319 		const ODatabaseExport::TColumnVector* pVec = getDestVector();
1320 		appendColumns( xSuppDestinationColumns, pVec );
1321 		// now append the primary key
1322 		Reference<XKeysSupplier> xKeySup(xTable,UNO_QUERY);
1323 		appendKey(xKeySup,pVec);
1324 
1325 		Reference<XAppend> xAppend(xTables,UNO_QUERY);
1326 		if(xAppend.is())
1327 			xAppend->appendByDescriptor(xTable);
1328 
1329 		//	xTable = NULL;
1330 		// we need to reget the table because after appending it it is no longer valid
1331 		if(xTables->hasByName(m_sName))
1332 			xTables->getByName(m_sName) >>= xTable;
1333 		else
1334 		{
1335 			::rtl::OUString sComposedName(
1336                 ::dbtools::composeTableName( m_xDestConnection->getMetaData(), xTable, ::dbtools::eInDataManipulation, false, false, false ) );
1337 			if(xTables->hasByName(sComposedName))
1338 			{
1339 				xTables->getByName(sComposedName) >>= xTable;
1340 				m_sName = sComposedName;
1341 			}
1342 			else
1343 				xTable = NULL;
1344 		}
1345 		if(xTable.is())
1346 		{
1347             xSuppDestinationColumns.set( xTable, UNO_QUERY_THROW );
1348 			// insert new table name into table filter
1349 			::dbaui::appendToFilter( m_xDestConnection, m_sName, GetFactory(), this );
1350 
1351             // copy ui settings
1352             m_rSourceObject.copyUISettingsTo( xTable );
1353             //copy filter and sorting
1354             m_rSourceObject.copyFilterAndSortingTo(m_xDestConnection,xTable);
1355 			// set column mappings
1356 			Reference<XNameAccess> xNameAccess = xSuppDestinationColumns->getColumns();
1357 			Sequence< ::rtl::OUString> aSeq = xNameAccess->getElementNames();
1358 			const ::rtl::OUString* pIter = aSeq.getConstArray();
1359 			const ::rtl::OUString* pEnd	  = pIter + aSeq.getLength();
1360 
1361 			::std::vector<int> aAlreadyFound(m_vColumnPos.size(),0);
1362 
1363 			for(sal_Int32 nNewPos=1;pIter != pEnd;++pIter,++nNewPos)
1364 			{
1365 				ODatabaseExport::TColumns::const_iterator aDestIter = m_vDestColumns.find(*pIter);
1366 
1367 				if ( aDestIter != m_vDestColumns.end() )
1368 				{
1369 					ODatabaseExport::TColumnVector::const_iterator aFind = ::std::find(m_aDestVec.begin(),m_aDestVec.end(),aDestIter);
1370 					sal_Int32 nPos = (aFind - m_aDestVec.begin())+1;
1371 
1372 					ODatabaseExport::TPositions::iterator aPosFind = ::std::find_if(
1373                         m_vColumnPos.begin(),
1374                         m_vColumnPos.end(),
1375 						::std::compose1(    ::std::bind2nd( ::std::equal_to< sal_Int32 >(), nPos ),
1376                                             ::std::select1st< ODatabaseExport::TPositions::value_type >()
1377                         )
1378                     );
1379 
1380 					if ( m_vColumnPos.end() != aPosFind )
1381 					{
1382 						aPosFind->second = nNewPos;
1383 						OSL_ENSURE( m_vColumnTypes.size() > size_t( aPosFind - m_vColumnPos.begin() ),
1384                             "Invalid index for vector!" );
1385 						m_vColumnTypes[ aPosFind - m_vColumnPos.begin() ] = (*aFind)->second->GetType();
1386 					}
1387 				}
1388 			}
1389 		}
1390 	}
1391 	else if(xTables.is() && xTables->hasByName(m_sName))
1392 		xTables->getByName(m_sName) >>= xTable;
1393 
1394 	return xTable;
1395 }
1396 
1397 // -----------------------------------------------------------------------------
supportsPrimaryKey(const Reference<XConnection> & _rxConnection)1398 bool OCopyTableWizard::supportsPrimaryKey( const Reference< XConnection >& _rxConnection )
1399 {
1400     OSL_PRECOND( _rxConnection.is(), "OCopyTableWizard::supportsPrimaryKey: invalid connection!" );
1401 	if ( !_rxConnection.is() )
1402         return false;
1403 
1404     ::dbtools::DatabaseMetaData aMetaData( _rxConnection );
1405     return aMetaData.supportsPrimaryKeys();
1406 }
1407 
1408 // -----------------------------------------------------------------------------
supportsViews(const Reference<XConnection> & _rxConnection)1409 bool OCopyTableWizard::supportsViews( const Reference< XConnection >& _rxConnection )
1410 {
1411     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::supportsViews" );
1412     OSL_PRECOND( _rxConnection.is(), "OCopyTableWizard::supportsViews: invalid connection!" );
1413     if ( !_rxConnection.is() )
1414         return false;
1415 
1416     bool bSupportsViews( false );
1417     try
1418     {
1419         Reference< XDatabaseMetaData > xMetaData( _rxConnection->getMetaData(), UNO_SET_THROW );
1420 	    Reference< XViewsSupplier > xViewSups( _rxConnection, UNO_QUERY );
1421         bSupportsViews = xViewSups.is();
1422 	    if ( !bSupportsViews )
1423 	    {
1424 		    try
1425 		    {
1426 			    Reference< XResultSet > xRs( xMetaData->getTableTypes(), UNO_SET_THROW );
1427                 Reference< XRow > xRow( xRs, UNO_QUERY_THROW );
1428 				while ( xRs->next() )
1429 				{
1430 					::rtl::OUString sValue = xRow->getString( 1 );
1431 					if ( !xRow->wasNull() && sValue.equalsIgnoreAsciiCaseAscii( "View" ) )
1432 					{
1433 						bSupportsViews = true;
1434 						break;
1435 					}
1436 				}
1437 		    }
1438 		    catch( const SQLException& )
1439 		    {
1440                 DBG_UNHANDLED_EXCEPTION();
1441 		    }
1442 	    }
1443     }
1444     catch( const Exception& )
1445     {
1446     	DBG_UNHANDLED_EXCEPTION();
1447     }
1448     return bSupportsViews;
1449 }
1450 
1451 // -----------------------------------------------------------------------------
getMaxColumnNameLength() const1452 sal_Int32 OCopyTableWizard::getMaxColumnNameLength() const
1453 {
1454     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::getMaxColumnNameLength" );
1455 	sal_Int32 nLen = 0;
1456 	if ( m_xDestConnection.is() )
1457 	{
1458 		try
1459 		{
1460 			Reference< XDatabaseMetaData > xMetaData( m_xDestConnection->getMetaData(), UNO_SET_THROW );
1461 			nLen = xMetaData->getMaxColumnNameLength();
1462 		}
1463 		catch(const Exception&)
1464 		{
1465             DBG_UNHANDLED_EXCEPTION();
1466 		}
1467 	}
1468 	return nLen;
1469 }
1470 // -----------------------------------------------------------------------------
setOperation(const sal_Int16 _nOperation)1471 void OCopyTableWizard::setOperation( const sal_Int16 _nOperation )
1472 {
1473     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::setOperation" );
1474 	m_nOperation = _nOperation;
1475 }
1476 // -----------------------------------------------------------------------------
getOperation() const1477 sal_Int16 OCopyTableWizard::getOperation() const
1478 {
1479     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::getOperation" );
1480 	return m_nOperation;
1481 }
1482 // -----------------------------------------------------------------------------
convertColumnName(const TColumnFindFunctor & _rCmpFunctor,const::rtl::OUString & _sColumnName,const::rtl::OUString & _sExtraChars,sal_Int32 _nMaxNameLen)1483 ::rtl::OUString OCopyTableWizard::convertColumnName(const TColumnFindFunctor&	_rCmpFunctor,
1484 													const ::rtl::OUString&	_sColumnName,
1485 													const ::rtl::OUString&	_sExtraChars,
1486 													sal_Int32				_nMaxNameLen)
1487 {
1488     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::convertColumnName" );
1489 	::rtl::OUString sAlias = _sColumnName;
1490 	if ( isSQL92CheckEnabled( m_xDestConnection ) )
1491 		sAlias = ::dbtools::convertName2SQLName(_sColumnName,_sExtraChars);
1492 	if((_nMaxNameLen && sAlias.getLength() > _nMaxNameLen) || _rCmpFunctor(sAlias))
1493 	{
1494 		sal_Int32 nDiff = 1;
1495 		do
1496 		{
1497 			++nDiff;
1498 			if(_nMaxNameLen && sAlias.getLength() >= _nMaxNameLen)
1499 				sAlias = sAlias.copy(0,sAlias.getLength() - (sAlias.getLength()-_nMaxNameLen+nDiff));
1500 
1501 			::rtl::OUString sName(sAlias);
1502 			sal_Int32 nPos = 1;
1503 			sName += ::rtl::OUString::valueOf(nPos);
1504 
1505 			while(_rCmpFunctor(sName))
1506 			{
1507 				sName = sAlias;
1508 				sName += ::rtl::OUString::valueOf(++nPos);
1509 			}
1510 			sAlias = sName;
1511 			// we have to check again, it could happen that the name is already to long
1512 		}
1513 		while(_nMaxNameLen && sAlias.getLength() > _nMaxNameLen);
1514 	}
1515 	OSL_ENSURE(m_mNameMapping.find(_sColumnName) == m_mNameMapping.end(),"name doubled!");
1516 	m_mNameMapping[_sColumnName] = sAlias;
1517 	return sAlias;
1518 }
1519 
1520 // -----------------------------------------------------------------------------
removeColumnNameFromNameMap(const::rtl::OUString & _sName)1521 void OCopyTableWizard::removeColumnNameFromNameMap(const ::rtl::OUString& _sName)
1522 {
1523     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::removeColumnNameFromNameMap" );
1524     m_mNameMapping.erase(_sName);
1525 }
1526 
1527 // -----------------------------------------------------------------------------
supportsType(sal_Int32 _nDataType,sal_Int32 & _rNewDataType)1528 sal_Bool OCopyTableWizard::supportsType(sal_Int32 _nDataType,sal_Int32& _rNewDataType)
1529 {
1530     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::supportsType" );
1531 	sal_Bool bRet = m_aDestTypeInfo.find(_nDataType) != m_aDestTypeInfo.end();
1532 	if ( bRet )
1533 		_rNewDataType = _nDataType;
1534 	return bRet;
1535 }
1536 
1537 // -----------------------------------------------------------------------------
convertType(const TOTypeInfoSP & _pType,sal_Bool & _bNotConvert)1538 TOTypeInfoSP OCopyTableWizard::convertType(const TOTypeInfoSP& _pType,sal_Bool& _bNotConvert)
1539 {
1540     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::convertType" );
1541 	if ( !m_bInterConnectionCopy )
1542         // no need to convert if the source and destination connection are the same
1543 		return _pType;
1544 
1545 	sal_Bool bForce;
1546 	TOTypeInfoSP pType = ::dbaui::getTypeInfoFromType(m_aDestTypeInfo,_pType->nType,_pType->aTypeName,_pType->aCreateParams,_pType->nPrecision,_pType->nMaximumScale,_pType->bAutoIncrement,bForce);
1547 	if ( !pType.get() || bForce )
1548 	{ // no type found so we have to find the correct one ourself
1549 		sal_Int32 nDefaultType = DataType::VARCHAR;
1550 		switch(_pType->nType)
1551 		{
1552 			case DataType::TINYINT:
1553 				if(supportsType(DataType::SMALLINT,nDefaultType))
1554 					break;
1555 				// run through
1556 			case DataType::SMALLINT:
1557 				if(supportsType(DataType::INTEGER,nDefaultType))
1558 					break;
1559 				// run through
1560 			case DataType::INTEGER:
1561 				if(supportsType(DataType::FLOAT,nDefaultType))
1562 					break;
1563 				// run through
1564 			case DataType::FLOAT:
1565 				if(supportsType(DataType::REAL,nDefaultType))
1566 					break;
1567 				// run through
1568 			case DataType::DATE:
1569 			case DataType::TIME:
1570 				if( DataType::DATE == _pType->nType || DataType::TIME == _pType->nType )
1571 				{
1572 					if(supportsType(DataType::TIMESTAMP,nDefaultType))
1573 						break;
1574 				}
1575 				// run through
1576 			case DataType::TIMESTAMP:
1577 			case DataType::REAL:
1578 			case DataType::BIGINT:
1579 				if ( supportsType(DataType::DOUBLE,nDefaultType) )
1580 					break;
1581 				// run through
1582 			case DataType::DOUBLE:
1583 				if ( supportsType(DataType::NUMERIC,nDefaultType) )
1584 					break;
1585 				// run through
1586 			case DataType::NUMERIC:
1587 				supportsType(DataType::DECIMAL,nDefaultType);
1588 				break;
1589 			case DataType::DECIMAL:
1590 				if ( supportsType(DataType::NUMERIC,nDefaultType) )
1591 					break;
1592 				if ( supportsType(DataType::DOUBLE,nDefaultType) )
1593 					break;
1594 				break;
1595 			case DataType::VARCHAR:
1596 				if ( supportsType(DataType::LONGVARCHAR,nDefaultType) )
1597 					break;
1598 				break;
1599 			case DataType::LONGVARCHAR:
1600 				if ( supportsType(DataType::CLOB,nDefaultType) )
1601 					break;
1602 				break;
1603             case DataType::BINARY:
1604 				if ( supportsType(DataType::VARBINARY,nDefaultType) )
1605 					break;
1606 				break;
1607             case DataType::VARBINARY:
1608 				if ( supportsType(DataType::LONGVARBINARY,nDefaultType) )
1609 					break;
1610 				break;
1611             case DataType::LONGVARBINARY:
1612 				if ( supportsType(DataType::BLOB,nDefaultType) )
1613 					break;
1614                 if ( supportsType(DataType::LONGVARCHAR,nDefaultType) )
1615 					break;
1616                 if ( supportsType(DataType::CLOB,nDefaultType) )
1617 					break;
1618 				break;
1619 			default:
1620 				nDefaultType = DataType::VARCHAR;
1621 		}
1622 		pType = ::dbaui::getTypeInfoFromType(m_aDestTypeInfo,nDefaultType,_pType->aTypeName,_pType->aCreateParams,_pType->nPrecision,_pType->nMaximumScale,_pType->bAutoIncrement,bForce);
1623 		if ( !pType.get() )
1624 		{
1625 			_bNotConvert = sal_False;
1626 			::rtl::OUString sCreate(RTL_CONSTASCII_USTRINGPARAM("x"));
1627 			pType = ::dbaui::getTypeInfoFromType(m_aDestTypeInfo,DataType::VARCHAR,_pType->aTypeName,sCreate,50,0,sal_False,bForce);
1628 			if ( !pType.get() )
1629 				pType = m_pTypeInfo;
1630 		}
1631 		else if ( bForce )
1632 			_bNotConvert = sal_False;
1633 	}
1634 	return pType;
1635 }
1636 // -----------------------------------------------------------------------------
createUniqueName(const::rtl::OUString & _sName)1637 ::rtl::OUString OCopyTableWizard::createUniqueName(const ::rtl::OUString& _sName)
1638 {
1639     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::createUniqueName" );
1640 	::rtl::OUString sName = _sName;
1641     Sequence< ::rtl::OUString > aColumnNames( m_rSourceObject.getColumnNames() );
1642 	if ( aColumnNames.getLength() )
1643 		sName = ::dbtools::createUniqueName( aColumnNames, sName, sal_False );
1644 	else
1645 	{
1646 		if ( m_vSourceColumns.find(sName) != m_vSourceColumns.end())
1647 		{
1648 			sal_Int32 nPos = 0;
1649 			while(m_vSourceColumns.find(sName) != m_vSourceColumns.end())
1650 			{
1651 				sName = _sName;
1652 				sName += ::rtl::OUString::valueOf(++nPos);
1653 			}
1654 		}
1655 	}
1656 	return sName;
1657 }
1658 // -----------------------------------------------------------------------------
showColumnTypeNotSupported(const::rtl::OUString & _rColumnName)1659 void OCopyTableWizard::showColumnTypeNotSupported(const ::rtl::OUString& _rColumnName)
1660 {
1661     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "misc", "Ocke.Janssen@sun.com", "OCopyTableWizard::showColumnTypeNotSupported" );
1662 	String sMessage( ModuleRes( STR_UNKNOWN_TYPE_FOUND ) );
1663 	sMessage.SearchAndReplaceAscii("#1",_rColumnName);
1664     showError(sMessage);
1665 }
1666 //-------------------------------------------------------------------------------
showError(const::rtl::OUString & _sErrorMesage)1667 void OCopyTableWizard::showError(const ::rtl::OUString& _sErrorMesage)
1668 {
1669     SQLExceptionInfo aInfo(_sErrorMesage);
1670     showError(aInfo.get());
1671 }
1672 //-------------------------------------------------------------------------------
showError(const Any & _aError)1673 void OCopyTableWizard::showError(const Any& _aError)
1674 {
1675     if ( _aError.hasValue() && m_xInteractionHandler.is() )
1676     {
1677         try
1678         {
1679             ::rtl::Reference< ::comphelper::OInteractionRequest > xRequest( new ::comphelper::OInteractionRequest( _aError ) );
1680             m_xInteractionHandler->handle( xRequest.get() );
1681         }
1682         catch( const Exception& )
1683         {
1684         	DBG_UNHANDLED_EXCEPTION();
1685         }
1686     }
1687 }
1688 
1689