libsl3 1.2.41002
A C++ interface for SQLite
Loading...
Searching...
No Matches
database.hpp
1/******************************************************************************
2 ------------- Copyright (c) 2009-2023 H a r a l d A c h i t z ---------------
3 ---------- < h a r a l d dot a c h i t z at g m a i l dot c o m > ------------
4 ---- This Source Code Form is subject to the terms of the Mozilla Public -----
5 ---- License, v. 2.0. If a copy of the MPL was not distributed with this -----
6 ---------- file, You can obtain one at http://mozilla.org/MPL/2.0/. ----------
7 ******************************************************************************/
8
9#ifndef SL3_DATABASE_HPP_
10#define SL3_DATABASE_HPP_
11
12#include <memory>
13#include <string>
14
15#include <sl3/command.hpp>
16#include <sl3/config.hpp>
17#include <sl3/dataset.hpp>
18#include <sl3/dbvalue.hpp>
19
20struct sqlite3;
21
22namespace sl3
23{
24 namespace internal
25 {
26 class Connection;
27 }
28
29 /**
30 * \brief represents a SQLite3 Database
31 *
32 *
33 * Encapsulate some/the most - useful methods for a SQLite3 database object.
34 *
35 * A Database is opened when a instance is created and close when the
36 * instance
37 * goes out of scope.
38 *
39 * \note for valgrind: http://www.sqlite.org/cvstrac/tktview?tn=3428 \n
40 * since I don't know where to put this note else I place it just here
41 */
42 class LIBSL3_API Database
43 {
44 public:
45 Database (const Database&) = delete;
46 Database& operator= (const Database&) = delete;
47 Database& operator= (Database&&) = delete;
48
49 /**
50 * \brief Constructor
51 *
52 * Construction of this object opens, or creates a sqlite3 database.
53 * The exact behavior can be fine tuned using the openFlags parameter.
54 *
55 * \param name database name.
56 * \n If name is ":memory:" than the database will be an in memory
57 * database.
58 * \n If name has a size of 0 than the database will be private on disk
59 * database.
60 * \n Otherwise name will be interpreted as a file.
61 *
62 * \param openFlags if no flags are given, the defaults are
63 * SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE.
64 *
65 * \sa https://www.sqlite.org/c3ref/open.html
66 *
67 * \throw sl3::SQLite3Error if the database can not be opened
68 */
69 explicit Database (const std::string& name, int openFlags = 0);
70
71 /**
72 * \brief Destructor.
73 */
74 virtual ~Database () noexcept;
75
76 /**
77 * \brief Move constructor
78 *
79 * A Database is movable
80 */
81 Database (Database&&) noexcept;
82
83 /**
84 * \brief create a SqlCommand instance.
85 *
86 * Parameters that the statement might contain will be automatically
87 * deduced and created as DbVaraint values
88 *
89 * \param sql SQL statement
90 * \return a Command instance
91 */
92 Command prepare (const std::string& sql);
93
94 /**
95 * \brief create a Command.
96 *
97 * Given parameters will be used to set up the command parameters,
98 *
99 * \param sql SQL statement
100 * \param params parameters
101 *
102 * \throw sl3::ErrTypeMisMatch if params count is wrong
103 * \return a Command instance
104 */
105 Command prepare (const std::string& sql, const DbValues& params);
106
107 /**
108 * \brief Execute one or more SQL statements.
109 *
110 * \throw sl3::SQLite3Error in case of a problem.
111 *
112 * \param sql SQL Statements
113 */
114 void execute (const std::string& sql);
115
116 /**
117 * \brief Execute one or more SQL statements.
118 *
119 * Overload for const char to avoid a copy for larg command like
120 * create database scripts which are often static char*
121 *
122 * \throw sl3::SQLite3Error in case of a problem.
123 *
124 * \param sql SQL Statements
125 */
126 void execute (const char* sql);
127
128 /**
129 * \brief Execute one SQL statements and apply a SqlQueryHandler.
130 *
131 * \throw sl3::SQLite3Error in case of a problem.
132 *
133 * \param sql SQL Statements
134 * \param cb RowCallback to handle query result
135 */
136 void execute (const std::string& sql, RowCallback& cb);
137
138 /// shortcut for Command::Callback
140
141 /**
142 * \brief Execute one SQL statements and apply a QueryCallback.
143 *
144 * \throw sl3::SQLite3Error in case of a problem.
145 *
146 * \param sql SQL Statements
147 * \param cb Callback to handle query result
148 */
149 void execute (const std::string& sql, Callback cb);
150
151 /**
152 * \brief Execute a SQL query and return the result.
153 *
154 * \throw sl3::SQLite3Error in case of a problem.
155 *
156 * \param sql SQL Statements
157 * \return a Dataset with the result.
158 */
159 Dataset select (const std::string& sql);
160
161 /**
162 * \brief Execute a SQL query and returns the result .
163 *
164 * If Types are
165 *
166 * \throw sl3::SQLite3Error in case of a problems.
167 * \throw sl3::ErrTypeMisMatch in case of incorrect types.
168 *
169 * \param sql SQL Statements
170 * \param types wanted types of the returned Dataset
171 * \return a Dataset with the result.
172 */
173 Dataset select (const std::string& sql, const Types& types);
174
175 /**
176 * \brief Select a single value form the database.
177 *
178 * This is a quick way to get single value results for queries like
179 * "SELECT COUNT(*) FROM someTable;" \n
180 *
181 * This function returns the first column of the first result row of the
182 * given query.
183 * If query returns no rows, the return value will be null.
184 *
185 * \throw sl3::SQLite3Error in case of a problems.
186 *
187 * \param sql SQL statement
188 * \return DbValue of the first available result.
189 */
190 DbValue selectValue (const std::string& sql);
191
192 /**
193 * \brief select a single typed value form the database.
194 *
195 * This is a quick way to get single value results for queries like
196 * "SELECT COUNT(*) FROM someTable;" \n
197 *
198 * This function returns the first column of the first result row of the
199 * given query.
200 * If query returns no rows, the return value will be null.
201 *
202 * \throw sl3::ErrTypeMisMatch if return type differs from requested type
203 * \throw sl3::SQLite3Error in case of a problems.
204 * \param sql SQL statement
205 * \param type result has to be of that Type
206 *
207 * \return DbValue of the first available result.
208 */
209 DbValue selectValue (const std::string& sql, Type type);
210
211 /**
212 * \brief Returns last SQLite3 extended result code
213 *
214 * \note SQLite3 result code in case of a failure is triggered within a
215 * SQLite3Error.
216 *
217 * The return value is only valid if the last call failed.
218 *
219 * \note This function returns extended result codes
220 *
221 * \return SQLite3 extended error code
222 */
223 int getMostRecentErrCode ();
224
225 /**
226 * \brief Returns most recent error message.
227 *
228 *
229 * \return SQLite3 error message.
230 */
231 std::string getMostRecentErrMsg ();
232
233 /**
234 * \brief Returns number of row that have changed since database opening.
235 *
236 * Returns the number of rows that have been changed
237 * Through successful SQL INSERT/UPDATE or DELETE statements since database
238 * was opened.
239 *
240 * \return Count of changed rows
241 */
242 std::size_t getTotalChanges ();
243
244 /**
245 * \brief Rows that have been changed from the most recent SQL statement.
246 *
247 * Returns the number of rows that have been changed from the most recent
248 * successful SQL INSERT/UPDATE or DELETE statement.
249 *
250 * \return Count of changed rows
251 */
252 std::size_t getRecentlyChanged ();
253
254 /**
255 * \brief returns rowid of the most recent successful INSERT statement
256 *
257 * Returns the rowid (ROWID, OID, or _ROWID_ or the column of
258 * type INTEGER PRIMARY KEY )
259 * of the most recent successful INSERT into the database.
260 * \n If no successful INSERTs have ever occurred on that database,
261 * zero is returned.
262 *
263 * \return rowid
264 */
265 int64_t getLastInsertRowid ();
266
267 /**
268 * \brief Transaction Guard
269 *
270 * Scope guard for transaction.
271 * If an instance of this class goes out of scope and commit has
272 * not been called, it will call Rollback.
273 */
275 {
276 sl3::Database* _db;
277
278 explicit Transaction (Database&);
279 friend class Database;
280
281 public:
282 Transaction (const Transaction&) = delete;
283 Transaction& operator= (const Transaction&) = delete;
284 Transaction& operator= (Transaction&&) = delete;
285
286 /** \brief Move constructor
287 * A Transaction is movalble.
288 */
290
291 /** \brief Destructor
292 *
293 * Calls ROLLBACK if the Transaction commit has not been called.
294 */
296
297 /** \brief Commit the transaction
298 *
299 * Calls commit transaction.
300 */
301 void commit ();
302 };
303
304 /**
305 * \brief Create a TransactionGuard
306 * \return Transaction instance
307 */
308 Transaction beginTransaction ();
309
310 protected:
311 /**
312 * \brief Access the underlying sqlite3 database.
313 *
314 * Derived classes may, if needed, access the pointer to
315 * the sqlite3 database.
316 *
317 * \note: Do not change the state of database (call close on it).
318 *
319 * \return a handle to the underlying sqlite3 database;
320 */
321 sqlite3* db ();
322
323 private:
324 /**
325 * \brief Define internal::Connection type.
326 *
327 * Only internal used
328 *
329 * This uses a shared_ptr.
330 * libsl3 allows a sl3::Database do go out of scope,
331 * but keep a sl3::Command instance.
332 * The Command instance is still connected, and the underlying sqlite3
333 * connection will be closed when the last Command instance is destroyed.
334 *
335 */
336 using ConnectionPtr = std::shared_ptr<internal::Connection>;
337
338 /**
339 * \brief Shared pointer for internal::Connection.
340 *
341 * Only internal used. A connection is shared with Command instances.
342 *
343 * If a database closes, the connection closes.
344 * A Command knows about that and will throw an exception if used
345 * after closing the database.
346 */
347 ConnectionPtr _connection;
348 };
349
350 /**
351 * \brief Wraps sqlite3_errstr() function
352 *
353 * The sqlite3_errstr() interface returns the English-language text
354 * that describes the result code, as UTF
355 * \param errcode err number
356 * \return Count of changed rows
357 */
358 std::string getErrStr (int errcode);
359
360}
361
362#endif /* ...DATABASE_HPP_ */
A compiled SQL command.
Definition: command.hpp:40
Transaction Guard.
Definition: database.hpp:275
Transaction(Transaction &&) noexcept
Move constructor A Transaction is movalble.
represents a SQLite3 Database
Definition: database.hpp:43
virtual ~Database() noexcept
Destructor.
Command::Callback Callback
shortcut for Command::Callback
Definition: database.hpp:139
Database(const std::string &name, int openFlags=0)
Constructor.
A utility for processing the result queries.
Definition: dataset.hpp:48
This class models the duck typing sqlite uses. It supports int, real, text, blob and null values.
Definition: dbvalue.hpp:43
A row of DbValues.
Definition: dbvalues.hpp:30
Callback for SQL Select statements.
Definition: rowcallback.hpp:30
A Container holding sl3::Type values.
Definition: types.hpp:62
Namespace of libSL3.
Definition: columns.hpp:18
Type
Definition: types.hpp:30
STL namespace.