blob: 055c29006cb8cc60e57db7778a41b856d369b356 [file] [log] [blame]
[email protected]2eec0a22012-07-24 01:59:581// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-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
[email protected]f0a54b22011-07-19 18:40:215#ifndef SQL_CONNECTION_H_
6#define SQL_CONNECTION_H_
[email protected]e5ffd0e42009-09-11 21:30:567
avi0b519202015-12-21 07:25:198#include <stddef.h>
tfarina720d4f32015-05-11 22:31:269#include <stdint.h>
mostynbd82cd9952016-04-11 20:05:3410#include <memory>
[email protected]e5ffd0e42009-09-11 21:30:5611#include <set>
[email protected]7d6aee4e2009-09-12 01:12:3312#include <string>
Victor Costan87cf8c72018-07-19 19:36:0413#include <utility>
[email protected]80abf152013-05-22 12:42:4214#include <vector>
[email protected]e5ffd0e42009-09-11 21:30:5615
[email protected]c3881b372013-05-17 08:39:4616#include "base/callback.h"
[email protected]9fe37552011-12-23 17:07:2017#include "base/compiler_specific.h"
Dmitry Skibaa9ad8fe42017-08-16 21:02:4818#include "base/containers/flat_map.h"
shessc8cd2a162015-10-22 20:30:4619#include "base/gtest_prod_util.h"
tfarina720d4f32015-05-11 22:31:2620#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1521#include "base/memory/ref_counted.h"
Victor Costan12daa3ac92018-07-19 01:05:5822#include "base/sequence_checker.h"
[email protected]35f7e5392012-07-27 19:54:5023#include "base/threading/thread_restrictions.h"
Victor Costan87cf8c72018-07-19 19:36:0424#include "base/time/tick_clock.h"
[email protected]d4526962011-11-10 21:40:2825#include "sql/sql_export.h"
Victor Costan12daa3ac92018-07-19 01:05:5826#include "sql/statement_id.h"
[email protected]e5ffd0e42009-09-11 21:30:5627
[email protected]e5ffd0e42009-09-11 21:30:5628struct sqlite3;
29struct sqlite3_stmt;
30
[email protected]a3ef4832013-02-02 05:12:3331namespace base {
32class FilePath;
shess58b8df82015-06-03 00:19:3233class HistogramBase;
dskibab4199f82016-11-21 20:16:1334namespace trace_event {
ssid1f4e5362016-12-08 20:41:3835class ProcessMemoryDump;
Victor Costan87cf8c72018-07-19 19:36:0436} // namespace trace_event
37} // namespace base
[email protected]a3ef4832013-02-02 05:12:3338
[email protected]e5ffd0e42009-09-11 21:30:5639namespace sql {
40
ssid3be5b1ec2016-01-13 14:21:5741class ConnectionMemoryDumpProvider;
[email protected]8d409412013-07-19 18:25:3042class Recovery;
[email protected]e5ffd0e42009-09-11 21:30:5643class Statement;
44
shess58b8df82015-06-03 00:19:3245// To allow some test classes to be friended.
46namespace test {
47class ScopedCommitHook;
shess976814402016-06-21 06:56:2548class ScopedErrorExpecter;
shess58b8df82015-06-03 00:19:3249class ScopedScalarFunction;
50class ScopedMockTimeSource;
Victor Costan87cf8c72018-07-19 19:36:0451} // namespace test
shess58b8df82015-06-03 00:19:3252
[email protected]faa604e2009-09-25 22:38:5953class Connection;
54
Victor Costan87cf8c72018-07-19 19:36:0455// Handle to an open SQLite database.
56//
57// Instances of this class are thread-unsafe and DCHECK that they are accessed
58// on the same sequence.
59//
60// TODO(pwnall): This should be renamed to Database. Class instances are
61// typically named "db_" / "db", and the class' equivalents in other systems
62// used by Chrome are named LevelDB::DB and blink::IDBDatabase.
ssid3be5b1ec2016-01-13 14:21:5763class SQL_EXPORT Connection {
[email protected]e5ffd0e42009-09-11 21:30:5664 private:
65 class StatementRef; // Forward declaration, see real one below.
66
67 public:
[email protected]765b44502009-10-02 05:01:4268 // The database is opened by calling Open[InMemory](). Any uncommitted
69 // transactions will be rolled back when this object is deleted.
[email protected]e5ffd0e42009-09-11 21:30:5670 Connection();
ssid3be5b1ec2016-01-13 14:21:5771 ~Connection();
[email protected]e5ffd0e42009-09-11 21:30:5672
73 // Pre-init configuration ----------------------------------------------------
74
[email protected]765b44502009-10-02 05:01:4275 // Sets the page size that will be used when creating a new database. This
[email protected]e5ffd0e42009-09-11 21:30:5676 // must be called before Init(), and will only have an effect on new
77 // databases.
78 //
79 // From sqlite.org: "The page size must be a power of two greater than or
80 // equal to 512 and less than or equal to SQLITE_MAX_PAGE_SIZE. The maximum
81 // value for SQLITE_MAX_PAGE_SIZE is 32768."
Victor Costan87cf8c72018-07-19 19:36:0482 void set_page_size(int page_size) {
83 DCHECK(!page_size || (page_size >= 512));
84 DCHECK(!page_size || !(page_size & (page_size - 1)))
85 << "page_size must be a power of two";
86
87 page_size_ = page_size;
88 }
[email protected]e5ffd0e42009-09-11 21:30:5689
90 // Sets the number of pages that will be cached in memory by sqlite. The
91 // total cache size in bytes will be page_size * cache_size. This must be
[email protected]765b44502009-10-02 05:01:4292 // called before Open() to have an effect.
Victor Costan87cf8c72018-07-19 19:36:0493 void set_cache_size(int cache_size) {
94 DCHECK_GE(cache_size, 0);
95
96 cache_size_ = cache_size;
97 }
[email protected]e5ffd0e42009-09-11 21:30:5698
99 // Call to put the database in exclusive locking mode. There is no "back to
100 // normal" flag because of some additional requirements sqlite puts on this
[email protected]4ab952f2014-04-01 20:18:16101 // transaction (requires another access to the DB) and because we don't
[email protected]e5ffd0e42009-09-11 21:30:56102 // actually need it.
103 //
104 // Exclusive mode means that the database is not unlocked at the end of each
105 // transaction, which means there may be less time spent initializing the
106 // next transaction because it doesn't have to re-aquire locks.
107 //
[email protected]765b44502009-10-02 05:01:42108 // This must be called before Open() to have an effect.
[email protected]e5ffd0e42009-09-11 21:30:56109 void set_exclusive_locking() { exclusive_locking_ = true; }
110
[email protected]81a2a602013-07-17 19:10:36111 // Call to cause Open() to restrict access permissions of the
112 // database file to only the owner.
Victor Costan87cf8c72018-07-19 19:36:04113 //
114 // This is only supported on OS_POSIX and is a noop on other platforms.
[email protected]81a2a602013-07-17 19:10:36115 void set_restrict_to_user() { restrict_to_user_ = true; }
116
shessa62504d2016-11-07 19:26:12117 // Call to use alternative status-tracking for mmap. Usually this is tracked
118 // in the meta table, but some databases have no meta table.
119 // TODO(shess): Maybe just have all databases use the alt option?
120 void set_mmap_alt_status() { mmap_alt_status_ = true; }
121
Victor Costan87cf8c72018-07-19 19:36:04122 // Opt out of memory-mapped file I/O.
shess7dbd4dee2015-10-06 17:39:16123 void set_mmap_disabled() { mmap_disabled_ = true; }
124
[email protected]c3881b372013-05-17 08:39:46125 // Set an error-handling callback. On errors, the error number (and
126 // statement, if available) will be passed to the callback.
127 //
128 // If no callback is set, the default action is to crash in debug
129 // mode or return failure in release mode.
Victor Costanc7e7f2e2018-07-18 20:07:55130 using ErrorCallback = base::RepeatingCallback<void(int, Statement*)>;
[email protected]c3881b372013-05-17 08:39:46131 void set_error_callback(const ErrorCallback& callback) {
132 error_callback_ = callback;
133 }
Victor Costan87cf8c72018-07-19 19:36:04134 bool has_error_callback() const { return !error_callback_.is_null(); }
135 void reset_error_callback() { error_callback_.Reset(); }
[email protected]c3881b372013-05-17 08:39:46136
shess58b8df82015-06-03 00:19:32137 // Set this to enable additional per-connection histogramming. Must be called
138 // before Open().
139 void set_histogram_tag(const std::string& tag);
[email protected]c088e3a32013-01-03 23:59:14140
[email protected]210ce0af2013-05-15 09:10:39141 // Record a sparse UMA histogram sample under
142 // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no
143 // histogram is recorded.
144 void AddTaggedHistogram(const std::string& name, size_t sample) const;
145
shess58b8df82015-06-03 00:19:32146 // Track various API calls and results. Values corrospond to UMA
147 // histograms, do not modify, or add or delete other than directly
148 // before EVENT_MAX_VALUE.
149 enum Events {
150 // Number of statements run, either with sql::Statement or Execute*().
151 EVENT_STATEMENT_RUN = 0,
152
153 // Number of rows returned by statements run.
154 EVENT_STATEMENT_ROWS,
155
156 // Number of statements successfully run (all steps returned SQLITE_DONE or
157 // SQLITE_ROW).
158 EVENT_STATEMENT_SUCCESS,
159
160 // Number of statements run by Execute() or ExecuteAndReturnErrorCode().
161 EVENT_EXECUTE,
162
163 // Number of rows changed by autocommit statements.
164 EVENT_CHANGES_AUTOCOMMIT,
165
166 // Number of rows changed by statements in transactions.
167 EVENT_CHANGES,
168
169 // Count actual SQLite transaction statements (not including nesting).
170 EVENT_BEGIN,
171 EVENT_COMMIT,
172 EVENT_ROLLBACK,
173
shessd90aeea82015-11-13 02:24:31174 // Track success and failure in GetAppropriateMmapSize().
175 // GetAppropriateMmapSize() should record at most one of these per run. The
176 // case of mapping everything is not recorded.
177 EVENT_MMAP_META_MISSING, // No meta table present.
178 EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table.
179 EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table.
180 EVENT_MMAP_VFS_FAILURE, // Failed to access VFS.
181 EVENT_MMAP_FAILED, // Failure from past run.
182 EVENT_MMAP_FAILED_NEW, // Read error in this run.
183 EVENT_MMAP_SUCCESS_NEW, // Read to EOF in this run.
184 EVENT_MMAP_SUCCESS_PARTIAL, // Read but did not reach EOF.
185 EVENT_MMAP_SUCCESS_NO_PROGRESS, // Read quota exhausted.
186
shessa62504d2016-11-07 19:26:12187 EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view.
188 EVENT_MMAP_STATUS_FAILURE_UPDATE,// Failure updating MmapStatus view.
189
shess58b8df82015-06-03 00:19:32190 // Leave this at the end.
191 // TODO(shess): |EVENT_MAX| causes compile fail on Windows.
192 EVENT_MAX_VALUE
193 };
194 void RecordEvent(Events event, size_t count);
Victor Costan87cf8c72018-07-19 19:36:04195 void RecordOneEvent(Events event) { RecordEvent(event, 1); }
shess58b8df82015-06-03 00:19:32196
[email protected]579446c2013-12-16 18:36:52197 // Run "PRAGMA integrity_check" and post each line of
198 // results into |messages|. Returns the success of running the
199 // statement - per the SQLite documentation, if no errors are found the
200 // call should succeed, and a single value "ok" should be in messages.
201 bool FullIntegrityCheck(std::vector<std::string>* messages);
202
203 // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method,
204 // interprets the results returning true if the the statement executes
205 // without error and results in a single "ok" value.
206 bool QuickIntegrityCheck() WARN_UNUSED_RESULT;
[email protected]80abf152013-05-22 12:42:42207
afakhry7c9abe72016-08-05 17:33:19208 // Meant to be called from a client error callback so that it's able to
209 // get diagnostic information about the database.
210 std::string GetDiagnosticInfo(int extended_error, Statement* statement);
211
ssid1f4e5362016-12-08 20:41:38212 // Reports memory usage into provided memory dump with the given name.
213 bool ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
214 const std::string& dump_name);
dskibab4199f82016-11-21 20:16:13215
[email protected]e5ffd0e42009-09-11 21:30:56216 // Initialization ------------------------------------------------------------
217
218 // Initializes the SQL connection for the given file, returning true if the
[email protected]35f2094c2009-12-29 22:46:55219 // file could be opened. You can call this or OpenInMemory.
[email protected]a3ef4832013-02-02 05:12:33220 bool Open(const base::FilePath& path) WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42221
222 // Initializes the SQL connection for a temporary in-memory database. There
223 // will be no associated file on disk, and the initial database will be
[email protected]35f2094c2009-12-29 22:46:55224 // empty. You can call this or Open.
[email protected]9fe37552011-12-23 17:07:20225 bool OpenInMemory() WARN_UNUSED_RESULT;
[email protected]765b44502009-10-02 05:01:42226
[email protected]8d409412013-07-19 18:25:30227 // Create a temporary on-disk database. The database will be
228 // deleted after close. This kind of database is similar to
229 // OpenInMemory() for small databases, but can page to disk if the
230 // database becomes large.
231 bool OpenTemporary() WARN_UNUSED_RESULT;
232
[email protected]41a97c812013-02-07 02:35:38233 // Returns true if the database has been successfully opened.
Victor Costan87cf8c72018-07-19 19:36:04234 bool is_open() const { return static_cast<bool>(db_); }
[email protected]e5ffd0e42009-09-11 21:30:56235
236 // Closes the database. This is automatically performed on destruction for
237 // you, but this allows you to close the database early. You must not call
238 // any other functions after closing it. It is permissable to call Close on
239 // an uninitialized or already-closed database.
240 void Close();
241
[email protected]8ada10f2013-12-21 00:42:34242 // Reads the first <cache-size>*<page-size> bytes of the file to prime the
243 // filesystem cache. This can be more efficient than faulting pages
244 // individually. Since this involves blocking I/O, it should only be used if
245 // the caller will immediately read a substantial amount of data from the
246 // database.
[email protected]e5ffd0e42009-09-11 21:30:56247 //
[email protected]8ada10f2013-12-21 00:42:34248 // TODO(shess): Design a set of histograms or an experiment to inform this
249 // decision. Preloading should almost always improve later performance
250 // numbers for this database simply because it pulls operations forward, but
251 // if the data isn't actually used soon then preloading just slows down
252 // everything else.
[email protected]e5ffd0e42009-09-11 21:30:56253 void Preload();
254
[email protected]be7995f12013-07-18 18:49:14255 // Try to trim the cache memory used by the database. If |aggressively| is
256 // true, this function will try to free all of the cache memory it can. If
257 // |aggressively| is false, this function will try to cut cache memory
258 // usage by half.
259 void TrimMemory(bool aggressively);
260
[email protected]8e0c01282012-04-06 19:36:49261 // Raze the database to the ground. This approximates creating a
262 // fresh database from scratch, within the constraints of SQLite's
263 // locking protocol (locks and open handles can make doing this with
264 // filesystem operations problematic). Returns true if the database
265 // was razed.
266 //
267 // false is returned if the database is locked by some other
Carlos Knippschild46800c9f2017-09-02 02:21:43268 // process.
[email protected]8e0c01282012-04-06 19:36:49269 //
270 // NOTE(shess): Raze() will DCHECK in the following situations:
271 // - database is not open.
272 // - the connection has a transaction open.
273 // - a SQLite issue occurs which is structural in nature (like the
274 // statements used are broken).
275 // Since Raze() is expected to be called in unexpected situations,
276 // these all return false, since it is unlikely that the caller
277 // could fix them.
[email protected]6d42f152012-11-10 00:38:24278 //
279 // The database's page size is taken from |page_size_|. The
280 // existing database's |auto_vacuum| setting is lost (the
281 // possibility of corruption makes it unreliable to pull it from the
282 // existing database). To re-enable on the empty database requires
283 // running "PRAGMA auto_vacuum = 1;" then "VACUUM".
284 //
285 // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1,
286 // so Raze() sets auto_vacuum to 1.
287 //
288 // TODO(shess): Raze() needs a connection so cannot clear SQLITE_NOTADB.
289 // TODO(shess): Bake auto_vacuum into Connection's API so it can
290 // just pick up the default.
[email protected]8e0c01282012-04-06 19:36:49291 bool Raze();
[email protected]8e0c01282012-04-06 19:36:49292
[email protected]41a97c812013-02-07 02:35:38293 // Breaks all outstanding transactions (as initiated by
[email protected]8d409412013-07-19 18:25:30294 // BeginTransaction()), closes the SQLite database, and poisons the
295 // object so that all future operations against the Connection (or
296 // its Statements) fail safely, without side effects.
[email protected]41a97c812013-02-07 02:35:38297 //
[email protected]8d409412013-07-19 18:25:30298 // This is intended as an alternative to Close() in error callbacks.
299 // Close() should still be called at some point.
300 void Poison();
301
302 // Raze() the database and Poison() the handle. Returns the return
303 // value from Raze().
304 // TODO(shess): Rename to RazeAndPoison().
[email protected]41a97c812013-02-07 02:35:38305 bool RazeAndClose();
306
[email protected]8d2e39e2013-06-24 05:55:08307 // Delete the underlying database files associated with |path|.
308 // This should be used on a database which has no existing
309 // connections. If any other connections are open to the same
310 // database, this could cause odd results or corruption (for
311 // instance if a hot journal is deleted but the associated database
312 // is not).
313 //
314 // Returns true if the database file and associated journals no
315 // longer exist, false otherwise. If the database has never
316 // existed, this will return true.
317 static bool Delete(const base::FilePath& path);
318
[email protected]e5ffd0e42009-09-11 21:30:56319 // Transactions --------------------------------------------------------------
320
321 // Transaction management. We maintain a virtual transaction stack to emulate
322 // nested transactions since sqlite can't do nested transactions. The
323 // limitation is you can't roll back a sub transaction: if any transaction
324 // fails, all transactions open will also be rolled back. Any nested
325 // transactions after one has rolled back will return fail for Begin(). If
326 // Begin() fails, you must not call Commit or Rollback().
327 //
328 // Normally you should use sql::Transaction to manage a transaction, which
329 // will scope it to a C++ context.
330 bool BeginTransaction();
331 void RollbackTransaction();
332 bool CommitTransaction();
333
[email protected]8d409412013-07-19 18:25:30334 // Rollback all outstanding transactions. Use with care, there may
335 // be scoped transactions on the stack.
336 void RollbackAllTransactions();
337
[email protected]e5ffd0e42009-09-11 21:30:56338 // Returns the current transaction nesting, which will be 0 if there are
339 // no open transactions.
340 int transaction_nesting() const { return transaction_nesting_; }
341
[email protected]8d409412013-07-19 18:25:30342 // Attached databases---------------------------------------------------------
343
344 // SQLite supports attaching multiple database files to a single
345 // handle. Attach the database in |other_db_path| to the current
346 // handle under |attachment_point|. |attachment_point| should only
347 // contain characters from [a-zA-Z0-9_].
348 //
Victor Costan8a87f7e52017-11-10 01:29:30349 // Attaching a database while a transaction is open will have
350 // platform-dependent results, as explained below.
351 //
352 // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can
353 // be attached while a transaction is opened. However, these databases cannot
Victor Costan70bedf22018-07-18 21:21:14354 // be detached until the transaction is committed or aborted.
[email protected]8d409412013-07-19 18:25:30355 bool AttachDatabase(const base::FilePath& other_db_path,
356 const char* attachment_point);
357 bool DetachDatabase(const char* attachment_point);
358
[email protected]e5ffd0e42009-09-11 21:30:56359 // Statements ----------------------------------------------------------------
360
361 // Executes the given SQL string, returning true on success. This is
362 // normally used for simple, 1-off statements that don't take any bound
363 // parameters and don't return any data (e.g. CREATE TABLE).
[email protected]9fe37552011-12-23 17:07:20364 //
[email protected]eff1fa522011-12-12 23:50:59365 // This will DCHECK if the |sql| contains errors.
[email protected]9fe37552011-12-23 17:07:20366 //
367 // Do not use ignore_result() to ignore all errors. Use
368 // ExecuteAndReturnErrorCode() and ignore only specific errors.
369 bool Execute(const char* sql) WARN_UNUSED_RESULT;
[email protected]e5ffd0e42009-09-11 21:30:56370
[email protected]eff1fa522011-12-12 23:50:59371 // Like Execute(), but returns the error code given by SQLite.
[email protected]9fe37552011-12-23 17:07:20372 int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT;
[email protected]eff1fa522011-12-12 23:50:59373
[email protected]e5ffd0e42009-09-11 21:30:56374 // Returns a statement for the given SQL using the statement cache. It can
375 // take a nontrivial amount of work to parse and compile a statement, so
376 // keeping commonly-used ones around for future use is important for
377 // performance.
378 //
[email protected]eff1fa522011-12-12 23:50:59379 // If the |sql| has an error, an invalid, inert StatementRef is returned (and
380 // the code will crash in debug). The caller must deal with this eventuality,
381 // either by checking validity of the |sql| before calling, by correctly
382 // handling the return of an inert statement, or both.
[email protected]e5ffd0e42009-09-11 21:30:56383 //
384 // The StatementID and the SQL must always correspond to one-another. The
385 // ID is the lookup into the cache, so crazy things will happen if you use
386 // different SQL with the same ID.
387 //
388 // You will normally use the SQL_FROM_HERE macro to generate a statement
389 // ID associated with the current line of code. This gives uniqueness without
390 // you having to manage unique names. See StatementID above for more.
391 //
392 // Example:
[email protected]3273dce2010-01-27 16:08:08393 // sql::Statement stmt(connection_.GetCachedStatement(
394 // SQL_FROM_HERE, "SELECT * FROM foo"));
[email protected]e5ffd0e42009-09-11 21:30:56395 // if (!stmt)
396 // return false; // Error creating statement.
Victor Costan12daa3ac92018-07-19 01:05:58397 scoped_refptr<StatementRef> GetCachedStatement(StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:56398 const char* sql);
399
[email protected]eff1fa522011-12-12 23:50:59400 // Used to check a |sql| statement for syntactic validity. If the statement is
401 // valid SQL, returns true.
402 bool IsSQLValid(const char* sql);
403
[email protected]e5ffd0e42009-09-11 21:30:56404 // Returns a non-cached statement for the given SQL. Use this for SQL that
405 // is only executed once or only rarely (there is overhead associated with
406 // keeping a statement cached).
407 //
408 // See GetCachedStatement above for examples and error information.
409 scoped_refptr<StatementRef> GetUniqueStatement(const char* sql);
410
411 // Info querying -------------------------------------------------------------
412
shessa62504d2016-11-07 19:26:12413 // Returns true if the given structure exists. Instead of test-then-create,
414 // callers should almost always prefer the "IF NOT EXISTS" version of the
415 // CREATE statement.
[email protected]e2cadec82011-12-13 02:00:53416 bool DoesIndexExist(const char* index_name) const;
shessa62504d2016-11-07 19:26:12417 bool DoesTableExist(const char* table_name) const;
418 bool DoesViewExist(const char* table_name) const;
[email protected]e2cadec82011-12-13 02:00:53419
[email protected]e5ffd0e42009-09-11 21:30:56420 // Returns true if a column with the given name exists in the given table.
[email protected]1ed78a32009-09-15 20:24:17421 bool DoesColumnExist(const char* table_name, const char* column_name) const;
[email protected]e5ffd0e42009-09-11 21:30:56422
423 // Returns sqlite's internal ID for the last inserted row. Valid only
424 // immediately after an insert.
tfarina720d4f32015-05-11 22:31:26425 int64_t GetLastInsertRowId() const;
[email protected]e5ffd0e42009-09-11 21:30:56426
[email protected]1ed78a32009-09-15 20:24:17427 // Returns sqlite's count of the number of rows modified by the last
428 // statement executed. Will be 0 if no statement has executed or the database
429 // is closed.
430 int GetLastChangeCount() const;
431
[email protected]e5ffd0e42009-09-11 21:30:56432 // Errors --------------------------------------------------------------------
433
434 // Returns the error code associated with the last sqlite operation.
435 int GetErrorCode() const;
436
[email protected]767718e52010-09-21 23:18:49437 // Returns the errno associated with GetErrorCode(). See
438 // SQLITE_LAST_ERRNO in SQLite documentation.
439 int GetLastErrno() const;
440
[email protected]e5ffd0e42009-09-11 21:30:56441 // Returns a pointer to a statically allocated string associated with the
442 // last sqlite operation.
443 const char* GetErrorMessage() const;
444
[email protected]92cd00a2013-08-16 11:09:58445 // Return a reproducible representation of the schema equivalent to
446 // running the following statement at a sqlite3 command-line:
447 // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4;
448 std::string GetSchema() const;
449
shess976814402016-06-21 06:56:25450 // Returns |true| if there is an error expecter (see SetErrorExpecter), and
451 // that expecter returns |true| when passed |error|. Clients which provide an
452 // |error_callback| should use IsExpectedSqliteError() to check for unexpected
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52453 // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see
shess976814402016-06-21 06:56:25454 // OnSqliteError implementation).
455 static bool IsExpectedSqliteError(int error);
[email protected]74cdede2013-09-25 05:39:57456
shessc8cd2a162015-10-22 20:30:46457 // Collect various diagnostic information and post a crash dump to aid
458 // debugging. Dump rate per database is limited to prevent overwhelming the
459 // crash server.
460 void ReportDiagnosticInfo(int extended_error, Statement* stmt);
461
Victor Costan87cf8c72018-07-19 19:36:04462 // Helper to return the current time from the time source.
463 base::TimeTicks NowTicks() const { return clock_->NowTicks(); }
464
465 // Intended for tests to inject a mock time source.
466 //
467 // Inlined to avoid generating code in the production binary.
468 inline void set_clock_for_testing(std::unique_ptr<base::TickClock> clock) {
469 clock_ = std::move(clock);
470 }
471
[email protected]e5ffd0e42009-09-11 21:30:56472 private:
[email protected]8d409412013-07-19 18:25:30473 // For recovery module.
474 friend class Recovery;
475
shess976814402016-06-21 06:56:25476 // Allow test-support code to set/reset error expecter.
477 friend class test::ScopedErrorExpecter;
[email protected]4350e322013-06-18 22:18:10478
[email protected]eff1fa522011-12-12 23:50:59479 // Statement accesses StatementRef which we don't want to expose to everybody
[email protected]e5ffd0e42009-09-11 21:30:56480 // (they should go through Statement).
481 friend class Statement;
482
shess58b8df82015-06-03 00:19:32483 friend class test::ScopedCommitHook;
484 friend class test::ScopedScalarFunction;
485 friend class test::ScopedMockTimeSource;
486
Victor Costan87cf8c72018-07-19 19:36:04487 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, CachedStatement);
shessc8cd2a162015-10-22 20:30:46488 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, CollectDiagnosticInfo);
shess9bf2c672015-12-18 01:18:08489 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSize);
shessa62504d2016-11-07 19:26:12490 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, GetAppropriateMmapSizeAltStatus);
ssid3be5b1ec2016-01-13 14:21:57491 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, OnMemoryDump);
shessc8cd2a162015-10-22 20:30:46492 FRIEND_TEST_ALL_PREFIXES(SQLConnectionTest, RegisterIntentToUpload);
shessf7fcc452017-04-19 22:10:41493 FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose);
shessc8cd2a162015-10-22 20:30:46494
[email protected]765b44502009-10-02 05:01:42495 // Internal initialize function used by both Init and InitInMemory. The file
496 // name is always 8 bits since we want to use the 8-bit version of
497 // sqlite3_open. The string can also be sqlite's special ":memory:" string.
[email protected]fed734a2013-07-17 04:45:13498 //
499 // |retry_flag| controls retrying the open if the error callback
500 // addressed errors using RazeAndClose().
501 enum Retry {
502 NO_RETRY = 0,
503 RETRY_ON_POISON
504 };
505 bool OpenInternal(const std::string& file_name, Retry retry_flag);
[email protected]765b44502009-10-02 05:01:42506
[email protected]41a97c812013-02-07 02:35:38507 // Internal close function used by Close() and RazeAndClose().
508 // |forced| indicates that orderly-shutdown checks should not apply.
509 void CloseInternal(bool forced);
510
[email protected]35f7e5392012-07-27 19:54:50511 // Check whether the current thread is allowed to make IO calls, but only
512 // if database wasn't open in memory. Function is inlined to be a no-op in
513 // official build.
shessc8cd2a162015-10-22 20:30:46514 void AssertIOAllowed() const {
[email protected]35f7e5392012-07-27 19:54:50515 if (!in_memory_)
Francois Doray66bdfd82017-10-20 13:50:37516 base::AssertBlockingAllowed();
[email protected]35f7e5392012-07-27 19:54:50517 }
518
shessa62504d2016-11-07 19:26:12519 // Internal helper for Does*Exist() functions.
520 bool DoesSchemaItemExist(const char* name, const char* type) const;
[email protected]e2cadec82011-12-13 02:00:53521
shess976814402016-06-21 06:56:25522 // Accessors for global error-expecter, for injecting behavior during tests.
523 // See test/scoped_error_expecter.h.
Victor Costanc7e7f2e2018-07-18 20:07:55524 using ErrorExpecterCallback = base::RepeatingCallback<bool(int)>;
shess976814402016-06-21 06:56:25525 static ErrorExpecterCallback* current_expecter_cb_;
526 static void SetErrorExpecter(ErrorExpecterCallback* expecter);
527 static void ResetErrorExpecter();
[email protected]4350e322013-06-18 22:18:10528
[email protected]e5ffd0e42009-09-11 21:30:56529 // A StatementRef is a refcounted wrapper around a sqlite statement pointer.
530 // Refcounting allows us to give these statements out to sql::Statement
531 // objects while also optionally maintaining a cache of compiled statements
532 // by just keeping a refptr to these objects.
533 //
534 // A statement ref can be valid, in which case it can be used, or invalid to
535 // indicate that the statement hasn't been created yet, has an error, or has
536 // been destroyed.
537 //
538 // The Connection may revoke a StatementRef in some error cases, so callers
539 // should always check validity before using.
[email protected]601dc6a2011-11-12 01:14:23540 class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> {
[email protected]e5ffd0e42009-09-11 21:30:56541 public:
Victor Costan3b02cdf2018-07-18 00:39:56542 REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
543
[email protected]41a97c812013-02-07 02:35:38544 // |connection| is the sql::Connection instance associated with
545 // the statement, and is used for tracking outstanding statements
Victor Costanbd623112018-07-18 04:17:27546 // and for error handling. Set to nullptr for invalid or untracked
547 // refs. |stmt| is the actual statement, and should only be null
[email protected]41a97c812013-02-07 02:35:38548 // to create an invalid ref. |was_valid| indicates whether the
549 // statement should be considered valid for diagnistic purposes.
Victor Costanbd623112018-07-18 04:17:27550 // |was_valid| can be true for a null |stmt| if the connection has
[email protected]41a97c812013-02-07 02:35:38551 // been forcibly closed by an error handler.
552 StatementRef(Connection* connection, sqlite3_stmt* stmt, bool was_valid);
[email protected]e5ffd0e42009-09-11 21:30:56553
554 // When true, the statement can be used.
555 bool is_valid() const { return !!stmt_; }
556
[email protected]41a97c812013-02-07 02:35:38557 // When true, the statement is either currently valid, or was
558 // previously valid but the connection was forcibly closed. Used
559 // for diagnostic checks.
560 bool was_valid() const { return was_valid_; }
561
Victor Costanbd623112018-07-18 04:17:27562 // If we've not been linked to a connection, this will be null.
563 //
564 // TODO(shess): connection_ can be nullptr in case of
565 // GetUntrackedStatement(), which prevents Statement::OnError() from
566 // forwarding errors.
[email protected]e5ffd0e42009-09-11 21:30:56567 Connection* connection() const { return connection_; }
568
569 // Returns the sqlite statement if any. If the statement is not active,
Victor Costanbd623112018-07-18 04:17:27570 // this will return nullptr.
[email protected]e5ffd0e42009-09-11 21:30:56571 sqlite3_stmt* stmt() const { return stmt_; }
572
Victor Costanbd623112018-07-18 04:17:27573 // Destroys the compiled statement and sets it to nullptr. The statement
574 // will no longer be active. |forced| is used to indicate if
575 // orderly-shutdown checks should apply (see Connection::RazeAndClose()).
[email protected]41a97c812013-02-07 02:35:38576 void Close(bool forced);
[email protected]e5ffd0e42009-09-11 21:30:56577
[email protected]35f7e5392012-07-27 19:54:50578 // Check whether the current thread is allowed to make IO calls, but only
579 // if database wasn't open in memory.
Victor Costanc7e7f2e2018-07-18 20:07:55580 void AssertIOAllowed() const {
581 if (connection_)
582 connection_->AssertIOAllowed();
583 }
[email protected]35f7e5392012-07-27 19:54:50584
[email protected]e5ffd0e42009-09-11 21:30:56585 private:
[email protected]877d55d2009-11-05 21:53:08586 friend class base::RefCounted<StatementRef>;
587
588 ~StatementRef();
589
[email protected]e5ffd0e42009-09-11 21:30:56590 Connection* connection_;
591 sqlite3_stmt* stmt_;
[email protected]41a97c812013-02-07 02:35:38592 bool was_valid_;
[email protected]e5ffd0e42009-09-11 21:30:56593
594 DISALLOW_COPY_AND_ASSIGN(StatementRef);
595 };
596 friend class StatementRef;
597
598 // Executes a rollback statement, ignoring all transaction state. Used
599 // internally in the transaction management code.
600 void DoRollback();
601
602 // Called by a StatementRef when it's being created or destroyed. See
603 // open_statements_ below.
604 void StatementRefCreated(StatementRef* ref);
605 void StatementRefDeleted(StatementRef* ref);
606
[email protected]2f496b42013-09-26 18:36:58607 // Called when a sqlite function returns an error, which is passed
608 // as |err|. The return value is the error code to be reflected
Victor Costanbd623112018-07-18 04:17:27609 // back to client code. |stmt| is non-null if the error relates to
610 // an sql::Statement instance. |sql| is non-nullptr if the error
[email protected]2f496b42013-09-26 18:36:58611 // relates to non-statement sql code (Execute, for instance). Both
Victor Costanbd623112018-07-18 04:17:27612 // can be null, but both should never be set.
[email protected]2f496b42013-09-26 18:36:58613 // NOTE(shess): Originally, the return value was intended to allow
614 // error handlers to transparently convert errors into success.
615 // Unfortunately, transactions are not generally restartable, so
616 // this did not work out.
shess9e77283d2016-06-13 23:53:20617 int OnSqliteError(int err, Statement* stmt, const char* sql) const;
[email protected]faa604e2009-09-25 22:38:59618
[email protected]5b96f3772010-09-28 16:30:57619 // Like |Execute()|, but retries if the database is locked.
[email protected]9fe37552011-12-23 17:07:20620 bool ExecuteWithTimeout(const char* sql, base::TimeDelta ms_timeout)
621 WARN_UNUSED_RESULT;
[email protected]5b96f3772010-09-28 16:30:57622
shess9e77283d2016-06-13 23:53:20623 // Implementation helper for GetUniqueStatement() and GetUntrackedStatement().
624 // |tracking_db| is the db the resulting ref should register with for
Victor Costanbd623112018-07-18 04:17:27625 // outstanding statement tracking, which should be |this| to track or null to
shess9e77283d2016-06-13 23:53:20626 // not track.
627 scoped_refptr<StatementRef> GetStatementImpl(
628 sql::Connection* tracking_db, const char* sql) const;
629
630 // Helper for implementing const member functions. Like GetUniqueStatement(),
631 // except the StatementRef is not entered into |open_statements_|, so an
632 // outstanding StatementRef from this function can block closing the database.
633 // The StatementRef will not call OnSqliteError(), because that can call
634 // |error_callback_| which can close the database.
[email protected]2eec0a22012-07-24 01:59:58635 scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const;
636
[email protected]579446c2013-12-16 18:36:52637 bool IntegrityCheckHelper(
638 const char* pragma_sql,
639 std::vector<std::string>* messages) WARN_UNUSED_RESULT;
640
shess58b8df82015-06-03 00:19:32641 // Record time spent executing explicit COMMIT statements.
642 void RecordCommitTime(const base::TimeDelta& delta);
643
644 // Record time in DML (Data Manipulation Language) statements such as INSERT
645 // or UPDATE outside of an explicit transaction. Due to implementation
646 // limitations time spent on DDL (Data Definition Language) statements such as
647 // ALTER and CREATE is not included.
648 void RecordAutoCommitTime(const base::TimeDelta& delta);
649
650 // Record all time spent on updating the database. This includes CommitTime()
651 // and AutoCommitTime(), plus any time spent spilling to the journal if
652 // transactions do not fit in cache.
653 void RecordUpdateTime(const base::TimeDelta& delta);
654
655 // Record all time spent running statements, including time spent doing
656 // updates and time spent on read-only queries.
657 void RecordQueryTime(const base::TimeDelta& delta);
658
659 // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is
660 // true, autocommit time if the database is not in a transaction, or update
661 // time if the database is in a transaction. Also records change count to
662 // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT.
663 void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only);
664
shess7dbd4dee2015-10-06 17:39:16665 // Release page-cache memory if memory-mapped I/O is enabled and the database
666 // was changed. Passing true for |implicit_change_performed| allows
667 // overriding the change detection for cases like DDL (CREATE, DROP, etc),
668 // which do not participate in the total-rows-changed tracking.
669 void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed);
670
shessc8cd2a162015-10-22 20:30:46671 // Returns the results of sqlite3_db_filename(), which should match the path
672 // passed to Open().
673 base::FilePath DbPath() const;
674
675 // Helper to prevent uploading too many diagnostic dumps for a given database,
676 // since every dump will likely show the same problem. Returns |true| if this
677 // function was not previously called for this database, and the persistent
678 // storage which tracks state was updated.
679 //
680 // |false| is returned if the function was previously called for this
681 // database, even across restarts. |false| is also returned if the persistent
682 // storage cannot be updated, possibly indicating problems requiring user or
683 // admin intervention, such as filesystem corruption or disk full. |false| is
684 // also returned if the persistent storage contains invalid data or is not
685 // readable.
686 //
687 // TODO(shess): It would make sense to reset the persistent state if the
688 // database is razed or recovered, or if the diagnostic code adds new
689 // capabilities.
690 bool RegisterIntentToUpload() const;
691
692 // Helper to collect diagnostic info for a corrupt database.
693 std::string CollectCorruptionInfo();
694
695 // Helper to collect diagnostic info for errors.
696 std::string CollectErrorInfo(int error, Statement* stmt) const;
697
shessd90aeea82015-11-13 02:24:31698 // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors
699 // can make it unsafe to map a file, so the file is read using regular I/O,
700 // with any errors causing 0 (don't map anything) to be returned. If the
701 // entire file is read without error, a large value is returned which will
702 // allow the entire file to be mapped in most cases.
703 //
704 // Results are recorded in the database's meta table for future reference, so
705 // the file should only be read through once.
706 size_t GetAppropriateMmapSize();
707
shessa62504d2016-11-07 19:26:12708 // Helpers for GetAppropriateMmapSize().
709 bool GetMmapAltStatus(int64_t* status);
710 bool SetMmapAltStatus(int64_t status);
711
Victor Costanbd623112018-07-18 04:17:27712 // The actual sqlite database. Will be null before Init has been called or if
[email protected]e5ffd0e42009-09-11 21:30:56713 // Init resulted in an error.
714 sqlite3* db_;
715
716 // Parameters we'll configure in sqlite before doing anything else. Zero means
717 // use the default value.
718 int page_size_;
719 int cache_size_;
720 bool exclusive_locking_;
[email protected]81a2a602013-07-17 19:10:36721 bool restrict_to_user_;
[email protected]e5ffd0e42009-09-11 21:30:56722
Victor Costanc7e7f2e2018-07-18 20:07:55723 // Holds references to all cached statements so they remain active.
724 //
725 // flat_map is appropriate here because the codebase has ~400 cached
726 // statements, and each statement is at most one insertion in the map
727 // throughout a process' lifetime.
728 base::flat_map<StatementID, scoped_refptr<StatementRef>> statement_cache_;
[email protected]e5ffd0e42009-09-11 21:30:56729
730 // A list of all StatementRefs we've given out. Each ref must register with
731 // us when it's created or destroyed. This allows us to potentially close
732 // any open statements when we encounter an error.
Victor Costanc7e7f2e2018-07-18 20:07:55733 std::set<StatementRef*> open_statements_;
[email protected]e5ffd0e42009-09-11 21:30:56734
735 // Number of currently-nested transactions.
736 int transaction_nesting_;
737
738 // True if any of the currently nested transactions have been rolled back.
739 // When we get to the outermost transaction, this will determine if we do
740 // a rollback instead of a commit.
741 bool needs_rollback_;
742
[email protected]35f7e5392012-07-27 19:54:50743 // True if database is open with OpenInMemory(), False if database is open
744 // with Open().
745 bool in_memory_;
746
[email protected]41a97c812013-02-07 02:35:38747 // |true| if the connection was closed using RazeAndClose(). Used
748 // to enable diagnostics to distinguish calls to never-opened
749 // databases (incorrect use of the API) from calls to once-valid
750 // databases.
751 bool poisoned_;
752
shessa62504d2016-11-07 19:26:12753 // |true| to use alternate storage for tracking mmap status.
754 bool mmap_alt_status_;
755
shess7dbd4dee2015-10-06 17:39:16756 // |true| if SQLite memory-mapped I/O is not desired for this connection.
757 bool mmap_disabled_;
758
759 // |true| if SQLite memory-mapped I/O was enabled for this connection.
760 // Used by ReleaseCacheMemoryIfNeeded().
761 bool mmap_enabled_;
762
763 // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened
764 // since memory was last released.
765 int total_changes_at_last_release_;
766
[email protected]c3881b372013-05-17 08:39:46767 ErrorCallback error_callback_;
768
[email protected]210ce0af2013-05-15 09:10:39769 // Tag for auxiliary histograms.
770 std::string histogram_tag_;
[email protected]c088e3a32013-01-03 23:59:14771
shess58b8df82015-06-03 00:19:32772 // Linear histogram for RecordEvent().
773 base::HistogramBase* stats_histogram_;
774
775 // Histogram for tracking time taken in commit.
776 base::HistogramBase* commit_time_histogram_;
777
778 // Histogram for tracking time taken in autocommit updates.
779 base::HistogramBase* autocommit_time_histogram_;
780
781 // Histogram for tracking time taken in updates (including commit and
782 // autocommit).
783 base::HistogramBase* update_time_histogram_;
784
785 // Histogram for tracking time taken in all queries.
786 base::HistogramBase* query_time_histogram_;
787
788 // Source for timing information, provided to allow tests to inject time
789 // changes.
Victor Costan87cf8c72018-07-19 19:36:04790 std::unique_ptr<base::TickClock> clock_;
shess58b8df82015-06-03 00:19:32791
ssid3be5b1ec2016-01-13 14:21:57792 // Stores the dump provider object when db is open.
mostynbd82cd9952016-04-11 20:05:34793 std::unique_ptr<ConnectionMemoryDumpProvider> memory_dump_provider_;
ssid3be5b1ec2016-01-13 14:21:57794
[email protected]e5ffd0e42009-09-11 21:30:56795 DISALLOW_COPY_AND_ASSIGN(Connection);
796};
797
798} // namespace sql
799
[email protected]f0a54b22011-07-19 18:40:21800#endif // SQL_CONNECTION_H_