blob: ed0ff1a8a3fc055b999eef00bba877dde8430d85 [file] [log] [blame]
benm@chromium.org98b6f8b12012-02-10 13:31:591// Copyright (c) 2012 The Chromium Authors. All rights reserved.
brettw@chromium.orge5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
tfarina@chromium.orgf0a54b22011-07-19 18:40:215#ifndef SQL_STATEMENT_H_
6#define SQL_STATEMENT_H_
brettw@chromium.orge5ffd0e42009-09-11 21:30:567
tfarina720d4f32015-05-11 22:31:268#include <stdint.h>
Victor Costanf40a87572021-01-07 20:22:159
brettw@chromium.orge5ffd0e42009-09-11 21:30:5610#include <string>
11#include <vector>
12
Victor Costane56cc682018-12-27 01:53:4613#include "base/component_export.h"
Victor Costan698ae04502021-07-08 07:31:0914#include "base/containers/span.h"
Victor Costanc27863df2021-07-14 22:17:5215#include "base/dcheck_is_on.h"
levin@chromium.org3b63f8f42011-03-28 01:54:1516#include "base/memory/ref_counted.h"
Victor Costan3a325b812018-07-23 22:16:1817#include "base/sequence_checker.h"
Jan Wilken Dörrie9720dce2020-07-21 17:14:2318#include "base/strings/string_piece_forward.h"
Victor Costanb3793d62021-07-15 20:21:2819#include "base/thread_annotations.h"
Victor Costanad6b0112021-04-06 00:53:4820#include "base/time/time.h"
Victor Costancfbfa602018-08-01 23:24:4621#include "sql/database.h"
brettw@chromium.orge5ffd0e42009-09-11 21:30:5622
23namespace sql {
24
brettw@chromium.org765b44502009-10-02 05:01:4225// Possible return values from ColumnType in a statement. These should match
26// the values in sqlite3.h.
Victor Costan57aecd232019-04-04 09:09:5727enum class ColumnType {
28 kInteger = 1,
29 kFloat = 2,
30 kText = 3,
31 kBlob = 4,
32 kNull = 5,
brettw@chromium.org765b44502009-10-02 05:01:4233};
34
Victor Costanf40a87572021-01-07 20:22:1535// Compiles and executes SQL statements.
36//
37// This class is not thread-safe. An instance must be accessed from a single
38// sequence. This is enforced in DCHECK-enabled builds.
39//
brettw@chromium.orge5ffd0e42009-09-11 21:30:5640// Normal usage:
nick@chromium.org3273dce2010-01-27 16:08:0841// sql::Statement s(connection_.GetUniqueStatement(...));
brettw@chromium.orge5ffd0e42009-09-11 21:30:5642// s.BindInt(0, a);
43// if (s.Step())
44// return s.ColumnString(0);
cpu@chromium.orgfaa604e2009-09-25 22:38:5945//
shess@chromium.orgeff1fa522011-12-12 23:50:5946// If there are errors getting the statement, the statement will be inert; no
47// mutating or database-access methods will work. If you need to check for
48// validity, use:
49// if (!s.is_valid())
50// return false;
51//
cpu@chromium.orgfaa604e2009-09-25 22:38:5952// Step() and Run() just return true to signal success. If you want to handle
53// specific errors such as database corruption, install an error handler in
54// in the connection object using set_error_delegate().
Victor Costane56cc682018-12-27 01:53:4655class COMPONENT_EXPORT(SQL) Statement {
brettw@chromium.orge5ffd0e42009-09-11 21:30:5656 public:
57 // Creates an uninitialized statement. The statement will be invalid until
58 // you initialize it via Assign.
59 Statement();
60
Victor Costancfbfa602018-08-01 23:24:4661 explicit Statement(scoped_refptr<Database::StatementRef> ref);
Victor Costan00c76432021-07-07 16:55:5862
63 Statement(const Statement&) = delete;
64 Statement& operator=(const Statement&) = delete;
65
brettw@chromium.orge5ffd0e42009-09-11 21:30:5666 ~Statement();
67
68 // Initializes this object with the given statement, which may or may not
69 // be valid. Use is_valid() to check if it's OK.
Victor Costancfbfa602018-08-01 23:24:4670 void Assign(scoped_refptr<Database::StatementRef> ref);
brettw@chromium.orge5ffd0e42009-09-11 21:30:5671
Robert Ogden7b0e36302019-10-17 17:12:3072 // Resets the statement to an uninitialized state corresponding to
shess@chromium.org85fc27b02012-02-17 02:15:0973 // the default constructor, releasing the StatementRef.
74 void Clear();
75
brettw@chromium.orge5ffd0e42009-09-11 21:30:5676 // Returns true if the statement can be executed. All functions can still
77 // be used if the statement is invalid, but they will return failure or some
78 // default value. This is because the statement can become invalid in the
gbillock@chromium.orgbed29d942011-12-22 19:25:5179 // middle of executing a command if there is a serious error and the database
brettw@chromium.orge5ffd0e42009-09-11 21:30:5680 // has to be reset.
Victor Costanf40a87572021-01-07 20:22:1581 bool is_valid() const {
Victor Costanf40a87572021-01-07 20:22:1582 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
Victor Costanf40a87572021-01-07 20:22:1583
84 return ref_->is_valid();
85 }
brettw@chromium.orge5ffd0e42009-09-11 21:30:5686
brettw@chromium.orge5ffd0e42009-09-11 21:30:5687 // Running -------------------------------------------------------------------
88
89 // Executes the statement, returning true on success. This is like Step but
90 // for when there is no output, like an INSERT statement.
91 bool Run();
92
93 // Executes the statement, returning true if there is a row of data returned.
94 // You can keep calling Step() until it returns false to iterate through all
95 // the rows in your result set.
96 //
97 // When Step returns false, the result is either that there is no more data
98 // or there is an error. This makes it most convenient for loop usage. If you
99 // need to disambiguate these cases, use Succeeded().
100 //
101 // Typical example:
102 // while (s.Step()) {
103 // ...
104 // }
105 // return s.Succeeded();
106 bool Step();
107
michaelbai@chromium.org389e0a42012-04-25 21:36:41108 // Resets the statement to its initial condition. This includes any current
109 // result row, and also the bound variables if the |clear_bound_vars| is true.
110 void Reset(bool clear_bound_vars);
brettw@chromium.orge5ffd0e42009-09-11 21:30:56111
112 // Returns true if the last executed thing in this statement succeeded. If
113 // there was no last executed thing or the statement is invalid, this will
114 // return false.
115 bool Succeeded() const;
116
117 // Binding -------------------------------------------------------------------
118
Victor Costan11e241f2021-07-14 04:31:18119 // These all take a 0-based parameter index and return true on success.
brettw@chromium.orge5ffd0e42009-09-11 21:30:56120 // strings there may be out of memory.
Victor Costan11e241f2021-07-14 04:31:18121 void BindNull(int param_index);
122 void BindBool(int param_index, bool val);
123 void BindInt(int param_index, int val);
124 void BindInt(int param_index,
Victor Costan58980e052021-07-13 03:14:15125 int64_t val) = delete; // Call BindInt64() instead.
Victor Costan11e241f2021-07-14 04:31:18126 void BindInt64(int param_index, int64_t val);
127 void BindDouble(int param_index, double val);
128 void BindCString(int param_index, const char* val);
129 void BindString(int param_index, base::StringPiece val);
130 void BindString16(int param_index, base::StringPiece16 value);
131 void BindBlob(int param_index, base::span<const uint8_t> value);
Victor Costan698ae04502021-07-08 07:31:09132
133 // Overload that makes it easy to pass in std::string values.
Victor Costan11e241f2021-07-14 04:31:18134 void BindBlob(int param_index, base::span<const char> value) {
135 BindBlob(param_index, base::as_bytes(base::make_span(value)));
Victor Costan698ae04502021-07-08 07:31:09136 }
brettw@chromium.orge5ffd0e42009-09-11 21:30:56137
Victor Costanad6b0112021-04-06 00:53:48138 // Conforms with base::Time serialization recommendations.
139 //
140 // This is equivalent to the following snippets, which should be replaced.
141 // * BindInt64(col, val.ToInternalValue())
142 // * BindInt64(col, val.ToDeltaSinceWindowsEpoch().InMicroseconds())
143 //
144 // Features that serialize base::Time in other ways, such as ToTimeT() or
145 // ToJavaTime(), will require a database migration to be converted to this
146 // (recommended) serialization method.
147 //
148 // TODO(crbug.com/1195962): Migrate all time serialization to this method, and
149 // then remove the migration details above.
Victor Costan11e241f2021-07-14 04:31:18150 void BindTime(int param_index, base::Time time);
Victor Costanad6b0112021-04-06 00:53:48151
brettw@chromium.orge5ffd0e42009-09-11 21:30:56152 // Retrieving ----------------------------------------------------------------
153
154 // Returns the number of output columns in the result.
155 int ColumnCount() const;
156
brettw@chromium.org765b44502009-10-02 05:01:42157 // Returns the type associated with the given column.
158 //
159 // Watch out: the type may be undefined if you've done something to cause a
160 // "type conversion." This means requesting the value of a column of a type
161 // where that type is not the native type. For safety, call ColumnType only
162 // on a column before getting the value out in any way.
Victor Costan081d5342021-07-15 14:23:59163 ColumnType GetColumnType(int col);
brettw@chromium.org765b44502009-10-02 05:01:42164
brettw@chromium.orge5ffd0e42009-09-11 21:30:56165 // These all take a 0-based argument index.
Victor Costan081d5342021-07-15 14:23:59166 bool ColumnBool(int column_index);
167 int ColumnInt(int column_index);
168 int64_t ColumnInt64(int column_index);
169 double ColumnDouble(int column_index);
170 std::string ColumnString(int column_index);
171 std::u16string ColumnString16(int column_index);
brettw@chromium.orge5ffd0e42009-09-11 21:30:56172
Victor Costanad6b0112021-04-06 00:53:48173 // Conforms with base::Time serialization recommendations.
174 //
175 // This is equivalent to the following snippets, which should be replaced.
176 // * base::Time::FromInternalValue(ColumnInt64(col))
177 // * base::Time::FromDeltaSinceWindowsEpoch(
Peter Kastinge5a38ed2021-10-02 03:06:35178 // base::Microseconds(ColumnInt64(col)))
Victor Costanad6b0112021-04-06 00:53:48179 //
180 // TODO(crbug.com/1195962): Migrate all time serialization to this method, and
181 // then remove the migration details above.
Victor Costan081d5342021-07-15 14:23:59182 base::Time ColumnTime(int column_index);
Victor Costanad6b0112021-04-06 00:53:48183
Victor Costan1268a9992021-07-16 17:16:39184 // Returns a span pointing to a buffer containing the blob data.
185 //
186 // The span's contents should be copied to a caller-owned buffer immediately.
187 // Any method call on the Statement may invalidate the span.
188 //
189 // The span will be empty (and may have a null data) if the underlying blob is
190 // empty. Code that needs to distinguish between empty blobs and NULL should
191 // call GetColumnType() before calling ColumnBlob().
192 base::span<const uint8_t> ColumnBlob(int column_index);
193
Victor Costan081d5342021-07-15 14:23:59194 bool ColumnBlobAsString(int column_index, std::string* result);
195 bool ColumnBlobAsVector(int column_index, std::vector<char>* result);
196 bool ColumnBlobAsVector(int column_index, std::vector<uint8_t>* result);
brettw@chromium.orge5ffd0e42009-09-11 21:30:56197
cpu@chromium.orgfaa604e2009-09-25 22:38:59198 // Diagnostics --------------------------------------------------------------
199
200 // Returns the original text of sql statement. Do not keep a pointer to it.
201 const char* GetSQLStatement();
202
brettw@chromium.orge5ffd0e42009-09-11 21:30:56203 private:
Victor Costancfbfa602018-08-01 23:24:46204 friend class Database;
shess58b8df82015-06-03 00:19:32205
brettw@chromium.orge5ffd0e42009-09-11 21:30:56206 // This is intended to check for serious errors and report them to the
Victor Costancfbfa602018-08-01 23:24:46207 // Database object. It takes a sqlite error code, and returns the same
brettw@chromium.orge5ffd0e42009-09-11 21:30:56208 // code. Currently this function just updates the succeeded flag, but will be
209 // enhanced in the future to do the notification.
210 int CheckError(int err);
211
shess@chromium.orgeff1fa522011-12-12 23:50:59212 // Should be called by all mutating methods to check that the statement is
213 // valid. Returns true if the statement is valid. DCHECKS and returns false
214 // if it is not.
215 // The reason for this is to handle two specific cases in which a Statement
216 // may be invalid. The first case is that the programmer made an SQL error.
217 // Those cases need to be DCHECKed so that we are guaranteed to find them
218 // before release. The second case is that the computer has an error (probably
219 // out of disk space) which is prohibiting the correct operation of the
220 // database. Our testing apparatus should not exhibit this defect, but release
221 // situations may. Therefore, the code is handling disjoint situations in
222 // release and test. In test, we're ensuring correct SQL. In release, we're
223 // ensuring that contracts are honored in error edge cases.
224 bool CheckValid() const;
225
Victor Costan5e785e32019-02-26 20:39:31226 // Helper for Run() and Step(), calls sqlite3_step() and returns the checked
227 // value from it.
228 int StepInternal();
shess58b8df82015-06-03 00:19:32229
brettw@chromium.orge5ffd0e42009-09-11 21:30:56230 // The actual sqlite statement. This may be unique to us, or it may be cached
Victor Costancfbfa602018-08-01 23:24:46231 // by the Database, which is why it's ref-counted. This pointer is
Victor Costanbd623112018-07-18 04:17:27232 // guaranteed non-null.
Victor Costanb3793d62021-07-15 20:21:28233 scoped_refptr<Database::StatementRef> ref_
234 GUARDED_BY_CONTEXT(sequence_checker_);
brettw@chromium.orge5ffd0e42009-09-11 21:30:56235
236 // See Succeeded() for what this holds.
Victor Costanb3793d62021-07-15 20:21:28237 bool succeeded_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
brettw@chromium.orge5ffd0e42009-09-11 21:30:56238
Victor Costanc27863df2021-07-14 22:17:52239#if DCHECK_IS_ON()
240 // Used to DCHECK() that Bind*() is called before Step() or Run() are called.
Victor Costanb3793d62021-07-15 20:21:28241 bool step_called_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
242 bool run_called_ GUARDED_BY_CONTEXT(sequence_checker_) = false;
Victor Costanc27863df2021-07-14 22:17:52243#endif // DCHECK_IS_ON()
244
Victor Costanf40a87572021-01-07 20:22:15245 SEQUENCE_CHECKER(sequence_checker_);
brettw@chromium.orge5ffd0e42009-09-11 21:30:56246};
247
248} // namespace sql
249
tfarina@chromium.orgf0a54b22011-07-19 18:40:21250#endif // SQL_STATEMENT_H_