1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_dbaccess.hxx"
26 
27 #ifndef DBACCESS_SOURCE_SDBTOOLS_CONNECTION_OBJECTNAMES_HXX
28 #include "objectnames.hxx"
29 #endif
30 
31 #ifndef DBACCESS_MODULE_SDBT_HXX
32 #include "module_sdbt.hxx"
33 #endif
34 #ifndef DBACCESS_SDBT_RESOURCE_HRC
35 #include "sdbt_resource.hrc"
36 #endif
37 
38 /** === begin UNO includes === **/
39 #include <com/sun/star/lang/NullPointerException.hpp>
40 #include <com/sun/star/sdb/CommandType.hpp>
41 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
42 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
43 #include <com/sun/star/sdb/ErrorCondition.hpp>
44 /** === end UNO includes === **/
45 
46 #include <connectivity/dbmetadata.hxx>
47 #include <connectivity/dbtools.hxx>
48 #include <connectivity/sqlerror.hxx>
49 #include <cppuhelper/exc_hlp.hxx>
50 #include <rtl/ustrbuf.hxx>
51 #include <tools/string.hxx>
52 
53 #include <boost/shared_ptr.hpp>
54 
55 //........................................................................
56 namespace sdbtools
57 {
58 //........................................................................
59 
60 	/** === begin UNO using === **/
61     using ::com::sun::star::uno::Reference;
62     using ::com::sun::star::sdbc::XConnection;
63     using ::com::sun::star::lang::NullPointerException;
64     using ::com::sun::star::lang::IllegalArgumentException;
65     using ::com::sun::star::uno::RuntimeException;
66     using ::com::sun::star::sdbc::SQLException;
67     using ::com::sun::star::sdbc::XDatabaseMetaData;
68     using ::com::sun::star::uno::XInterface;
69     using ::com::sun::star::container::XNameAccess;
70     using ::com::sun::star::sdbc::XDatabaseMetaData;
71     using ::com::sun::star::uno::UNO_QUERY_THROW;
72     using ::com::sun::star::sdbcx::XTablesSupplier;
73     using ::com::sun::star::sdb::XQueriesSupplier;
74     using ::com::sun::star::uno::Exception;
75     using ::com::sun::star::uno::makeAny;
76     using ::com::sun::star::uno::Any;
77 	/** === end UNO using === **/
78 
79     namespace CommandType = ::com::sun::star::sdb::CommandType;
80     namespace ErrorCondition = ::com::sun::star::sdb::ErrorCondition;
81 
82 	//====================================================================
83 	//= INameValidation
84 	//====================================================================
85     class INameValidation
86     {
87     public:
88         virtual bool validateName( const ::rtl::OUString& _rName ) = 0;
89         virtual void validateName_throw( const ::rtl::OUString& _rName ) = 0;
90 
~INameValidation()91         virtual ~INameValidation() { }
92     };
93     typedef ::boost::shared_ptr< INameValidation >   PNameValidation;
94 
95 	//====================================================================
96 	//= PlainExistenceCheck
97 	//====================================================================
98     class PlainExistenceCheck : public INameValidation
99     {
100     private:
101         const ::comphelper::ComponentContext    m_aContext;
102         Reference< XConnection >                m_xConnection;
103         Reference< XNameAccess >                m_xContainer;
104 
105     public:
PlainExistenceCheck(const::comphelper::ComponentContext & _rContext,const Reference<XConnection> & _rxConnection,const Reference<XNameAccess> & _rxContainer)106         PlainExistenceCheck( const ::comphelper::ComponentContext& _rContext, const Reference< XConnection >& _rxConnection, const Reference< XNameAccess >& _rxContainer )
107             :m_aContext( _rContext )
108             ,m_xConnection( _rxConnection )
109             ,m_xContainer( _rxContainer )
110         {
111             OSL_ENSURE( m_xContainer.is(), "PlainExistenceCheck::PlainExistenceCheck: this will crash!" );
112         }
113 
114         // INameValidation
validateName(const::rtl::OUString & _rName)115         virtual bool validateName( const ::rtl::OUString& _rName )
116         {
117             return !m_xContainer->hasByName( _rName );
118         }
119 
validateName_throw(const::rtl::OUString & _rName)120         virtual void validateName_throw( const ::rtl::OUString& _rName )
121         {
122             if ( validateName( _rName ) )
123                 return;
124 
125             ::connectivity::SQLError aErrors( m_aContext );
126             SQLException aError( aErrors.getSQLException( ErrorCondition::DB_OBJECT_NAME_IS_USED, m_xConnection, _rName ) );
127 
128             ::dbtools::DatabaseMetaData aMeta( m_xConnection );
129             if ( aMeta.supportsSubqueriesInFrom() )
130             {
131                 String sNeedDistinctNames( SdbtRes( STR_QUERY_AND_TABLE_DISTINCT_NAMES ) );
132                 aError.NextException <<= SQLException( sNeedDistinctNames, m_xConnection, ::rtl::OUString(), 0, Any() );
133             }
134 
135             throw aError;
136         }
137     };
138 
139 	//====================================================================
140 	//= TableValidityCheck
141 	//====================================================================
142     class TableValidityCheck : public INameValidation
143     {
144         const ::comphelper::ComponentContext  m_aContext;
145         const Reference< XConnection >        m_xConnection;
146 
147     public:
TableValidityCheck(const::comphelper::ComponentContext & _rContext,const Reference<XConnection> & _rxConnection)148         TableValidityCheck( const ::comphelper::ComponentContext& _rContext, const Reference< XConnection >& _rxConnection )
149             :m_aContext( _rContext )
150             ,m_xConnection( _rxConnection )
151         {
152         }
153 
validateName(const::rtl::OUString & _rName)154         virtual bool validateName( const ::rtl::OUString& _rName )
155         {
156             ::dbtools::DatabaseMetaData aMeta( m_xConnection );
157             if  ( !aMeta.restrictIdentifiersToSQL92() )
158                 return true;
159 
160             ::rtl::OUString sCatalog, sSchema, sName;
161             ::dbtools::qualifiedNameComponents(
162                 m_xConnection->getMetaData(), _rName, sCatalog, sSchema, sName, ::dbtools::eInTableDefinitions );
163 
164             ::rtl::OUString sExtraNameCharacters( m_xConnection->getMetaData()->getExtraNameCharacters() );
165             if  (   ( sCatalog.getLength() && !::dbtools::isValidSQLName( sCatalog, sExtraNameCharacters ) )
166                 ||  ( sSchema.getLength() && !::dbtools::isValidSQLName( sSchema, sExtraNameCharacters ) )
167                 ||  ( sName.getLength() && !::dbtools::isValidSQLName( sName, sExtraNameCharacters ) )
168                 )
169                 return false;
170 
171             return true;
172         }
173 
validateName_throw(const::rtl::OUString & _rName)174         virtual void validateName_throw( const ::rtl::OUString& _rName )
175         {
176             if ( validateName( _rName ) )
177                 return;
178 
179             ::connectivity::SQLError aErrors( m_aContext );
180             aErrors.raiseException( ErrorCondition::DB_INVALID_SQL_NAME, m_xConnection, _rName );
181         }
182     };
183 
184 	//====================================================================
185 	//= QueryValidityCheck
186 	//====================================================================
187     class QueryValidityCheck : public INameValidation
188     {
189         const ::comphelper::ComponentContext    m_aContext;
190         const Reference< XConnection >          m_xConnection;
191 
192     public:
QueryValidityCheck(const::comphelper::ComponentContext & _rContext,const Reference<XConnection> & _rxConnection)193         QueryValidityCheck( const ::comphelper::ComponentContext& _rContext, const Reference< XConnection >& _rxConnection )
194             :m_aContext( _rContext )
195             ,m_xConnection( _rxConnection )
196         {
197         }
198 
validateName_getErrorCondition(const::rtl::OUString & _rName)199         inline ::connectivity::ErrorCondition validateName_getErrorCondition( const ::rtl::OUString& _rName )
200         {
201             if  (   ( _rName.indexOf( (sal_Unicode)34  ) >= 0 )  // "
202                 ||  ( _rName.indexOf( (sal_Unicode)39  ) >= 0 )  // '
203                 ||  ( _rName.indexOf( (sal_Unicode)96  ) >= 0 )  //
204                 ||  ( _rName.indexOf( (sal_Unicode)145 ) >= 0 )  //
205                 ||  ( _rName.indexOf( (sal_Unicode)146 ) >= 0 )  //
206                 ||  ( _rName.indexOf( (sal_Unicode)180 ) >= 0 )  // #86621# removed unparsable chars
207                 )
208                 return ErrorCondition::DB_QUERY_NAME_WITH_QUOTES;
209 
210             if ( _rName.indexOf( '/') >= 0 )
211                 return ErrorCondition::DB_OBJECT_NAME_WITH_SLASHES;
212 
213             return 0;
214         }
215 
validateName(const::rtl::OUString & _rName)216         virtual bool validateName( const ::rtl::OUString& _rName )
217         {
218             if ( validateName_getErrorCondition( _rName ) != 0 )
219                 return false;
220             return true;
221         }
222 
validateName_throw(const::rtl::OUString & _rName)223         virtual void validateName_throw( const ::rtl::OUString& _rName )
224         {
225             ::connectivity::ErrorCondition nErrorCondition = validateName_getErrorCondition( _rName );
226             if ( nErrorCondition != 0 )
227             {
228                 ::connectivity::SQLError aErrors( m_aContext );
229                 aErrors.raiseException( nErrorCondition, m_xConnection );
230             }
231         }
232     };
233 
234 	//====================================================================
235 	//= CombinedNameCheck
236 	//====================================================================
237     class CombinedNameCheck : public INameValidation
238     {
239     private:
240         PNameValidation  m_pPrimary;
241         PNameValidation  m_pSecondary;
242 
243     public:
CombinedNameCheck(PNameValidation _pPrimary,PNameValidation _pSecondary)244         CombinedNameCheck( PNameValidation _pPrimary, PNameValidation _pSecondary )
245             :m_pPrimary( _pPrimary )
246             ,m_pSecondary( _pSecondary )
247         {
248             OSL_ENSURE( m_pPrimary.get() && m_pSecondary.get(), "CombinedNameCheck::CombinedNameCheck: this will crash!" );
249         }
250 
251         // INameValidation
validateName(const::rtl::OUString & _rName)252         virtual bool validateName( const ::rtl::OUString& _rName )
253         {
254             return m_pPrimary->validateName( _rName ) && m_pSecondary->validateName( _rName );
255         }
256 
validateName_throw(const::rtl::OUString & _rName)257         virtual void validateName_throw( const ::rtl::OUString& _rName )
258         {
259             m_pPrimary->validateName_throw( _rName );
260             m_pSecondary->validateName_throw( _rName );
261         }
262     };
263 
264 	//====================================================================
265 	//= NameCheckFactory
266 	//====================================================================
267     class NameCheckFactory
268     {
269     public:
270         /** creates an INameValidation instance which can be used to check the existence of query or table names
271 
272             @param _rContext
273                 the component's context
274 
275             @param  _nCommandType
276                 the type of objects (CommandType::TABLE or CommandType::QUERY) of which names shall be checked for existence
277 
278             @param  _rxConnection
279                 the connection relative to which the names are to be checked. Must be an SDB-level connection
280 
281             @throws IllegalArgumentException
282                 if the given connection is no SDB-level connection
283 
284             @throws IllegalArgumentException
285                 if the given command type is neither CommandType::TABLE or CommandType::QUERY
286         */
287         static  PNameValidation  createExistenceCheck(
288                     const ::comphelper::ComponentContext& _rContext,
289                     sal_Int32 _nCommandType,
290                     const Reference< XConnection >& _rxConnection
291                 );
292 
293         /** creates an INameValidation instance which can be used to check the validity of a query or table name
294 
295             @param _rContext
296                 the component's context
297 
298             @param  _nCommandType
299                 the type of objects (CommandType::TABLE or CommandType::QUERY) of which names shall be validated
300 
301             @param  _rxConnection
302                 the connection relative to which the names are to be checked. Must be an SDB-level connection
303 
304             @throws IllegalArgumentException
305                 if the given connection is no SDB-level connection
306 
307             @throws IllegalArgumentException
308                 if the given command type is neither CommandType::TABLE or CommandType::QUERY
309         */
310         static  PNameValidation  createValidityCheck(
311                     const ::comphelper::ComponentContext& _rContext,
312                     const sal_Int32 _nCommandType,
313                     const Reference< XConnection >& _rxConnection
314                 );
315 
316     private:
317         NameCheckFactory();                                     // never implemented
318 
319     private:
320         static  void    verifyCommandType( sal_Int32 _nCommandType );
321     };
322 
323 	//--------------------------------------------------------------------
verifyCommandType(sal_Int32 _nCommandType)324     void NameCheckFactory::verifyCommandType( sal_Int32 _nCommandType )
325     {
326         if  (   ( _nCommandType != CommandType::TABLE )
327             &&  ( _nCommandType != CommandType::QUERY )
328             )
329             throw IllegalArgumentException(
330                 String( SdbtRes( STR_INVALID_COMMAND_TYPE ) ),
331                 NULL,
332                 0
333             );
334     }
335 
336 	//--------------------------------------------------------------------
createExistenceCheck(const::comphelper::ComponentContext & _rContext,sal_Int32 _nCommandType,const Reference<XConnection> & _rxConnection)337     PNameValidation  NameCheckFactory::createExistenceCheck( const ::comphelper::ComponentContext& _rContext, sal_Int32 _nCommandType, const Reference< XConnection >& _rxConnection )
338     {
339         verifyCommandType( _nCommandType );
340 
341         ::dbtools::DatabaseMetaData aMeta( _rxConnection );
342 
343         Reference< XNameAccess > xTables, xQueries;
344         try
345         {
346             Reference< XTablesSupplier > xSuppTables( _rxConnection, UNO_QUERY_THROW );
347             Reference< XQueriesSupplier > xQueriesSupplier( _rxConnection, UNO_QUERY_THROW );
348             xTables.set( xSuppTables->getTables(), UNO_QUERY_THROW );
349             xQueries.set( xQueriesSupplier->getQueries(), UNO_QUERY_THROW );
350         }
351         catch( const Exception& )
352         {
353         	throw IllegalArgumentException(
354                 String( SdbtRes( STR_CONN_WITHOUT_QUERIES_OR_TABLES ) ),
355                 NULL,
356                 0
357             );
358         }
359 
360         PNameValidation pTableCheck( new PlainExistenceCheck( _rContext, _rxConnection, xTables ) );
361         PNameValidation pQueryCheck( new PlainExistenceCheck( _rContext, _rxConnection, xQueries ) );
362         PNameValidation pReturn;
363 
364         if ( aMeta.supportsSubqueriesInFrom() )
365             pReturn.reset( new CombinedNameCheck( pTableCheck, pQueryCheck ) );
366         else if ( _nCommandType == CommandType::TABLE )
367             pReturn = pTableCheck;
368         else
369             pReturn = pQueryCheck;
370         return pReturn;
371     }
372 
373 	//--------------------------------------------------------------------
createValidityCheck(const::comphelper::ComponentContext & _rContext,sal_Int32 _nCommandType,const Reference<XConnection> & _rxConnection)374     PNameValidation  NameCheckFactory::createValidityCheck( const ::comphelper::ComponentContext& _rContext, sal_Int32 _nCommandType, const Reference< XConnection >& _rxConnection )
375     {
376         verifyCommandType( _nCommandType );
377 
378         Reference< XDatabaseMetaData > xMeta;
379         try
380         {
381             xMeta.set( _rxConnection->getMetaData(), UNO_QUERY_THROW );
382         }
383         catch( const Exception& )
384         {
385         	throw IllegalArgumentException(
386                 ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "The connection could not provide its database's meta data." ) ),
387                 NULL,
388                 0
389             );
390         }
391 
392         if ( _nCommandType == CommandType::TABLE )
393             return PNameValidation( new TableValidityCheck( _rContext, _rxConnection ) );
394         return PNameValidation( new QueryValidityCheck( _rContext, _rxConnection ) );
395     }
396 
397 	//====================================================================
398 	//= ObjectNames_Impl
399 	//====================================================================
400     struct ObjectNames_Impl
401     {
402         SdbtClient  m_aModuleClient;    // keep the module alive as long as this instance lives
403     };
404 
405 	//====================================================================
406 	//= ObjectNames
407 	//====================================================================
408 	//--------------------------------------------------------------------
ObjectNames(const::comphelper::ComponentContext & _rContext,const Reference<XConnection> & _rxConnection)409     ObjectNames::ObjectNames( const ::comphelper::ComponentContext& _rContext, const Reference< XConnection >& _rxConnection )
410         :ConnectionDependentComponent( _rContext )
411         ,m_pImpl( new ObjectNames_Impl )
412     {
413         if ( !_rxConnection.is() )
414             throw NullPointerException();
415         setWeakConnection( _rxConnection );
416     }
417 
418 	//--------------------------------------------------------------------
~ObjectNames()419     ObjectNames::~ObjectNames()
420     {
421     }
422 
423     //--------------------------------------------------------------------
suggestName(::sal_Int32 _CommandType,const::rtl::OUString & _BaseName)424     ::rtl::OUString SAL_CALL ObjectNames::suggestName( ::sal_Int32 _CommandType, const ::rtl::OUString& _BaseName ) throw (IllegalArgumentException, RuntimeException)
425     {
426         EntryGuard aGuard( *this );
427 
428         PNameValidation pNameCheck( NameCheckFactory::createExistenceCheck( getContext(), _CommandType, getConnection() ) );
429 
430         String sBaseName( _BaseName );
431         if ( sBaseName.Len() == 0 )
432         {
433             if ( _CommandType == CommandType::TABLE )
434                 sBaseName = String( SdbtRes( STR_BASENAME_TABLE ) );
435             else
436                 sBaseName = String( SdbtRes( STR_BASENAME_QUERY ) );
437         }
438 
439         ::rtl::OUString sName( sBaseName );
440         sal_Int32 i = 1;
441         while ( !pNameCheck->validateName( sName ) )
442         {
443             ::rtl::OUStringBuffer aNameBuffer;
444             aNameBuffer.append( sBaseName );
445             aNameBuffer.appendAscii( " " );
446             aNameBuffer.append( (sal_Int32)++i );
447             sName = aNameBuffer.makeStringAndClear();
448         }
449 
450         return sName;
451     }
452 
453     //--------------------------------------------------------------------
convertToSQLName(const::rtl::OUString & Name)454     ::rtl::OUString SAL_CALL ObjectNames::convertToSQLName( const ::rtl::OUString& Name ) throw (RuntimeException)
455     {
456         EntryGuard aGuard( *this );
457         Reference< XDatabaseMetaData > xMeta( getConnection()->getMetaData(), UNO_QUERY_THROW );
458         return ::dbtools::convertName2SQLName( Name, xMeta->getExtraNameCharacters() );
459     }
460 
461     //--------------------------------------------------------------------
isNameUsed(::sal_Int32 _CommandType,const::rtl::OUString & _Name)462     ::sal_Bool SAL_CALL ObjectNames::isNameUsed( ::sal_Int32 _CommandType, const ::rtl::OUString& _Name ) throw (IllegalArgumentException, RuntimeException)
463     {
464         EntryGuard aGuard( *this );
465 
466         PNameValidation pNameCheck( NameCheckFactory::createExistenceCheck( getContext(), _CommandType, getConnection()) );
467         return !pNameCheck->validateName( _Name );
468     }
469 
470     //--------------------------------------------------------------------
isNameValid(::sal_Int32 _CommandType,const::rtl::OUString & _Name)471     ::sal_Bool SAL_CALL ObjectNames::isNameValid( ::sal_Int32 _CommandType, const ::rtl::OUString& _Name ) throw (IllegalArgumentException, RuntimeException)
472     {
473         EntryGuard aGuard( *this );
474 
475         PNameValidation pNameCheck( NameCheckFactory::createValidityCheck( getContext(), _CommandType, getConnection()) );
476         return pNameCheck->validateName( _Name );
477     }
478 
479     //--------------------------------------------------------------------
checkNameForCreate(::sal_Int32 _CommandType,const::rtl::OUString & _Name)480     void SAL_CALL ObjectNames::checkNameForCreate( ::sal_Int32 _CommandType, const ::rtl::OUString& _Name ) throw (SQLException, RuntimeException)
481     {
482         EntryGuard aGuard( *this );
483 
484         PNameValidation pNameCheck( NameCheckFactory::createExistenceCheck( getContext(), _CommandType, getConnection() ) );
485         pNameCheck->validateName_throw( _Name );
486 
487         pNameCheck = NameCheckFactory::createValidityCheck( getContext(), _CommandType, getConnection() );
488         pNameCheck->validateName_throw( _Name );
489     }
490 
491 //........................................................................
492 } // namespace sdbtools
493 //........................................................................
494 
495