1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
11  *   Licensed to the Apache Software Foundation (ASF) under one or more
12  *   contributor license agreements. See the NOTICE file distributed
13  *   with this work for additional information regarding copyright
14  *   ownership. The ASF licenses this file to you under the Apache
15  *   License, Version 2.0 (the "License"); you may not use this file
16  *   except in compliance with the License. You may obtain a copy of
17  *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
18  */
19 
20 #include <connectivity/sqlparse.hxx>
21 #include <ado/APreparedStatement.hxx>
22 #include <com/sun/star/sdbc/DataType.hpp>
23 #include <ado/AResultSetMetaData.hxx>
24 #include <ado/AResultSet.hxx>
25 #include <ado/ADriver.hxx>
26 #include <com/sun/star/lang/DisposedException.hpp>
27 #include <cppuhelper/typeprovider.hxx>
28 #include <cppuhelper/queryinterface.hxx>
29 #include <comphelper/processfactory.hxx>
30 #include <comphelper/sequence.hxx>
31 #include <comphelper/types.hxx>
32 #include <connectivity/dbexception.hxx>
33 #include <connectivity/dbtools.hxx>
34 #include <rtl/ref.hxx>
35 #include <strings.hrc>
36 
37 #include <limits>
38 
39 #define CHECK_RETURN(x)                                                 \
40     if(!x)                                                              \
41         ADOS::ThrowException(m_pConnection->getConnection(),*this);
42 
43 #ifdef max
44 #   undef max
45 #endif
46 
47 using namespace connectivity::ado;
48 using namespace connectivity;
49 using namespace com::sun::star::uno;
50 using namespace com::sun::star::lang;
51 using namespace com::sun::star::beans;
52 using namespace com::sun::star::sdbc;
53 using namespace com::sun::star::util;
54 
55 IMPLEMENT_SERVICE_INFO(OPreparedStatement,"com.sun.star.sdbcx.APreparedStatement","com.sun.star.sdbc.PreparedStatement");
56 
OPreparedStatement(OConnection * _pConnection,const OUString & sql)57 OPreparedStatement::OPreparedStatement( OConnection* _pConnection, const OUString& sql)
58     : OStatement_Base( _pConnection )
59 {
60     osl_atomic_increment( &m_refCount );
61 
62     OSQLParser aParser(_pConnection->getDriver()->getContext());
63     OUString sErrorMessage;
64     OUString sNewSql;
65     std::unique_ptr<OSQLParseNode> pNode = aParser.parseTree(sErrorMessage,sql);
66     if(pNode)
67     {   // special handling for parameters
68         //  we recursive replace all occurrences of ? in the statement and
69         //  replace them with name like "parame" */
70         sal_Int32 nParameterCount = 0;
71         replaceParameterNodeName(pNode.get(), "parame", nParameterCount);
72         pNode->parseNodeToStr( sNewSql, _pConnection );
73     }
74     else
75         sNewSql = sql;
76     CHECK_RETURN(m_Command.put_CommandText(sNewSql))
77     CHECK_RETURN(m_Command.put_Prepared(VARIANT_TRUE))
78     m_pParameters = m_Command.get_Parameters();
79     m_pParameters->AddRef();
80     m_pParameters->Refresh();
81 
82     osl_atomic_decrement( &m_refCount );
83 }
84 
~OPreparedStatement()85 OPreparedStatement::~OPreparedStatement()
86 {
87     if (m_pParameters)
88     {
89         OSL_FAIL( "OPreparedStatement::~OPreparedStatement: not disposed!" );
90         m_pParameters->Release();
91         m_pParameters = nullptr;
92     }
93 }
94 
queryInterface(const Type & rType)95 Any SAL_CALL OPreparedStatement::queryInterface( const Type & rType )
96 {
97     Any aRet = OStatement_Base::queryInterface(rType);
98     return aRet.hasValue() ? aRet : ::cppu::queryInterface( rType,
99                                         static_cast< XPreparedStatement*>(this),
100                                         static_cast< XParameters*>(this),
101                                         static_cast< XResultSetMetaDataSupplier*>(this));
102 }
103 
getTypes()104 css::uno::Sequence< css::uno::Type > SAL_CALL OPreparedStatement::getTypes(  )
105 {
106     ::cppu::OTypeCollection aTypes( cppu::UnoType<XPreparedStatement>::get(),
107                                     cppu::UnoType<XParameters>::get(),
108                                     cppu::UnoType<XResultSetMetaDataSupplier>::get());
109 
110     return ::comphelper::concatSequences(aTypes.getTypes(),OStatement_Base::getTypes());
111 }
112 
getMetaData()113 Reference< XResultSetMetaData > SAL_CALL OPreparedStatement::getMetaData(  )
114 {
115     if(!m_xMetaData.is() && m_RecordSet.IsValid())
116         m_xMetaData = new OResultSetMetaData(m_RecordSet);
117     return m_xMetaData;
118 }
119 
disposing()120 void OPreparedStatement::disposing()
121 {
122     m_xMetaData.clear();
123     if (m_pParameters)
124     {
125         m_pParameters->Release();
126         m_pParameters = nullptr;
127     }
128     OStatement_Base::disposing();
129 }
130 
close()131 void SAL_CALL OPreparedStatement::close(  )
132 {
133 
134     {
135         ::osl::MutexGuard aGuard( m_aMutex );
136         checkDisposed(OStatement_BASE::rBHelper.bDisposed);
137 
138     }
139     dispose();
140 
141 }
142 
execute()143 sal_Bool SAL_CALL OPreparedStatement::execute(  )
144 {
145     ::osl::MutexGuard aGuard( m_aMutex );
146     checkDisposed(OStatement_BASE::rBHelper.bDisposed);
147 
148     clearWarnings ();
149 
150     // Call SQLExecute
151     try {
152         ADORecordset* pSet=nullptr;
153         CHECK_RETURN(m_Command.Execute(m_RecordsAffected,m_Parameters,adCmdUnknown,&pSet))
154         m_RecordSet.set(pSet);
155     }
156     catch (SQLWarning&)
157     {
158         //TODO: Save pointer to warning and save with ResultSet
159         // object once it is created.
160     }
161     return m_RecordSet.IsValid();
162 }
163 
executeUpdate()164 sal_Int32 SAL_CALL OPreparedStatement::executeUpdate(  )
165 {
166     ::osl::MutexGuard aGuard( m_aMutex );
167     checkDisposed(OStatement_BASE::rBHelper.bDisposed);
168 
169 
170     ADORecordset* pSet=nullptr;
171     CHECK_RETURN(m_Command.Execute(m_RecordsAffected,m_Parameters,adCmdUnknown,&pSet))
172     if ( VT_ERROR == m_RecordsAffected.getType() )
173     {
174         ADOS::ThrowException(m_pConnection->getConnection(),*this);
175         // to be sure that we get the error really thrown
176         throw SQLException();
177     }
178     m_RecordSet.set(pSet);
179     return m_RecordsAffected.getInt32();
180 }
181 
setParameter(sal_Int32 parameterIndex,const DataTypeEnum & _eType,sal_Int32 _nSize,const OLEVariant & Val)182 void OPreparedStatement::setParameter(sal_Int32 parameterIndex, const DataTypeEnum& _eType,
183                                       sal_Int32 _nSize,const OLEVariant& Val)
184 {
185     ::osl::MutexGuard aGuard( m_aMutex );
186     checkDisposed(OStatement_BASE::rBHelper.bDisposed);
187 
188 
189     sal_Int32 nCount = 0;
190     m_pParameters->get_Count(&nCount);
191     if(nCount < (parameterIndex-1))
192     {
193         OUString sDefaultName = "parame" + OUString::number(parameterIndex);
194         ADOParameter* pParam = m_Command.CreateParameter(sDefaultName,_eType,adParamInput,_nSize,Val);
195         if(pParam)
196         {
197             m_pParameters->Append(pParam);
198         }
199     }
200     else
201     {
202         WpADOParameter aParam;
203         m_pParameters->get_Item(OLEVariant(sal_Int32(parameterIndex-1)),&aParam);
204         if(aParam)
205         {
206             DataTypeEnum eType = aParam.GetADOType();
207             if ( _eType != eType && _eType != adDBTimeStamp )
208             {
209                 aParam.put_Type(_eType);
210                 eType = _eType;
211                 aParam.put_Size(_nSize);
212             }
213 
214             if ( adVarBinary == eType && aParam.GetAttributes() == adParamLong )
215             {
216                 aParam.AppendChunk(Val);
217             }
218             else
219                 CHECK_RETURN(aParam.PutValue(Val));
220         }
221     }
222     ADOS::ThrowException(m_pConnection->getConnection(),*this);
223 }
224 
setString(sal_Int32 parameterIndex,const OUString & x)225 void SAL_CALL OPreparedStatement::setString( sal_Int32 parameterIndex, const OUString& x )
226 {
227     setParameter( parameterIndex, adLongVarWChar, std::numeric_limits< sal_Int32 >::max(), x );
228 }
229 
getConnection()230 Reference< XConnection > SAL_CALL OPreparedStatement::getConnection(  )
231 {
232     ::osl::MutexGuard aGuard( m_aMutex );
233     checkDisposed(OStatement_BASE::rBHelper.bDisposed);
234 
235     return static_cast<Reference< XConnection >>(m_pConnection);
236 }
237 
executeQuery()238 Reference< XResultSet > SAL_CALL OPreparedStatement::executeQuery(  )
239 {
240     ::osl::MutexGuard aGuard( m_aMutex );
241     checkDisposed(OStatement_BASE::rBHelper.bDisposed);
242 
243     // first clear the old things
244     m_xMetaData.clear();
245     disposeResultSet();
246     if(m_RecordSet.IsValid())
247         m_RecordSet.Close();
248     m_RecordSet.clear();
249 
250     // then create the new ones
251     m_RecordSet.Create();
252     OLEVariant aCmd;
253     aCmd.setIDispatch(m_Command);
254     OLEVariant aCon;
255     aCon.setNoArg();
256     CHECK_RETURN(m_RecordSet.put_CacheSize(m_nFetchSize))
257     CHECK_RETURN(m_RecordSet.put_MaxRecords(m_nMaxRows))
258     CHECK_RETURN(m_RecordSet.Open(aCmd,aCon,m_eCursorType,m_eLockType,adOpenUnspecified))
259     CHECK_RETURN(m_RecordSet.get_CacheSize(m_nFetchSize))
260     CHECK_RETURN(m_RecordSet.get_MaxRecords(m_nMaxRows))
261     CHECK_RETURN(m_RecordSet.get_CursorType(m_eCursorType))
262     CHECK_RETURN(m_RecordSet.get_LockType(m_eLockType))
263 
264     rtl::Reference<OResultSet> pSet = new OResultSet(m_RecordSet,this);
265     pSet->construct();
266     pSet->setMetaData(getMetaData());
267     m_xResultSet = WeakReference<XResultSet>(pSet);
268 
269     return pSet;
270 }
271 
setBoolean(sal_Int32 parameterIndex,sal_Bool x)272 void SAL_CALL OPreparedStatement::setBoolean( sal_Int32 parameterIndex, sal_Bool x )
273 {
274     setParameter(parameterIndex,adBoolean,sizeof(x),bool(x));
275 }
276 
setByte(sal_Int32 parameterIndex,sal_Int8 x)277 void SAL_CALL OPreparedStatement::setByte( sal_Int32 parameterIndex, sal_Int8 x )
278 {
279     setParameter(parameterIndex,adTinyInt,sizeof(x),x);
280 }
281 
setDate(sal_Int32 parameterIndex,const Date & x)282 void SAL_CALL OPreparedStatement::setDate( sal_Int32 parameterIndex, const Date& x )
283 {
284     setParameter(parameterIndex,adDBDate,sizeof(x),x);
285 }
286 
setTime(sal_Int32 parameterIndex,const css::util::Time & x)287 void SAL_CALL OPreparedStatement::setTime( sal_Int32 parameterIndex, const css::util::Time& x )
288 {
289     setParameter(parameterIndex,adDBTime,sizeof(x),x);
290 }
291 
setTimestamp(sal_Int32 parameterIndex,const DateTime & x)292 void SAL_CALL OPreparedStatement::setTimestamp( sal_Int32 parameterIndex, const DateTime& x )
293 {
294     setParameter(parameterIndex,adDBTimeStamp,sizeof(x),x);
295 }
296 
setDouble(sal_Int32 parameterIndex,double x)297 void SAL_CALL OPreparedStatement::setDouble( sal_Int32 parameterIndex, double x )
298 {
299     setParameter(parameterIndex,adDouble,sizeof(x),x);
300 }
301 
setFloat(sal_Int32 parameterIndex,float x)302 void SAL_CALL OPreparedStatement::setFloat( sal_Int32 parameterIndex, float x )
303 {
304     setParameter(parameterIndex,adSingle,sizeof(x),x);
305 }
306 
setInt(sal_Int32 parameterIndex,sal_Int32 x)307 void SAL_CALL OPreparedStatement::setInt( sal_Int32 parameterIndex, sal_Int32 x )
308 {
309     setParameter(parameterIndex,adInteger,sizeof(x),x);
310 }
311 
setLong(sal_Int32 parameterIndex,sal_Int64 x)312 void SAL_CALL OPreparedStatement::setLong( sal_Int32 parameterIndex, sal_Int64 x )
313 {
314     setParameter(parameterIndex,adBigInt,sizeof(x),x);
315 }
316 
setNull(sal_Int32 parameterIndex,sal_Int32)317 void SAL_CALL OPreparedStatement::setNull( sal_Int32 parameterIndex, sal_Int32 /*sqlType*/ )
318 {
319     OLEVariant aVal;
320     aVal.setNull();
321     setParameter(parameterIndex,adEmpty,0,aVal);
322 }
323 
setClob(sal_Int32,const Reference<XClob> &)324 void SAL_CALL OPreparedStatement::setClob( sal_Int32 /*parameterIndex*/, const Reference< XClob >& /*x*/ )
325 {
326     ::dbtools::throwFeatureNotImplementedSQLException( "XRowUpdate::setClob", *this );
327 }
328 
setBlob(sal_Int32,const Reference<XBlob> &)329 void SAL_CALL OPreparedStatement::setBlob( sal_Int32 /*parameterIndex*/, const Reference< XBlob >& /*x*/ )
330 {
331     ::dbtools::throwFeatureNotImplementedSQLException( "XRowUpdate::setBlob", *this );
332 }
333 
setArray(sal_Int32,const Reference<XArray> &)334 void SAL_CALL OPreparedStatement::setArray( sal_Int32 /*parameterIndex*/, const Reference< XArray >& /*x*/ )
335 {
336     ::dbtools::throwFeatureNotImplementedSQLException( "XRowUpdate::setArray", *this );
337 }
338 
setRef(sal_Int32,const Reference<XRef> &)339 void SAL_CALL OPreparedStatement::setRef( sal_Int32 /*parameterIndex*/, const Reference< XRef >& /*x*/ )
340 {
341     ::dbtools::throwFeatureNotImplementedSQLException( "XRowUpdate::setRef", *this );
342 }
343 
setObjectWithInfo(sal_Int32 parameterIndex,const Any & x,sal_Int32 sqlType,sal_Int32 scale)344 void SAL_CALL OPreparedStatement::setObjectWithInfo( sal_Int32 parameterIndex, const Any& x, sal_Int32 sqlType, sal_Int32 scale )
345 {
346     switch(sqlType)
347     {
348         case DataType::DECIMAL:
349         case DataType::NUMERIC:
350             setString(parameterIndex,::comphelper::getString(x));
351             break;
352         default:
353             ::dbtools::setObjectWithInfo(this,parameterIndex,x,sqlType,scale);
354             break;
355     }
356 }
357 
setObjectNull(sal_Int32 parameterIndex,sal_Int32 sqlType,const OUString &)358 void SAL_CALL OPreparedStatement::setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const OUString& /*typeName*/ )
359 {
360     setNull(parameterIndex,sqlType);
361 }
362 
setObject(sal_Int32 parameterIndex,const Any & x)363 void SAL_CALL OPreparedStatement::setObject( sal_Int32 parameterIndex, const Any& x )
364 {
365     if(!::dbtools::implSetObject(this,parameterIndex,x))
366     {
367         const OUString sError( m_pConnection->getResources().getResourceStringWithSubstitution(
368                 STR_UNKNOWN_PARA_TYPE,
369                 "$position$", OUString::number(parameterIndex)
370              ) );
371         ::dbtools::throwGenericSQLException(sError,*this);
372     }
373 }
374 
setShort(sal_Int32 parameterIndex,sal_Int16 x)375 void SAL_CALL OPreparedStatement::setShort( sal_Int32 parameterIndex, sal_Int16 x )
376 {
377     setParameter(parameterIndex,adSmallInt,sizeof(x),x);
378 }
379 
setBytes(sal_Int32 parameterIndex,const Sequence<sal_Int8> & x)380 void SAL_CALL OPreparedStatement::setBytes( sal_Int32 parameterIndex, const Sequence< sal_Int8 >& x )
381 {
382     setParameter(parameterIndex,adVarBinary,sizeof(sal_Int8)*x.getLength(),x);
383 }
384 
setCharacterStream(sal_Int32,const Reference<css::io::XInputStream> &,sal_Int32)385 void SAL_CALL OPreparedStatement::setCharacterStream( sal_Int32 /*parameterIndex*/, const Reference< css::io::XInputStream >& /*x*/, sal_Int32 /*length*/ )
386 {
387     ::dbtools::throwFeatureNotImplementedSQLException( "XParameters::setCharacterStream", *this );
388 }
389 
setBinaryStream(sal_Int32 parameterIndex,const Reference<css::io::XInputStream> & x,sal_Int32 length)390 void SAL_CALL OPreparedStatement::setBinaryStream( sal_Int32 parameterIndex, const Reference< css::io::XInputStream >& x, sal_Int32 length )
391 {
392     if(x.is())
393     {
394         Sequence< sal_Int8 > aData;
395         x->readBytes(aData,length);
396         setBytes(parameterIndex,aData);
397     }
398 }
399 
clearParameters()400 void SAL_CALL OPreparedStatement::clearParameters(  )
401 {
402     ::osl::MutexGuard aGuard( m_aMutex );
403     checkDisposed(OStatement_BASE::rBHelper.bDisposed);
404 
405 
406     if(m_pParameters)
407     {
408         sal_Int32 nCount = 0;
409         m_pParameters->get_Count(&nCount);
410         OLEVariant aVal;
411         aVal.setEmpty();
412         for(sal_Int32 i=0;i<nCount;++i)
413         {
414             WpADOParameter aParam;
415             m_pParameters->get_Item(OLEVariant(i),&aParam);
416             if(aParam)
417             {
418                 CHECK_RETURN(aParam.PutValue(aVal));
419             }
420         }
421     }
422 }
423 
acquire()424 void SAL_CALL OPreparedStatement::acquire() noexcept
425 {
426     OStatement_Base::acquire();
427 }
428 
release()429 void SAL_CALL OPreparedStatement::release() noexcept
430 {
431     OStatement_Base::release();
432 }
433 
replaceParameterNodeName(OSQLParseNode const * _pNode,const OUString & _sDefaultName,sal_Int32 & _rParameterCount)434 void OPreparedStatement::replaceParameterNodeName(OSQLParseNode const * _pNode,
435                                                   const OUString& _sDefaultName,
436                                                   sal_Int32& _rParameterCount)
437 {
438     sal_Int32 nCount = _pNode->count();
439     for(sal_Int32 i=0;i < nCount;++i)
440     {
441         OSQLParseNode* pChildNode = _pNode->getChild(i);
442         if(SQL_ISRULE(pChildNode,parameter) && pChildNode->count() == 1)
443         {
444             OSQLParseNode* pNewNode = new OSQLParseNode(OUString(":") ,SQLNodeType::Punctuation,0);
445             pChildNode->replaceAndDelete(pChildNode->getChild(0), pNewNode);
446             OUString sParameterName = _sDefaultName + OUString::number(++_rParameterCount);
447             pChildNode->append(new OSQLParseNode( sParameterName,SQLNodeType::Name,0));
448         }
449         else
450             replaceParameterNodeName(pChildNode,_sDefaultName,_rParameterCount);
451 
452     }
453 }
454 
455 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
456