1 /* This file is part of the KDE project
2    Copyright (C) 2005-2016 Jarosław Staniek <staniek@kde.org>
3 
4    This library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Library General Public
6    License as published by the Free Software Foundation; either
7    version 2 of the License, or (at your option) any later version.
8 
9    This library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Library General Public License for more details.
13 
14    You should have received a copy of the GNU Library General Public License
15    along with this library; see the file COPYING.LIB.  If not, write to
16    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18 */
19 
20 #ifndef KDB_PREPAREDSTATEMENT_H
21 #define KDB_PREPAREDSTATEMENT_H
22 
23 #include <QVariant>
24 #include <QStringList>
25 #include <QSharedData>
26 
27 #include "KDbField.h"
28 #include "KDbResult.h"
29 
30 class KDbFieldList;
31 class KDbPreparedStatementInterface;
32 
33 //! Prepared statement paraneters used in KDbPreparedStatement::execute()
34 typedef QList<QVariant> KDbPreparedStatementParameters;
35 
36 /*! @short Prepared database command for optimizing sequences of multiple database actions
37 
38   Currently INSERT and SELECT statements are supported.
39   For example when using KDbPreparedStatement for INSERTs,
40   you can gain about 30% speedup compared to using multiple
41   connection.insertRecord(*tabelSchema, dbRecordBuffer).
42 
43   To use KDbPreparedStatement, create is using KDbConnection:prepareStatement(),
44   providing table schema; set up parameters using operator << ( const QVariant& value );
45   and call execute() when ready. KDbPreparedStatement objects are accessed
46   using KDE shared pointers, i.e KDbPreparedStatement, so you do not need
47   to remember about destroying them. However, when underlying KDbConnection object
48   is destroyed, KDbPreparedStatement should not be used.
49 
50   Let's assume tableSchema contains two columns NUMBER integer and TEXT text.
51   Following code inserts 10000 records with random numbers and text strings
52   obtained elsewhere using getText(i).
53   @code
54   bool insertMultiple(KDbConnection* conn, KDbTableSchema* tableSchema)
55   {
56     KDbPreparedStatement statement = conn->prepareStatement(
57       KDbPreparedStatement::Insert, tableSchema);
58     for (i=0; i<10000; i++) {
59       KDbPreparedStatementParameters parameters;
60       parameters << qrand() << getText(i);
61       if (!statement.execute(parameters))
62         return false;
63     }
64     return true;
65   }
66   @endcode
67 
68   If you do not call clearParameters() after every insert, you can insert
69   the same value multiple times using execute() what increases efficiency even more.
70 
71   Another use case is inserting large objects (BLOBs or CLOBs).
72   Depending on database backend, you can avoid escaping BLOBs.
73   See KexiFormView::storeData() for example use.
74 */
75 class KDB_EXPORT KDbPreparedStatement : public KDbResultable
76 {
77 public:
78 
79     //! Defines type of the prepared statement.
80     enum Type {
81         InvalidStatement, //!< Used only in invalid statements
82         SelectStatement,  //!< SELECT statement will be prepared end executed
83         InsertStatement   //!< INSERT statement will be prepared end executed
84     };
85 
86     //! @internal
87     class KDB_EXPORT Data : public QSharedData {
88     public:
89         Data();
90         Data(Type _type, KDbPreparedStatementInterface* _iface, KDbFieldList* _fields,
91              const QStringList& _whereFieldNames);
92         ~Data();
93         Type type;
94         KDbFieldList *fields;
95         QStringList whereFieldNames;
96         const KDbField::List* fieldsForParameters; //!< fields where we'll put the inserted parameters
97         KDbField::List* whereFields; //!< temporary, used for select statements, based on whereFieldNames
98         bool dirty; //!< true if the statement has to be internally
99                     //!< prepared (possible again) before calling executeInternal()
100         KDbPreparedStatementInterface *iface;
101         quint64 lastInsertRecordId;
102     };
103 
104     //! Creates an invalid prepared statement.
105     KDbPreparedStatement();
106 
107     ~KDbPreparedStatement() override;
108 
109     bool isValid() const;
110 
111     KDbPreparedStatement::Type type() const;
112 
113     void setType(KDbPreparedStatement::Type type);
114 
115     const KDbFieldList* fields() const;
116 
117     //! Sets fields for the statement. Does nothing if @a fields is @c nullptr.
118     void setFields(KDbFieldList* fields);
119 
120     QStringList whereFieldNames() const;
121 
122     void setWhereFieldNames(const QStringList& whereFieldNames);
123 
124     /*! Executes the prepared statement using @a parameters parameters.
125      A number parameters set up for the statement must be the same as a number of fields
126      defined in the underlying database table.
127      @return false on failure. Detailed error status can be obtained
128      from KDbConnection object that was used to create this statement object. */
129     bool execute(const KDbPreparedStatementParameters& parameters);
130 
131     /*! @return unique identifier of the most recently inserted record.
132      Typically this is just primary key value. This identifier could be reused when we want
133      to reference just inserted record. If there was no insertion recently performed,
134      std::numeric_limits<quint64>::max() is returned. */
135     quint64 lastInsertRecordId() const;
136 
137 protected:
138     //! Creates a new prepared statement. In your code use
139     //! Users call KDbConnection:prepareStatement() instead.
140     KDbPreparedStatement(KDbPreparedStatementInterface* iface, Type type,
141                          KDbFieldList* fields,
142                          const QStringList& whereFieldNames = QStringList());
143 
144     friend class KDbConnection;
145 
146 private:
147 //! @todo is this portable across backends?
148     bool generateStatementString(KDbEscapedString* s);
149     bool generateSelectStatementString(KDbEscapedString * s);
150     bool generateInsertStatementString(KDbEscapedString * s);
151 
152     QSharedDataPointer<Data> d;
153 };
154 
155 #endif
156