C++ binding for the SQLite library https://code.ireas.org/sqlitepp/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sqlitepp.h 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. // Copyright (C) 2014--2015 Robin Krahl <robin.krahl@ireas.org>
  2. // MIT license -- http://opensource.org/licenses/MIT
  3. #ifndef SQLITEPP_SQLITEPP_H_
  4. #define SQLITEPP_SQLITEPP_H_
  5. #include <sqlite3.h>
  6. #include <stdexcept>
  7. #include <memory>
  8. #include <string>
  9. /// \file
  10. /// \brief Defines all classes of the sqlitepp library in the namespace
  11. /// sqlitepp.
  12. /// \mainpage sqlitepp -- C++ wrapper for SQLite3
  13. /// **sqlitepp** is a C++ wrapper for the official SQLite3 C API.
  14. ///
  15. /// \section compile Compiling sqlitepp
  16. /// sqlitepp uses CMake as a build tool. To build sqlitepp from source,
  17. /// download the source from GitHub and then execute these commands:
  18. /// \code
  19. /// $ mkdir bin && cd bin
  20. /// $ cmake .. && make
  21. /// \endcode
  22. ///
  23. /// \section using Using sqlitepp
  24. ///
  25. /// \subsection connect Connecting to a database
  26. /// To connect to a SQLite database, you just have to create a new
  27. /// sqlitepp::Database object.
  28. /// \code{.cpp}
  29. /// sqlitepp::Database database("/path/to/database.sqlite");
  30. /// \endcode
  31. /// This snippet is equivalent to:
  32. /// \code{.cpp}
  33. /// sqlitepp::Database database;
  34. /// database.open("/path/to/database.sqlite");
  35. /// \endcode
  36. /// If the database file does not already exist, it is created. If an error
  37. /// occurs during the creation of the database, a sqlitepp::DatabaseError
  38. /// is thrown.
  39. ///
  40. /// \subsection execute Executing a simple statement
  41. /// To execute a simple statement, use sqlitepp::Database::execute:
  42. /// \code{.cpp}
  43. /// sqlitepp::Database database("/path/to/database.sqlite");
  44. /// database.execute("CREATE TABLE test (id, value);");
  45. /// \endcode
  46. ///
  47. /// \subsection prepare Executing complex statements
  48. /// If you want to execute more complex statements, for example selection or
  49. /// insertion, use prepared statements. You can prepare a statement using
  50. /// sqlitepp::Database::prepare. You can then bind values (if necessary) using
  51. /// the `bind` methods of sqlitepp::Statement and execute the statement using
  52. /// sqlitepp::Statement::execute. `execute` returns a sqlitepp::ResultSet that
  53. /// stores the returned values (if any).
  54. ///
  55. /// \subsubsection insert Example 1: insert
  56. /// The recommended way to handle insertions are named bindings:
  57. /// \code{.cpp}
  58. /// sqlitepp::Database database("/path/to/database.sqlite");
  59. /// std::shared_ptr<sqlitepp::Statement> statement = database.prepare(
  60. /// "INSERT INTO test (id, value) VALUES (:id, :value);");
  61. ///
  62. /// // insert (1, "test value")
  63. /// statement->bind(":id", 1);
  64. /// statement->bind(":value", "test value");
  65. /// statement->execute();
  66. /// statement->reset();
  67. ///
  68. /// // insert (2, "other value")
  69. /// statement->bind(":id", 2);
  70. /// statement->bind(":value", "other value");
  71. /// statement->execute();
  72. /// \endcode
  73. ///
  74. /// \subsubsection select Example 2: select
  75. /// \code{.cpp}
  76. /// sqlitepp::Database database("/path/to/database.sqlite");
  77. /// std::shared_ptr<sqlitepp::Statement> statement = database.prepare(
  78. /// "SELECT id, value FROM test;");
  79. /// ResultSet resultSet = statement.execute();
  80. /// while (resultSet.canRead()) {
  81. /// std::cout << "ID: " << resultSet.readInt(0) << "\tvalue: "
  82. /// << resultSet.readString(1) << std::endl;
  83. /// resultSet.next();
  84. /// }
  85. /// \endcode
  86. ///
  87. /// \section concepts Concepts
  88. /// \subsection error Error handling
  89. /// If an error occurs during an operation, an exception is thrown. All
  90. /// SQLite3 database errors are wrapped in sqlitepp::DatabaseError. If a
  91. /// method returns, it was successful (if not stated otherwise in the method
  92. /// documentation).
  93. ///
  94. /// \subsection resources Resources
  95. /// sqlitepp uses RAII. This means that the destructors of sqlitepp::Database
  96. /// and sqlitepp::Statement take care of freeing their resources once they
  97. /// are destroyed. You can force them to free their resources using the
  98. /// `close` methods.
  99. /// \brief Contains all classes of the sqlitepp library.
  100. namespace sqlitepp {
  101. /// \brief A class that forbids copying and assignments for all subclasses.
  102. ///
  103. /// This class defines a private, unimplemented copy constructor and assignment
  104. /// method so that copies and assignments fail at compile-time. This class is
  105. /// inspired by Scott Meyers, <em>Effective C++</em>, 3rd Edition, Item 6.
  106. class Uncopyable {
  107. protected:
  108. Uncopyable() {}
  109. ~Uncopyable() {}
  110. private:
  111. Uncopyable(const Uncopyable&);
  112. Uncopyable& operator=(const Uncopyable&);
  113. };
  114. /// \brief An element that has the two states *open* and *closed*.
  115. ///
  116. /// Subclasses of this class may define methods that require the object to be
  117. /// in a specific state. Refer to the implementing class&rsquo;s documentation
  118. /// for more information about the methods that require a specific state.
  119. ///
  120. /// The default state depends on the implementation. You can check the state of
  121. /// an object using the isOpen() method.
  122. ///
  123. /// Implementing classes may use setOpen() to change the state and
  124. /// requireOpen() to throw a std::logic_error if the object is currently not
  125. /// open.
  126. class Openable {
  127. public:
  128. /// \brief Checks whether this object is open.
  129. ///
  130. /// \returns `true` if this object is open; `false` if it is closed
  131. bool isOpen() const;
  132. protected:
  133. /// \brief Creates a new Openable.
  134. ///
  135. /// \param open `true` if the objet should be open per default; `false` if
  136. /// it shoukd be closed per defaut
  137. /// \param name the name of the implementing class used in error messages
  138. Openable(const bool open, const std::string& name);
  139. /// \brief Requires this object to be open and throws an exception if it is
  140. /// not.
  141. ///
  142. /// This method should be used at the beginning of other subclass methods
  143. /// that require this object to be open. The error message of the exception
  144. /// will contain the class name passed to the constructor.
  145. ///
  146. /// \throws std::logic_error if this object is not open
  147. void requireOpen() const;
  148. /// \brief Changes the state of this object.
  149. ///
  150. /// \param open the new state of this object (`true` if it should be opened;
  151. /// `false` if it should be closed)
  152. void setOpen(const bool open);
  153. private:
  154. bool m_open;
  155. const std::string& m_name;
  156. };
  157. /// \brief An error that occurred during a database operation.
  158. ///
  159. /// This error class is only used for errors that occured in the SQLite3
  160. /// library and that are related to database operations. If there are other
  161. /// problems, for example wrong states or illegal arguments, appropriate other
  162. /// exceptions are thrown.
  163. ///
  164. /// This exception class stores the SQLite3 error code and the error message.
  165. ///
  166. /// \sa [SQLite Result Codes](https://www.sqlite.org/c3ref/c_abort.html)
  167. class DatabaseError : public std::runtime_error {
  168. public:
  169. /// \brief Creates a new DatabaseError with the given code and the default
  170. /// message.
  171. ///
  172. /// The message is retrieved from the default SQLite3 error messages.
  173. ///
  174. /// \param errorCode the SQLite3 error code
  175. /// \sa [SQLite Result Codes](https://www.sqlite.org/c3ref/c_abort.html)
  176. explicit DatabaseError(const int errorCode);
  177. /// \brief Creates a new DatabaseError with the given code and message.
  178. ///
  179. /// \param errorCode the SQLite3 error code
  180. /// \param errorMessage the according error message
  181. /// \sa [SQLite Result Codes](https://www.sqlite.org/c3ref/c_abort.html)
  182. DatabaseError(const int errorCode, const std::string& errorMessage);
  183. /// \brief Returns the SQLite3 error code for this error.
  184. ///
  185. /// \sa [SQLite Result Codes](https://www.sqlite.org/c3ref/c_abort.html)
  186. int errorCode() const;
  187. private:
  188. const int m_errorCode;
  189. static std::string getErrorMessage(const int errorCode,
  190. const std::string& errorMessage);
  191. };
  192. class Database;
  193. class ResultSet;
  194. /// \brief A handle for a SQLite3 statement.
  195. ///
  196. /// This class stores a reference to a prepared SQLite3 statement and provides
  197. /// methods to bind parameters to the query, execute it and read the results.
  198. /// If a database operation fails, a DatabaseError is thrown.
  199. ///
  200. /// Use Database::prepare to obtain instances of this class.
  201. class Statement : private Uncopyable, public Openable {
  202. public:
  203. /// \brief Deconstructs this object and finalizes the statement.
  204. ///
  205. /// Errors that occur when the statement is finalized are ignored as they
  206. /// already occured during the last operation.
  207. ~Statement();
  208. /// \brief Binds the given double value to the column with the given index.
  209. ///
  210. /// \param index the index of the column to bind the value to
  211. /// \param value the value to bind to that column
  212. /// \throws std::logic_error if the statement is not open
  213. /// \throws std::out_of_range if the given index is out of range
  214. /// \throws std::runtime_error if there is not enough memory to bind the
  215. /// value
  216. /// \throws DatabaseError if an database error occured during the binding
  217. void bind(const int index, const double value);
  218. /// \brief Binds the given double value to the column with the given name.
  219. ///
  220. /// \param index the name of the column to bind the value to
  221. /// \param value the value to bind to that column
  222. /// \throws std::logic_error if the statement is not open
  223. /// \throws std::invalid_argument if there is no column witht the given name
  224. /// \throws std::runtime_error if there is not enough memory to bind the
  225. /// value
  226. /// \throws DatabaseError if an database error occured during the binding
  227. void bind(const std::string& name, const double value);
  228. /// \brief Binds the given integer value to the column with the given index.
  229. ///
  230. /// \param index the index of the column to bind the value to
  231. /// \param value the value to bind to that column
  232. /// \throws std::logic_error if the statement is not open
  233. /// \throws std::out_of_range if the given index is out of range
  234. /// \throws std::runtime_error if there is not enough memory to bind the
  235. /// value
  236. /// \throws DatabaseError if an database error occured during the binding
  237. void bind(const int index, const int value);
  238. /// \brief Binds the given integer value to the column with the given name.
  239. ///
  240. /// \param index the name of the column to bind the value to
  241. /// \param value the value to bind to that column
  242. /// \throws std::logic_error if the statement is not open
  243. /// \throws std::invalid_argument if there is no column witht the given name
  244. /// \throws std::runtime_error if there is not enough memory to bind the
  245. /// value
  246. /// \throws DatabaseError if an database error occured during the binding
  247. void bind(const std::string& name, const int value);
  248. /// \brief Binds the given string value to the column with the given index.
  249. ///
  250. /// \param index the index of the column to bind the value to
  251. /// \param value the value to bind to that column
  252. /// \throws std::logic_error if the statement is not open
  253. /// \throws std::out_of_range if the given index is out of range
  254. /// \throws std::runtime_error if there is not enough memory to bind the
  255. /// value
  256. /// \throws DatabaseError if an database error occured during the binding
  257. void bind(const int index, const std::string& value);
  258. /// \brief Binds the given string value to the column with the given name.
  259. ///
  260. /// \param index the name of the column to bind the value to
  261. /// \param value the value to bind to that column
  262. /// \throws std::logic_error if the statement is not open
  263. /// \throws std::invalid_argument if there is no column witht the given name
  264. /// \throws std::runtime_error if there is not enough memory to bind the
  265. /// value
  266. /// \throws DatabaseError if an database error occured during the binding
  267. void bind(const std::string& name, const std::string& value);
  268. /// \brief Closes this statement.
  269. ///
  270. /// Once you closed this statement, you may no longer access it. Any errors
  271. /// that occur during finalization are ignored as they already occurred
  272. /// during the last operation.
  273. void close();
  274. /// \brief Executes this statement and returns the result (if any).
  275. ///
  276. /// \returns the result returned from the query (empty if there was no result)
  277. /// \throws std::logic_error if the statement is not open
  278. /// \throws DatabaseError if a database error occurs during the query
  279. /// execution
  280. ResultSet execute();
  281. /// \brief Resets the statement.
  282. ///
  283. /// Resets the statement so that it can be re-executed. Bindings are not
  284. /// resetted.
  285. ///
  286. /// \returns `true` if the reset was successful; otherwise `false`
  287. /// \throws std::logic_error if the statement is not open
  288. bool reset();
  289. private:
  290. explicit Statement(sqlite3_stmt* handle);
  291. int getParameterIndex(const std::string& name) const;
  292. void handleBindResult(const int index, const int result) const;
  293. void requireCanRead() const;
  294. void setInstancePointer(const std::weak_ptr<Statement>& instancePointer);
  295. bool step();
  296. sqlite3_stmt* m_handle;
  297. bool m_canRead;
  298. std::weak_ptr<Statement> m_instancePointer;
  299. friend class Database;
  300. friend class ResultSet;
  301. };
  302. /// \brief A handle for a SQLite3 database.
  303. ///
  304. /// This class stores a reference to a SQLite3 database and provides methods
  305. /// to open, query and change this database. After you successfully opened a
  306. /// database (using the constructor Database(const std::string&) or using the
  307. /// open(const std::string&) method), you can execute and prepare statements.
  308. /// You can check whether the database is currently open using isOpen().
  309. ///
  310. /// If you try to call a method that queries or updates the database and the
  311. /// database is not open, a std::logic_error is thrown. If a database operation
  312. /// fails, a DatabaseError is thrown.
  313. class Database : private Uncopyable, public Openable {
  314. public:
  315. /// \brief Creates a new closed database.
  316. ///
  317. /// Before you can access this database, you have to open a database file
  318. /// using open(std::string&).
  319. Database();
  320. /// \brief Creates a new database and opens the given file.
  321. ///
  322. /// The given file must either be a valid SQLite3 database file or may not
  323. /// exist yet. This constructor is an abbreviation for:
  324. /// \code{.cpp}
  325. /// Database database;
  326. /// database.open(file);
  327. /// \endcode
  328. ///
  329. /// \param file the name of the database file (not required to exist)
  330. /// \throws std::runtime_error if there is not enough memory to create a
  331. /// database connection
  332. /// \throws DatabaseError if the SQLite3 database could not be opened
  333. explicit Database(const std::string& file);
  334. /// \brief Destructs this object and closes the database connection.
  335. ///
  336. /// Errors that occur closing the database are ignored.
  337. ~Database();
  338. /// \brief Closes the database if it is open.
  339. ///
  340. /// \throws DatabaseError if the database cannot be closed
  341. void close();
  342. /// \brief Executes the given SQL string.
  343. ///
  344. /// You can only call this method if there is an open database connection.
  345. /// If you want to access the values returned by a SQL statement, use
  346. /// prepare(const std::string&) instead.
  347. ///
  348. /// \param sql the SQL statement to execute
  349. /// \throws std::logic_error if the database is not open
  350. /// \throws DatabaseError if an error occurred during the execution
  351. void execute(const std::string& sql);
  352. /// \brief Opens the given database file.
  353. ///
  354. /// The given file must either be a valid SQLite3 database file or may not
  355. /// exist yet. You can only open a new connection when the previous
  356. /// connection has been closed (if any).
  357. ///
  358. /// \param file the name of the database file (not required to exist)
  359. /// \throws std::logic_error if the database is already open
  360. /// \throws std::runtime_error if there is not enough memory to create a
  361. /// database connection
  362. /// \throws DatabaseError if the SQLite3 database could not be opened
  363. void open(const std::string& file);
  364. /// \brief Prepares a statement and returns a pointer to it.
  365. ///
  366. /// You can either pass a complete SQL statement or a statement with
  367. /// wildcards. If you use wildcards, you can bind them to a value using the
  368. /// returned Statement.
  369. ///
  370. /// \param sql the SQL statement to prepare (may contain wildcards)
  371. /// \returns a pointer to the prepared statement
  372. /// \throws std::logic_error if the database is not open
  373. /// \throws DatabaseError if an error occurred during the preparation
  374. std::shared_ptr<Statement> prepare(const std::string& sql);
  375. private:
  376. sqlite3* m_handle;
  377. };
  378. /// \brief A result set returned from a SQL query.
  379. ///
  380. /// As long as there is data (`canRead()`), you can read it using the
  381. /// `read*Type*` methods. To advance to the next row, use `next()`.
  382. class ResultSet {
  383. public:
  384. /// \brief Checks whether there is data to read.
  385. ///
  386. /// \returns `true` if there is data to read; otherwise `false`
  387. bool canRead() const;
  388. /// \brief Returns the column count of the result data.
  389. ///
  390. /// You may only call this method when there is data to read (canRead()).
  391. ///
  392. /// \returns the column count of the result
  393. /// \throws std::logic_error if the statement is not open or there is no
  394. /// data to read
  395. int columnCount() const;
  396. /// \brief Steps to the next row of the result (if there is one).
  397. ///
  398. /// \returns `true` if there is new data to read or `false` if there are
  399. /// no more results
  400. /// \throws std::logic_error if the statement is not open
  401. /// \throws DatabaseError if a database error occurs during the query
  402. /// execution
  403. bool next();
  404. /// \brief Returns the current double value of the result column with the
  405. /// given index.
  406. ///
  407. /// You may only call this metod when there is data to read (canRead()).
  408. ///
  409. /// \param column the index of the column to read from
  410. /// \returns the current value of the result column with the given index
  411. /// \throws std::logic_error if the statement is not open or there is no
  412. /// data to read
  413. double readDouble(const int column) const;
  414. /// \brief Returns the current integer value of the result column with the
  415. /// given index.
  416. ///
  417. /// You may only call this metod when there is data to read (canRead()).
  418. ///
  419. /// \param column the index of the column to read from
  420. /// \returns the current value of the result column with the given index
  421. /// \throws std::logic_error if the statement is not open or there is no
  422. /// data to read
  423. int readInt(const int column) const;
  424. /// \brief Returns the current string value of the result column with the
  425. /// given index.
  426. ///
  427. /// You may only call this metod when there is data to read (canRead()).
  428. ///
  429. /// \param column the index of the column to read from
  430. /// \returns the current value of the result column with the given index
  431. /// \throws std::logic_error if the statement is not open or there is no
  432. /// data to read
  433. std::string readString(const int column) const;
  434. private:
  435. explicit ResultSet(const std::shared_ptr<Statement> statement);
  436. const std::shared_ptr<Statement> m_statement;
  437. friend class Statement;
  438. };
  439. } // namespace sqlitepp
  440. #endif // SQLITEPP_SQLITEPP_H_