xref: /minix3/external/bsd/kyua-cli/dist/utils/sqlite/statement.cpp (revision 3260d16f34636651fb9ef891a1ffe03fd23b513d)
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 #if defined(__minix) && !defined(NDEBUG)
175     const bool data =
176 #endif /* defined(__minix) && !defined(NDEBUG) */
177     step();
178     INV_MSG(!data, "The statement should not have produced any rows, but it "
179             "did");
180 }
181 
182 
183 /// Performs a processing step on the statement.
184 ///
185 /// \return True if the statement returned a row; false if the processing has
186 /// finished.
187 ///
188 /// \throw api_error If the processing of the step raises an error.
189 bool
step(void)190 sqlite::statement::step(void)
191 {
192     const int error = ::sqlite3_step(_pimpl->stmt);
193     switch (error) {
194     case SQLITE_DONE:
195         LD("Step statement; no more rows");
196         return false;
197     case SQLITE_ROW:
198         LD("Step statement; row available for processing");
199         return true;
200     default:
201         throw api_error::from_database(_pimpl->db, "sqlite3_step");
202     }
203     UNREACHABLE;
204 }
205 
206 
207 /// Returns the number of columns in the step result.
208 ///
209 /// \return The number of columns available for data retrieval.
210 int
column_count(void)211 sqlite::statement::column_count(void)
212 {
213     return ::sqlite3_column_count(_pimpl->stmt);
214 }
215 
216 
217 /// Returns the name of a particular column in the result.
218 ///
219 /// \param index The column to request the name of.
220 ///
221 /// \return The name of the requested column.
222 std::string
column_name(const int index)223 sqlite::statement::column_name(const int index)
224 {
225     const char* name = ::sqlite3_column_name(_pimpl->stmt, index);
226     if (name == NULL)
227         throw api_error::from_database(_pimpl->db, "sqlite3_column_name");
228     return name;
229 }
230 
231 
232 /// Returns the type of a particular column in the result.
233 ///
234 /// \param index The column to request the type of.
235 ///
236 /// \return The type of the requested column.
237 sqlite::type
column_type(const int index)238 sqlite::statement::column_type(const int index)
239 {
240     return c_type_to_cxx(::sqlite3_column_type(_pimpl->stmt, index));
241 }
242 
243 
244 /// Finds a column by name.
245 ///
246 /// \param name The name of the column to search for.
247 ///
248 /// \return The column identifier.
249 ///
250 /// \throw value_error If the name cannot be found.
251 int
column_id(const char * name)252 sqlite::statement::column_id(const char* name)
253 {
254     std::map< std::string, int >& cache = _pimpl->column_cache;
255 
256     if (cache.empty()) {
257         for (int i = 0; i < column_count(); i++) {
258             const std::string aux_name = column_name(i);
259             INV(cache.find(aux_name) == cache.end());
260             cache[aux_name] = i;
261         }
262     }
263 
264     const std::map< std::string, int >::const_iterator iter = cache.find(name);
265     if (iter == cache.end())
266         throw invalid_column_error(name);
267     else
268         return (*iter).second;
269 }
270 
271 
272 /// Returns a particular column in the result as a blob.
273 ///
274 /// \param index The column to retrieve.
275 ///
276 /// \return A block of memory with the blob contents.  Note that the pointer
277 /// returned by this call will be invalidated on the next call to any SQLite API
278 /// function.
279 sqlite::blob
column_blob(const int index)280 sqlite::statement::column_blob(const int index)
281 {
282     PRE(column_type(index) == type_blob);
283     return blob(::sqlite3_column_blob(_pimpl->stmt, index),
284                 ::sqlite3_column_bytes(_pimpl->stmt, index));
285 }
286 
287 
288 /// Returns a particular column in the result as a double.
289 ///
290 /// \param index The column to retrieve.
291 ///
292 /// \return The double value.
293 double
column_double(const int index)294 sqlite::statement::column_double(const int index)
295 {
296     PRE(column_type(index) == type_float);
297     return ::sqlite3_column_double(_pimpl->stmt, index);
298 }
299 
300 
301 /// Returns a particular column in the result as an integer.
302 ///
303 /// \param index The column to retrieve.
304 ///
305 /// \return The integer value.  Note that the value may not fit in an integer
306 /// depending on the platform.  Use column_int64 to retrieve the integer without
307 /// truncation.
308 int
column_int(const int index)309 sqlite::statement::column_int(const int index)
310 {
311     PRE(column_type(index) == type_integer);
312     return ::sqlite3_column_int(_pimpl->stmt, index);
313 }
314 
315 
316 /// Returns a particular column in the result as a 64-bit integer.
317 ///
318 /// \param index The column to retrieve.
319 ///
320 /// \return The integer value.
321 int64_t
column_int64(const int index)322 sqlite::statement::column_int64(const int index)
323 {
324     PRE(column_type(index) == type_integer);
325     return ::sqlite3_column_int64(_pimpl->stmt, index);
326 }
327 
328 
329 /// Returns a particular column in the result as a double.
330 ///
331 /// \param index The column to retrieve.
332 ///
333 /// \return A C string with the contents.  Note that the pointer returned by
334 /// this call will be invalidated on the next call to any SQLite API function.
335 /// If you want to be extra safe, store the result in a std::string to not worry
336 /// about this.
337 std::string
column_text(const int index)338 sqlite::statement::column_text(const int index)
339 {
340     PRE(column_type(index) == type_text);
341     return reinterpret_cast< const char* >(::sqlite3_column_text(
342         _pimpl->stmt, index));
343 }
344 
345 
346 /// Returns the number of bytes stored in the column.
347 ///
348 /// \pre This is only valid for columns of type blob and text.
349 ///
350 /// \param index The column to retrieve the size of.
351 ///
352 /// \return The number of bytes in the column.  Remember that strings are stored
353 /// in their UTF-8 representation; this call returns the number of *bytes*, not
354 /// characters.
355 int
column_bytes(const int index)356 sqlite::statement::column_bytes(const int index)
357 {
358     PRE(column_type(index) == type_blob || column_type(index) == type_text);
359     return ::sqlite3_column_bytes(_pimpl->stmt, index);
360 }
361 
362 
363 /// Type-checked version of column_blob.
364 ///
365 /// \param name The name of the column to retrieve.
366 ///
367 /// \return The same as column_blob if the value can be retrieved.
368 ///
369 /// \throw error If the type of the cell to retrieve is invalid.
370 /// \throw invalid_column_error If name is invalid.
371 sqlite::blob
safe_column_blob(const char * name)372 sqlite::statement::safe_column_blob(const char* name)
373 {
374     const int column = column_id(name);
375     if (column_type(column) != sqlite::type_blob)
376         throw sqlite::error(F("Column '%s' is not a blob") % name);
377     return column_blob(column);
378 }
379 
380 
381 /// Type-checked version of column_double.
382 ///
383 /// \param name The name of the column to retrieve.
384 ///
385 /// \return The same as column_double if the value can be retrieved.
386 ///
387 /// \throw error If the type of the cell to retrieve is invalid.
388 /// \throw invalid_column_error If name is invalid.
389 double
safe_column_double(const char * name)390 sqlite::statement::safe_column_double(const char* name)
391 {
392     const int column = column_id(name);
393     if (column_type(column) != sqlite::type_float)
394         throw sqlite::error(F("Column '%s' is not a float") % name);
395     return column_double(column);
396 }
397 
398 
399 /// Type-checked version of column_int.
400 ///
401 /// \param name The name of the column to retrieve.
402 ///
403 /// \return The same as column_int if the value can be retrieved.
404 ///
405 /// \throw error If the type of the cell to retrieve is invalid.
406 /// \throw invalid_column_error If name is invalid.
407 int
safe_column_int(const char * name)408 sqlite::statement::safe_column_int(const char* name)
409 {
410     const int column = column_id(name);
411     if (column_type(column) != sqlite::type_integer)
412         throw sqlite::error(F("Column '%s' is not an integer") % name);
413     return column_int(column);
414 }
415 
416 
417 /// Type-checked version of column_int64.
418 ///
419 /// \param name The name of the column to retrieve.
420 ///
421 /// \return The same as column_int64 if the value can be retrieved.
422 ///
423 /// \throw error If the type of the cell to retrieve is invalid.
424 /// \throw invalid_column_error If name is invalid.
425 int64_t
safe_column_int64(const char * name)426 sqlite::statement::safe_column_int64(const char* name)
427 {
428     const int column = column_id(name);
429     if (column_type(column) != sqlite::type_integer)
430         throw sqlite::error(F("Column '%s' is not an integer") % name);
431     return column_int64(column);
432 }
433 
434 
435 /// Type-checked version of column_text.
436 ///
437 /// \param name The name of the column to retrieve.
438 ///
439 /// \return The same as column_text if the value can be retrieved.
440 ///
441 /// \throw error If the type of the cell to retrieve is invalid.
442 /// \throw invalid_column_error If name is invalid.
443 std::string
safe_column_text(const char * name)444 sqlite::statement::safe_column_text(const char* name)
445 {
446     const int column = column_id(name);
447     if (column_type(column) != sqlite::type_text)
448         throw sqlite::error(F("Column '%s' is not a string") % name);
449     return column_text(column);
450 }
451 
452 
453 /// Type-checked version of column_bytes.
454 ///
455 /// \param name The name of the column to retrieve the size of.
456 ///
457 /// \return The same as column_bytes if the value can be retrieved.
458 ///
459 /// \throw error If the type of the cell to retrieve the size of is invalid.
460 /// \throw invalid_column_error If name is invalid.
461 int
safe_column_bytes(const char * name)462 sqlite::statement::safe_column_bytes(const char* name)
463 {
464     const int column = column_id(name);
465     if (column_type(column) != sqlite::type_blob &&
466         column_type(column) != sqlite::type_text)
467         throw sqlite::error(F("Column '%s' is not a blob or a string") % name);
468     return column_bytes(column);
469 }
470 
471 
472 /// Resets a statement to allow further processing.
473 void
reset(void)474 sqlite::statement::reset(void)
475 {
476     (void)::sqlite3_reset(_pimpl->stmt);
477 }
478 
479 
480 /// Binds a blob to a prepared statement.
481 ///
482 /// \param index The index of the binding.
483 /// \param b Description of the blob, which must remain valid during the
484 ///     execution of the statement.
485 ///
486 /// \throw api_error If the binding fails.
487 void
bind(const int index,const blob & b)488 sqlite::statement::bind(const int index, const blob& b)
489 {
490     const int error = ::sqlite3_bind_blob(_pimpl->stmt, index, b.memory, b.size,
491                                           SQLITE_STATIC);
492     handle_bind_error(_pimpl->db, "sqlite3_bind_blob", error);
493 }
494 
495 
496 /// Binds a double value to a prepared statement.
497 ///
498 /// \param index The index of the binding.
499 /// \param value The double value to bind.
500 ///
501 /// \throw api_error If the binding fails.
502 void
bind(const int index,const double value)503 sqlite::statement::bind(const int index, const double value)
504 {
505     const int error = ::sqlite3_bind_double(_pimpl->stmt, index, value);
506     handle_bind_error(_pimpl->db, "sqlite3_bind_double", error);
507 }
508 
509 
510 /// Binds an integer value to a prepared statement.
511 ///
512 /// \param index The index of the binding.
513 /// \param value The integer value to bind.
514 ///
515 /// \throw api_error If the binding fails.
516 void
bind(const int index,const int value)517 sqlite::statement::bind(const int index, const int value)
518 {
519     const int error = ::sqlite3_bind_int(_pimpl->stmt, index, value);
520     handle_bind_error(_pimpl->db, "sqlite3_bind_int", error);
521 }
522 
523 
524 /// Binds a 64-bit integer value to a prepared statement.
525 ///
526 /// \param index The index of the binding.
527 /// \param value The 64-bin integer value to bind.
528 ///
529 /// \throw api_error If the binding fails.
530 void
bind(const int index,const int64_t value)531 sqlite::statement::bind(const int index, const int64_t value)
532 {
533     const int error = ::sqlite3_bind_int64(_pimpl->stmt, index, value);
534     handle_bind_error(_pimpl->db, "sqlite3_bind_int64", error);
535 }
536 
537 
538 /// Binds a NULL value to a prepared statement.
539 ///
540 /// \param index The index of the binding.
541 /// \param unused_null An instance of the null class.
542 ///
543 /// \throw api_error If the binding fails.
544 void
bind(const int index,const null & UTILS_UNUSED_PARAM (null))545 sqlite::statement::bind(const int index,
546                              const null& UTILS_UNUSED_PARAM(null))
547 {
548     const int error = ::sqlite3_bind_null(_pimpl->stmt, index);
549     handle_bind_error(_pimpl->db, "sqlite3_bind_null", error);
550 }
551 
552 
553 /// Binds a text string to a prepared statement.
554 ///
555 /// \param index The index of the binding.
556 /// \param text The string to bind.  SQLite generates an internal copy of this
557 ///     string, so the original string object does not have to remain live.  We
558 ///     do this because handling the lifetime of std::string objects is very
559 ///     hard (think about implicit conversions), so it is very easy to shoot
560 ///     ourselves in the foot if we don't do this.
561 ///
562 /// \throw api_error If the binding fails.
563 void
bind(const int index,const std::string & text)564 sqlite::statement::bind(const int index, const std::string& text)
565 {
566     const int error = ::sqlite3_bind_text(_pimpl->stmt, index, text.c_str(),
567                                           text.length(), SQLITE_TRANSIENT);
568     handle_bind_error(_pimpl->db, "sqlite3_bind_text", error);
569 }
570 
571 
572 /// Returns the index of the highest parameter.
573 ///
574 /// \return A parameter index.
575 int
bind_parameter_count(void)576 sqlite::statement::bind_parameter_count(void)
577 {
578     return ::sqlite3_bind_parameter_count(_pimpl->stmt);
579 }
580 
581 
582 /// Returns the index of a named parameter.
583 ///
584 /// \param name The name of the parameter to be queried; must exist.
585 ///
586 /// \return A parameter index.
587 int
bind_parameter_index(const std::string & name)588 sqlite::statement::bind_parameter_index(const std::string& name)
589 {
590     const int index = ::sqlite3_bind_parameter_index(_pimpl->stmt,
591                                                      name.c_str());
592     PRE_MSG(index > 0, "Parameter name not in statement");
593     return index;
594 }
595 
596 
597 /// Returns the name of a parameter by index.
598 ///
599 /// \param index The index to query; must be valid.
600 ///
601 /// \return The name of the parameter.
602 std::string
bind_parameter_name(const int index)603 sqlite::statement::bind_parameter_name(const int index)
604 {
605     const char* name = ::sqlite3_bind_parameter_name(_pimpl->stmt, index);
606     PRE_MSG(name != NULL, "Index value out of range or nameless parameter");
607     return std::string(name);
608 }
609 
610 
611 /// Clears any bindings and releases their memory.
612 void
clear_bindings(void)613 sqlite::statement::clear_bindings(void)
614 {
615     const int error = ::sqlite3_clear_bindings(_pimpl->stmt);
616 #if defined(__minix) && defined(NDEBUG)
617 #undef PRE_MSG
618 #define PRE_MSG(expr, msg) \
619     do { \
620         if (!(expr)) \
621             utils::sanity_failure(utils::precondition, __FILE__, __LINE__, msg); \
622     } while (0)
623 #endif /* defined(__minix) && defined(NDEBUG) */
624     PRE_MSG(error == SQLITE_OK, "SQLite3 contract has changed; it should "
625             "only return SQLITE_OK");
626 }
627