xref: /freebsd/contrib/kyua/utils/sqlite/statement.cpp (revision 5f4c09dd85bff675e0ca63c55ea3c517e0fddfcc)
1 // Copyright 2011 The Kyua Authors.
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/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"
45 
46 namespace sqlite = utils::sqlite;
47 
48 
49 namespace {
50 
51 
52 static sqlite::type c_type_to_cxx(const int) UTILS_PURE;
53 
54 
55 /// Maps a SQLite 3 data type to our own representation.
56 ///
57 /// \param original The native SQLite 3 data type.
58 ///
59 /// \return Our internal representation for the native data type.
60 static sqlite::type
61 c_type_to_cxx(const int original)
62 {
63     switch (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");
70     }
71     UNREACHABLE;
72 }
73 
74 
75 /// Handles the return value of a sqlite3_bind_* call.
76 ///
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.
80 ///
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.
83 static void
84 handle_bind_error(sqlite::database& db, const char* api_function,
85                   const int error)
86 {
87     switch (error) {
88     case SQLITE_OK:
89         return;
90     case SQLITE_RANGE:
91         UNREACHABLE_MSG("Invalid index for bind argument");
92     case SQLITE_NOMEM:
93         throw std::bad_alloc();
94     default:
95         throw sqlite::api_error::from_database(db, api_function);
96     }
97 }
98 
99 
100 }  // anonymous namespace
101 
102 
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;
107 
108     /// The SQLite 3 internal statement.
109     ::sqlite3_stmt* stmt;
110 
111     /// Cache for the column names in a statement; lazily initialized.
112     std::map< std::string, int > column_cache;
113 
114     /// Constructor.
115     ///
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_) :
123         db(db_),
124         stmt(stmt_)
125     {
126     }
127 
128     /// Destructor.
129     ///
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.
136     ~impl(void)
137     {
138         (void)::sqlite3_finalize(stmt);
139     }
140 };
141 
142 
143 /// Initializes a statement object.
144 ///
145 /// This is an internal function.  Use database::create_statement() to
146 /// instantiate one of these objects.
147 ///
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)))
153 {
154 }
155 
156 
157 /// Destructor for the statement.
158 ///
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)
162 {
163 }
164 
165 
166 /// Executes a statement that is not supposed to return any data.
167 ///
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.
171 ///
172 /// \pre The statement to execute will not produce any rows.
173 void
174 sqlite::statement::step_without_results(void)
175 {
176     const bool data = step();
177     INV_MSG(!data, "The statement should not have produced any rows, but it "
178             "did");
179 }
180 
181 
182 /// Performs a processing step on the statement.
183 ///
184 /// \return True if the statement returned a row; false if the processing has
185 /// finished.
186 ///
187 /// \throw api_error If the processing of the step raises an error.
188 bool
189 sqlite::statement::step(void)
190 {
191     const int error = ::sqlite3_step(_pimpl->stmt);
192     switch (error) {
193     case SQLITE_DONE:
194         LD("Step statement; no more rows");
195         return false;
196     case SQLITE_ROW:
197         LD("Step statement; row available for processing");
198         return true;
199     default:
200         throw api_error::from_database(_pimpl->db, "sqlite3_step");
201     }
202     UNREACHABLE;
203 }
204 
205 
206 /// Returns the number of columns in the step result.
207 ///
208 /// \return The number of columns available for data retrieval.
209 int
210 sqlite::statement::column_count(void)
211 {
212     return ::sqlite3_column_count(_pimpl->stmt);
213 }
214 
215 
216 /// Returns the name of a particular column in the result.
217 ///
218 /// \param index The column to request the name of.
219 ///
220 /// \return The name of the requested column.
221 std::string
222 sqlite::statement::column_name(const int index)
223 {
224     const char* name = ::sqlite3_column_name(_pimpl->stmt, index);
225     if (name == NULL)
226         throw api_error::from_database(_pimpl->db, "sqlite3_column_name");
227     return name;
228 }
229 
230 
231 /// Returns the type of a particular column in the result.
232 ///
233 /// \param index The column to request the type of.
234 ///
235 /// \return The type of the requested column.
236 sqlite::type
237 sqlite::statement::column_type(const int index)
238 {
239     return c_type_to_cxx(::sqlite3_column_type(_pimpl->stmt, index));
240 }
241 
242 
243 /// Finds a column by name.
244 ///
245 /// \param name The name of the column to search for.
246 ///
247 /// \return The column identifier.
248 ///
249 /// \throw value_error If the name cannot be found.
250 int
251 sqlite::statement::column_id(const char* name)
252 {
253     std::map< std::string, int >& cache = _pimpl->column_cache;
254 
255     if (cache.empty()) {
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());
259             cache[aux_name] = i;
260         }
261     }
262 
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);
266     else
267         return (*iter).second;
268 }
269 
270 
271 /// Returns a particular column in the result as a blob.
272 ///
273 /// \param index The column to retrieve.
274 ///
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
277 /// function.
278 sqlite::blob
279 sqlite::statement::column_blob(const int index)
280 {
281     PRE(column_type(index) == type_blob);
282     return blob(::sqlite3_column_blob(_pimpl->stmt, index),
283                 ::sqlite3_column_bytes(_pimpl->stmt, index));
284 }
285 
286 
287 /// Returns a particular column in the result as a double.
288 ///
289 /// \param index The column to retrieve.
290 ///
291 /// \return The double value.
292 double
293 sqlite::statement::column_double(const int index)
294 {
295     PRE(column_type(index) == type_float);
296     return ::sqlite3_column_double(_pimpl->stmt, index);
297 }
298 
299 
300 /// Returns a particular column in the result as an integer.
301 ///
302 /// \param index The column to retrieve.
303 ///
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
306 /// truncation.
307 int
308 sqlite::statement::column_int(const int index)
309 {
310     PRE(column_type(index) == type_integer);
311     return ::sqlite3_column_int(_pimpl->stmt, index);
312 }
313 
314 
315 /// Returns a particular column in the result as a 64-bit integer.
316 ///
317 /// \param index The column to retrieve.
318 ///
319 /// \return The integer value.
320 int64_t
321 sqlite::statement::column_int64(const int index)
322 {
323     PRE(column_type(index) == type_integer);
324     return ::sqlite3_column_int64(_pimpl->stmt, index);
325 }
326 
327 
328 /// Returns a particular column in the result as a double.
329 ///
330 /// \param index The column to retrieve.
331 ///
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
335 /// about this.
336 std::string
337 sqlite::statement::column_text(const int index)
338 {
339     PRE(column_type(index) == type_text);
340     return reinterpret_cast< const char* >(::sqlite3_column_text(
341         _pimpl->stmt, index));
342 }
343 
344 
345 /// Returns the number of bytes stored in the column.
346 ///
347 /// \pre This is only valid for columns of type blob and text.
348 ///
349 /// \param index The column to retrieve the size of.
350 ///
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
353 /// characters.
354 int
355 sqlite::statement::column_bytes(const int index)
356 {
357     PRE(column_type(index) == type_blob || column_type(index) == type_text);
358     return ::sqlite3_column_bytes(_pimpl->stmt, index);
359 }
360 
361 
362 /// Type-checked version of column_blob.
363 ///
364 /// \param name The name of the column to retrieve.
365 ///
366 /// \return The same as column_blob if the value can be retrieved.
367 ///
368 /// \throw error If the type of the cell to retrieve is invalid.
369 /// \throw invalid_column_error If name is invalid.
370 sqlite::blob
371 sqlite::statement::safe_column_blob(const char* name)
372 {
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);
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
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(_pimpl->db.db_filename(),
395                             F("Column '%s' is not a float") % name);
396     return column_double(column);
397 }
398 
399 
400 /// Type-checked version of column_int.
401 ///
402 /// \param name The name of the column to retrieve.
403 ///
404 /// \return The same as column_int if the value can be retrieved.
405 ///
406 /// \throw error If the type of the cell to retrieve is invalid.
407 /// \throw invalid_column_error If name is invalid.
408 int
409 sqlite::statement::safe_column_int(const char* name)
410 {
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);
416 }
417 
418 
419 /// Type-checked version of column_int64.
420 ///
421 /// \param name The name of the column to retrieve.
422 ///
423 /// \return The same as column_int64 if the value can be retrieved.
424 ///
425 /// \throw error If the type of the cell to retrieve is invalid.
426 /// \throw invalid_column_error If name is invalid.
427 int64_t
428 sqlite::statement::safe_column_int64(const char* name)
429 {
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);
435 }
436 
437 
438 /// Type-checked version of column_text.
439 ///
440 /// \param name The name of the column to retrieve.
441 ///
442 /// \return The same as column_text if the value can be retrieved.
443 ///
444 /// \throw error If the type of the cell to retrieve is invalid.
445 /// \throw invalid_column_error If name is invalid.
446 std::string
447 sqlite::statement::safe_column_text(const char* name)
448 {
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);
454 }
455 
456 
457 /// Type-checked version of column_bytes.
458 ///
459 /// \param name The name of the column to retrieve the size of.
460 ///
461 /// \return The same as column_bytes if the value can be retrieved.
462 ///
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.
465 int
466 sqlite::statement::safe_column_bytes(const char* name)
467 {
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);
474 }
475 
476 
477 /// Resets a statement to allow further processing.
478 void
479 sqlite::statement::reset(void)
480 {
481     (void)::sqlite3_reset(_pimpl->stmt);
482 }
483 
484 
485 /// Binds a blob to a prepared statement.
486 ///
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.
490 ///
491 /// \throw api_error If the binding fails.
492 void
493 sqlite::statement::bind(const int index, const blob& b)
494 {
495     const int error = ::sqlite3_bind_blob(_pimpl->stmt, index, b.memory, b.size,
496                                           SQLITE_STATIC);
497     handle_bind_error(_pimpl->db, "sqlite3_bind_blob", error);
498 }
499 
500 
501 /// Binds a double value to a prepared statement.
502 ///
503 /// \param index The index of the binding.
504 /// \param value The double value to bind.
505 ///
506 /// \throw api_error If the binding fails.
507 void
508 sqlite::statement::bind(const int index, const double value)
509 {
510     const int error = ::sqlite3_bind_double(_pimpl->stmt, index, value);
511     handle_bind_error(_pimpl->db, "sqlite3_bind_double", error);
512 }
513 
514 
515 /// Binds an integer value to a prepared statement.
516 ///
517 /// \param index The index of the binding.
518 /// \param value The integer value to bind.
519 ///
520 /// \throw api_error If the binding fails.
521 void
522 sqlite::statement::bind(const int index, const int value)
523 {
524     const int error = ::sqlite3_bind_int(_pimpl->stmt, index, value);
525     handle_bind_error(_pimpl->db, "sqlite3_bind_int", error);
526 }
527 
528 
529 /// Binds a 64-bit integer value to a prepared statement.
530 ///
531 /// \param index The index of the binding.
532 /// \param value The 64-bin integer value to bind.
533 ///
534 /// \throw api_error If the binding fails.
535 void
536 sqlite::statement::bind(const int index, const int64_t value)
537 {
538     const int error = ::sqlite3_bind_int64(_pimpl->stmt, index, value);
539     handle_bind_error(_pimpl->db, "sqlite3_bind_int64", error);
540 }
541 
542 
543 /// Binds a NULL value to a prepared statement.
544 ///
545 /// \param index The index of the binding.
546 ///
547 /// \throw api_error If the binding fails.
548 void
549 sqlite::statement::bind(const int index, const null& /* null */)
550 {
551     const int error = ::sqlite3_bind_null(_pimpl->stmt, index);
552     handle_bind_error(_pimpl->db, "sqlite3_bind_null", error);
553 }
554 
555 
556 /// Binds a text string to a prepared statement.
557 ///
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.
564 ///
565 /// \throw api_error If the binding fails.
566 void
567 sqlite::statement::bind(const int index, const std::string& text)
568 {
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);
572 }
573 
574 
575 /// Returns the index of the highest parameter.
576 ///
577 /// \return A parameter index.
578 int
579 sqlite::statement::bind_parameter_count(void)
580 {
581     return ::sqlite3_bind_parameter_count(_pimpl->stmt);
582 }
583 
584 
585 /// Returns the index of a named parameter.
586 ///
587 /// \param name The name of the parameter to be queried; must exist.
588 ///
589 /// \return A parameter index.
590 int
591 sqlite::statement::bind_parameter_index(const std::string& name)
592 {
593     const int index = ::sqlite3_bind_parameter_index(_pimpl->stmt,
594                                                      name.c_str());
595     PRE_MSG(index > 0, "Parameter name not in statement");
596     return index;
597 }
598 
599 
600 /// Returns the name of a parameter by index.
601 ///
602 /// \param index The index to query; must be valid.
603 ///
604 /// \return The name of the parameter.
605 std::string
606 sqlite::statement::bind_parameter_name(const int index)
607 {
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);
611 }
612 
613 
614 /// Clears any bindings and releases their memory.
615 void
616 sqlite::statement::clear_bindings(void)
617 {
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");
621 }
622