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 
26 #include "precompiled_dbaccess.hxx"
27 
28 #include "dbastrings.hrc"
29 #include "FilteredContainer.hxx"
30 #include "RefreshListener.hxx"
31 #include "sdbcoretools.hxx"
32 #include <com/sun/star/sdbc/XRow.hpp>
33 #include <connectivity/dbtools.hxx>
34 #include <tools/wldcrd.hxx>
35 #include <tools/diagnose_ex.h>
36 #include <rtl/logfile.hxx>
37 #include <boost/optional.hpp>
38 
39 namespace dbaccess
40 {
41 	using namespace dbtools;
42 	using namespace ::com::sun::star::uno;
43 	using namespace ::com::sun::star::lang;
44 	using namespace ::com::sun::star::beans;
45 	using namespace ::com::sun::star::sdbc;
46 	using namespace ::com::sun::star::sdb;
47 	using namespace ::com::sun::star::sdbcx;
48 	using namespace ::com::sun::star::util;
49 	using namespace ::com::sun::star::container;
50 	using namespace ::osl;
51 	using namespace ::comphelper;
52 	using namespace ::cppu;
53 	using namespace ::connectivity::sdbcx;
54 
55 //------------------------------------------------------------------------------
56 /** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
57 */
createWildCardVector(Sequence<::rtl::OUString> & _rTableFilter,::std::vector<WildCard> & _rOut)58 sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
59 {
60     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "api", "Ocke.Janssen@sun.com", "OFilteredContainer::createWildCardVector" );
61 	// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
62 	// for them
63 	::rtl::OUString* pTableFilters = _rTableFilter.getArray();
64 	::rtl::OUString* pEnd		   = pTableFilters + _rTableFilter.getLength();
65 	sal_Int32 nShiftPos = 0;
66 	for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
67 	{
68 		if (pTableFilters->indexOf('%') != -1)
69 		{
70 			_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
71 		}
72 		else
73 		{
74 			if (nShiftPos != i)
75 			{
76 				_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
77 			}
78 			++nShiftPos;
79 		}
80 	}
81 	// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
82 	_rTableFilter.realloc(nShiftPos);
83 	return nShiftPos;
84 }
85 
86     // -------------------------------------------------------------------------
lcl_isElementAllowed(const::rtl::OUString & _rName,const Sequence<::rtl::OUString> & _rTableFilter,const::std::vector<WildCard> & _rWCSearch)87 	bool lcl_isElementAllowed(  const ::rtl::OUString& _rName,
88                                 const Sequence< ::rtl::OUString >& _rTableFilter,
89                                 const ::std::vector< WildCard >& _rWCSearch )
90 	{
91 		sal_Int32 nTableFilterLen = _rTableFilter.getLength();
92 
93         const ::rtl::OUString* tableFilter = _rTableFilter.getConstArray();
94         const ::rtl::OUString* tableFilterEnd = _rTableFilter.getConstArray() + nTableFilterLen;
95         bool bFilterMatch = ::std::find( tableFilter, tableFilterEnd, _rName ) != tableFilterEnd;
96 		// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
97 		if (!bFilterMatch && !_rWCSearch.empty())
98 		{	// or if one of the wildcrad expression matches
99 			for	(	::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
100 					aLoop != _rWCSearch.end() && !bFilterMatch;
101 					++aLoop
102 				)
103 				bFilterMatch = aLoop->Matches( _rName );
104 		}
105 
106 		return bFilterMatch;
107 	}
108 
109     //--------------------------------------------------------------------------
110     typedef ::boost::optional< ::rtl::OUString >    OptionalString;
111     struct TableInfo
112     {
113         OptionalString  sComposedName;
114         OptionalString  sType;
115         OptionalString  sCatalog;
116         OptionalString  sSchema;
117         OptionalString  sName;
118 
TableInfodbaccess::TableInfo119         TableInfo( const ::rtl::OUString& _composedName )
120             :sComposedName( _composedName )
121         {
122         }
123 
TableInfodbaccess::TableInfo124         TableInfo( const ::rtl::OUString& _catalog, const ::rtl::OUString& _schema, const ::rtl::OUString& _name,
125             const ::rtl::OUString& _type )
126             :sComposedName()
127             ,sType( _type )
128             ,sCatalog( _catalog )
129             ,sSchema( _schema )
130             ,sName( _name )
131         {
132         }
133     };
134     typedef ::std::vector< TableInfo >    TableInfos;
135 
136     //--------------------------------------------------------------------------
lcl_ensureComposedName(TableInfo & _io_tableInfo,const Reference<XDatabaseMetaData> & _metaData)137     void lcl_ensureComposedName( TableInfo& _io_tableInfo, const Reference< XDatabaseMetaData >& _metaData )
138     {
139         if ( !_metaData.is() )
140             throw RuntimeException();
141 
142         if ( !_io_tableInfo.sComposedName )
143         {
144             OSL_ENSURE( !!_io_tableInfo.sCatalog && !!_io_tableInfo.sSchema && !!_io_tableInfo.sName, "lcl_ensureComposedName: How should I composed the name from nothing!?" );
145 
146             _io_tableInfo.sComposedName = OptionalString(
147                 composeTableName( _metaData, *_io_tableInfo.sCatalog, *_io_tableInfo.sSchema, *_io_tableInfo.sName,
148                 sal_False, ::dbtools::eInDataManipulation )
149             );
150         }
151     }
152 
153     //--------------------------------------------------------------------------
lcl_ensureType(TableInfo & _io_tableInfo,const Reference<XDatabaseMetaData> & _metaData,const Reference<XNameAccess> & _masterContainer)154     void lcl_ensureType( TableInfo& _io_tableInfo, const Reference< XDatabaseMetaData >& _metaData, const Reference< XNameAccess >& _masterContainer )
155     {
156         if ( !!_io_tableInfo.sType )
157             return;
158 
159         lcl_ensureComposedName( _io_tableInfo, _metaData );
160 
161         if ( !_masterContainer.is() )
162             throw RuntimeException();
163 
164         ::rtl::OUString sTypeName;
165         try
166         {
167             Reference< XPropertySet > xTable( _masterContainer->getByName( *_io_tableInfo.sComposedName ), UNO_QUERY_THROW );
168             OSL_VERIFY( xTable->getPropertyValue( PROPERTY_TYPE ) >>= sTypeName );
169         }
170         catch( const Exception& )
171         {
172         	DBG_UNHANDLED_EXCEPTION();
173         }
174         _io_tableInfo.sType = OptionalString( sTypeName );
175     }
176 
177     //--------------------------------------------------------------------------
lcl_filter(const TableInfos & _unfilteredTables,const Sequence<::rtl::OUString> & _tableFilter,const Sequence<::rtl::OUString> & _tableTypeFilter,const Reference<XDatabaseMetaData> & _metaData,const Reference<XNameAccess> & _masterContainer)178     connectivity::TStringVector lcl_filter( const TableInfos& _unfilteredTables,
179         const Sequence< ::rtl::OUString >& _tableFilter, const Sequence< ::rtl::OUString >& _tableTypeFilter,
180         const Reference< XDatabaseMetaData >& _metaData, const Reference< XNameAccess >& _masterContainer )
181     {
182         TableInfos aFilteredTables;
183 
184         // first, filter for the table names
185         sal_Int32 nTableFilterCount = _tableFilter.getLength();
186         sal_Bool dontFilterTableNames = ( ( nTableFilterCount == 1 ) && _tableFilter[0].equalsAsciiL( "%", 1 ) );
187 		if( dontFilterTableNames )
188         {
189             aFilteredTables = _unfilteredTables;
190         }
191         else
192 		{
193 			// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
194 			// for them
195 			::std::vector< WildCard > aWildCardTableFilter;
196 			Sequence< ::rtl::OUString > aNonWildCardTableFilter = _tableFilter;
197 			nTableFilterCount = createWildCardVector( aNonWildCardTableFilter, aWildCardTableFilter );
198 
199             TableInfos aUnfilteredTables( _unfilteredTables );
200 			aUnfilteredTables.reserve( nTableFilterCount + ( aWildCardTableFilter.size() * 10 ) );
201 
202             for (   TableInfos::iterator table = aUnfilteredTables.begin();
203                     table != aUnfilteredTables.end();
204                     ++table
205                 )
206             {
207                 lcl_ensureComposedName( *table, _metaData );
208 
209 				if ( lcl_isElementAllowed( *table->sComposedName, aNonWildCardTableFilter, aWildCardTableFilter ) )
210 					aFilteredTables.push_back( *table );
211             }
212 		}
213 
214         // second, filter for the table types
215         sal_Int32 nTableTypeFilterCount = _tableTypeFilter.getLength();
216         sal_Bool dontFilterTableTypes = ( ( nTableTypeFilterCount == 1 ) && _tableTypeFilter[0].equalsAsciiL( "%", 1 ) );
217         dontFilterTableTypes = dontFilterTableTypes || ( nTableTypeFilterCount == 0 );
218             // (for TableTypeFilter, unlike TableFilter, "empty" means "do not filter at all")
219         if ( !dontFilterTableTypes )
220         {
221             TableInfos aUnfilteredTables;
222             aUnfilteredTables.swap( aFilteredTables );
223 
224             const ::rtl::OUString* pTableTypeFilterBegin = _tableTypeFilter.getConstArray();
225             const ::rtl::OUString* pTableTypeFilterEnd = pTableTypeFilterBegin + _tableTypeFilter.getLength();
226 
227             for (   TableInfos::iterator table = aUnfilteredTables.begin();
228                     table != aUnfilteredTables.end();
229                     ++table
230                 )
231             {
232                 // ensure that we know the table type
233                 lcl_ensureType( *table, _metaData, _masterContainer );
234 
235                 if ( ::std::find( pTableTypeFilterBegin, pTableTypeFilterEnd, *table->sType ) != pTableTypeFilterEnd )
236                     aFilteredTables.push_back( *table );
237             }
238         }
239 
240 		connectivity::TStringVector aReturn;
241         for (   TableInfos::iterator table = aFilteredTables.begin();
242                 table != aFilteredTables.end();
243                 ++table
244             )
245         {
246             lcl_ensureComposedName( *table, _metaData );
247             aReturn.push_back( *table->sComposedName );
248         }
249         return aReturn;
250     }
251 
252     //==========================================================================
253 	//= OViewContainer
254 	//==========================================================================
OFilteredContainer(::cppu::OWeakObject & _rParent,::osl::Mutex & _rMutex,const Reference<XConnection> & _xCon,sal_Bool _bCase,IRefreshListener * _pRefreshListener,::dbtools::IWarningsContainer * _pWarningsContainer,oslInterlockedCount & _nInAppend)255 	OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
256 								 ::osl::Mutex& _rMutex,
257 								 const Reference< XConnection >& _xCon,
258 								 sal_Bool _bCase,
259 								 IRefreshListener*	_pRefreshListener,
260                                  ::dbtools::IWarningsContainer* _pWarningsContainer
261                                  ,oslInterlockedCount& _nInAppend)
262 	    :OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
263 	    ,m_bConstructed(sal_False)
264 	    ,m_pWarningsContainer(_pWarningsContainer)
265 	    ,m_pRefreshListener(_pRefreshListener)
266         ,m_nInAppend(_nInAppend)
267 	    ,m_xConnection(_xCon)
268 	{
269 	}
270     // -------------------------------------------------------------------------
construct(const Reference<XNameAccess> & _rxMasterContainer,const Sequence<::rtl::OUString> & _rTableFilter,const Sequence<::rtl::OUString> & _rTableTypeFilter)271 	void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
272 									const Sequence< ::rtl::OUString >& _rTableFilter,
273 									const Sequence< ::rtl::OUString >& _rTableTypeFilter)
274 	{
275         try
276         {
277             Reference<XConnection> xCon = m_xConnection;
278             if ( xCon.is() )
279                 m_xMetaData = xCon->getMetaData();
280         }
281         catch(SQLException&)
282         {
283             DBG_UNHANDLED_EXCEPTION();
284         }
285 
286         m_xMasterContainer = _rxMasterContainer;
287 
288         if ( m_xMasterContainer.is() )
289         {
290             addMasterContainerListener();
291 
292             TableInfos aUnfilteredTables;
293 
294             Sequence< ::rtl::OUString > aNames = m_xMasterContainer->getElementNames();
295             const ::rtl::OUString*  name = aNames.getConstArray();
296             const ::rtl::OUString*  nameEnd = name + aNames.getLength();
297             for ( ; name != nameEnd; ++name )
298                 aUnfilteredTables.push_back( TableInfo( *name ) );
299 
300             reFill( lcl_filter( aUnfilteredTables,
301                 _rTableFilter, _rTableTypeFilter, m_xMetaData, m_xMasterContainer ) );
302 
303             m_bConstructed = sal_True;
304         }
305         else
306         {
307             construct( _rTableFilter, _rTableTypeFilter );
308         }
309     }
310     //------------------------------------------------------------------------------
construct(const Sequence<::rtl::OUString> & _rTableFilter,const Sequence<::rtl::OUString> & _rTableTypeFilter)311 	void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
312 	{
313 		// build sorted versions of the filter sequences, so the visibility decision is faster
314 		Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
315 		sal_Int32	nTableFilterLen = aTableFilter.getLength();
316 
317 	    // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
318 	    // for them
319 	    ::std::vector< WildCard > aWCSearch;
320 	    nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
321 
322 	    try
323 	    {
324             Reference< XConnection > xCon( m_xConnection, UNO_SET_THROW );
325 			m_xMetaData.set( xCon->getMetaData(), UNO_SET_THROW );
326 
327             // create a table table filter suitable for the XDatabaseMetaData::getTables call,
328             // taking into account both the externally-provided table type filter, and any
329             // table type restriction which is inherent to the container
330             Sequence< ::rtl::OUString > aTableTypeFilter;
331             ::rtl::OUString sInherentTableTypeRestriction( getTableTypeRestriction() );
332             if ( sInherentTableTypeRestriction.getLength() )
333             {
334                 if ( _rTableTypeFilter.getLength() != 0 )
335                 {
336                     const ::rtl::OUString* tableType    = _rTableTypeFilter.getConstArray();
337                     const ::rtl::OUString* tableTypeEnd = tableType + _rTableTypeFilter.getLength();
338                     for ( ; tableType != tableTypeEnd; ++tableType )
339                     {
340                         if ( *tableType == sInherentTableTypeRestriction )
341                             break;
342                     }
343                     if ( tableType == tableTypeEnd )
344                     {   // the only table type which can be part of this container is not allowed
345                         // by the externally provided table type filter.
346                         m_bConstructed = sal_True;
347                         return;
348                     }
349                 }
350                 aTableTypeFilter.realloc( 1 );
351                 aTableTypeFilter[0] = sInherentTableTypeRestriction;
352             }
353             else
354             {
355                 // no container-inherent restriction for the table types
356                 if ( _rTableTypeFilter.getLength() == 0 )
357                 {   // no externally-provided table type filter => use the default filter
358                     getAllTableTypeFilter( aTableTypeFilter );
359                 }
360                 else
361                 {
362                     aTableTypeFilter = _rTableTypeFilter;
363                 }
364             }
365 
366             static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
367             Reference< XResultSet > xTables = m_xMetaData->getTables( Any(), sAll, sAll, aTableTypeFilter );
368             Reference< XRow > xCurrentRow( xTables, UNO_QUERY_THROW );
369 
370             TableInfos aUnfilteredTables;
371 
372             ::rtl::OUString sCatalog, sSchema, sName, sType;
373             while ( xTables->next() )
374             {
375                 sCatalog	= xCurrentRow->getString(1);
376                 sSchema		= xCurrentRow->getString(2);
377                 sName		= xCurrentRow->getString(3);
378                 sType       = xCurrentRow->getString(4);
379 
380                 aUnfilteredTables.push_back( TableInfo( sCatalog, sSchema, sName, sType ) );
381             }
382 
383             reFill( lcl_filter( aUnfilteredTables,
384                 _rTableFilter, aTableTypeFilter, m_xMetaData, NULL ) );
385 
386             disposeComponent( xTables );
387         }
388 		catch (const Exception&)
389 		{
390 			DBG_UNHANDLED_EXCEPTION();
391 			disposing();
392 			return;
393 		}
394 
395 		m_bConstructed = sal_True;
396 	}
397 
398     //------------------------------------------------------------------------------
disposing()399 	void OFilteredContainer::disposing()
400 	{
401 		OCollection::disposing();
402 
403         if ( m_xMasterContainer.is() )
404 		    removeMasterContainerListener();
405 
406 		m_xMasterContainer	= NULL;
407 		m_xMetaData			= NULL;
408 		m_pWarningsContainer = NULL;
409 		m_pRefreshListener	= NULL;
410 		m_bConstructed		= sal_False;
411 	}
412 
413     // -------------------------------------------------------------------------
impl_refresh()414     void OFilteredContainer::impl_refresh() throw(RuntimeException)
415     {
416         RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "api", "Ocke.Janssen@sun.com", "OFilteredContainer::impl_refresh" );
417 	    if ( m_pRefreshListener )
418 	    {
419 		    m_bConstructed = sal_False;
420 		    Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
421 		    if ( xRefresh.is() )
422 			    xRefresh->refresh();
423 		    m_pRefreshListener->refresh(this);
424 	    }
425     }
426 
427 	// -----------------------------------------------------------------------------
getNameForObject(const ObjectType & _xObject)428     ::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
429     {
430         OSL_ENSURE( _xObject.is(), "OFilteredContainer::getNameForObject: Object is NULL!" );
431 	    return ::dbtools::composeTableName( m_xMetaData, _xObject, ::dbtools::eInDataManipulation, false, false, false );
432     }
433 
434     // -----------------------------------------------------------------------------
435     // multiple to obtain all tables from XDatabaseMetaData::getTables, via passing a particular
436     // table type filter:
437     // adhere to the standard, which requests to pass a NULL table type filter, if
438     // you want to retrieve all tables
439     #define FILTER_MODE_STANDARD 0
440     // only pass %, which is not allowed by the standard, but understood by some drivers
441     #define FILTER_MODE_WILDCARD 1
442     // only pass TABLE and VIEW
443     #define FILTER_MODE_FIXED    2
444     // do the thing which showed to be the safest way, understood by nearly all
445     // drivers, even the ones which do not understand the standard
446     #define FILTER_MODE_MIX_ALL  3
447 
getAllTableTypeFilter(Sequence<::rtl::OUString> & _rFilter) const448     void OFilteredContainer::getAllTableTypeFilter( Sequence< ::rtl::OUString >& /* [out] */ _rFilter ) const
449     {
450         sal_Int32 nFilterMode = FILTER_MODE_MIX_ALL;
451             // for compatibility reasons, this is the default: we used this way before we
452             // introduced the TableTypeFilterMode setting
453 
454         // obtain the data source we belong to, and the TableTypeFilterMode setting
455         Any aFilterModeSetting;
456         if ( getDataSourceSetting( getDataSource( (Reference< XInterface >)m_rParent ), "TableTypeFilterMode", aFilterModeSetting ) )
457         {
458             OSL_VERIFY( aFilterModeSetting >>= nFilterMode );
459         }
460 
461         const ::rtl::OUString sAll( RTL_CONSTASCII_USTRINGPARAM( "%" ) );
462 	    const ::rtl::OUString sView( RTL_CONSTASCII_USTRINGPARAM( "VIEW" ) );
463 	    const ::rtl::OUString sTable( RTL_CONSTASCII_USTRINGPARAM( "TABLE" ) );
464 
465         switch ( nFilterMode )
466         {
467         default:
468             OSL_ENSURE( sal_False, "OTableContainer::getAllTableTypeFilter: unknown TableTypeFilterMode!" );
469         case FILTER_MODE_MIX_ALL:
470             _rFilter.realloc( 3 );
471             _rFilter[0] = sView;
472             _rFilter[1] = sTable;
473             _rFilter[2] = sAll;
474             break;
475         case FILTER_MODE_FIXED:
476             _rFilter.realloc( 2 );
477             _rFilter[0] = sView;
478             _rFilter[1] = sTable;
479             break;
480         case FILTER_MODE_WILDCARD:
481             _rFilter.realloc( 1 );
482             _rFilter[0] = sAll;
483             break;
484         case FILTER_MODE_STANDARD:
485             _rFilter.realloc( 0 );
486             break;
487         }
488     }
489 
490 // ..............................................................................
491 } // namespace
492 // ..............................................................................
493 
494 
495