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/statement.hpp"
30 
31 extern "C" {
32 #include <sqlite3.h>
33 }
34 
35 #include <map>
36 
37 #include "utils/defs.hpp"
38 #include "utils/format/macros.hpp"
39 #include "utils/logging/macros.hpp"
40 #include "utils/sanity.hpp"
41 #include "utils/sqlite/c_gate.hpp"
42 #include "utils/sqlite/exceptions.hpp"
43 
44 namespace sqlite = utils::sqlite;
45 
46 
47 namespace {
48 
49 
50 static sqlite::type c_type_to_cxx(const int) UTILS_PURE;
51 
52 
53 /// Maps a SQLite 3 data type to our own representation.
54 ///
55 /// \param original The native SQLite 3 data type.
56 ///
57 /// \return Our internal representation for the native data type.
58 static sqlite::type
c_type_to_cxx(const int original)59 c_type_to_cxx(const int original)
60 {
61     switch (original) {
62     case SQLITE_BLOB: return sqlite::type_blob;
63     case SQLITE_FLOAT: return sqlite::type_float;
64     case SQLITE_INTEGER: return sqlite::type_integer;
65     case SQLITE_NULL: return sqlite::type_null;
66     case SQLITE_TEXT: return sqlite::type_text;
67     default: UNREACHABLE_MSG("Unknown data type returned by SQLite 3");
68     }
69     UNREACHABLE;
70 }
71 
72 
73 /// Handles the return value of a sqlite3_bind_* call.
74 ///
75 /// \param db The database the call was made on.
76 /// \param api_function The name of the sqlite3_bind_* function called.
77 /// \param error The error code returned by the function; can be SQLITE_OK.
78 ///
79 /// \throw std::bad_alloc If there was no memory for the binding.
80 /// \throw api_error If the binding fails for any other reason.
81 static void
handle_bind_error(sqlite::database & db,const char * api_function,const int error)82 handle_bind_error(sqlite::database& db, const char* api_function,
83                   const int error)
84 {
85     switch (error) {
86     case SQLITE_OK:
87         return;
88     case SQLITE_RANGE:
89         UNREACHABLE_MSG("Invalid index for bind argument");
90     case SQLITE_NOMEM:
91         throw std::bad_alloc();
92     default:
93         throw sqlite::api_error::from_database(db, api_function);
94     }
95 }
96 
97 
98 }  // anonymous namespace
99 
100 
101 /// Internal implementation for sqlite::statement.
102 struct utils::sqlite::statement::impl {
103     /// The database this statement belongs to.
104     sqlite::database& db;
105 
106     /// The SQLite 3 internal statement.
107     ::sqlite3_stmt* stmt;
108 
109     /// Cache for the column names in a statement; lazily initialized.
110     std::map< std::string, int > column_cache;
111 
112     /// Constructor.
113     ///
114     /// \param db_ The database this statement belongs to.  Be aware that we
115     ///     keep a *reference* to the database; in other words, if the database
116     ///     vanishes, this object will become invalid.  (It'd be trivial to keep
117     ///     a shallow copy here instead, but I feel that statements that outlive
118     ///     their database represents sloppy programming.)
119     /// \param stmt_ The SQLite internal statement.
implutils::sqlite::statement::impl120     impl(database& db_, ::sqlite3_stmt* stmt_) :
121         db(db_),
122         stmt(stmt_)
123     {
124     }
125 
126     /// Destructor.
127     ///
128     /// It is important to keep this as part of the 'impl' class instead of the
129     /// container class.  The 'impl' class is destroyed exactly once (because it
130     /// is managed by a shared_ptr) and thus releasing the resources here is
131     /// OK.  However, the container class is potentially released many times,
132     /// which means that we would be double-freeing the internal object and
133     /// reusing invalid data.
~implutils::sqlite::statement::impl134     ~impl(void)
135     {
136         (void)::sqlite3_finalize(stmt);
137     }
138 };
139 
140 
141 /// Initializes a statement object.
142 ///
143 /// This is an internal function.  Use database::create_statement() to
144 /// instantiate one of these objects.
145 ///
146 /// \param db The database this statement belongs to.
147 /// \param raw_stmt A void pointer representing a SQLite native statement of
148 ///     type sqlite3_stmt.
statement(database & db,void * raw_stmt)149 sqlite::statement::statement(database& db, void* raw_stmt) :
150     _pimpl(new impl(db, static_cast< ::sqlite3_stmt* >(raw_stmt)))
151 {
152 }
153 
154 
155 /// Destructor for the statement.
156 ///
157 /// Remember that statements are reference-counted, so the statement will only
158 /// cease to be valid once its last copy is destroyed.
~statement(void)159 sqlite::statement::~statement(void)
160 {
161 }
162 
163 
164 /// Executes a statement that is not supposed to return any data.
165 ///
166 /// Use this function to execute DDL and INSERT statements; i.e. statements that
167 /// only have one processing step and deliver no rows.  This frees the caller
168 /// from having to deal with the return value of the step() function.
169 ///
170 /// \pre The statement to execute will not produce any rows.
171 void
step_without_results(void)172 sqlite::statement::step_without_results(void)
173 {
174     const bool data = step();
175     INV_MSG(!data, "The statement should not have produced any rows, but it "
176             "did");
177 }
178 
179 
180 /// Performs a processing step on the statement.
181 ///
182 /// \return True if the statement returned a row; false if the processing has
183 /// finished.
184 ///
185 /// \throw api_error If the processing of the step raises an error.
186 bool
step(void)187 sqlite::statement::step(void)
188 {
189     const int error = ::sqlite3_step(_pimpl->stmt);
190     switch (error) {
191     case SQLITE_DONE:
192         LD("Step statement; no more rows");
193         return false;
194     case SQLITE_ROW:
195         LD("Step statement; row available for processing");
196         return true;
197     default:
198         throw api_error::from_database(_pimpl->db, "sqlite3_step");
199     }
200     UNREACHABLE;
201 }
202 
203 
204 /// Returns the number of columns in the step result.
205 ///
206 /// \return The number of columns available for data retrieval.
207 int
column_count(void)208 sqlite::statement::column_count(void)
209 {
210     return ::sqlite3_column_count(_pimpl->stmt);
211 }
212 
213 
214 /// Returns the name of a particular column in the result.
215 ///
216 /// \param index The column to request the name of.
217 ///
218 /// \return The name of the requested column.
219 std::string
column_name(const int index)220 sqlite::statement::column_name(const int index)
221 {
222     const char* name = ::sqlite3_column_name(_pimpl->stmt, index);
223     if (name == NULL)
224         throw api_error::from_database(_pimpl->db, "sqlite3_column_name");
225     return name;
226 }
227 
228 
229 /// Returns the type of a particular column in the result.
230 ///
231 /// \param index The column to request the type of.
232 ///
233 /// \return The type of the requested column.
234 sqlite::type
column_type(const int index)235 sqlite::statement::column_type(const int index)
236 {
237     return c_type_to_cxx(::sqlite3_column_type(_pimpl->stmt, index));
238 }
239 
240 
241 /// Finds a column by name.
242 ///
243 /// \param name The name of the column to search for.
244 ///
245 /// \return The column identifier.
246 ///
247 /// \throw value_error If the name cannot be found.
248 int
column_id(const char * name)249 sqlite::statement::column_id(const char* name)
250 {
251     std::map< std::string, int >& cache = _pimpl->column_cache;
252 
253     if (cache.empty()) {
254         for (int i = 0; i < column_count(); i++) {
255             const std::string aux_name = column_name(i);
256             INV(cache.find(aux_name) == cache.end());
257             cache[aux_name] = i;
258         }
259     }
260 
261     const std::map< std::string, int >::const_iterator iter = cache.find(name);
262     if (iter == cache.end())
263         throw invalid_column_error(name);
264     else
265         return (*iter).second;
266 }
267 
268 
269 /// Returns a particular column in the result as a blob.
270 ///
271 /// \param index The column to retrieve.
272 ///
273 /// \return A block of memory with the blob contents.  Note that the pointer
274 /// returned by this call will be invalidated on the next call to any SQLite API
275 /// function.
276 sqlite::blob
column_blob(const int index)277 sqlite::statement::column_blob(const int index)
278 {
279     PRE(column_type(index) == type_blob);
280     return blob(::sqlite3_column_blob(_pimpl->stmt, index),
281                 ::sqlite3_column_bytes(_pimpl->stmt, index));
282 }
283 
284 
285 /// Returns a particular column in the result as a double.
286 ///
287 /// \param index The column to retrieve.
288 ///
289 /// \return The double value.
290 double
column_double(const int index)291 sqlite::statement::column_double(const int index)
292 {
293     PRE(column_type(index) == type_float);
294     return ::sqlite3_column_double(_pimpl->stmt, index);
295 }
296 
297 
298 /// Returns a particular column in the result as an integer.
299 ///
300 /// \param index The column to retrieve.
301 ///
302 /// \return The integer value.  Note that the value may not fit in an integer
303 /// depending on the platform.  Use column_int64 to retrieve the integer without
304 /// truncation.
305 int
column_int(const int index)306 sqlite::statement::column_int(const int index)
307 {
308     PRE(column_type(index) == type_integer);
309     return ::sqlite3_column_int(_pimpl->stmt, index);
310 }
311 
312 
313 /// Returns a particular column in the result as a 64-bit integer.
314 ///
315 /// \param index The column to retrieve.
316 ///
317 /// \return The integer value.
318 int64_t
column_int64(const int index)319 sqlite::statement::column_int64(const int index)
320 {
321     PRE(column_type(index) == type_integer);
322     return ::sqlite3_column_int64(_pimpl->stmt, index);
323 }
324 
325 
326 /// Returns a particular column in the result as a double.
327 ///
328 /// \param index The column to retrieve.
329 ///
330 /// \return A C string with the contents.  Note that the pointer returned by
331 /// this call will be invalidated on the next call to any SQLite API function.
332 /// If you want to be extra safe, store the result in a std::string to not worry
333 /// about this.
334 std::string
column_text(const int index)335 sqlite::statement::column_text(const int index)
336 {
337     PRE(column_type(index) == type_text);
338     return reinterpret_cast< const char* >(::sqlite3_column_text(
339         _pimpl->stmt, index));
340 }
341 
342 
343 /// Returns the number of bytes stored in the column.
344 ///
345 /// \pre This is only valid for columns of type blob and text.
346 ///
347 /// \param index The column to retrieve the size of.
348 ///
349 /// \return The number of bytes in the column.  Remember that strings are stored
350 /// in their UTF-8 representation; this call returns the number of *bytes*, not
351 /// characters.
352 int
column_bytes(const int index)353 sqlite::statement::column_bytes(const int index)
354 {
355     PRE(column_type(index) == type_blob || column_type(index) == type_text);
356     return ::sqlite3_column_bytes(_pimpl->stmt, index);
357 }
358 
359 
360 /// Type-checked version of column_blob.
361 ///
362 /// \param name The name of the column to retrieve.
363 ///
364 /// \return The same as column_blob if the value can be retrieved.
365 ///
366 /// \throw error If the type of the cell to retrieve is invalid.
367 /// \throw invalid_column_error If name is invalid.
368 sqlite::blob
safe_column_blob(const char * name)369 sqlite::statement::safe_column_blob(const char* name)
370 {
371     const int column = column_id(name);
372     if (column_type(column) != sqlite::type_blob)
373         throw sqlite::error(F("Column '%s' is not a blob") % name);
374     return column_blob(column);
375 }
376 
377 
378 /// Type-checked version of column_double.
379 ///
380 /// \param name The name of the column to retrieve.
381 ///
382 /// \return The same as column_double if the value can be retrieved.
383 ///
384 /// \throw error If the type of the cell to retrieve is invalid.
385 /// \throw invalid_column_error If name is invalid.
386 double
safe_column_double(const char * name)387 sqlite::statement::safe_column_double(const char* name)
388 {
389     const int column = column_id(name);
390     if (column_type(column) != sqlite::type_float)
391         throw sqlite::error(F("Column '%s' is not a float") % name);
392     return column_double(column);
393 }
394 
395 
396 /// Type-checked version of column_int.
397 ///
398 /// \param name The name of the column to retrieve.
399 ///
400 /// \return The same as column_int if the value can be retrieved.
401 ///
402 /// \throw error If the type of the cell to retrieve is invalid.
403 /// \throw invalid_column_error If name is invalid.
404 int
safe_column_int(const char * name)405 sqlite::statement::safe_column_int(const char* name)
406 {
407     const int column = column_id(name);
408     if (column_type(column) != sqlite::type_integer)
409         throw sqlite::error(F("Column '%s' is not an integer") % name);
410     return column_int(column);
411 }
412 
413 
414 /// Type-checked version of column_int64.
415 ///
416 /// \param name The name of the column to retrieve.
417 ///
418 /// \return The same as column_int64 if the value can be retrieved.
419 ///
420 /// \throw error If the type of the cell to retrieve is invalid.
421 /// \throw invalid_column_error If name is invalid.
422 int64_t
safe_column_int64(const char * name)423 sqlite::statement::safe_column_int64(const char* name)
424 {
425     const int column = column_id(name);
426     if (column_type(column) != sqlite::type_integer)
427         throw sqlite::error(F("Column '%s' is not an integer") % name);
428     return column_int64(column);
429 }
430 
431 
432 /// Type-checked version of column_text.
433 ///
434 /// \param name The name of the column to retrieve.
435 ///
436 /// \return The same as column_text if the value can be retrieved.
437 ///
438 /// \throw error If the type of the cell to retrieve is invalid.
439 /// \throw invalid_column_error If name is invalid.
440 std::string
safe_column_text(const char * name)441 sqlite::statement::safe_column_text(const char* name)
442 {
443     const int column = column_id(name);
444     if (column_type(column) != sqlite::type_text)
445         throw sqlite::error(F("Column '%s' is not a string") % name);
446     return column_text(column);
447 }
448 
449 
450 /// Type-checked version of column_bytes.
451 ///
452 /// \param name The name of the column to retrieve the size of.
453 ///
454 /// \return The same as column_bytes if the value can be retrieved.
455 ///
456 /// \throw error If the type of the cell to retrieve the size of is invalid.
457 /// \throw invalid_column_error If name is invalid.
458 int
safe_column_bytes(const char * name)459 sqlite::statement::safe_column_bytes(const char* name)
460 {
461     const int column = column_id(name);
462     if (column_type(column) != sqlite::type_blob &&
463         column_type(column) != sqlite::type_text)
464         throw sqlite::error(F("Column '%s' is not a blob or a string") % name);
465     return column_bytes(column);
466 }
467 
468 
469 /// Resets a statement to allow further processing.
470 void
reset(void)471 sqlite::statement::reset(void)
472 {
473     (void)::sqlite3_reset(_pimpl->stmt);
474 }
475 
476 
477 /// Binds a blob to a prepared statement.
478 ///
479 /// \param index The index of the binding.
480 /// \param b Description of the blob, which must remain valid during the
481 ///     execution of the statement.
482 ///
483 /// \throw api_error If the binding fails.
484 void
bind(const int index,const blob & b)485 sqlite::statement::bind(const int index, const blob& b)
486 {
487     const int error = ::sqlite3_bind_blob(_pimpl->stmt, index, b.memory, b.size,
488                                           SQLITE_STATIC);
489     handle_bind_error(_pimpl->db, "sqlite3_bind_blob", error);
490 }
491 
492 
493 /// Binds a double value to a prepared statement.
494 ///
495 /// \param index The index of the binding.
496 /// \param value The double value to bind.
497 ///
498 /// \throw api_error If the binding fails.
499 void
bind(const int index,const double value)500 sqlite::statement::bind(const int index, const double value)
501 {
502     const int error = ::sqlite3_bind_double(_pimpl->stmt, index, value);
503     handle_bind_error(_pimpl->db, "sqlite3_bind_double", error);
504 }
505 
506 
507 /// Binds an integer value to a prepared statement.
508 ///
509 /// \param index The index of the binding.
510 /// \param value The integer value to bind.
511 ///
512 /// \throw api_error If the binding fails.
513 void
bind(const int index,const int value)514 sqlite::statement::bind(const int index, const int value)
515 {
516     const int error = ::sqlite3_bind_int(_pimpl->stmt, index, value);
517     handle_bind_error(_pimpl->db, "sqlite3_bind_int", error);
518 }
519 
520 
521 /// Binds a 64-bit integer value to a prepared statement.
522 ///
523 /// \param index The index of the binding.
524 /// \param value The 64-bin integer value to bind.
525 ///
526 /// \throw api_error If the binding fails.
527 void
bind(const int index,const int64_t value)528 sqlite::statement::bind(const int index, const int64_t value)
529 {
530     const int error = ::sqlite3_bind_int64(_pimpl->stmt, index, value);
531     handle_bind_error(_pimpl->db, "sqlite3_bind_int64", error);
532 }
533 
534 
535 /// Binds a NULL value to a prepared statement.
536 ///
537 /// \param index The index of the binding.
538 /// \param unused_null An instance of the null class.
539 ///
540 /// \throw api_error If the binding fails.
541 void
bind(const int index,const null & UTILS_UNUSED_PARAM (null))542 sqlite::statement::bind(const int index,
543                              const null& UTILS_UNUSED_PARAM(null))
544 {
545     const int error = ::sqlite3_bind_null(_pimpl->stmt, index);
546     handle_bind_error(_pimpl->db, "sqlite3_bind_null", error);
547 }
548 
549 
550 /// Binds a text string to a prepared statement.
551 ///
552 /// \param index The index of the binding.
553 /// \param text The string to bind.  SQLite generates an internal copy of this
554 ///     string, so the original string object does not have to remain live.  We
555 ///     do this because handling the lifetime of std::string objects is very
556 ///     hard (think about implicit conversions), so it is very easy to shoot
557 ///     ourselves in the foot if we don't do this.
558 ///
559 /// \throw api_error If the binding fails.
560 void
bind(const int index,const std::string & text)561 sqlite::statement::bind(const int index, const std::string& text)
562 {
563     const int error = ::sqlite3_bind_text(_pimpl->stmt, index, text.c_str(),
564                                           text.length(), SQLITE_TRANSIENT);
565     handle_bind_error(_pimpl->db, "sqlite3_bind_text", error);
566 }
567 
568 
569 /// Returns the index of the highest parameter.
570 ///
571 /// \return A parameter index.
572 int
bind_parameter_count(void)573 sqlite::statement::bind_parameter_count(void)
574 {
575     return ::sqlite3_bind_parameter_count(_pimpl->stmt);
576 }
577 
578 
579 /// Returns the index of a named parameter.
580 ///
581 /// \param name The name of the parameter to be queried; must exist.
582 ///
583 /// \return A parameter index.
584 int
bind_parameter_index(const std::string & name)585 sqlite::statement::bind_parameter_index(const std::string& name)
586 {
587     const int index = ::sqlite3_bind_parameter_index(_pimpl->stmt,
588                                                      name.c_str());
589     PRE_MSG(index > 0, "Parameter name not in statement");
590     return index;
591 }
592 
593 
594 /// Returns the name of a parameter by index.
595 ///
596 /// \param index The index to query; must be valid.
597 ///
598 /// \return The name of the parameter.
599 std::string
bind_parameter_name(const int index)600 sqlite::statement::bind_parameter_name(const int index)
601 {
602     const char* name = ::sqlite3_bind_parameter_name(_pimpl->stmt, index);
603     PRE_MSG(name != NULL, "Index value out of range or nameless parameter");
604     return std::string(name);
605 }
606 
607 
608 /// Clears any bindings and releases their memory.
609 void
clear_bindings(void)610 sqlite::statement::clear_bindings(void)
611 {
612     const int error = ::sqlite3_clear_bindings(_pimpl->stmt);
613     PRE_MSG(error == SQLITE_OK, "SQLite3 contract has changed; it should "
614             "only return SQLITE_OK");
615 }
616