1 // Copyright 2011 Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 //   notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 //   notice, this list of conditions and the following disclaimer in the
12 //   documentation and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors
14 //   may be used to endorse or promote products derived from this software
15 //   without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 #include "utils/sqlite/database.hpp"
30 
31 extern "C" {
32 #include <sqlite3.h>
33 }
34 
35 #include <stdexcept>
36 
37 #include "utils/format/macros.hpp"
38 #include "utils/logging/macros.hpp"
39 #include "utils/sanity.hpp"
40 #include "utils/sqlite/exceptions.hpp"
41 #include "utils/sqlite/statement.ipp"
42 #include "utils/sqlite/transaction.hpp"
43 
44 namespace sqlite = utils::sqlite;
45 
46 
47 /// Internal implementation for sqlite::database.
48 struct utils::sqlite::database::impl {
49     /// The SQLite 3 internal database.
50     ::sqlite3* db;
51 
52     /// Whether we own the database or not (to decide if we close it).
53     bool owned;
54 
55     /// Constructor.
56     ///
57     /// \param db_ The SQLite internal database.
58     /// \param owned_ Whether this object owns the db_ object or not.  If it
59     ///     does, the internal db_ will be released during destruction.
60     impl(::sqlite3* db_, const bool owned_) :
61         db(db_),
62         owned(owned_)
63     {
64     }
65 
66     /// Destructor.
67     ///
68     /// It is important to keep this as part of the 'impl' class instead of the
69     /// container class.  The 'impl' class is destroyed exactly once (because it
70     /// is managed by a shared_ptr) and thus releasing the resources here is
71     /// OK.  However, the container class is potentially released many times,
72     /// which means that we would be double-freeing the internal object and
73     /// reusing invalid data.
74     ~impl(void)
75     {
76         if (owned && db != NULL)
77             close();
78     }
79 
80     /// Exception-safe version of sqlite3_open_v2.
81     ///
82     /// \param file The path to the database file to be opened.
83     /// \param flags The flags to be passed to the open routine.
84     ///
85     /// \return The opened database.
86     ///
87     /// \throw std::bad_alloc If there is not enough memory to open the
88     ///     database.
89     /// \throw api_error If there is any problem opening the database.
90     static ::sqlite3*
91     safe_open(const char* file, const int flags)
92     {
93         ::sqlite3* db;
94         const int error = ::sqlite3_open_v2(file, &db, flags, NULL);
95         if (error != SQLITE_OK) {
96             if (db == NULL)
97                 throw std::bad_alloc();
98             else {
99                 sqlite::database error_db(db, true);
100                 throw sqlite::api_error::from_database(error_db,
101                                                        "sqlite3_open_v2");
102             }
103         }
104         INV(db != NULL);
105         return db;
106     }
107 
108     /// Shared code for the public close() method.
109     void
110     close(void)
111     {
112         PRE(db != NULL);
113 #if defined(__minix) && !defined(NDEBUG)
114         int error =
115 #endif /* defined(__minix) && !defined(NDEBUG) */
116         ::sqlite3_close(db);
117         // For now, let's consider a return of SQLITE_BUSY an error.  We should
118         // not be trying to close a busy database in our code.  Maybe revisit
119         // this later to raise busy errors as exceptions.
120         PRE(error == SQLITE_OK);
121         db = NULL;
122     }
123 };
124 
125 
126 /// Initializes the SQLite database.
127 ///
128 /// You must share the same database object alongside the lifetime of your
129 /// SQLite session.  As soon as the object is destroyed, the session is
130 /// terminated.
131 ///
132 /// \param db_ Raw pointer to the C SQLite 3 object.
133 /// \param owned_ Whether this instance will own the pointer or not.
134 sqlite::database::database(void* db_, const bool owned_) :
135     _pimpl(new impl(static_cast< ::sqlite3* >(db_), owned_))
136 {
137 }
138 
139 
140 /// Destructor for the SQLite 3 database.
141 ///
142 /// Closes the session unless it has already been closed by calling the
143 /// close() method.  It is recommended to explicitly close the session in the
144 /// code.
145 sqlite::database::~database(void)
146 {
147 }
148 
149 
150 /// Opens a memory-based temporary SQLite database.
151 ///
152 /// \return An in-memory database instance.
153 ///
154 /// \throw std::bad_alloc If there is not enough memory to open the database.
155 /// \throw api_error If there is any problem opening the database.
156 sqlite::database
157 sqlite::database::in_memory(void)
158 {
159     return database(impl::safe_open(":memory:", SQLITE_OPEN_READWRITE), true);
160 }
161 
162 
163 /// Opens a named on-disk SQLite database.
164 ///
165 /// \param file The path to the database file to be opened.  This does not
166 ///     accept the values "" and ":memory:"; use temporary() and in_memory()
167 ///     instead.
168 /// \param open_flags The flags to be passed to the open routine.
169 ///
170 /// \return A file-backed database instance.
171 ///
172 /// \throw std::bad_alloc If there is not enough memory to open the database.
173 /// \throw api_error If there is any problem opening the database.
174 sqlite::database
175 sqlite::database::open(const fs::path& file, int open_flags)
176 {
177     PRE_MSG(!file.str().empty(), "Use database::temporary() instead");
178     PRE_MSG(file.str() != ":memory:", "Use database::in_memory() instead");
179 
180     int flags = 0;
181     if (open_flags & open_readonly) {
182         flags |= SQLITE_OPEN_READONLY;
183         open_flags &= ~open_readonly;
184     }
185     if (open_flags & open_readwrite) {
186         flags |= SQLITE_OPEN_READWRITE;
187         open_flags &= ~open_readwrite;
188     }
189     if (open_flags & open_create) {
190         flags |= SQLITE_OPEN_CREATE;
191         open_flags &= ~open_create;
192     }
193     PRE(open_flags == 0);
194 
195     return database(impl::safe_open(file.c_str(), flags), true);
196 }
197 
198 
199 /// Opens an unnamed on-disk SQLite database.
200 ///
201 /// \return A file-backed database instance.
202 ///
203 /// \throw std::bad_alloc If there is not enough memory to open the database.
204 /// \throw api_error If there is any problem opening the database.
205 sqlite::database
206 sqlite::database::temporary(void)
207 {
208     return database(impl::safe_open("", SQLITE_OPEN_READWRITE), true);
209 }
210 
211 
212 /// Gets the internal sqlite3 object.
213 ///
214 /// \return The raw SQLite 3 database.  This is returned as a void pointer to
215 /// prevent including the sqlite3.h header file from our public interface.  The
216 /// only way to call this method is by using the c_gate module, and c_gate takes
217 /// care of casting this object to the appropriate type.
218 void*
219 sqlite::database::raw_database(void)
220 {
221     return _pimpl->db;
222 }
223 
224 
225 /// Terminates the connection to the database.
226 ///
227 /// It is recommended to call this instead of relying on the destructor to do
228 /// the cleanup, but it is not a requirement to use close().
229 ///
230 /// \pre close() has not yet been called.
231 void
232 sqlite::database::close(void)
233 {
234     _pimpl->close();
235 }
236 
237 
238 /// Executes an arbitrary SQL string.
239 ///
240 /// As the documentation explains, this is unsafe.  The code should really be
241 /// preparing statements and executing them step by step.  However, it is
242 /// perfectly fine to use this function for, e.g. the initial creation of
243 /// tables in a database and in tests.
244 ///
245 /// \param sql The SQL commands to be executed.
246 ///
247 /// \throw api_error If there is any problem while processing the SQL.
248 void
249 sqlite::database::exec(const std::string& sql)
250 {
251     const int error = ::sqlite3_exec(_pimpl->db, sql.c_str(), NULL, NULL, NULL);
252     if (error != SQLITE_OK)
253         throw api_error::from_database(*this, "sqlite3_exec");
254 }
255 
256 
257 /// Opens a new transaction.
258 ///
259 /// \return An object representing the state of the transaction.
260 ///
261 /// \throw api_error If there is any problem while opening the transaction.
262 sqlite::transaction
263 sqlite::database::begin_transaction(void)
264 {
265     exec("BEGIN TRANSACTION");
266     return transaction(*this);
267 }
268 
269 
270 /// Prepares a new statement.
271 ///
272 /// \param sql The SQL statement to prepare.
273 ///
274 /// \return The prepared statement.
275 sqlite::statement
276 sqlite::database::create_statement(const std::string& sql)
277 {
278     LD(F("Creating statement: %s") % sql);
279     sqlite3_stmt* stmt;
280     const int error = ::sqlite3_prepare_v2(_pimpl->db, sql.c_str(),
281                                            sql.length() + 1, &stmt, NULL);
282     if (error != SQLITE_OK)
283         throw api_error::from_database(*this, "sqlite3_prepare_v2");
284     return statement(*this, static_cast< void* >(stmt));
285 }
286 
287 
288 /// Returns the row identifier of the last insert.
289 ///
290 /// \return A row identifier.
291 int64_t
292 sqlite::database::last_insert_rowid(void)
293 {
294     return ::sqlite3_last_insert_rowid(_pimpl->db);
295 }
296