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 20KB

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