statement.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef SQL_STATEMENT_H_
  5. #define SQL_STATEMENT_H_
  6. #include <stdint.h>
  7. #include <string>
  8. #include <vector>
  9. #include "base/component_export.h"
  10. #include "base/containers/span.h"
  11. #include "base/dcheck_is_on.h"
  12. #include "base/memory/ref_counted.h"
  13. #include "base/sequence_checker.h"
  14. #include "base/strings/string_piece_forward.h"
  15. #include "base/thread_annotations.h"
  16. #include "base/time/time.h"
  17. #include "sql/database.h"
  18. namespace sql {
  19. enum class SqliteResultCode : int;
  20. // Possible return values from ColumnType in a statement. These should match
  21. // the values in sqlite3.h.
  22. enum class ColumnType {
  23. kInteger = 1,
  24. kFloat = 2,
  25. kText = 3,
  26. kBlob = 4,
  27. kNull = 5,
  28. };
  29. // Compiles and executes SQL statements.
  30. //
  31. // This class is not thread-safe. An instance must be accessed from a single
  32. // sequence. This is enforced in DCHECK-enabled builds.
  33. //
  34. // Normal usage:
  35. // sql::Statement s(connection_.GetUniqueStatement(...));
  36. // s.BindInt(0, a);
  37. // if (s.Step())
  38. // return s.ColumnString(0);
  39. //
  40. // If there are errors getting the statement, the statement will be inert; no
  41. // mutating or database-access methods will work. If you need to check for
  42. // validity, use:
  43. // if (!s.is_valid())
  44. // return false;
  45. //
  46. // Step() and Run() just return true to signal success. If you want to handle
  47. // specific errors such as database corruption, install an error handler in
  48. // in the connection object using set_error_delegate().
  49. class COMPONENT_EXPORT(SQL) Statement {
  50. public:
  51. // Creates an uninitialized statement. The statement will be invalid until
  52. // you initialize it via Assign.
  53. Statement();
  54. explicit Statement(scoped_refptr<Database::StatementRef> ref);
  55. Statement(const Statement&) = delete;
  56. Statement& operator=(const Statement&) = delete;
  57. ~Statement();
  58. // Initializes this object with the given statement, which may or may not
  59. // be valid. Use is_valid() to check if it's OK.
  60. void Assign(scoped_refptr<Database::StatementRef> ref);
  61. // Resets the statement to an uninitialized state corresponding to
  62. // the default constructor, releasing the StatementRef.
  63. void Clear();
  64. // Returns true if the statement can be executed. All functions can still
  65. // be used if the statement is invalid, but they will return failure or some
  66. // default value. This is because the statement can become invalid in the
  67. // middle of executing a command if there is a serious error and the database
  68. // has to be reset.
  69. bool is_valid() const {
  70. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  71. return ref_->is_valid();
  72. }
  73. // Running -------------------------------------------------------------------
  74. // Executes the statement, returning true on success. This is like Step but
  75. // for when there is no output, like an INSERT statement.
  76. bool Run();
  77. // Executes the statement, returning true if there is a row of data returned.
  78. // You can keep calling Step() until it returns false to iterate through all
  79. // the rows in your result set.
  80. //
  81. // When Step returns false, the result is either that there is no more data
  82. // or there is an error. This makes it most convenient for loop usage. If you
  83. // need to disambiguate these cases, use Succeeded().
  84. //
  85. // Typical example:
  86. // while (s.Step()) {
  87. // ...
  88. // }
  89. // return s.Succeeded();
  90. bool Step();
  91. // Resets the statement to its initial condition. This includes any current
  92. // result row, and also the bound variables if the |clear_bound_vars| is true.
  93. void Reset(bool clear_bound_vars);
  94. // Returns true if the last executed thing in this statement succeeded. If
  95. // there was no last executed thing or the statement is invalid, this will
  96. // return false.
  97. bool Succeeded() const;
  98. // Binding -------------------------------------------------------------------
  99. // These all take a 0-based parameter index and return true on success.
  100. // strings there may be out of memory.
  101. void BindNull(int param_index);
  102. void BindBool(int param_index, bool val);
  103. void BindInt(int param_index, int val);
  104. void BindInt(int param_index,
  105. int64_t val) = delete; // Call BindInt64() instead.
  106. void BindInt64(int param_index, int64_t val);
  107. void BindDouble(int param_index, double val);
  108. void BindCString(int param_index, const char* val);
  109. void BindString(int param_index, base::StringPiece val);
  110. void BindString16(int param_index, base::StringPiece16 value);
  111. void BindBlob(int param_index, base::span<const uint8_t> value);
  112. // Overload that makes it easy to pass in std::string values.
  113. void BindBlob(int param_index, base::span<const char> value) {
  114. BindBlob(param_index, base::as_bytes(base::make_span(value)));
  115. }
  116. // Conforms with base::Time serialization recommendations.
  117. //
  118. // This is equivalent to the following snippets, which should be replaced.
  119. // * BindInt64(col, val.ToInternalValue())
  120. // * BindInt64(col, val.ToDeltaSinceWindowsEpoch().InMicroseconds())
  121. //
  122. // Features that serialize base::Time in other ways, such as ToTimeT() or
  123. // ToJavaTime(), will require a database migration to be converted to this
  124. // (recommended) serialization method.
  125. //
  126. // TODO(crbug.com/1195962): Migrate all time serialization to this method, and
  127. // then remove the migration details above.
  128. void BindTime(int param_index, base::Time time);
  129. // Retrieving ----------------------------------------------------------------
  130. // Returns the number of output columns in the result.
  131. int ColumnCount() const;
  132. // Returns the type associated with the given column.
  133. //
  134. // Watch out: the type may be undefined if you've done something to cause a
  135. // "type conversion." This means requesting the value of a column of a type
  136. // where that type is not the native type. For safety, call ColumnType only
  137. // on a column before getting the value out in any way.
  138. ColumnType GetColumnType(int col);
  139. // These all take a 0-based argument index.
  140. bool ColumnBool(int column_index);
  141. int ColumnInt(int column_index);
  142. int64_t ColumnInt64(int column_index);
  143. double ColumnDouble(int column_index);
  144. std::string ColumnString(int column_index);
  145. std::u16string ColumnString16(int column_index);
  146. // Conforms with base::Time serialization recommendations.
  147. //
  148. // This is equivalent to the following snippets, which should be replaced.
  149. // * base::Time::FromInternalValue(ColumnInt64(col))
  150. // * base::Time::FromDeltaSinceWindowsEpoch(
  151. // base::Microseconds(ColumnInt64(col)))
  152. //
  153. // TODO(crbug.com/1195962): Migrate all time serialization to this method, and
  154. // then remove the migration details above.
  155. base::Time ColumnTime(int column_index);
  156. // Returns a span pointing to a buffer containing the blob data.
  157. //
  158. // The span's contents should be copied to a caller-owned buffer immediately.
  159. // Any method call on the Statement may invalidate the span.
  160. //
  161. // The span will be empty (and may have a null data) if the underlying blob is
  162. // empty. Code that needs to distinguish between empty blobs and NULL should
  163. // call GetColumnType() before calling ColumnBlob().
  164. base::span<const uint8_t> ColumnBlob(int column_index);
  165. bool ColumnBlobAsString(int column_index, std::string* result);
  166. bool ColumnBlobAsVector(int column_index, std::vector<char>* result);
  167. bool ColumnBlobAsVector(int column_index, std::vector<uint8_t>* result);
  168. // Diagnostics --------------------------------------------------------------
  169. // Returns the original text of a SQL statement WITHOUT any bound values.
  170. // Intended for logging in case of failures. Note that DOES NOT return any
  171. // bound values, because that would cause a privacy / PII issue for logging.
  172. std::string GetSQLStatement();
  173. private:
  174. friend class Database;
  175. // Checks SQLite result codes and handles any errors.
  176. //
  177. // Returns `sqlite_result_code`. This gives callers the convenience of writing
  178. // "return CheckSqliteResultCode(sqlite_result_code)" and gives the compiler
  179. // the opportunity of doing tail call optimization (TCO) on the code above.
  180. //
  181. // This method reports error codes to the associated Database, and updates
  182. // internal state to reflect whether the statement succeeded or not.
  183. SqliteResultCode CheckSqliteResultCode(SqliteResultCode sqlite_result_code);
  184. // Should be called by all mutating methods to check that the statement is
  185. // valid. Returns true if the statement is valid. DCHECKS and returns false
  186. // if it is not.
  187. // The reason for this is to handle two specific cases in which a Statement
  188. // may be invalid. The first case is that the programmer made an SQL error.
  189. // Those cases need to be DCHECKed so that we are guaranteed to find them
  190. // before release. The second case is that the computer has an error (probably
  191. // out of disk space) which is prohibiting the correct operation of the
  192. // database. Our testing apparatus should not exhibit this defect, but release
  193. // situations may. Therefore, the code is handling disjoint situations in
  194. // release and test. In test, we're ensuring correct SQL. In release, we're
  195. // ensuring that contracts are honored in error edge cases.
  196. bool CheckValid() const;
  197. // Helper for Run() and Step(), calls sqlite3_step() and returns the checked
  198. // value from it.
  199. SqliteResultCode StepInternal();
  200. // The actual sqlite statement. This may be unique to us, or it may be cached
  201. // by the Database, which is why it's ref-counted. This pointer is
  202. // guaranteed non-null.
  203. scoped_refptr<Database::StatementRef> ref_
  204. GUARDED_BY_CONTEXT(sequence_checker_);
  205. // See Succeeded() for what this holds.
  206. bool succeeded_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  207. #if DCHECK_IS_ON()
  208. // Used to DCHECK() that Bind*() is called before Step() or Run() are called.
  209. bool step_called_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  210. bool run_called_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
  211. #endif // DCHECK_IS_ON()
  212. SEQUENCE_CHECKER(sequence_checker_);
  213. };
  214. } // namespace sql
  215. #endif // SQL_STATEMENT_H_