libsl3 1.3.51003
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 * Encapsulates some of the most useful methods for a SQLite3 database
34 * object.
35 * A Database is opened when an instance is created and closed
36 * when the
37 * instance 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:" then the database will be an in-memory
57 *
58 * database.
59 * \n If name has a size of 0 then the database will be a private on-disk
60
61 * * database.
62 * \n Otherwise name will be interpreted as a file.
63 *
64 * \param openFlags if no flags are given, the defaults are
65 * SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE.
66 *
67 * \sa https://www.sqlite.org/c3ref/open.html
68 *
69 * \throw sl3::SQLite3Error if the database can not be opened
70 */
71 explicit Database (const std::string& name, int openFlags = 0);
72
73 /**
74 * \brief Destructor.
75 */
76 virtual ~Database () noexcept;
77
78 /**
79 * \brief Move constructor
80 *
81 * A Database is movable
82 */
83 Database (Database&&) noexcept;
84
85 /**
86 * \brief Create an SQL command instance.
87 *
88 * Parameters that the statement might contain will be automatically
89 * deduced and created as DbVariant values
90 *
91 * \param sql SQL statement
92 * \return a Command instance
93 */
94 Command prepare (const std::string& sql);
95
96 /**
97 * \brief Create a Command.
98 *
99 * Given parameters will be used to set up the command parameters,
100 *
101 * \param sql SQL statement
102 * \param params parameters
103 *
104 * \throw sl3::ErrTypeMisMatch if params count is wrong
105 * \return a Command instance
106 */
107 Command prepare (const std::string& sql, const DbValues& params);
108
109 /**
110 * \brief Execute one or more SQL statements.
111 *
112 * \throw sl3::SQLite3Error in case of a problem.
113 *
114 * \param sql SQL Statements
115 */
116 void execute (const std::string& sql);
117
118 /**
119 * \brief Execute one or more SQL statements.
120 *
121 * Overload for const char* to avoid a copy for large commands like
122 *
123 * create-database scripts, which are often static char*.
124 *
125 * \throw sl3::SQLite3Error in case of a problem.
126 *
127 * \param sql SQL Statements
128 */
129 void execute (const char* sql);
130
131 /**
132 * \brief Execute one SQL statement and apply a SqlQueryHandler.
133 *
134 * \throw sl3::SQLite3Error in case of a problem.
135 *
136 * \param sql SQL Statements
137 * \param cb RowCallback to handle query result
138 */
139 void execute (const std::string& sql, RowCallback& cb);
140
141 /// shortcut for Command::Callback
143
144 /**
145 * \brief Execute one SQL statement and apply a QueryCallback.
146 *
147 * \throw sl3::SQLite3Error in case of a problem.
148 *
149 * \param sql SQL Statements
150 * \param cb Callback to handle query result
151 */
152 void execute (const std::string& sql, Callback cb);
153
154 /**
155 * \brief Execute a SQL query and return the result.
156 *
157 * \throw sl3::SQLite3Error in case of a problem.
158 *
159 * \param sql SQL Statements
160 * \return a Dataset with the result.
161 */
162 Dataset select (const std::string& sql);
163
164 /**
165 * \brief Execute a SQL query and return the result.
166 *
167 * If Types are
168 *
169 * \throw sl3::SQLite3Error in case of problems.
170 * \throw
171 * sl3::ErrTypeMisMatch in case of incorrect types.
172 *
173 * \param sql SQL Statements
174 * \param types wanted types of the returned Dataset
175 * \return a Dataset with the result.
176 */
177 Dataset select (const std::string& sql, const Types& types);
178
179 /**
180 * \brief Select a single value from the database.
181 *
182 * This is a quick way to get single value results for queries like
183 * "SELECT COUNT(*) FROM someTable;" \n
184 *
185 * This function returns the first column of the first result row of the
186 * given query.
187 * If query returns no rows, the return value will be null.
188 *
189 * \throw sl3::SQLite3Error in case of problems.
190 *
191 * \param sql SQL statement
192 * \return DbValue of the first available result.
193 */
194 DbValue selectValue (const std::string& sql);
195
196 /**
197 * \brief Select a single typed value from the database.
198 *
199 * This is a quick way to get single value results for queries like
200 * "SELECT COUNT(*) FROM someTable;" \n
201 *
202 * This function returns the first column of the first result row of the
203 * given query.
204 * If query returns no rows, the return value will be null.
205 *
206 * \throw sl3::ErrTypeMisMatch if return type differs from requested type
207 * \throw sl3::SQLite3Error in case of problems.
208 * \param sql SQL
209 * statement
210 * \param type result has to be of that Type
211 *
212 * \return DbValue of the first available result.
213 */
214 DbValue selectValue (const std::string& sql, Type type);
215
216 /**
217 * \brief Returns last SQLite3 extended result code
218 *
219 * \note SQLite3 result code in case of a failure is triggered within a
220 * SQLite3Error.
221 *
222 * The return value is only valid if the last call failed.
223 *
224 * \note This function returns extended result codes
225 *
226 * \return SQLite3 extended error code
227 */
229
230 /**
231 * \brief Returns most recent error message.
232 *
233 *
234 * \return SQLite3 error message.
235 */
237
238 /**
239 * \brief Returns the number of rows that have changed since the database
240 * was opened.
241 *
242 * Returns the number of rows that have been changed
243 * through successful SQL INSERT/UPDATE or DELETE statements since the
244 * database was opened.
245 *
246 * \return Count of changed rows
247 */
249
250 /**
251 * \brief Rows that have been changed from the most recent SQL statement.
252 *
253 * Returns the number of rows that have been changed from the most recent
254 * successful SQL INSERT/UPDATE or DELETE statement.
255 *
256 * \return Count of changed rows
257 */
259
260 /**
261 * \brief Returns the rowid of the most recent successful INSERT statement
262 *
263 * Returns the rowid (ROWID, OID, or _ROWID_ or the column of
264 * type INTEGER PRIMARY KEY )
265 * of the most recent successful INSERT into the database.
266 * \n If no successful INSERTs have ever occurred on that database,
267 * zero is returned.
268 *
269 * \return rowid
270 */
272
273 /**
274 * \brief Transaction Guard
275 *
276 * Scope guard for transaction.
277 * If an instance of this class goes out of scope and commit has
278 * not been called, it will call Rollback.
279 */
280 class Transaction
281 {
282 sl3::Database* _db;
283
284 explicit Transaction (Database&);
285 friend class Database;
286
287 public:
288 Transaction (const Transaction&) = delete;
289 Transaction& operator= (const Transaction&) = delete;
290 Transaction& operator= (Transaction&&) = delete;
291
292 /** \brief Move constructor
293 * A Transaction is movable.
294 */
295 Transaction (Transaction&&) noexcept;
296
297 /** \brief Destructor
298 *
299 * Calls ROLLBACK if the Transaction commit has not been called.
300 */
301 ~Transaction ();
302
303 /** \brief Commit the transaction
304 *
305 * Calls commit transaction.
306 */
307 void commit ();
308 };
309
310 /**
311 * \brief Create a TransactionGuard
312 * \return Transaction instance
313 */
315
316 protected:
317 /**
318 * \brief Access the underlying sqlite3 database.
319 *
320 * Derived classes may, if needed, access the pointer to
321 * the sqlite3 database.
322 *
323 * \note: Do not change the state of database (call close on it).
324 *
325 * \return a handle to the underlying sqlite3 database;
326 */
327 sqlite3* db ();
328
329 private:
330 /**
331 * \brief Define internal::Connection type.
332 *
333 * Only internal used
334 *
335 * This uses a shared_ptr.
336 * libsl3 allows a sl3::Database to go out of scope,
337 * but keep a
338 * sl3::Command instance. The Command instance is still connected, and the
339 * underlying sqlite3 connection will be closed when the last Command
340 * instance is destroyed.
341 *
342 */
343 using ConnectionPtr = std::shared_ptr<internal::Connection>;
344
345 /**
346 * \brief Shared pointer for internal::Connection.
347 *
348 * Only internal used. A connection is shared with Command instances.
349 *
350 * If a database closes, the connection closes.
351 * A Command knows about that and will throw an exception if used
352 * after closing the database.
353 */
354 ConnectionPtr _connection;
355 };
356
357 /**
358 * \brief Wraps sqlite3_errstr() function
359 *
360 * The sqlite3_errstr() interface returns the English-language text
361 * that describes the result code, as UTF
362 * \param errcode err number
363 * \return Count of changed rows
364 */
365 std::string getErrStr (int errcode);
366
367}
368
369#endif /* ...DATABASE_HPP_ */
A compiled SQL command.
Definition command.hpp:40
Transaction Guard.
Definition database.hpp:281
void commit()
Commit the transaction.
Transaction(Transaction &&) noexcept
Move constructor A Transaction is movable.
Represents a SQLite3 database.
Definition database.hpp:43
Dataset select(const std::string &sql)
Execute a SQL query and return the result.
std::string getMostRecentErrMsg()
Returns most recent error message.
virtual ~Database() noexcept
Destructor.
Transaction beginTransaction()
Create a TransactionGuard.
int getMostRecentErrCode()
Returns last SQLite3 extended result code.
sqlite3 * db()
Access the underlying sqlite3 database.
std::size_t getTotalChanges()
Returns the number of rows that have changed since the database was opened.
std::size_t getRecentlyChanged()
Rows that have been changed from the most recent SQL statement.
int64_t getLastInsertRowid()
Returns the rowid of the most recent successful INSERT statement.
Command::Callback Callback
shortcut for Command::Callback
Definition database.hpp:142
DbValue selectValue(const std::string &sql)
Select a single value from the database.
Database(const std::string &name, int openFlags=0)
Constructor.
void execute(const std::string &sql)
Execute one or more SQL statements.
Command prepare(const std::string &sql)
Create an SQL command instance.
A utility for processing query results.
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:63
Namespace of libSL3.
Definition columns.hpp:18
std::string getErrStr(int errcode)
Wraps sqlite3_errstr() function.
Type
Definition types.hpp:30
STL namespace.