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.
implutils::sqlite::database::impl60     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.
~implutils::sqlite::database::impl74     ~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*
safe_openutils::sqlite::database::impl91     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
closeutils::sqlite::database::impl110     close(void)
111     {
112         PRE(db != NULL);
113         int error = ::sqlite3_close(db);
114         // For now, let's consider a return of SQLITE_BUSY an error.  We should
115         // not be trying to close a busy database in our code.  Maybe revisit
116         // this later to raise busy errors as exceptions.
117         PRE(error == SQLITE_OK);
118         db = NULL;
119     }
120 };
121 
122 
123 /// Initializes the SQLite database.
124 ///
125 /// You must share the same database object alongside the lifetime of your
126 /// SQLite session.  As soon as the object is destroyed, the session is
127 /// terminated.
128 ///
129 /// \param db_ Raw pointer to the C SQLite 3 object.
130 /// \param owned_ Whether this instance will own the pointer or not.
database(void * db_,const bool owned_)131 sqlite::database::database(void* db_, const bool owned_) :
132     _pimpl(new impl(static_cast< ::sqlite3* >(db_), owned_))
133 {
134 }
135 
136 
137 /// Destructor for the SQLite 3 database.
138 ///
139 /// Closes the session unless it has already been closed by calling the
140 /// close() method.  It is recommended to explicitly close the session in the
141 /// code.
~database(void)142 sqlite::database::~database(void)
143 {
144 }
145 
146 
147 /// Opens a memory-based temporary SQLite database.
148 ///
149 /// \return An in-memory database instance.
150 ///
151 /// \throw std::bad_alloc If there is not enough memory to open the database.
152 /// \throw api_error If there is any problem opening the database.
153 sqlite::database
in_memory(void)154 sqlite::database::in_memory(void)
155 {
156     return database(impl::safe_open(":memory:", SQLITE_OPEN_READWRITE), true);
157 }
158 
159 
160 /// Opens a named on-disk SQLite database.
161 ///
162 /// \param file The path to the database file to be opened.  This does not
163 ///     accept the values "" and ":memory:"; use temporary() and in_memory()
164 ///     instead.
165 /// \param open_flags The flags to be passed to the open routine.
166 ///
167 /// \return A file-backed database instance.
168 ///
169 /// \throw std::bad_alloc If there is not enough memory to open the database.
170 /// \throw api_error If there is any problem opening the database.
171 sqlite::database
open(const fs::path & file,int open_flags)172 sqlite::database::open(const fs::path& file, int open_flags)
173 {
174     PRE_MSG(!file.str().empty(), "Use database::temporary() instead");
175     PRE_MSG(file.str() != ":memory:", "Use database::in_memory() instead");
176 
177     int flags = 0;
178     if (open_flags & open_readonly) {
179         flags |= SQLITE_OPEN_READONLY;
180         open_flags &= ~open_readonly;
181     }
182     if (open_flags & open_readwrite) {
183         flags |= SQLITE_OPEN_READWRITE;
184         open_flags &= ~open_readwrite;
185     }
186     if (open_flags & open_create) {
187         flags |= SQLITE_OPEN_CREATE;
188         open_flags &= ~open_create;
189     }
190     PRE(open_flags == 0);
191 
192     return database(impl::safe_open(file.c_str(), flags), true);
193 }
194 
195 
196 /// Opens an unnamed on-disk SQLite database.
197 ///
198 /// \return A file-backed database instance.
199 ///
200 /// \throw std::bad_alloc If there is not enough memory to open the database.
201 /// \throw api_error If there is any problem opening the database.
202 sqlite::database
temporary(void)203 sqlite::database::temporary(void)
204 {
205     return database(impl::safe_open("", SQLITE_OPEN_READWRITE), true);
206 }
207 
208 
209 /// Gets the internal sqlite3 object.
210 ///
211 /// \return The raw SQLite 3 database.  This is returned as a void pointer to
212 /// prevent including the sqlite3.h header file from our public interface.  The
213 /// only way to call this method is by using the c_gate module, and c_gate takes
214 /// care of casting this object to the appropriate type.
215 void*
raw_database(void)216 sqlite::database::raw_database(void)
217 {
218     return _pimpl->db;
219 }
220 
221 
222 /// Terminates the connection to the database.
223 ///
224 /// It is recommended to call this instead of relying on the destructor to do
225 /// the cleanup, but it is not a requirement to use close().
226 ///
227 /// \pre close() has not yet been called.
228 void
close(void)229 sqlite::database::close(void)
230 {
231     _pimpl->close();
232 }
233 
234 
235 /// Executes an arbitrary SQL string.
236 ///
237 /// As the documentation explains, this is unsafe.  The code should really be
238 /// preparing statements and executing them step by step.  However, it is
239 /// perfectly fine to use this function for, e.g. the initial creation of
240 /// tables in a database and in tests.
241 ///
242 /// \param sql The SQL commands to be executed.
243 ///
244 /// \throw api_error If there is any problem while processing the SQL.
245 void
exec(const std::string & sql)246 sqlite::database::exec(const std::string& sql)
247 {
248     const int error = ::sqlite3_exec(_pimpl->db, sql.c_str(), NULL, NULL, NULL);
249     if (error != SQLITE_OK)
250         throw api_error::from_database(*this, "sqlite3_exec");
251 }
252 
253 
254 /// Opens a new transaction.
255 ///
256 /// \return An object representing the state of the transaction.
257 ///
258 /// \throw api_error If there is any problem while opening the transaction.
259 sqlite::transaction
begin_transaction(void)260 sqlite::database::begin_transaction(void)
261 {
262     exec("BEGIN TRANSACTION");
263     return transaction(*this);
264 }
265 
266 
267 /// Prepares a new statement.
268 ///
269 /// \param sql The SQL statement to prepare.
270 ///
271 /// \return The prepared statement.
272 sqlite::statement
create_statement(const std::string & sql)273 sqlite::database::create_statement(const std::string& sql)
274 {
275     LD(F("Creating statement: %s") % sql);
276     sqlite3_stmt* stmt;
277     const int error = ::sqlite3_prepare_v2(_pimpl->db, sql.c_str(),
278                                            sql.length() + 1, &stmt, NULL);
279     if (error != SQLITE_OK)
280         throw api_error::from_database(*this, "sqlite3_prepare_v2");
281     return statement(*this, static_cast< void* >(stmt));
282 }
283 
284 
285 /// Returns the row identifier of the last insert.
286 ///
287 /// \return A row identifier.
288 int64_t
last_insert_rowid(void)289 sqlite::database::last_insert_rowid(void)
290 {
291     return ::sqlite3_last_insert_rowid(_pimpl->db);
292 }
293