1 // Copyright 2011 The Kyua Authors.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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.
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.
29 #include "utils/sqlite/statement.hpp"
37 #include "utils/defs.hpp"
38 #include "utils/format/macros.hpp"
39 #include "utils/logging/macros.hpp"
40 #include "utils/noncopyable.hpp"
41 #include "utils/sanity.hpp"
42 #include "utils/sqlite/c_gate.hpp"
43 #include "utils/sqlite/database.hpp"
44 #include "utils/sqlite/exceptions.hpp"
46 namespace sqlite = utils::sqlite;
52 static sqlite::type c_type_to_cxx(const int) UTILS_PURE;
55 /// Maps a SQLite 3 data type to our own representation.
57 /// \param original The native SQLite 3 data type.
59 /// \return Our internal representation for the native data type.
61 c_type_to_cxx(const int original)
64 case SQLITE_BLOB: return sqlite::type_blob;
65 case SQLITE_FLOAT: return sqlite::type_float;
66 case SQLITE_INTEGER: return sqlite::type_integer;
67 case SQLITE_NULL: return sqlite::type_null;
68 case SQLITE_TEXT: return sqlite::type_text;
69 default: UNREACHABLE_MSG("Unknown data type returned by SQLite 3");
75 /// Handles the return value of a sqlite3_bind_* call.
77 /// \param db The database the call was made on.
78 /// \param api_function The name of the sqlite3_bind_* function called.
79 /// \param error The error code returned by the function; can be SQLITE_OK.
81 /// \throw std::bad_alloc If there was no memory for the binding.
82 /// \throw api_error If the binding fails for any other reason.
84 handle_bind_error(sqlite::database& db, const char* api_function,
91 UNREACHABLE_MSG("Invalid index for bind argument");
93 throw std::bad_alloc();
95 throw sqlite::api_error::from_database(db, api_function);
100 } // anonymous namespace
103 /// Internal implementation for sqlite::statement.
104 struct utils::sqlite::statement::impl : utils::noncopyable {
105 /// The database this statement belongs to.
106 sqlite::database& db;
108 /// The SQLite 3 internal statement.
109 ::sqlite3_stmt* stmt;
111 /// Cache for the column names in a statement; lazily initialized.
112 std::map< std::string, int > column_cache;
116 /// \param db_ The database this statement belongs to. Be aware that we
117 /// keep a *reference* to the database; in other words, if the database
118 /// vanishes, this object will become invalid. (It'd be trivial to keep
119 /// a shallow copy here instead, but I feel that statements that outlive
120 /// their database represents sloppy programming.)
121 /// \param stmt_ The SQLite internal statement.
122 impl(database& db_, ::sqlite3_stmt* stmt_) :
130 /// It is important to keep this as part of the 'impl' class instead of the
131 /// container class. The 'impl' class is destroyed exactly once (because it
132 /// is managed by a shared_ptr) and thus releasing the resources here is
133 /// OK. However, the container class is potentially released many times,
134 /// which means that we would be double-freeing the internal object and
135 /// reusing invalid data.
138 (void)::sqlite3_finalize(stmt);
143 /// Initializes a statement object.
145 /// This is an internal function. Use database::create_statement() to
146 /// instantiate one of these objects.
148 /// \param db The database this statement belongs to.
149 /// \param raw_stmt A void pointer representing a SQLite native statement of
150 /// type sqlite3_stmt.
151 sqlite::statement::statement(database& db, void* raw_stmt) :
152 _pimpl(new impl(db, static_cast< ::sqlite3_stmt* >(raw_stmt)))
157 /// Destructor for the statement.
159 /// Remember that statements are reference-counted, so the statement will only
160 /// cease to be valid once its last copy is destroyed.
161 sqlite::statement::~statement(void)
166 /// Executes a statement that is not supposed to return any data.
168 /// Use this function to execute DDL and INSERT statements; i.e. statements that
169 /// only have one processing step and deliver no rows. This frees the caller
170 /// from having to deal with the return value of the step() function.
172 /// \pre The statement to execute will not produce any rows.
174 sqlite::statement::step_without_results(void)
176 const bool data = step();
177 INV_MSG(!data, "The statement should not have produced any rows, but it "
182 /// Performs a processing step on the statement.
184 /// \return True if the statement returned a row; false if the processing has
187 /// \throw api_error If the processing of the step raises an error.
189 sqlite::statement::step(void)
191 const int error = ::sqlite3_step(_pimpl->stmt);
194 LD("Step statement; no more rows");
197 LD("Step statement; row available for processing");
200 throw api_error::from_database(_pimpl->db, "sqlite3_step");
206 /// Returns the number of columns in the step result.
208 /// \return The number of columns available for data retrieval.
210 sqlite::statement::column_count(void)
212 return ::sqlite3_column_count(_pimpl->stmt);
216 /// Returns the name of a particular column in the result.
218 /// \param index The column to request the name of.
220 /// \return The name of the requested column.
222 sqlite::statement::column_name(const int index)
224 const char* name = ::sqlite3_column_name(_pimpl->stmt, index);
226 throw api_error::from_database(_pimpl->db, "sqlite3_column_name");
231 /// Returns the type of a particular column in the result.
233 /// \param index The column to request the type of.
235 /// \return The type of the requested column.
237 sqlite::statement::column_type(const int index)
239 return c_type_to_cxx(::sqlite3_column_type(_pimpl->stmt, index));
243 /// Finds a column by name.
245 /// \param name The name of the column to search for.
247 /// \return The column identifier.
249 /// \throw value_error If the name cannot be found.
251 sqlite::statement::column_id(const char* name)
253 std::map< std::string, int >& cache = _pimpl->column_cache;
256 for (int i = 0; i < column_count(); i++) {
257 const std::string aux_name = column_name(i);
258 INV(cache.find(aux_name) == cache.end());
263 const std::map< std::string, int >::const_iterator iter = cache.find(name);
264 if (iter == cache.end())
265 throw invalid_column_error(_pimpl->db.db_filename(), name);
267 return (*iter).second;
271 /// Returns a particular column in the result as a blob.
273 /// \param index The column to retrieve.
275 /// \return A block of memory with the blob contents. Note that the pointer
276 /// returned by this call will be invalidated on the next call to any SQLite API
279 sqlite::statement::column_blob(const int index)
281 PRE(column_type(index) == type_blob);
282 return blob(::sqlite3_column_blob(_pimpl->stmt, index),
283 ::sqlite3_column_bytes(_pimpl->stmt, index));
287 /// Returns a particular column in the result as a double.
289 /// \param index The column to retrieve.
291 /// \return The double value.
293 sqlite::statement::column_double(const int index)
295 PRE(column_type(index) == type_float);
296 return ::sqlite3_column_double(_pimpl->stmt, index);
300 /// Returns a particular column in the result as an integer.
302 /// \param index The column to retrieve.
304 /// \return The integer value. Note that the value may not fit in an integer
305 /// depending on the platform. Use column_int64 to retrieve the integer without
308 sqlite::statement::column_int(const int index)
310 PRE(column_type(index) == type_integer);
311 return ::sqlite3_column_int(_pimpl->stmt, index);
315 /// Returns a particular column in the result as a 64-bit integer.
317 /// \param index The column to retrieve.
319 /// \return The integer value.
321 sqlite::statement::column_int64(const int index)
323 PRE(column_type(index) == type_integer);
324 return ::sqlite3_column_int64(_pimpl->stmt, index);
328 /// Returns a particular column in the result as a double.
330 /// \param index The column to retrieve.
332 /// \return A C string with the contents. Note that the pointer returned by
333 /// this call will be invalidated on the next call to any SQLite API function.
334 /// If you want to be extra safe, store the result in a std::string to not worry
337 sqlite::statement::column_text(const int index)
339 PRE(column_type(index) == type_text);
340 return reinterpret_cast< const char* >(::sqlite3_column_text(
341 _pimpl->stmt, index));
345 /// Returns the number of bytes stored in the column.
347 /// \pre This is only valid for columns of type blob and text.
349 /// \param index The column to retrieve the size of.
351 /// \return The number of bytes in the column. Remember that strings are stored
352 /// in their UTF-8 representation; this call returns the number of *bytes*, not
355 sqlite::statement::column_bytes(const int index)
357 PRE(column_type(index) == type_blob || column_type(index) == type_text);
358 return ::sqlite3_column_bytes(_pimpl->stmt, index);
362 /// Type-checked version of column_blob.
364 /// \param name The name of the column to retrieve.
366 /// \return The same as column_blob if the value can be retrieved.
368 /// \throw error If the type of the cell to retrieve is invalid.
369 /// \throw invalid_column_error If name is invalid.
371 sqlite::statement::safe_column_blob(const char* name)
373 const int column = column_id(name);
374 if (column_type(column) != sqlite::type_blob)
375 throw sqlite::error(_pimpl->db.db_filename(),
376 F("Column '%s' is not a blob") % name);
377 return column_blob(column);
381 /// Type-checked version of column_double.
383 /// \param name The name of the column to retrieve.
385 /// \return The same as column_double if the value can be retrieved.
387 /// \throw error If the type of the cell to retrieve is invalid.
388 /// \throw invalid_column_error If name is invalid.
390 sqlite::statement::safe_column_double(const char* name)
392 const int column = column_id(name);
393 if (column_type(column) != sqlite::type_float)
394 throw sqlite::error(_pimpl->db.db_filename(),
395 F("Column '%s' is not a float") % name);
396 return column_double(column);
400 /// Type-checked version of column_int.
402 /// \param name The name of the column to retrieve.
404 /// \return The same as column_int if the value can be retrieved.
406 /// \throw error If the type of the cell to retrieve is invalid.
407 /// \throw invalid_column_error If name is invalid.
409 sqlite::statement::safe_column_int(const char* name)
411 const int column = column_id(name);
412 if (column_type(column) != sqlite::type_integer)
413 throw sqlite::error(_pimpl->db.db_filename(),
414 F("Column '%s' is not an integer") % name);
415 return column_int(column);
419 /// Type-checked version of column_int64.
421 /// \param name The name of the column to retrieve.
423 /// \return The same as column_int64 if the value can be retrieved.
425 /// \throw error If the type of the cell to retrieve is invalid.
426 /// \throw invalid_column_error If name is invalid.
428 sqlite::statement::safe_column_int64(const char* name)
430 const int column = column_id(name);
431 if (column_type(column) != sqlite::type_integer)
432 throw sqlite::error(_pimpl->db.db_filename(),
433 F("Column '%s' is not an integer") % name);
434 return column_int64(column);
438 /// Type-checked version of column_text.
440 /// \param name The name of the column to retrieve.
442 /// \return The same as column_text if the value can be retrieved.
444 /// \throw error If the type of the cell to retrieve is invalid.
445 /// \throw invalid_column_error If name is invalid.
447 sqlite::statement::safe_column_text(const char* name)
449 const int column = column_id(name);
450 if (column_type(column) != sqlite::type_text)
451 throw sqlite::error(_pimpl->db.db_filename(),
452 F("Column '%s' is not a string") % name);
453 return column_text(column);
457 /// Type-checked version of column_bytes.
459 /// \param name The name of the column to retrieve the size of.
461 /// \return The same as column_bytes if the value can be retrieved.
463 /// \throw error If the type of the cell to retrieve the size of is invalid.
464 /// \throw invalid_column_error If name is invalid.
466 sqlite::statement::safe_column_bytes(const char* name)
468 const int column = column_id(name);
469 if (column_type(column) != sqlite::type_blob &&
470 column_type(column) != sqlite::type_text)
471 throw sqlite::error(_pimpl->db.db_filename(),
472 F("Column '%s' is not a blob or a string") % name);
473 return column_bytes(column);
477 /// Resets a statement to allow further processing.
479 sqlite::statement::reset(void)
481 (void)::sqlite3_reset(_pimpl->stmt);
485 /// Binds a blob to a prepared statement.
487 /// \param index The index of the binding.
488 /// \param b Description of the blob, which must remain valid during the
489 /// execution of the statement.
491 /// \throw api_error If the binding fails.
493 sqlite::statement::bind(const int index, const blob& b)
495 const int error = ::sqlite3_bind_blob(_pimpl->stmt, index, b.memory, b.size,
497 handle_bind_error(_pimpl->db, "sqlite3_bind_blob", error);
501 /// Binds a double value to a prepared statement.
503 /// \param index The index of the binding.
504 /// \param value The double value to bind.
506 /// \throw api_error If the binding fails.
508 sqlite::statement::bind(const int index, const double value)
510 const int error = ::sqlite3_bind_double(_pimpl->stmt, index, value);
511 handle_bind_error(_pimpl->db, "sqlite3_bind_double", error);
515 /// Binds an integer value to a prepared statement.
517 /// \param index The index of the binding.
518 /// \param value The integer value to bind.
520 /// \throw api_error If the binding fails.
522 sqlite::statement::bind(const int index, const int value)
524 const int error = ::sqlite3_bind_int(_pimpl->stmt, index, value);
525 handle_bind_error(_pimpl->db, "sqlite3_bind_int", error);
529 /// Binds a 64-bit integer value to a prepared statement.
531 /// \param index The index of the binding.
532 /// \param value The 64-bin integer value to bind.
534 /// \throw api_error If the binding fails.
536 sqlite::statement::bind(const int index, const int64_t value)
538 const int error = ::sqlite3_bind_int64(_pimpl->stmt, index, value);
539 handle_bind_error(_pimpl->db, "sqlite3_bind_int64", error);
543 /// Binds a NULL value to a prepared statement.
545 /// \param index The index of the binding.
547 /// \throw api_error If the binding fails.
549 sqlite::statement::bind(const int index, const null& /* null */)
551 const int error = ::sqlite3_bind_null(_pimpl->stmt, index);
552 handle_bind_error(_pimpl->db, "sqlite3_bind_null", error);
556 /// Binds a text string to a prepared statement.
558 /// \param index The index of the binding.
559 /// \param text The string to bind. SQLite generates an internal copy of this
560 /// string, so the original string object does not have to remain live. We
561 /// do this because handling the lifetime of std::string objects is very
562 /// hard (think about implicit conversions), so it is very easy to shoot
563 /// ourselves in the foot if we don't do this.
565 /// \throw api_error If the binding fails.
567 sqlite::statement::bind(const int index, const std::string& text)
569 const int error = ::sqlite3_bind_text(_pimpl->stmt, index, text.c_str(),
570 text.length(), SQLITE_TRANSIENT);
571 handle_bind_error(_pimpl->db, "sqlite3_bind_text", error);
575 /// Returns the index of the highest parameter.
577 /// \return A parameter index.
579 sqlite::statement::bind_parameter_count(void)
581 return ::sqlite3_bind_parameter_count(_pimpl->stmt);
585 /// Returns the index of a named parameter.
587 /// \param name The name of the parameter to be queried; must exist.
589 /// \return A parameter index.
591 sqlite::statement::bind_parameter_index(const std::string& name)
593 const int index = ::sqlite3_bind_parameter_index(_pimpl->stmt,
595 PRE_MSG(index > 0, "Parameter name not in statement");
600 /// Returns the name of a parameter by index.
602 /// \param index The index to query; must be valid.
604 /// \return The name of the parameter.
606 sqlite::statement::bind_parameter_name(const int index)
608 const char* name = ::sqlite3_bind_parameter_name(_pimpl->stmt, index);
609 PRE_MSG(name != NULL, "Index value out of range or nameless parameter");
610 return std::string(name);
614 /// Clears any bindings and releases their memory.
616 sqlite::statement::clear_bindings(void)
618 const int error = ::sqlite3_clear_bindings(_pimpl->stmt);
619 PRE_MSG(error == SQLITE_OK, "SQLite3 contract has changed; it should "
620 "only return SQLITE_OK");