xref: /trunk/main/dbaccess/source/ui/tabledesign/TableController.cxx (revision e8df90a080f9dc7518c4b937d7dcd461d7b4d178)
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 // MARKER(update_precomp.py): autogen include statement, do not remove
23 #include "precompiled_dbui.hxx"
24 
25 #include "FieldDescriptions.hxx"
26 #include "TEditControl.hxx"
27 #include "TableController.hxx"
28 #include "TableDesignView.hxx"
29 #include "TableRow.hxx"
30 #include "TypeInfo.hxx"
31 #include "UITools.hxx"
32 #include "browserids.hxx"
33 #include "dbu_reghelper.hxx"
34 #include "dbu_tbl.hrc"
35 #include "dbustrings.hrc"
36 #include "defaultobjectnamecheck.hxx"
37 #include "dlgsave.hxx"
38 #include "dsmeta.hxx"
39 #include "indexdialog.hxx"
40 #include "sqlmessage.hxx"
41 
42 /** === begin UNO includes === **/
43 #include <com/sun/star/container/XChild.hpp>
44 #include <com/sun/star/container/XNameContainer.hpp>
45 #include <com/sun/star/frame/FrameSearchFlag.hpp>
46 #include <com/sun/star/frame/XTitleChangeListener.hpp>
47 #include <com/sun/star/frame/XUntitledNumbers.hpp>
48 #include <com/sun/star/io/XActiveDataSink.hpp>
49 #include <com/sun/star/io/XActiveDataSource.hpp>
50 #include <com/sun/star/sdb/CommandType.hpp>
51 #include <com/sun/star/sdb/SQLContext.hpp>
52 #include <com/sun/star/sdbc/ColumnValue.hpp>
53 #include <com/sun/star/sdbc/SQLWarning.hpp>
54 #include <com/sun/star/sdbc/XRow.hpp>
55 #include <com/sun/star/sdbcx/KeyType.hpp>
56 #include <com/sun/star/sdbcx/XAlterTable.hpp>
57 #include <com/sun/star/sdbcx/XAppend.hpp>
58 #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
59 #include <com/sun/star/sdbcx/XDrop.hpp>
60 #include <com/sun/star/sdbcx/XIndexesSupplier.hpp>
61 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
62 #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
63 /** === end UNO includes === **/
64 
65 #include <comphelper/extract.hxx>
66 #include <comphelper/streamsection.hxx>
67 #include <comphelper/types.hxx>
68 #include <connectivity/dbexception.hxx>
69 #include <connectivity/dbtools.hxx>
70 #include <connectivity/dbmetadata.hxx>
71 #include <cppuhelper/exc_hlp.hxx>
72 #include <sfx2/sfxsids.hrc>
73 #include <tools/diagnose_ex.h>
74 #include <tools/string.hxx>
75 #include <vcl/msgbox.hxx>
76 
77 #include <boost/mem_fn.hpp>
78 #include <boost/bind.hpp>
79 
80 #include <algorithm>
81 #include <functional>
82 
createRegistryInfo_OTableControl()83 extern "C" void SAL_CALL createRegistryInfo_OTableControl()
84 {
85     static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::OTableController > aAutoRegistration;
86 }
87 
88 using namespace ::com::sun::star;
89 using namespace ::com::sun::star::uno;
90 using namespace ::com::sun::star::io;
91 using namespace ::com::sun::star::beans;
92 using namespace ::com::sun::star::frame;
93 using namespace ::com::sun::star::util;
94 using namespace ::com::sun::star::lang;
95 using namespace ::com::sun::star::container;
96 using namespace ::com::sun::star::sdbcx;
97 using namespace ::com::sun::star::sdbc;
98 using namespace ::com::sun::star::sdb;
99 using namespace ::com::sun::star::ui;
100 using namespace ::com::sun::star::util;
101 using namespace ::dbtools;
102 using namespace ::dbaui;
103 using namespace ::comphelper;
104 
105 // Anzahl Spalten beim Neuanlegen
106 #define NEWCOLS        128
107 
108 namespace
109 {
dropTable(const Reference<XNameAccess> & _rxTable,const::rtl::OUString & _sTableName)110     void dropTable(const Reference<XNameAccess>& _rxTable,const ::rtl::OUString& _sTableName)
111     {
112         if ( _rxTable->hasByName(_sTableName) )
113         {
114             Reference<XDrop> xNameCont(_rxTable,UNO_QUERY);
115             OSL_ENSURE(xNameCont.is(),"No drop interface for tables!");
116             if ( xNameCont.is() )
117                 xNameCont->dropByName(_sTableName);
118         }
119     }
120     //------------------------------------------------------------------------------
121     struct OTableRowCompare
122     {
123         typedef ::boost::shared_ptr<OTableRow> first_argument_type;
124         typedef ::rtl::OUString second_argument_type;
125         typedef bool result_type;
operator ()__anon7e30dee80111::OTableRowCompare126         bool operator() (const  ::boost::shared_ptr<OTableRow>  lhs, const ::rtl::OUString& rhs) const
127         {
128             OFieldDescription* pField = lhs->GetActFieldDescr();
129             return pField && pField->GetName() == rhs;
130         }
131     };
132 
133 }
134 
135 //------------------------------------------------------------------------------
getImplementationName()136 ::rtl::OUString SAL_CALL OTableController::getImplementationName()
137 {
138     return getImplementationName_Static();
139 }
140 
141 //------------------------------------------------------------------------------
getImplementationName_Static()142 ::rtl::OUString OTableController::getImplementationName_Static()
143 {
144     return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.OTableDesign");
145 }
146 //------------------------------------------------------------------------------
getSupportedServiceNames_Static(void)147 Sequence< ::rtl::OUString> OTableController::getSupportedServiceNames_Static(void)
148 {
149     Sequence< ::rtl::OUString> aSupported(1);
150     aSupported.getArray()[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdb.TableDesign");
151     return aSupported;
152 }
153 //-------------------------------------------------------------------------
getSupportedServiceNames()154 Sequence< ::rtl::OUString> SAL_CALL OTableController::getSupportedServiceNames()
155 {
156     return getSupportedServiceNames_Static();
157 }
158 // -------------------------------------------------------------------------
Create(const Reference<XMultiServiceFactory> & _rxFactory)159 Reference< XInterface > SAL_CALL OTableController::Create(const Reference<XMultiServiceFactory >& _rxFactory)
160 {
161     return *(new OTableController(_rxFactory));
162 }
163 
DBG_NAME(OTableController)164 DBG_NAME(OTableController)
165 // -----------------------------------------------------------------------------
166 OTableController::OTableController(const Reference< XMultiServiceFactory >& _rM) : OTableController_BASE(_rM)
167     ,m_sTypeNames(ModuleRes(STR_TABLEDESIGN_DBFIELDTYPES))
168     ,m_pTypeInfo()
169     ,m_bAllowAutoIncrementValue(sal_False)
170     ,m_bNew(sal_True)
171 {
172     DBG_CTOR(OTableController,NULL);
173 
174     InvalidateAll();
175     m_pTypeInfo = TOTypeInfoSP(new OTypeInfo());
176     m_pTypeInfo->aUIName = m_sTypeNames.GetToken(TYPE_OTHER);
177 }
178 // -----------------------------------------------------------------------------
~OTableController()179 OTableController::~OTableController()
180 {
181     m_aTypeInfoIndex.clear();
182     m_aTypeInfo.clear();
183 
184     DBG_DTOR(OTableController,NULL);
185 }
186 
187 // -----------------------------------------------------------------------------
startTableListening()188 void OTableController::startTableListening()
189 {
190     Reference< XComponent >  xComponent(m_xTable, UNO_QUERY);
191     if (xComponent.is())
192         xComponent->addEventListener(static_cast<XModifyListener*>(this));
193 }
194 
195 // -----------------------------------------------------------------------------
stopTableListening()196 void OTableController::stopTableListening()
197 {
198     Reference< XComponent >  xComponent(m_xTable, UNO_QUERY);
199     if (xComponent.is())
200         xComponent->removeEventListener(static_cast<XModifyListener*>(this));
201 }
202 
203 // -----------------------------------------------------------------------------
disposing()204 void OTableController::disposing()
205 {
206     OTableController_BASE::disposing();
207     clearView();
208 
209     m_vRowList.clear();
210 }
211 // -----------------------------------------------------------------------------
GetState(sal_uInt16 _nId) const212 FeatureState OTableController::GetState(sal_uInt16 _nId) const
213 {
214     FeatureState aReturn;
215     // (disabled automatically)
216 
217     switch (_nId)
218     {
219         case ID_BROWSER_CLOSE:
220             aReturn.bEnabled = sal_True;
221             break;
222         case ID_BROWSER_EDITDOC:
223             aReturn.bChecked = isEditable();
224             aReturn.bEnabled = m_bNew || isEditable();// the editable flag is set through this one -> || isAddAllowed() || isDropAllowed() || isAlterAllowed();
225             break;
226         case ID_BROWSER_SAVEDOC:
227             aReturn.bEnabled = impl_isModified();
228             if ( aReturn.bEnabled )
229             {
230                 ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter = ::std::find_if(m_vRowList.begin(),m_vRowList.end(),
231                     ::boost::mem_fn(&OTableRow::isValid));
232                 aReturn.bEnabled = aIter != m_vRowList.end();
233             }
234             break;
235         case ID_BROWSER_SAVEASDOC:
236             aReturn.bEnabled = isConnected() && isEditable();
237             if ( aReturn.bEnabled )
238             {
239                 ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter = ::std::find_if(m_vRowList.begin(),m_vRowList.end(),
240                     ::boost::mem_fn(&OTableRow::isValid));
241                 aReturn.bEnabled = aIter != m_vRowList.end();
242             }
243             break;
244 
245         case ID_BROWSER_CUT:
246             aReturn.bEnabled = isEditable() && m_aCurrentFrame.isActive() && getView() && static_cast<OTableDesignView*>(getView())->isCutAllowed();
247             break;
248         case ID_BROWSER_COPY:
249             aReturn.bEnabled = m_aCurrentFrame.isActive() && getView() && static_cast<OTableDesignView*>(getView())->isCopyAllowed();
250             break;
251         case ID_BROWSER_PASTE:
252             aReturn.bEnabled = isEditable() && m_aCurrentFrame.isActive() && getView() && static_cast<OTableDesignView*>(getView())->isPasteAllowed();
253             break;
254         case SID_INDEXDESIGN:
255             aReturn.bEnabled =
256                 (   (   ((!m_bNew && impl_isModified()) || impl_isModified())
257                     ||  Reference< XIndexesSupplier >(m_xTable, UNO_QUERY).is()
258                     )
259                 &&  isConnected()
260                 );
261             if ( aReturn.bEnabled )
262             {
263                 ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter = ::std::find_if(m_vRowList.begin(),m_vRowList.end(),
264                     ::boost::mem_fn(&OTableRow::isValid));
265                 aReturn.bEnabled = aIter != m_vRowList.end();
266             }
267             break;
268         default:
269             aReturn = OTableController_BASE::GetState(_nId);
270     }
271     return aReturn;
272 }
273 // -----------------------------------------------------------------------------
Execute(sal_uInt16 _nId,const Sequence<PropertyValue> & aArgs)274 void OTableController::Execute(sal_uInt16 _nId, const Sequence< PropertyValue >& aArgs)
275 {
276     switch(_nId)
277     {
278         case ID_BROWSER_EDITDOC:
279             setEditable(!isEditable());
280             static_cast<OTableDesignView*>(getView())->setReadOnly(!isEditable());
281             InvalidateFeature(ID_BROWSER_PASTE);
282             InvalidateFeature(SID_BROWSER_CLEAR_QUERY);
283             break;
284         case ID_BROWSER_SAVEASDOC:
285             doSaveDoc(sal_True);
286             break;
287         case ID_BROWSER_SAVEDOC:
288             static_cast<OTableDesignView*>(getView())->GetEditorCtrl()->SaveCurRow();
289             doSaveDoc(sal_False);
290             break;
291         case ID_BROWSER_CUT:
292             static_cast<OTableDesignView*>(getView())->cut();
293             break;
294         case ID_BROWSER_COPY:
295             static_cast<OTableDesignView*>(getView())->copy();
296             break;
297         case ID_BROWSER_PASTE:
298             static_cast<OTableDesignView*>(getView())->paste();
299             break;
300         case SID_INDEXDESIGN:
301             doEditIndexes();
302             break;
303         default:
304             OTableController_BASE::Execute(_nId,aArgs);
305     }
306     InvalidateFeature(_nId);
307 }
308 
309 // -----------------------------------------------------------------------------
doSaveDoc(sal_Bool _bSaveAs)310 sal_Bool OTableController::doSaveDoc(sal_Bool _bSaveAs)
311 {
312     if (!isConnected())
313         reconnect(sal_True); // ask the user for a new connection
314     Reference<XTablesSupplier> xTablesSup(getConnection(),UNO_QUERY);
315 
316     if (!xTablesSup.is())
317     {
318         String aMessage(ModuleRes(STR_TABLEDESIGN_CONNECTION_MISSING));
319         OSQLWarningBox( getView(), aMessage ).Execute();
320         return sal_False;
321     }
322 
323     // check if a column exists
324     // TODO
325 
326     Reference<XNameAccess> xTables;
327     ::rtl::OUString sCatalog, sSchema;
328 
329     sal_Bool bNew = (0 == m_sName.getLength());
330     bNew = bNew || m_bNew || _bSaveAs;
331 
332     try
333     {
334         xTables = xTablesSup->getTables();
335         OSL_ENSURE(xTables.is(),"The tables can't be null!");
336         bNew = bNew || (xTables.is() && !xTables->hasByName(m_sName));
337 
338         // first we need a name for our query so ask the user
339         if(bNew)
340         {
341             String aDefaultName;
342             if (_bSaveAs && !bNew)
343                  aDefaultName = String(m_sName);
344             else
345             {
346                 String aName = String(ModuleRes(STR_TBL_TITLE));
347                 aDefaultName = aName.GetToken(0,' ');
348                 //aDefaultName = getPrivateTitle();
349                 aDefaultName = ::dbtools::createUniqueName(xTables,aDefaultName);
350             }
351 
352             DynamicTableOrQueryNameCheck aNameChecker( getConnection(), CommandType::TABLE );
353             OSaveAsDlg aDlg( getView(), CommandType::TABLE, getORB(), getConnection(), aDefaultName, aNameChecker );
354             if ( aDlg.Execute() != RET_OK )
355                 return sal_False;
356 
357             m_sName = aDlg.getName();
358             sCatalog = aDlg.getCatalog();
359             sSchema  = aDlg.getSchema();
360         }
361 
362         // did we get a name
363         if(!m_sName.getLength())
364             return sal_False;
365     }
366     catch(Exception&)
367     {
368         OSL_ENSURE(sal_False, "OTableController::doSaveDoc: nothing is expected to happen here!");
369     }
370 
371     sal_Bool bAlter = sal_False;
372     sal_Bool bError = sal_False;
373     SQLExceptionInfo aInfo;
374     try
375     {
376         // check the columns for double names
377         if(!checkColumns(bNew || !xTables->hasByName(m_sName)))
378         {
379             // #105323# OJ
380             return sal_False;
381         }
382 
383         Reference<XPropertySet> xTable;
384         if(bNew || !xTables->hasByName(m_sName)) // just to make sure the table already exists
385         {
386             dropTable(xTables,m_sName);
387 
388             Reference<XDataDescriptorFactory> xFact(xTables,UNO_QUERY);
389             OSL_ENSURE(xFact.is(),"OTableController::doSaveDoc: No XDataDescriptorFactory available!");
390             xTable = xFact->createDataDescriptor();
391             OSL_ENSURE(xTable.is(),"OTableController::doSaveDoc: Create query failed!");
392             // to set the name is only allowed when the query is new
393             xTable->setPropertyValue(PROPERTY_CATALOGNAME,makeAny(sCatalog));
394             xTable->setPropertyValue(PROPERTY_SCHEMANAME,makeAny(sSchema));
395             xTable->setPropertyValue(PROPERTY_NAME,makeAny(m_sName));
396 
397             // now append the columns
398             Reference<XColumnsSupplier> xColSup(xTable,UNO_QUERY);
399             appendColumns(xColSup,bNew);
400             // now append the primary key
401             Reference<XKeysSupplier> xKeySup(xTable,UNO_QUERY);
402             appendPrimaryKey(xKeySup,bNew);
403         }
404         // now set the properties
405         if(bNew)
406         {
407             Reference<XAppend> xAppend(xTables,UNO_QUERY);
408             OSL_ENSURE(xAppend.is(),"OTableController::doSaveDoc: No XAppend Interface!");
409             xAppend->appendByDescriptor(xTable);
410 
411             assignTable();
412             if(!m_xTable.is()) // correct name and try again
413             {
414                 // it can be that someone inserted new data for us
415                 m_sName = ::dbtools::composeTableName( getConnection()->getMetaData(), xTable, ::dbtools::eInDataManipulation, false, false, false );
416                 assignTable();
417             }
418             // now check if our datasource has set a tablefilter and if append the new table name to it
419             ::dbaui::appendToFilter(getConnection(),m_sName,getORB(),getView()); // we are not interested in the return value
420             Reference< frame::XTitleChangeListener> xEventListener(impl_getTitleHelper_throw(),UNO_QUERY);
421             if ( xEventListener.is() )
422             {
423                 frame::TitleChangedEvent aEvent;
424                 xEventListener->titleChanged(aEvent);
425             }
426             releaseNumberForComponent();
427         }
428         else if(m_xTable.is())
429         {
430             bAlter = sal_True;
431             alterColumns();
432         }
433         reSyncRows();
434     }
435     catch(const SQLContext& e)
436     {
437         aInfo = SQLExceptionInfo(e);
438     }
439     catch(const SQLWarning& e)
440     {
441         aInfo = SQLExceptionInfo(e);
442     }
443     catch(const SQLException& e)
444     {
445         aInfo = SQLExceptionInfo(e);
446     }
447     catch(const ElementExistException& )
448     {
449         String sText( ModuleRes( STR_NAME_ALREADY_EXISTS ) );
450         sText.SearchAndReplaceAscii( "#" , m_sName);
451         OSQLMessageBox aDlg( getView(), String( ModuleRes( STR_ERROR_DURING_CREATION ) ), sText, WB_OK, OSQLMessageBox::Error );
452 
453         aDlg.Execute();
454         bError = sal_True;
455     }
456     catch( const Exception& )
457     {
458         bError = sal_True;
459         DBG_UNHANDLED_EXCEPTION();
460     }
461 
462     if ( aInfo.isValid() )
463         aInfo.prepend( String( ModuleRes( STR_TABLEDESIGN_SAVE_ERROR ) ) );
464     showError(aInfo);
465 
466     if (aInfo.isValid() || bError)
467     {
468         if(!bAlter || bNew)
469         {
470             m_sName = ::rtl::OUString();
471             stopTableListening();
472             m_xTable = NULL;
473         }
474         //  reload(); // a error occurred so we have to reload
475     }
476     return ! (aInfo.isValid() || bError);
477 }
478 
479 // -----------------------------------------------------------------------------
doEditIndexes()480 void OTableController::doEditIndexes()
481 {
482     // table needs to be saved before editing indexes
483     if (m_bNew || isModified())
484     {
485         QueryBox aAsk(getView(), ModuleRes(QUERY_SAVE_TABLE_EDIT_INDEXES));
486         if (RET_YES != aAsk.Execute())
487             return;
488 
489         if (!doSaveDoc(sal_False))
490             return;
491 
492         OSL_ENSURE(!m_bNew && !isModified(), "OTableController::doEditIndexes: what the hell did doSaveDoc do?");
493     }
494 
495     Reference< XNameAccess > xIndexes;          // will be the keys of the table
496     Sequence< ::rtl::OUString > aFieldNames;    // will be the column names of the table
497     try
498     {
499         // get the keys
500         Reference< XIndexesSupplier > xIndexesSupp(m_xTable, UNO_QUERY);
501         if (xIndexesSupp.is())
502         {
503             xIndexes = xIndexesSupp->getIndexes();
504             OSL_ENSURE(xIndexes.is(), "OTableController::doEditIndexes: no keys got from the indexes supplier!");
505         }
506         else
507             OSL_ENSURE(sal_False, "OTableController::doEditIndexes: should never have reached this (no indexes supplier)!");
508 
509         // get the field names
510         Reference< XColumnsSupplier > xColSupp(m_xTable, UNO_QUERY);
511         OSL_ENSURE(xColSupp.is(), "OTableController::doEditIndexes: no columns supplier!");
512         if (xColSupp.is())
513         {
514             Reference< XNameAccess > xCols = xColSupp->getColumns();
515             OSL_ENSURE(xCols.is(), "OTableController::doEditIndexes: no columns!");
516             if (xCols.is())
517                 aFieldNames = xCols->getElementNames();
518         }
519     }
520     catch( const Exception& )
521     {
522         DBG_UNHANDLED_EXCEPTION();
523     }
524 
525     if (!xIndexes.is())
526         return;
527 
528     DbaIndexDialog aDialog(getView(), aFieldNames, xIndexes, getConnection(),getORB(),isConnected() ? getConnection()->getMetaData().is() && getConnection()->getMetaData()->getMaxColumnsInIndex() : sal_Int32(0));
529     if (RET_OK != aDialog.Execute())
530         return;
531 
532 }
533 
534 // -----------------------------------------------------------------------------
impl_initialize()535 void OTableController::impl_initialize()
536 {
537     try
538     {
539         OTableController_BASE::impl_initialize();
540 
541         const NamedValueCollection& rArguments( getInitParams() );
542 
543         rArguments.get_ensureType( (::rtl::OUString)PROPERTY_CURRENTTABLE, m_sName );
544 
545         // read autoincrement value set in the datasource
546         ::dbaui::fillAutoIncrementValue(getDataSource(),m_bAllowAutoIncrementValue,m_sAutoIncrementValue);
547 
548         assignTable();
549     }
550     catch( const Exception& )
551     {
552         DBG_UNHANDLED_EXCEPTION();
553     }
554 
555     try
556     {
557         ::dbaui::fillTypeInfo(getConnection(),m_sTypeNames,m_aTypeInfo,m_aTypeInfoIndex);               // fill the needed type information
558     }
559     catch(const SQLException&)
560     {
561         OSQLWarningBox( getView(), ModuleRes( STR_NO_TYPE_INFO_AVAILABLE ) ).Execute();
562         throw;
563     }
564     try
565     {
566         loadData();                 // fill the column information form the table
567         getView()->initialize();    // show the windows and fill with our information
568         ClearUndoManager();
569         setModified(sal_False);     // and we are not modified yet
570     }
571     catch( const Exception& )
572     {
573         DBG_UNHANDLED_EXCEPTION();
574     }
575 }
576 // -----------------------------------------------------------------------------
Construct(Window * pParent)577 sal_Bool OTableController::Construct(Window* pParent)
578 {
579     setView( * new OTableDesignView( pParent, getORB(), *this ) );
580     OTableController_BASE::Construct(pParent);
581 //  m_pView->Construct();
582 //  m_pView->Show();
583     return sal_True;
584 }
585 // -----------------------------------------------------------------------------
suspend(sal_Bool)586 sal_Bool SAL_CALL OTableController::suspend(sal_Bool /*_bSuspend*/)
587 {
588     if ( getBroadcastHelper().bInDispose || getBroadcastHelper().bDisposed )
589         return sal_True;
590 
591     vos::OGuard aSolarGuard( Application::GetSolarMutex() );
592     ::osl::MutexGuard aGuard( getMutex() );
593     if ( getView() && getView()->IsInModalMode() )
594         return sal_False;
595     if ( getView() )
596         static_cast<OTableDesignView*>(getView())->GrabFocus();
597     sal_Bool bCheck = sal_True;
598     if ( isModified() )
599     {
600         ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aIter = ::std::find_if(m_vRowList.begin(),m_vRowList.end(),
601             ::boost::mem_fn(&OTableRow::isValid));
602         if ( aIter != m_vRowList.end() )
603         {
604             QueryBox aQry(getView(), ModuleRes(TABLE_DESIGN_SAVEMODIFIED));
605             switch (aQry.Execute())
606             {
607                 case RET_YES:
608                     Execute(ID_BROWSER_SAVEDOC,Sequence<PropertyValue>());
609                     if ( isModified() )
610                         bCheck = sal_False; // when we save the table this must be false else some press cancel
611                     break;
612                 case RET_CANCEL:
613                     bCheck = sal_False;
614                 default:
615                     break;
616             }
617         }
618         else if ( !m_bNew )
619         {
620             QueryBox aQry(getView(), ModuleRes(TABLE_DESIGN_ALL_ROWS_DELETED));
621             switch (aQry.Execute())
622             {
623                 case RET_YES:
624                     {
625                         try
626                         {
627                             Reference<XTablesSupplier> xTablesSup(getConnection(),UNO_QUERY);
628                             Reference<XNameAccess> xTables = xTablesSup->getTables();
629                             dropTable(xTables,m_sName);
630                         }
631                         catch(const Exception&)
632                         {
633                             OSL_ENSURE(sal_False, "OTableController::suspend: nothing is expected to happen here!");
634                         }
635 
636                     }
637                     break;
638                 case RET_CANCEL:
639                     bCheck = sal_False;
640                 default:
641                     break;
642             }
643         }
644     }
645 /*
646     if ( bCheck )
647         OSingleDocumentController::suspend(_bSuspend);
648 */
649     return bCheck;
650 }
651 // -----------------------------------------------------------------------------
describeSupportedFeatures()652 void OTableController::describeSupportedFeatures()
653 {
654     OSingleDocumentController::describeSupportedFeatures();
655 
656     implDescribeSupportedFeature( ".uno:Redo",          ID_BROWSER_REDO,        CommandGroup::EDIT );
657     implDescribeSupportedFeature( ".uno:Save",          ID_BROWSER_SAVEDOC,     CommandGroup::EDIT );
658     implDescribeSupportedFeature( ".uno:Undo",          ID_BROWSER_UNDO,        CommandGroup::EDIT );
659     implDescribeSupportedFeature( ".uno:HelpMenu",      SID_HELPMENU,           CommandGroup::APPLICATION );
660     implDescribeSupportedFeature( ".uno:NewDoc",        SID_NEWDOC,             CommandGroup::DOCUMENT );
661     implDescribeSupportedFeature( ".uno:SaveAs",        ID_BROWSER_SAVEASDOC,   CommandGroup::DOCUMENT );
662     implDescribeSupportedFeature( ".uno:DBIndexDesign", SID_INDEXDESIGN,        CommandGroup::APPLICATION );
663     implDescribeSupportedFeature( ".uno:EditDoc",       ID_BROWSER_EDITDOC,     CommandGroup::EDIT );
664 }
665 // -----------------------------------------------------------------------------
impl_onModifyChanged()666 void OTableController::impl_onModifyChanged()
667 {
668     OSingleDocumentController::impl_onModifyChanged();
669     InvalidateFeature( SID_INDEXDESIGN );
670 }
671 // -----------------------------------------------------------------------------
disposing(const EventObject & _rSource)672 void SAL_CALL OTableController::disposing( const EventObject& _rSource )
673 {
674     if ( _rSource.Source == m_xTable )
675     {   // some deleted our table so we have a new one
676         stopTableListening();
677         m_xTable    = NULL;
678         m_bNew      = sal_True;
679         setModified(sal_True);
680     }
681     else
682         OTableController_BASE::disposing( _rSource );
683 }
684 // -----------------------------------------------------------------------------
Save(const Reference<XObjectOutputStream> & _rxOut)685 void OTableController::Save(const Reference< XObjectOutputStream>& _rxOut)
686 {
687     OStreamSection aSection(_rxOut.get());
688 
689 }
690 // -----------------------------------------------------------------------------
Load(const Reference<XObjectInputStream> & _rxIn)691 void OTableController::Load(const Reference< XObjectInputStream>& _rxIn)
692 {
693     OStreamSection aSection(_rxIn.get());
694 }
695 
696 // -----------------------------------------------------------------------------
losingConnection()697 void OTableController::losingConnection( )
698 {
699     // let the base class do its reconnect
700     OTableController_BASE::losingConnection( );
701 
702     // remove from the table
703     Reference< XComponent >  xComponent(m_xTable, UNO_QUERY);
704     if (xComponent.is())
705     {
706         Reference<XEventListener> xEvtL( static_cast< ::cppu::OWeakObject*>(this), UNO_QUERY);
707         xComponent->removeEventListener(xEvtL);
708     }
709     stopTableListening();
710     m_xTable    = NULL;
711     assignTable();
712     if(!m_xTable.is())
713     {
714         m_bNew      = sal_True;
715         setModified(sal_True);
716     }
717     InvalidateAll();
718 }
719 // -----------------------------------------------------------------------------
getTypeInfoByType(sal_Int32 _nDataType) const720 TOTypeInfoSP OTableController::getTypeInfoByType(sal_Int32 _nDataType) const
721 {
722     return queryTypeInfoByType(_nDataType,m_aTypeInfo);
723 }
724 // -----------------------------------------------------------------------------
appendColumns(Reference<XColumnsSupplier> & _rxColSup,sal_Bool _bNew,sal_Bool _bKeyColumns)725 void OTableController::appendColumns(Reference<XColumnsSupplier>& _rxColSup,sal_Bool _bNew,sal_Bool _bKeyColumns)
726 {
727     try
728     {
729         // now append the columns
730         OSL_ENSURE(_rxColSup.is(),"No columns supplier");
731         if(!_rxColSup.is())
732             return;
733         Reference<XNameAccess> xColumns = _rxColSup->getColumns();
734         OSL_ENSURE(xColumns.is(),"No columns");
735         Reference<XDataDescriptorFactory> xColumnFactory(xColumns,UNO_QUERY);
736 
737         Reference<XAppend> xAppend(xColumns,UNO_QUERY);
738         OSL_ENSURE(xAppend.is(),"No XAppend Interface!");
739 
740         ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aIter = m_vRowList.begin();
741         ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aEnd = m_vRowList.end();
742         for(;aIter != aEnd;++aIter)
743         {
744             OSL_ENSURE(*aIter,"OTableRow is null!");
745             OFieldDescription* pField = (*aIter)->GetActFieldDescr();
746             if ( !pField || (!_bNew && (*aIter)->IsReadOnly() && !_bKeyColumns) )
747                 continue;
748 
749             Reference<XPropertySet> xColumn;
750             if(pField->IsPrimaryKey() || !_bKeyColumns)
751                 xColumn = xColumnFactory->createDataDescriptor();
752             if(xColumn.is())
753             {
754                 if(!_bKeyColumns)
755                     ::dbaui::setColumnProperties(xColumn,pField);
756                 else
757                     xColumn->setPropertyValue(PROPERTY_NAME,makeAny(pField->GetName()));
758 
759                 xAppend->appendByDescriptor(xColumn);
760                 xColumn = NULL;
761                 // now only the settings are missing
762                 if(xColumns->hasByName(pField->GetName()))
763                 {
764                     xColumns->getByName(pField->GetName()) >>= xColumn;
765                     if(xColumn.is())
766                         pField->copyColumnSettingsTo(xColumn);
767                 }
768                 else
769                 {
770                     OSL_ENSURE(sal_False, "OTableController::appendColumns: invalid field name!");
771                 }
772 
773             }
774         }
775     }
776     catch(const SQLException& )
777     {
778         showError( SQLExceptionInfo( ::cppu::getCaughtException() ) );
779     }
780     catch( const Exception& )
781     {
782         DBG_UNHANDLED_EXCEPTION();
783     }
784 }
785 // -----------------------------------------------------------------------------
appendPrimaryKey(Reference<XKeysSupplier> & _rxSup,sal_Bool _bNew)786 void OTableController::appendPrimaryKey(Reference<XKeysSupplier>& _rxSup,sal_Bool _bNew)
787 {
788     if(!_rxSup.is())
789         return; // the database doesn't support keys
790 
791     OSL_ENSURE(_rxSup.is(),"No XKeysSupplier!");
792     Reference<XIndexAccess> xKeys(_rxSup->getKeys(),UNO_QUERY);
793     Reference<XPropertySet> xProp;
794     const sal_Int32 nCount = xKeys->getCount();
795     for(sal_Int32 i=0;i< nCount ;++i)
796     {
797         xKeys->getByIndex(i) >>= xProp;
798         sal_Int32 nKeyType = 0;
799         xProp->getPropertyValue(PROPERTY_TYPE) >>= nKeyType;
800         if(KeyType::PRIMARY == nKeyType)
801         {
802             return; // primary key already exists after appending a column
803         }
804     }
805     Reference<XDataDescriptorFactory> xKeyFactory(xKeys,UNO_QUERY);
806     OSL_ENSURE(xKeyFactory.is(),"No XDataDescriptorFactory Interface!");
807     if ( !xKeyFactory.is() )
808         return;
809     Reference<XAppend> xAppend(xKeyFactory,UNO_QUERY);
810     OSL_ENSURE(xAppend.is(),"No XAppend Interface!");
811 
812     Reference<XPropertySet> xKey = xKeyFactory->createDataDescriptor();
813     OSL_ENSURE(xKey.is(),"Key is null!");
814     xKey->setPropertyValue(PROPERTY_TYPE,makeAny(KeyType::PRIMARY));
815 
816     Reference<XColumnsSupplier> xColSup(xKey,UNO_QUERY);
817     if(xColSup.is())
818     {
819         appendColumns(xColSup,_bNew,sal_True);
820         Reference<XNameAccess> xColumns = xColSup->getColumns();
821         if(xColumns->hasElements())
822             xAppend->appendByDescriptor(xKey);
823     }
824 }
825 // -----------------------------------------------------------------------------
loadData()826 void OTableController::loadData()
827 {
828     //////////////////////////////////////////////////////////////////////
829     // Wenn Datenstruktur bereits vorhanden, Struktur leeren
830     m_vRowList.clear();
831 
832     ::boost::shared_ptr<OTableRow>  pTabEdRow;
833     Reference< XDatabaseMetaData> xMetaData = getMetaData( );
834     //////////////////////////////////////////////////////////////////////
835     // Datenstruktur mit Daten aus DatenDefinitionsObjekt füllen
836     if(m_xTable.is() && xMetaData.is())
837     {
838         Reference<XColumnsSupplier> xColSup(m_xTable,UNO_QUERY);
839         OSL_ENSURE(xColSup.is(),"No XColumnsSupplier!");
840         Reference<XNameAccess> xColumns = xColSup->getColumns();
841         OFieldDescription* pActFieldDescr = NULL;
842         String aType;
843         //////////////////////////////////////////////////////////////////////
844         // ReadOnly-Flag
845         // Bei Drop darf keine Zeile editierbar sein.
846         // Bei Add dürfen nur die leeren Zeilen editierbar sein.
847         // Bei Add und Drop können alle Zeilen editiert werden.
848         //  sal_Bool bReadOldRow = xMetaData->supportsAlterTableWithAddColumn() && xMetaData->supportsAlterTableWithDropColumn();
849         sal_Bool bIsAlterAllowed = isAlterAllowed();
850         Sequence< ::rtl::OUString> aColumns = xColumns->getElementNames();
851         const ::rtl::OUString* pIter    = aColumns.getConstArray();
852         const ::rtl::OUString* pEnd     = pIter + aColumns.getLength();
853 
854         for(;pIter != pEnd;++pIter)
855         {
856             Reference<XPropertySet> xColumn;
857             xColumns->getByName(*pIter) >>= xColumn;
858             sal_Int32 nType         = 0;
859             sal_Int32 nScale        = 0;
860             sal_Int32 nPrecision    = 0;
861             sal_Int32 nNullable     = 0;
862             sal_Int32 nFormatKey    = 0;
863             sal_Int32 nAlign        = 0;
864 
865             sal_Bool bIsAutoIncrement = false, bIsCurrency = false;
866             ::rtl::OUString sName,sDescription,sTypeName,sHelpText;
867             Any aControlDefault;
868 
869             // get the properties from the column
870             xColumn->getPropertyValue(PROPERTY_NAME)            >>= sName;
871             xColumn->getPropertyValue(PROPERTY_TYPENAME)        >>= sTypeName;
872             xColumn->getPropertyValue(PROPERTY_ISNULLABLE)      >>= nNullable;
873             xColumn->getPropertyValue(PROPERTY_ISAUTOINCREMENT) >>= bIsAutoIncrement;
874             xColumn->getPropertyValue(PROPERTY_ISCURRENCY)      >>= bIsCurrency;
875             xColumn->getPropertyValue(PROPERTY_TYPE)            >>= nType;
876             xColumn->getPropertyValue(PROPERTY_SCALE)           >>= nScale;
877             xColumn->getPropertyValue(PROPERTY_PRECISION)       >>= nPrecision;
878             xColumn->getPropertyValue(PROPERTY_DESCRIPTION)     >>= sDescription;
879 
880             if(xColumn->getPropertySetInfo()->hasPropertyByName(PROPERTY_HELPTEXT))
881                 xColumn->getPropertyValue(PROPERTY_HELPTEXT)    >>= sHelpText;
882 
883             if(xColumn->getPropertySetInfo()->hasPropertyByName(PROPERTY_CONTROLDEFAULT))
884                 aControlDefault = xColumn->getPropertyValue(PROPERTY_CONTROLDEFAULT);
885             if(xColumn->getPropertySetInfo()->hasPropertyByName(PROPERTY_FORMATKEY))
886                 xColumn->getPropertyValue(PROPERTY_FORMATKEY)   >>= nFormatKey;
887             if(xColumn->getPropertySetInfo()->hasPropertyByName(PROPERTY_ALIGN))
888                 xColumn->getPropertyValue(PROPERTY_ALIGN)       >>= nAlign;
889 
890             pTabEdRow.reset(new OTableRow());
891             pTabEdRow->SetReadOnly(!bIsAlterAllowed);
892             // search for type
893             sal_Bool bForce;
894             ::rtl::OUString sCreate(RTL_CONSTASCII_USTRINGPARAM("x"));
895             TOTypeInfoSP pTypeInfo = ::dbaui::getTypeInfoFromType(m_aTypeInfo,nType,sTypeName,sCreate,nPrecision,nScale,bIsAutoIncrement,bForce);
896             if ( !pTypeInfo.get() )
897                 pTypeInfo = m_pTypeInfo;
898             pTabEdRow->SetFieldType( pTypeInfo, bForce );
899 
900             pActFieldDescr = pTabEdRow->GetActFieldDescr();
901             OSL_ENSURE(pActFieldDescr, "OTableController::loadData: invalid field description generated by the table row!");
902             if ( pActFieldDescr )
903             {
904                 pActFieldDescr->SetName(sName);
905                 pActFieldDescr->SetFormatKey(nFormatKey);
906                 //  pActFieldDescr->SetPrimaryKey(pPrimary->GetValue());
907                 pActFieldDescr->SetDescription(sDescription);
908                 pActFieldDescr->SetHelpText(sHelpText);
909                 pActFieldDescr->SetAutoIncrement(bIsAutoIncrement);
910                 pActFieldDescr->SetHorJustify(dbaui::mapTextJustify(nAlign));
911                 pActFieldDescr->SetCurrency(bIsCurrency);
912 
913                 //////////////////////////////////////////////////////////////////////
914                 // Spezielle Daten
915                 pActFieldDescr->SetIsNullable(nNullable);
916                 pActFieldDescr->SetControlDefault(aControlDefault);
917                 pActFieldDescr->SetPrecision(nPrecision);
918                 pActFieldDescr->SetScale(nScale);
919             }
920             m_vRowList.push_back( pTabEdRow);
921         }
922         // fill the primary  key information
923         Reference<XNameAccess> xKeyColumns  = getKeyColumns();
924         if(xKeyColumns.is())
925         {
926             Sequence< ::rtl::OUString> aKeyColumns = xKeyColumns->getElementNames();
927             const ::rtl::OUString* pKeyBegin    = aKeyColumns.getConstArray();
928             const ::rtl::OUString* pKeyEnd      = pKeyBegin + aKeyColumns.getLength();
929 
930             for(;pKeyBegin != pKeyEnd;++pKeyBegin)
931             {
932                 ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator rowIter = m_vRowList.begin();
933                 ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator rowEnd = m_vRowList.end();
934                 for(;rowIter != rowEnd;++rowIter)
935                 {
936                     if((*rowIter)->GetActFieldDescr()->GetName() == *pKeyBegin)
937                     {
938                         (*rowIter)->SetPrimaryKey(sal_True);
939                         break;
940                     }
941                 }
942             }
943         }
944     }
945 
946     //////////////////////////////////////////////////////////////////////
947     // Leere Zeilen füllen
948 
949     OTypeInfoMap::iterator aTypeIter = m_aTypeInfo.find(DataType::VARCHAR);
950     if(aTypeIter == m_aTypeInfo.end())
951         aTypeIter = m_aTypeInfo.begin();
952 
953     OSL_ENSURE(aTypeIter != m_aTypeInfo.end(),"We have no type information!");
954 
955     bool bReadRow = !isAddAllowed();
956     for(sal_Int32 i=m_vRowList.size(); i < NEWCOLS; i++ )
957     {
958         pTabEdRow.reset(new OTableRow());
959         pTabEdRow->SetReadOnly(bReadRow);
960         m_vRowList.push_back( pTabEdRow);
961     }
962 }
963 // -----------------------------------------------------------------------------
getKeyColumns() const964 Reference<XNameAccess> OTableController::getKeyColumns() const
965 {
966     return getPrimaryKeyColumns_throw(m_xTable);
967 }
968 // -----------------------------------------------------------------------------
checkColumns(sal_Bool _bNew)969 sal_Bool OTableController::checkColumns(sal_Bool _bNew)
970 {
971     sal_Bool bOk = sal_True;
972     sal_Bool bFoundPKey = sal_False;
973     Reference< XDatabaseMetaData > xMetaData = getMetaData( );
974     DatabaseMetaData aMetaData( getConnection() );
975 
976     ::comphelper::UStringMixEqual bCase(xMetaData.is() ? xMetaData->supportsMixedCaseQuotedIdentifiers() : sal_True);
977     ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter = m_vRowList.begin();
978     ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aEnd = m_vRowList.end();
979     for(;aIter != aEnd;++aIter)
980     {
981         OFieldDescription* pFieldDesc = (*aIter)->GetActFieldDescr();
982         if (pFieldDesc && pFieldDesc->GetName().getLength())
983         {
984             bFoundPKey |=  (*aIter)->IsPrimaryKey();
985             // first check for duplicate names
986             ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter2 = aIter+1;
987             for(;aIter2 != aEnd;++aIter2)
988             {
989                 OFieldDescription* pCompareDesc = (*aIter2)->GetActFieldDescr();
990                 if (pCompareDesc && bCase(pCompareDesc->GetName(),pFieldDesc->GetName()))
991                 {
992                     String strMessage = String(ModuleRes(STR_TABLEDESIGN_DUPLICATE_NAME));
993                     strMessage.SearchAndReplaceAscii("$column$", pFieldDesc->GetName());
994                     OSQLWarningBox( getView(), strMessage ).Execute();
995                     return sal_False;
996                 }
997             }
998         }
999     }
1000     if ( _bNew && !bFoundPKey && aMetaData.supportsPrimaryKeys() )
1001     {
1002         String sTitle(ModuleRes(STR_TABLEDESIGN_NO_PRIM_KEY_HEAD));
1003         String sMsg(ModuleRes(STR_TABLEDESIGN_NO_PRIM_KEY));
1004         OSQLMessageBox aBox(getView(), sTitle,sMsg, WB_YES_NO_CANCEL | WB_DEF_YES);
1005 
1006         switch ( aBox.Execute() )
1007         {
1008         case RET_YES:
1009         {
1010             ::boost::shared_ptr<OTableRow>  pNewRow(new OTableRow());
1011             TOTypeInfoSP pTypeInfo = ::dbaui::queryPrimaryKeyType(m_aTypeInfo);
1012             if ( !pTypeInfo.get() )
1013                 break;
1014 
1015             pNewRow->SetFieldType( pTypeInfo );
1016             OFieldDescription* pActFieldDescr = pNewRow->GetActFieldDescr();
1017 
1018             pActFieldDescr->SetAutoIncrement(sal_False); // #95927# pTypeInfo->bAutoIncrement
1019             pActFieldDescr->SetIsNullable(ColumnValue::NO_NULLS);
1020 
1021             pActFieldDescr->SetName( createUniqueName(::rtl::OUString::createFromAscii("ID") ));
1022             pActFieldDescr->SetPrimaryKey( sal_True );
1023             m_vRowList.insert(m_vRowList.begin(),pNewRow);
1024 
1025             static_cast<OTableDesignView*>(getView())->GetEditorCtrl()->Invalidate();
1026             static_cast<OTableDesignView*>(getView())->GetEditorCtrl()->RowInserted(0);
1027         }
1028         break;
1029         case RET_CANCEL:
1030             bOk = sal_False;
1031             break;
1032         }
1033     }
1034     return bOk;
1035 }
1036 // -----------------------------------------------------------------------------
alterColumns()1037 void OTableController::alterColumns()
1038 {
1039     Reference<XColumnsSupplier> xColSup(m_xTable,UNO_QUERY_THROW);
1040     OSL_ENSURE(xColSup.is(),"What happen here?!");
1041 
1042     Reference<XNameAccess> xColumns = xColSup->getColumns();
1043     Reference<XIndexAccess> xIdxColumns(xColumns,UNO_QUERY_THROW);
1044     OSL_ENSURE(xColumns.is(),"No columns");
1045     if ( !xColumns.is() )
1046         return;
1047     Reference<XAlterTable> xAlter(m_xTable,UNO_QUERY);  // can be null
1048 
1049     sal_Int32 nColumnCount = xIdxColumns->getCount();
1050     Reference<XDrop> xDrop(xColumns,UNO_QUERY);         // can be null
1051     Reference<XAppend> xAppend(xColumns,UNO_QUERY);     // can be null
1052     Reference<XDataDescriptorFactory> xColumnFactory(xColumns,UNO_QUERY); // can be null
1053 
1054     sal_Bool bReload = sal_False; // refresh the data
1055 
1056     // contains all columns names which are already handled those which are not in the list will be deleted
1057     Reference< XDatabaseMetaData> xMetaData = getMetaData( );
1058 
1059     ::std::map< ::rtl::OUString,sal_Bool,::comphelper::UStringMixLess> aColumns(xMetaData.is() ? (xMetaData->supportsMixedCaseQuotedIdentifiers() ? true : false): sal_True);
1060     ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aIter = m_vRowList.begin();
1061     ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aEnd = m_vRowList.end();
1062     // first look for columns where something other than the name changed
1063     sal_Int32 nPos = 0;
1064     for(;aIter != aEnd;++aIter,++nPos)
1065     {
1066         OSL_ENSURE(*aIter,"OTableRow is null!");
1067         OFieldDescription* pField = (*aIter)->GetActFieldDescr();
1068         if ( !pField )
1069             continue;
1070         if ( (*aIter)->IsReadOnly() )
1071         {
1072             aColumns[pField->GetName()] = sal_True;
1073             continue;
1074         }
1075 
1076         Reference<XPropertySet> xColumn;
1077         if ( xColumns->hasByName(pField->GetName()) )
1078         {
1079             aColumns[pField->GetName()] = sal_True;
1080             xColumns->getByName(pField->GetName()) >>= xColumn;
1081             OSL_ENSURE(xColumn.is(),"Column is null!");
1082 
1083             sal_Int32 nType=0,nPrecision=0,nScale=0,nNullable=0;
1084             sal_Bool bAutoIncrement = false;
1085             ::rtl::OUString sTypeName,sDescription;
1086 
1087             xColumn->getPropertyValue(PROPERTY_TYPE)            >>= nType;
1088             xColumn->getPropertyValue(PROPERTY_PRECISION)       >>= nPrecision;
1089             xColumn->getPropertyValue(PROPERTY_SCALE)           >>= nScale;
1090             xColumn->getPropertyValue(PROPERTY_ISNULLABLE)      >>= nNullable;
1091             xColumn->getPropertyValue(PROPERTY_ISAUTOINCREMENT) >>= bAutoIncrement;
1092             xColumn->getPropertyValue(PROPERTY_DESCRIPTION)     >>= sDescription;
1093 
1094             try { xColumn->getPropertyValue(PROPERTY_TYPENAME) >>= sTypeName; }
1095             catch( const Exception& )
1096             {
1097                 OSL_ENSURE( sal_False, "no TypeName property?!" );
1098                 // since this is a last minute fix for #i41785#, I want to be on the safe side,
1099                 // and catch errors here as early as possible (instead of the whole process of altering
1100                 // the columns failing)
1101                 // Normally, sdbcx::Column objects are expected to have a TypeName property
1102             }
1103 
1104             //  xColumn->getPropertyValue(PROPERTY_ISCURRENCY,::cppu::bool2any(pField->IsCurrency()));
1105             // check if something changed
1106             if((nType != pField->GetType()                  ||
1107                 sTypeName != pField->GetTypeName()         ||
1108                 (nPrecision != pField->GetPrecision() && nPrecision )       ||
1109                 nScale != pField->GetScale()                ||
1110                 nNullable != pField->GetIsNullable()        ||
1111                 sDescription != pField->GetDescription()        ||
1112                 bAutoIncrement != pField->IsAutoIncrement())&&
1113                 xColumnFactory.is())
1114             {
1115                 Reference<XPropertySet> xNewColumn;
1116                 xNewColumn = xColumnFactory->createDataDescriptor();
1117                 ::dbaui::setColumnProperties(xNewColumn,pField);
1118                 // first try to alter the column
1119                 sal_Bool bNotOk = sal_False;
1120                 try
1121                 {
1122                     // first try if we can alter the column
1123                     if(xAlter.is())
1124                         xAlter->alterColumnByName(pField->GetName(),xNewColumn);
1125                 }
1126                 catch(const SQLException&)
1127                 {
1128                     if(xDrop.is() && xAppend.is())
1129                     {
1130                         String aMessage( ModuleRes( STR_TABLEDESIGN_ALTER_ERROR ) );
1131                         aMessage.SearchAndReplaceAscii( "$column$", pField->GetName() );
1132 
1133                         SQLExceptionInfo aError( ::cppu::getCaughtException() );
1134                         OSQLWarningBox aMsg( getView(), aMessage, WB_YES_NO | WB_DEF_YES , &aError );
1135                         bNotOk = aMsg.Execute() == RET_YES;
1136                     }
1137                     else
1138                         throw;
1139                 }
1140                 // if something went wrong or we can't alter columns
1141                 // drop and append a new one
1142                 if((!xAlter.is() || bNotOk) && xDrop.is() && xAppend.is())
1143                 {
1144                     xDrop->dropByName(pField->GetName());
1145                     try
1146                     {
1147                         xAppend->appendByDescriptor(xNewColumn);
1148                     }
1149                     catch(const SQLException&)
1150                     { // an error occurred so we try to reactivate the old one
1151                         xAppend->appendByDescriptor(xColumn);
1152                         throw;
1153                     }
1154                 }
1155                 // exceptions are caught outside
1156                 xNewColumn = NULL;
1157                 if(xColumns->hasByName(pField->GetName()))
1158                     xColumns->getByName(pField->GetName()) >>= xColumn;
1159                 bReload = sal_True;
1160             }
1161 
1162 
1163         }
1164         else if(xColumnFactory.is() && xAlter.is() && nPos < nColumnCount)
1165         { // we can't find the column so we could try it with the index before we drop and append a new column
1166             try
1167             {
1168                 Reference<XPropertySet> xNewColumn;
1169                 xNewColumn = xColumnFactory->createDataDescriptor();
1170                 ::dbaui::setColumnProperties(xNewColumn,pField);
1171                 xAlter->alterColumnByIndex(nPos,xNewColumn);
1172                 if(xColumns->hasByName(pField->GetName()))
1173                 {   // ask for the append by name
1174                     aColumns[pField->GetName()] = sal_True;
1175                     xColumns->getByName(pField->GetName()) >>= xColumn;
1176                     if(xColumn.is())
1177                         pField->copyColumnSettingsTo(xColumn);
1178                 }
1179                 else
1180                 {
1181                     OSL_ENSURE(sal_False, "OTableController::alterColumns: invalid column (2)!");
1182                 }
1183             }
1184             catch(const SQLException&)
1185             { // we couldn't alter the column so we have to add new columns
1186                 bReload = sal_True;
1187                 if(xDrop.is() && xAppend.is())
1188                 {
1189                     String aMessage(ModuleRes(STR_TABLEDESIGN_ALTER_ERROR));
1190                     aMessage.SearchAndReplaceAscii("$column$",pField->GetName());
1191                     OSQLWarningBox aMsg( getView(), aMessage, WB_YES_NO | WB_DEF_YES );
1192                     if ( aMsg.Execute() != RET_YES )
1193                     {
1194                         Reference<XPropertySet> xNewColumn(xIdxColumns->getByIndex(nPos),UNO_QUERY_THROW);
1195                         ::rtl::OUString sName;
1196                         xNewColumn->getPropertyValue(PROPERTY_NAME) >>= sName;
1197                         aColumns[sName] = sal_True;
1198                         aColumns[pField->GetName()] = sal_True;
1199                         continue;
1200                     }
1201                 }
1202                 else
1203                     throw;
1204             }
1205         }
1206         else
1207             bReload = sal_True;
1208     } // for(sal_Int32 nPos = 0;aIter != aEnd;++aIter,++nPos)
1209     // alter column settings
1210     aIter = m_vRowList.begin();
1211 
1212     // first look for columns where something other than the name changed
1213     for(nPos = 0;aIter != aEnd;++aIter,++nPos)
1214     {
1215         OSL_ENSURE(*aIter,"OTableRow is null!");
1216         OFieldDescription* pField = (*aIter)->GetActFieldDescr();
1217         if ( !pField )
1218             continue;
1219         if ( (*aIter)->IsReadOnly() )
1220         {
1221             aColumns[pField->GetName()] = sal_True;
1222             continue;
1223         }
1224 
1225         Reference<XPropertySet> xColumn;
1226         if ( xColumns->hasByName(pField->GetName()) )
1227         {
1228             xColumns->getByName(pField->GetName()) >>= xColumn;
1229             Reference<XPropertySetInfo> xInfo = xColumn->getPropertySetInfo();
1230             if ( xInfo->hasPropertyByName(PROPERTY_HELPTEXT) )
1231                 xColumn->setPropertyValue(PROPERTY_HELPTEXT,makeAny(pField->GetHelpText()));
1232 
1233             if(xInfo->hasPropertyByName(PROPERTY_CONTROLDEFAULT))
1234                 xColumn->setPropertyValue(PROPERTY_CONTROLDEFAULT,pField->GetControlDefault());
1235             if(xInfo->hasPropertyByName(PROPERTY_FORMATKEY))
1236                 xColumn->setPropertyValue(PROPERTY_FORMATKEY,makeAny(pField->GetFormatKey()));
1237             if(xInfo->hasPropertyByName(PROPERTY_ALIGN))
1238                 xColumn->setPropertyValue(PROPERTY_ALIGN,makeAny(dbaui::mapTextAllign(pField->GetHorJustify())));
1239         } // if ( xColumns->hasByName(pField->GetName()) )
1240     }
1241     // second drop all columns which could be found by name
1242     Reference<XNameAccess> xKeyColumns  = getKeyColumns();
1243     // now we have to look for the columns who could be deleted
1244     if ( xDrop.is() )
1245     {
1246         Sequence< ::rtl::OUString> aColumnNames = xColumns->getElementNames();
1247         const ::rtl::OUString* pIter = aColumnNames.getConstArray();
1248         const ::rtl::OUString* pEnd = pIter + aColumnNames.getLength();
1249         for(;pIter != pEnd;++pIter)
1250         {
1251             if(aColumns.find(*pIter) == aColumns.end()) // found a column to delete
1252             {
1253                 if(xKeyColumns.is() && xKeyColumns->hasByName(*pIter)) // check if this column is a member of the primary key
1254                 {
1255                     String aMsgT(ModuleRes(STR_TBL_COLUMN_IS_KEYCOLUMN));
1256                     aMsgT.SearchAndReplaceAscii("$column$",*pIter);
1257                     String aTitle(ModuleRes(STR_TBL_COLUMN_IS_KEYCOLUMN_TITLE));
1258                     OSQLMessageBox aMsg(getView(),aTitle,aMsgT,WB_YES_NO| WB_DEF_YES);
1259                     if(aMsg.Execute() == RET_YES)
1260                     {
1261                         xKeyColumns = NULL;
1262                         dropPrimaryKey();
1263                     }
1264                     else
1265                     {
1266                         bReload = sal_True;
1267                         continue;
1268                     }
1269                 }
1270                 try
1271                 {
1272                     xDrop->dropByName(*pIter);
1273                 }
1274                 catch (const SQLException&)
1275                 {
1276                     String sError( ModuleRes( STR_TABLEDESIGN_COULD_NOT_DROP_COL ) );
1277                     sError.SearchAndReplaceAscii( "$column$", *pIter );
1278 
1279                     SQLException aNewException;
1280                     aNewException.Message = sError;
1281                     aNewException.SQLState = ::rtl::OUString::createFromAscii( "S1000" );
1282                     aNewException.NextException = ::cppu::getCaughtException();
1283 
1284                     throw aNewException;
1285                 }
1286             }
1287         }
1288     }
1289 
1290     // third append the new columns
1291     aIter = m_vRowList.begin();
1292     for(;aIter != aEnd;++aIter)
1293     {
1294         OSL_ENSURE(*aIter,"OTableRow is null!");
1295         OFieldDescription* pField = (*aIter)->GetActFieldDescr();
1296         if ( !pField || (*aIter)->IsReadOnly() || aColumns.find(pField->GetName()) != aColumns.end() )
1297             continue;
1298 
1299         Reference<XPropertySet> xColumn;
1300         if(!xColumns->hasByName(pField->GetName()))
1301         {
1302             if(xColumnFactory.is() && xAppend.is())
1303             {// column not found by its name so we assume it is new
1304                 // Column is new
1305                 xColumn = xColumnFactory->createDataDescriptor();
1306                 ::dbaui::setColumnProperties(xColumn,pField);
1307                 xAppend->appendByDescriptor(xColumn);
1308                 if(xColumns->hasByName(pField->GetName()))
1309                 {   // ask for the append by name
1310                     aColumns[pField->GetName()] = sal_True;
1311                     xColumns->getByName(pField->GetName()) >>= xColumn;
1312                     if(xColumn.is())
1313                         pField->copyColumnSettingsTo(xColumn);
1314                 }
1315                 else
1316                 {
1317                     OSL_ENSURE(sal_False, "OTableController::alterColumns: invalid column!");
1318                 }
1319             }
1320         }
1321     }
1322 
1323 
1324     // check if we have to do something with the primary key
1325     sal_Bool bNeedDropKey = sal_False;
1326     sal_Bool bNeedAppendKey = sal_False;
1327     if ( xKeyColumns.is() )
1328     {
1329         aIter = m_vRowList.begin();
1330         for(;aIter != aEnd;++aIter)
1331         {
1332             OSL_ENSURE(*aIter,"OTableRow is null!");
1333             OFieldDescription* pField = (*aIter)->GetActFieldDescr();
1334             if ( !pField )
1335                 continue;
1336 
1337             if  (   pField->IsPrimaryKey()
1338                 &&  !xKeyColumns->hasByName( pField->GetName() )
1339                 )
1340             {   // new primary key column inserted which isn't already in the columns selection
1341                 bNeedDropKey = bNeedAppendKey = sal_True;
1342                 break;
1343             }
1344             else if (   !pField->IsPrimaryKey()
1345                     &&  xKeyColumns->hasByName( pField->GetName() )
1346                     )
1347             {   // found a column which currently is in the primary key, but is marked not to be anymore
1348                 bNeedDropKey = bNeedAppendKey = sal_True;
1349                 break;
1350             }
1351         }
1352     }
1353     else
1354     {   // no primary key available so we check if we should create one
1355         bNeedAppendKey = sal_True;
1356     }
1357 
1358     if ( bNeedDropKey && xKeyColumns.is() && xKeyColumns->getElementNames().getLength() )
1359         dropPrimaryKey();
1360 
1361     if ( bNeedAppendKey )
1362     {
1363         Reference< XKeysSupplier > xKeySup( m_xTable, UNO_QUERY );
1364         appendPrimaryKey( xKeySup ,sal_False);
1365     }
1366 
1367     reSyncRows();
1368 
1369     if ( bReload )
1370         reload();
1371 }
1372 // -----------------------------------------------------------------------------
dropPrimaryKey()1373 void OTableController::dropPrimaryKey()
1374 {
1375     SQLExceptionInfo aInfo;
1376     try
1377     {
1378         Reference<XKeysSupplier> xKeySup(m_xTable,UNO_QUERY);
1379         Reference<XIndexAccess> xKeys;
1380         if(xKeySup.is())
1381             xKeys = xKeySup->getKeys();
1382 
1383         if(xKeys.is())
1384         {
1385             Reference<XPropertySet> xProp;
1386             for(sal_Int32 i=0;i< xKeys->getCount();++i)
1387             {
1388                 xProp.set(xKeys->getByIndex(i),UNO_QUERY);
1389                 sal_Int32 nKeyType = 0;
1390                 xProp->getPropertyValue(PROPERTY_TYPE) >>= nKeyType;
1391                 if(KeyType::PRIMARY == nKeyType)
1392                 {
1393                     Reference<XDrop> xDrop(xKeys,UNO_QUERY);
1394                     xDrop->dropByIndex(i); // delete the key
1395                     break;
1396                 }
1397             }
1398         }
1399     }
1400     catch(const SQLContext& e)
1401     {
1402         aInfo = SQLExceptionInfo(e);
1403     }
1404     catch(const SQLWarning& e)
1405     {
1406         aInfo = SQLExceptionInfo(e);
1407     }
1408     catch(const SQLException& e)
1409     {
1410         aInfo = SQLExceptionInfo(e);
1411     }
1412     catch( const Exception& )
1413     {
1414         DBG_UNHANDLED_EXCEPTION();
1415     }
1416 
1417     showError(aInfo);
1418 }
1419 // -----------------------------------------------------------------------------
assignTable()1420 void OTableController::assignTable()
1421 {
1422     ::rtl::OUString sComposedName;
1423     // get the table
1424     if(m_sName.getLength())
1425     {
1426         Reference<XNameAccess> xNameAccess;
1427         Reference<XTablesSupplier> xSup(getConnection(),UNO_QUERY);
1428         if(xSup.is())
1429         {
1430             xNameAccess = xSup->getTables();
1431             OSL_ENSURE(xNameAccess.is(),"no nameaccess for the queries!");
1432 
1433             Reference<XPropertySet> xProp;
1434             if(xNameAccess->hasByName(m_sName) && ::cppu::extractInterface(xProp,xNameAccess->getByName(m_sName)) && xProp.is())
1435             {
1436                 m_xTable = xProp;
1437                 startTableListening();
1438 
1439                 // check if we set the table editable
1440                 Reference<XDatabaseMetaData> xMeta = getConnection()->getMetaData();
1441                 setEditable( xMeta.is() && !xMeta->isReadOnly() && (isAlterAllowed() || isDropAllowed() || isAddAllowed()) );
1442                 if(!isEditable())
1443                 {
1444                     static const sal_Bool aTrue = sal_True;
1445                     ::std::for_each(m_vRowList.begin(),m_vRowList.end(),boost::bind( &OTableRow::SetReadOnly, _1, boost::cref( aTrue )));
1446                 }
1447                 m_bNew = sal_False;
1448                 // be notified when the table is in disposing
1449                 InvalidateAll();
1450             }
1451         }
1452     }
1453     //updateTitle();
1454 }
1455 // -----------------------------------------------------------------------------
isAddAllowed() const1456 sal_Bool OTableController::isAddAllowed() const
1457 {
1458     Reference<XColumnsSupplier> xColsSup(m_xTable,UNO_QUERY);
1459     sal_Bool bAddAllowed = !m_xTable.is();
1460     if(xColsSup.is())
1461         bAddAllowed = Reference<XAppend>(xColsSup->getColumns(),UNO_QUERY).is();
1462 
1463     try
1464     {
1465         Reference< XDatabaseMetaData > xMetaData = getMetaData( );
1466         bAddAllowed = bAddAllowed || ( xMetaData.is() && xMetaData->supportsAlterTableWithAddColumn());
1467     }
1468     catch(Exception&)
1469     {
1470         DBG_UNHANDLED_EXCEPTION();
1471         bAddAllowed = sal_False;
1472     }
1473 
1474     return bAddAllowed;
1475 }
1476 // -----------------------------------------------------------------------------
isDropAllowed() const1477 sal_Bool OTableController::isDropAllowed() const
1478 {
1479     Reference<XColumnsSupplier> xColsSup(m_xTable,UNO_QUERY);
1480     sal_Bool bDropAllowed = !m_xTable.is();
1481     if(xColsSup.is())
1482     {
1483         Reference<XNameAccess> xNameAccess = xColsSup->getColumns();
1484         bDropAllowed = Reference<XDrop>(xNameAccess,UNO_QUERY).is() && xNameAccess->hasElements();
1485     }
1486 
1487     Reference< XDatabaseMetaData> xMetaData = getMetaData( );
1488     bDropAllowed = bDropAllowed || ( xMetaData.is() && xMetaData->supportsAlterTableWithDropColumn());
1489 
1490     return bDropAllowed;
1491 }
1492 // -----------------------------------------------------------------------------
isAlterAllowed() const1493 sal_Bool OTableController::isAlterAllowed() const
1494 {
1495     sal_Bool bAllowed(!m_xTable.is() || Reference<XAlterTable>(m_xTable,UNO_QUERY).is());
1496     return bAllowed;
1497 }
1498 // -----------------------------------------------------------------------------
reSyncRows()1499 void OTableController::reSyncRows()
1500 {
1501     sal_Bool bAlterAllowed  = isAlterAllowed();
1502     sal_Bool bAddAllowed    = isAddAllowed();
1503     ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aIter = m_vRowList.begin();
1504     ::std::vector< ::boost::shared_ptr<OTableRow> >::iterator aEnd = m_vRowList.end();
1505     for(;aIter != aEnd;++aIter)
1506     {
1507         OSL_ENSURE(*aIter,"OTableRow is null!");
1508         OFieldDescription* pField = (*aIter)->GetActFieldDescr();
1509         if ( pField )
1510             (*aIter)->SetReadOnly(!bAlterAllowed);
1511         else
1512             (*aIter)->SetReadOnly(!bAddAllowed);
1513 
1514     }
1515     static_cast<OTableDesignView*>(getView())->reSync();    // show the windows and fill with our information
1516 
1517     ClearUndoManager();
1518     setModified(sal_False);     // and we are not modified yet
1519 }
1520 // -----------------------------------------------------------------------------
createUniqueName(const::rtl::OUString & _rName)1521 ::rtl::OUString OTableController::createUniqueName(const ::rtl::OUString& _rName)
1522 {
1523     ::rtl::OUString sName = _rName;
1524     Reference< XDatabaseMetaData> xMetaData = getMetaData( );
1525 
1526     ::comphelper::UStringMixEqual bCase(xMetaData.is() ? xMetaData->supportsMixedCaseQuotedIdentifiers() : sal_True);
1527 
1528     ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter = m_vRowList.begin();
1529     ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aEnd = m_vRowList.end();
1530     for(sal_Int32 i=0;aIter != aEnd;++aIter)
1531     {
1532         OFieldDescription* pFieldDesc = (*aIter)->GetActFieldDescr();
1533         if (pFieldDesc && pFieldDesc->GetName().getLength() && bCase(sName,pFieldDesc->GetName()))
1534         { // found a second name of _rName so we need another
1535             sName = _rName + ::rtl::OUString::valueOf(++i);
1536             aIter = m_vRowList.begin(); // and retry
1537         }
1538     }
1539     return sName;
1540 }
1541 // -----------------------------------------------------------------------------
getPrivateTitle() const1542 ::rtl::OUString OTableController::getPrivateTitle() const
1543 {
1544     ::rtl::OUString sTitle;
1545     try
1546     {
1547         // get the table
1548         if ( m_sName.getLength() && getConnection().is() )
1549         {
1550             if ( m_xTable.is() )
1551                 sTitle = ::dbtools::composeTableName( getConnection()->getMetaData(), m_xTable, ::dbtools::eInDataManipulation, false, false, false );
1552             else
1553                 sTitle = m_sName;
1554         }
1555         if ( !sTitle.getLength() )
1556         {
1557             String aName = String(ModuleRes(STR_TBL_TITLE));
1558             sTitle = aName.GetToken(0,' ');
1559             sTitle += ::rtl::OUString::valueOf(getCurrentStartNumber());
1560         }
1561     }
1562     catch( const Exception& )
1563     {
1564         DBG_UNHANDLED_EXCEPTION();
1565     }
1566     return sTitle;
1567 }
1568 // -----------------------------------------------------------------------------
reload()1569 void OTableController::reload()
1570 {
1571     loadData();                 // fill the column information form the table
1572     static_cast<OTableDesignView*>(getView())->reSync();    // show the windows and fill with our information
1573     ClearUndoManager();
1574     setModified(sal_False);     // and we are not modified yet
1575     static_cast<OTableDesignView*>(getView())->Invalidate();
1576 }
1577 // -----------------------------------------------------------------------------
getFirstEmptyRowPosition()1578 sal_Int32 OTableController::getFirstEmptyRowPosition()
1579 {
1580     sal_Int32 nRet = -1;
1581     ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aIter = m_vRowList.begin();
1582     ::std::vector< ::boost::shared_ptr<OTableRow> >::const_iterator aEnd = m_vRowList.end();
1583     for(;aIter != aEnd;++aIter)
1584     {
1585         if ( !*aIter || !(*aIter)->GetActFieldDescr() || !(*aIter)->GetActFieldDescr()->GetName().getLength() )
1586         {
1587             nRet = aIter - m_vRowList.begin();
1588             break;
1589         }
1590     }
1591     if ( nRet == -1 )
1592     {
1593         bool bReadRow = !isAddAllowed();
1594         ::boost::shared_ptr<OTableRow> pTabEdRow(new OTableRow());
1595         pTabEdRow->SetReadOnly(bReadRow);
1596         nRet = m_vRowList.size();
1597         m_vRowList.push_back( pTabEdRow);
1598     }
1599     return nRet;
1600 }
1601 // -----------------------------------------------------------------------------
isAutoIncrementPrimaryKey() const1602 bool OTableController::isAutoIncrementPrimaryKey() const
1603 {
1604     return getSdbMetaData().isAutoIncrementPrimaryKey();
1605 }
1606 // -----------------------------------------------------------------------------
1607 
1608 /* vim: set noet sw=4 ts=4: */
1609