[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 5 | #ifndef SQL_DATABASE_H_ |
| 6 | #define SQL_DATABASE_H_ |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 7 | |
avi | 0b51920 | 2015-12-21 07:25:19 | [diff] [blame] | 8 | #include <stddef.h> |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 9 | #include <stdint.h> |
mostynb | d82cd995 | 2016-04-11 20:05:34 | [diff] [blame] | 10 | #include <memory> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 11 | #include <set> |
[email protected] | 7d6aee4e | 2009-09-12 01:12:33 | [diff] [blame] | 12 | #include <string> |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 13 | #include <utility> |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 14 | #include <vector> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 15 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 16 | #include "base/callback.h" |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 17 | #include "base/compiler_specific.h" |
Dmitry Skiba | a9ad8fe4 | 2017-08-16 21:02:48 | [diff] [blame] | 18 | #include "base/containers/flat_map.h" |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 19 | #include "base/gtest_prod_util.h" |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 20 | #include "base/macros.h" |
[email protected] | 3b63f8f4 | 2011-03-28 01:54:15 | [diff] [blame] | 21 | #include "base/memory/ref_counted.h" |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 22 | #include "base/sequence_checker.h" |
Etienne Pierre-Doray | 0400dfb6 | 2018-12-03 19:12:25 | [diff] [blame^] | 23 | #include "base/threading/scoped_blocking_call.h" |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 24 | #include "base/threading/thread_restrictions.h" |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 25 | #include "base/time/tick_clock.h" |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 26 | #include "sql/internal_api_token.h" |
[email protected] | d452696 | 2011-11-10 21:40:28 | [diff] [blame] | 27 | #include "sql/sql_export.h" |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 28 | #include "sql/statement_id.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 29 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 30 | struct sqlite3; |
| 31 | struct sqlite3_stmt; |
| 32 | |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 33 | namespace base { |
| 34 | class FilePath; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 35 | class HistogramBase; |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 36 | namespace trace_event { |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 37 | class ProcessMemoryDump; |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 38 | } // namespace trace_event |
| 39 | } // namespace base |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 40 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 41 | namespace sql { |
| 42 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 43 | class DatabaseMemoryDumpProvider; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 44 | class Statement; |
| 45 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 46 | // To allow some test classes to be friended. |
| 47 | namespace test { |
| 48 | class ScopedCommitHook; |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 49 | class ScopedErrorExpecter; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 50 | class ScopedScalarFunction; |
| 51 | class ScopedMockTimeSource; |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 52 | } // namespace test |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 53 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 54 | // Exposes private Database functionality to unit tests. |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 55 | // |
| 56 | // This class is only defined in test targets. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 57 | class DatabaseTestPeer; |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 58 | |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 59 | // Handle to an open SQLite database. |
| 60 | // |
| 61 | // Instances of this class are thread-unsafe and DCHECK that they are accessed |
| 62 | // on the same sequence. |
| 63 | // |
| 64 | // TODO(pwnall): This should be renamed to Database. Class instances are |
| 65 | // typically named "db_" / "db", and the class' equivalents in other systems |
| 66 | // used by Chrome are named LevelDB::DB and blink::IDBDatabase. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 67 | class SQL_EXPORT Database { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 68 | private: |
| 69 | class StatementRef; // Forward declaration, see real one below. |
| 70 | |
| 71 | public: |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 72 | // The database is opened by calling Open[InMemory](). Any uncommitted |
| 73 | // transactions will be rolled back when this object is deleted. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 74 | Database(); |
| 75 | ~Database(); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 76 | |
| 77 | // Pre-init configuration ---------------------------------------------------- |
| 78 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 79 | // Sets the page size that will be used when creating a new database. This |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 80 | // must be called before Init(), and will only have an effect on new |
| 81 | // databases. |
| 82 | // |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 83 | // The page size must be a power of two between 512 and 65536 inclusive. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 84 | void set_page_size(int page_size) { |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 85 | DCHECK_GE(page_size, 512); |
| 86 | DCHECK_LE(page_size, 65536); |
| 87 | DCHECK(!(page_size & (page_size - 1))) |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 88 | << "page_size must be a power of two"; |
| 89 | |
| 90 | page_size_ = page_size; |
| 91 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 92 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 93 | // The page size that will be used when creating a new database. |
| 94 | int page_size() const { return page_size_; } |
| 95 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 96 | // Sets the number of pages that will be cached in memory by sqlite. The |
| 97 | // total cache size in bytes will be page_size * cache_size. This must be |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 98 | // called before Open() to have an effect. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 99 | void set_cache_size(int cache_size) { |
| 100 | DCHECK_GE(cache_size, 0); |
| 101 | |
| 102 | cache_size_ = cache_size; |
| 103 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 104 | |
| 105 | // Call to put the database in exclusive locking mode. There is no "back to |
| 106 | // normal" flag because of some additional requirements sqlite puts on this |
[email protected] | 4ab952f | 2014-04-01 20:18:16 | [diff] [blame] | 107 | // transaction (requires another access to the DB) and because we don't |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 108 | // actually need it. |
| 109 | // |
| 110 | // Exclusive mode means that the database is not unlocked at the end of each |
| 111 | // transaction, which means there may be less time spent initializing the |
| 112 | // next transaction because it doesn't have to re-aquire locks. |
| 113 | // |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 114 | // This must be called before Open() to have an effect. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 115 | void set_exclusive_locking() { exclusive_locking_ = true; } |
| 116 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 117 | // 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 Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 122 | // Opt out of memory-mapped file I/O. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 123 | void set_mmap_disabled() { mmap_disabled_ = true; } |
| 124 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 125 | // 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 Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 130 | using ErrorCallback = base::RepeatingCallback<void(int, Statement*)>; |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 131 | void set_error_callback(const ErrorCallback& callback) { |
| 132 | error_callback_ = callback; |
| 133 | } |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 134 | bool has_error_callback() const { return !error_callback_.is_null(); } |
| 135 | void reset_error_callback() { error_callback_.Reset(); } |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 136 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 137 | // Set this to enable additional per-database histogramming. Must be called |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 138 | // before Open(). |
| 139 | void set_histogram_tag(const std::string& tag); |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 140 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 141 | // Record a sparse UMA histogram sample under |
| 142 | // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no |
| 143 | // histogram is recorded. |
Will Harris | b869359 | 2018-08-28 22:58:44 | [diff] [blame] | 144 | void AddTaggedHistogram(const std::string& name, int sample) const; |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 145 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 146 | // 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 | |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 174 | // 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 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 187 | EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view. |
| 188 | EVENT_MMAP_STATUS_FAILURE_UPDATE, // Failure updating MmapStatus view. |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 189 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 190 | // 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 Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 195 | void RecordOneEvent(Events event) { RecordEvent(event, 1); } |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 196 | |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 197 | // 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] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 207 | |
afakhry | 7c9abe7 | 2016-08-05 17:33:19 | [diff] [blame] | 208 | // 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 | |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 212 | // 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); |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 215 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 216 | // Initialization ------------------------------------------------------------ |
| 217 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 218 | // Initializes the SQL database for the given file, returning true if the |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 219 | // file could be opened. You can call this or OpenInMemory. |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 220 | bool Open(const base::FilePath& path) WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 221 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 222 | // Initializes the SQL database for a temporary in-memory database. There |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 223 | // will be no associated file on disk, and the initial database will be |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 224 | // empty. You can call this or Open. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 225 | bool OpenInMemory() WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 226 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 227 | // 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] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 233 | // Returns true if the database has been successfully opened. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 234 | bool is_open() const { return static_cast<bool>(db_); } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 235 | |
| 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] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 242 | // 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] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 247 | // |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 248 | // 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] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 253 | void Preload(); |
| 254 | |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 255 | // 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] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 261 | // 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 Knippschild | 46800c9f | 2017-09-02 02:21:43 | [diff] [blame] | 268 | // process. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 269 | // |
| 270 | // NOTE(shess): Raze() will DCHECK in the following situations: |
| 271 | // - database is not open. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 272 | // - the database has a transaction open. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 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] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 278 | // |
| 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 | // |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 288 | // TODO(shess): Raze() needs a database so cannot clear SQLITE_NOTADB. |
| 289 | // TODO(shess): Bake auto_vacuum into Database's API so it can |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 290 | // just pick up the default. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 291 | bool Raze(); |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 292 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 293 | // Breaks all outstanding transactions (as initiated by |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 294 | // BeginTransaction()), closes the SQLite database, and poisons the |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 295 | // object so that all future operations against the Database (or |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 296 | // its Statements) fail safely, without side effects. |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 297 | // |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 298 | // 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] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 305 | bool RazeAndClose(); |
| 306 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 307 | // Delete the underlying database files associated with |path|. This should be |
| 308 | // used on a database which is not opened by any Database instance. Open |
| 309 | // Database instances pointing to the database can cause odd results or |
| 310 | // corruption (for instance if a hot journal is deleted but the associated |
| 311 | // database is not). |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 312 | // |
| 313 | // Returns true if the database file and associated journals no |
| 314 | // longer exist, false otherwise. If the database has never |
| 315 | // existed, this will return true. |
| 316 | static bool Delete(const base::FilePath& path); |
| 317 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 318 | // Transactions -------------------------------------------------------------- |
| 319 | |
| 320 | // Transaction management. We maintain a virtual transaction stack to emulate |
| 321 | // nested transactions since sqlite can't do nested transactions. The |
| 322 | // limitation is you can't roll back a sub transaction: if any transaction |
| 323 | // fails, all transactions open will also be rolled back. Any nested |
| 324 | // transactions after one has rolled back will return fail for Begin(). If |
| 325 | // Begin() fails, you must not call Commit or Rollback(). |
| 326 | // |
| 327 | // Normally you should use sql::Transaction to manage a transaction, which |
| 328 | // will scope it to a C++ context. |
| 329 | bool BeginTransaction(); |
| 330 | void RollbackTransaction(); |
| 331 | bool CommitTransaction(); |
| 332 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 333 | // Rollback all outstanding transactions. Use with care, there may |
| 334 | // be scoped transactions on the stack. |
| 335 | void RollbackAllTransactions(); |
| 336 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 337 | // Returns the current transaction nesting, which will be 0 if there are |
| 338 | // no open transactions. |
| 339 | int transaction_nesting() const { return transaction_nesting_; } |
| 340 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 341 | // Attached databases--------------------------------------------------------- |
| 342 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 343 | // SQLite supports attaching multiple database files to a single connection. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 344 | // |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 345 | // Attach the database in |other_db_path| to the current connection under |
| 346 | // |attachment_point|. |attachment_point| must only contain characters from |
| 347 | // [a-zA-Z0-9_]. |
Victor Costan | 8a87f7e5 | 2017-11-10 01:29:30 | [diff] [blame] | 348 | // |
| 349 | // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can |
| 350 | // be attached while a transaction is opened. However, these databases cannot |
Victor Costan | 70bedf2 | 2018-07-18 21:21:14 | [diff] [blame] | 351 | // be detached until the transaction is committed or aborted. |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 352 | // |
| 353 | // These APIs are only exposed for use in recovery. They are extremely subtle |
| 354 | // and are not useful for features built on top of //sql. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 355 | bool AttachDatabase(const base::FilePath& other_db_path, |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 356 | const char* attachment_point, |
| 357 | InternalApiToken); |
| 358 | bool DetachDatabase(const char* attachment_point, InternalApiToken); |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 359 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 360 | // Statements ---------------------------------------------------------------- |
| 361 | |
| 362 | // Executes the given SQL string, returning true on success. This is |
| 363 | // normally used for simple, 1-off statements that don't take any bound |
| 364 | // parameters and don't return any data (e.g. CREATE TABLE). |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 365 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 366 | // This will DCHECK if the |sql| contains errors. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 367 | // |
| 368 | // Do not use ignore_result() to ignore all errors. Use |
| 369 | // ExecuteAndReturnErrorCode() and ignore only specific errors. |
| 370 | bool Execute(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 371 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 372 | // Like Execute(), but returns the error code given by SQLite. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 373 | int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 374 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 375 | // Returns a statement for the given SQL using the statement cache. It can |
| 376 | // take a nontrivial amount of work to parse and compile a statement, so |
| 377 | // keeping commonly-used ones around for future use is important for |
| 378 | // performance. |
| 379 | // |
Victor Costan | 613b430 | 2018-11-20 05:32:43 | [diff] [blame] | 380 | // The SQL_FROM_HERE macro is the recommended way of generating a StatementID. |
| 381 | // Code that generates custom IDs must ensure that a StatementID is never used |
| 382 | // for different SQL statements. Failing to meet this requirement results in |
| 383 | // incorrect behavior, and should be caught by a DCHECK. |
| 384 | // |
| 385 | // The SQL statement passed in |sql| must match the SQL statement reported |
| 386 | // back by SQLite. Mismatches are caught by a DCHECK, so any code that has |
| 387 | // automated test coverage or that was manually tested on a DCHECK build will |
| 388 | // not exhibit this problem. Mismatches generally imply that the statement |
| 389 | // passed in has extra whitespace or comments surrounding it, which waste |
| 390 | // storage and CPU cycles. |
| 391 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 392 | // If the |sql| has an error, an invalid, inert StatementRef is returned (and |
| 393 | // the code will crash in debug). The caller must deal with this eventuality, |
| 394 | // either by checking validity of the |sql| before calling, by correctly |
| 395 | // handling the return of an inert statement, or both. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 396 | // |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 397 | // Example: |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 398 | // sql::Statement stmt(database_.GetCachedStatement( |
[email protected] | 3273dce | 2010-01-27 16:08:08 | [diff] [blame] | 399 | // SQL_FROM_HERE, "SELECT * FROM foo")); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 400 | // if (!stmt) |
| 401 | // return false; // Error creating statement. |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 402 | scoped_refptr<StatementRef> GetCachedStatement(StatementID id, |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 403 | const char* sql); |
| 404 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 405 | // Used to check a |sql| statement for syntactic validity. If the statement is |
| 406 | // valid SQL, returns true. |
| 407 | bool IsSQLValid(const char* sql); |
| 408 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 409 | // Returns a non-cached statement for the given SQL. Use this for SQL that |
| 410 | // is only executed once or only rarely (there is overhead associated with |
| 411 | // keeping a statement cached). |
| 412 | // |
| 413 | // See GetCachedStatement above for examples and error information. |
| 414 | scoped_refptr<StatementRef> GetUniqueStatement(const char* sql); |
| 415 | |
| 416 | // Info querying ------------------------------------------------------------- |
| 417 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 418 | // Returns true if the given structure exists. Instead of test-then-create, |
| 419 | // callers should almost always prefer the "IF NOT EXISTS" version of the |
| 420 | // CREATE statement. |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 421 | bool DoesIndexExist(const char* index_name) const; |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 422 | bool DoesTableExist(const char* table_name) const; |
| 423 | bool DoesViewExist(const char* table_name) const; |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 424 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 425 | // Returns true if a column with the given name exists in the given table. |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 426 | bool DoesColumnExist(const char* table_name, const char* column_name) const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 427 | |
| 428 | // Returns sqlite's internal ID for the last inserted row. Valid only |
| 429 | // immediately after an insert. |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 430 | int64_t GetLastInsertRowId() const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 431 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 432 | // Returns sqlite's count of the number of rows modified by the last |
| 433 | // statement executed. Will be 0 if no statement has executed or the database |
| 434 | // is closed. |
| 435 | int GetLastChangeCount() const; |
| 436 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 437 | // Errors -------------------------------------------------------------------- |
| 438 | |
| 439 | // Returns the error code associated with the last sqlite operation. |
| 440 | int GetErrorCode() const; |
| 441 | |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 442 | // Returns the errno associated with GetErrorCode(). See |
| 443 | // SQLITE_LAST_ERRNO in SQLite documentation. |
| 444 | int GetLastErrno() const; |
| 445 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 446 | // Returns a pointer to a statically allocated string associated with the |
| 447 | // last sqlite operation. |
| 448 | const char* GetErrorMessage() const; |
| 449 | |
[email protected] | 92cd00a | 2013-08-16 11:09:58 | [diff] [blame] | 450 | // Return a reproducible representation of the schema equivalent to |
| 451 | // running the following statement at a sqlite3 command-line: |
| 452 | // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4; |
| 453 | std::string GetSchema() const; |
| 454 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 455 | // Returns |true| if there is an error expecter (see SetErrorExpecter), and |
| 456 | // that expecter returns |true| when passed |error|. Clients which provide an |
| 457 | // |error_callback| should use IsExpectedSqliteError() to check for unexpected |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 458 | // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 459 | // OnSqliteError implementation). |
| 460 | static bool IsExpectedSqliteError(int error); |
[email protected] | 74cdede | 2013-09-25 05:39:57 | [diff] [blame] | 461 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 462 | // Collect various diagnostic information and post a crash dump to aid |
| 463 | // debugging. Dump rate per database is limited to prevent overwhelming the |
| 464 | // crash server. |
| 465 | void ReportDiagnosticInfo(int extended_error, Statement* stmt); |
| 466 | |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 467 | // Helper to return the current time from the time source. |
| 468 | base::TimeTicks NowTicks() const { return clock_->NowTicks(); } |
| 469 | |
| 470 | // Intended for tests to inject a mock time source. |
| 471 | // |
| 472 | // Inlined to avoid generating code in the production binary. |
| 473 | inline void set_clock_for_testing(std::unique_ptr<base::TickClock> clock) { |
| 474 | clock_ = std::move(clock); |
| 475 | } |
| 476 | |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 477 | // Computes the path of a database's rollback journal. |
| 478 | // |
| 479 | // The journal file is created at the beginning of the database's first |
| 480 | // transaction. The file may be removed and re-created between transactions, |
| 481 | // depending on whether the database is opened in exclusive mode, and on |
| 482 | // configuration options. The journal file does not exist when the database |
| 483 | // operates in WAL mode. |
| 484 | // |
| 485 | // This is intended for internal use and tests. To preserve our ability to |
| 486 | // iterate on our SQLite configuration, features must avoid relying on |
| 487 | // the existence of specific files. |
| 488 | static base::FilePath JournalPath(const base::FilePath& db_path); |
| 489 | |
| 490 | // Computes the path of a database's write-ahead log (WAL). |
| 491 | // |
| 492 | // The WAL file exists while a database is opened in WAL mode. |
| 493 | // |
| 494 | // This is intended for internal use and tests. To preserve our ability to |
| 495 | // iterate on our SQLite configuration, features must avoid relying on |
| 496 | // the existence of specific files. |
| 497 | static base::FilePath WriteAheadLogPath(const base::FilePath& db_path); |
| 498 | |
| 499 | // Computes the path of a database's shared memory (SHM) file. |
| 500 | // |
| 501 | // The SHM file is used to coordinate between multiple processes using the |
| 502 | // same database in WAL mode. Thus, this file only exists for databases using |
| 503 | // WAL and not opened in exclusive mode. |
| 504 | // |
| 505 | // This is intended for internal use and tests. To preserve our ability to |
| 506 | // iterate on our SQLite configuration, features must avoid relying on |
| 507 | // the existence of specific files. |
| 508 | static base::FilePath SharedMemoryFilePath(const base::FilePath& db_path); |
| 509 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 510 | // Default page size for newly created databases. |
| 511 | // |
| 512 | // Guaranteed to match SQLITE_DEFAULT_PAGE_SIZE. |
| 513 | static constexpr int kDefaultPageSize = 4096; |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 514 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 515 | // Internal state accessed by other classes in //sql. |
| 516 | sqlite3* db(InternalApiToken) const { return db_; } |
| 517 | bool poisoned(InternalApiToken) const { return poisoned_; } |
| 518 | |
| 519 | private: |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 520 | // Allow test-support code to set/reset error expecter. |
| 521 | friend class test::ScopedErrorExpecter; |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 522 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 523 | // Statement accesses StatementRef which we don't want to expose to everybody |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 524 | // (they should go through Statement). |
| 525 | friend class Statement; |
| 526 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 527 | friend class DatabaseTestPeer; |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 528 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 529 | friend class test::ScopedCommitHook; |
| 530 | friend class test::ScopedScalarFunction; |
| 531 | friend class test::ScopedMockTimeSource; |
| 532 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 533 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CachedStatement); |
| 534 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CollectDiagnosticInfo); |
| 535 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSize); |
| 536 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSizeAltStatus); |
| 537 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, OnMemoryDump); |
| 538 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, RegisterIntentToUpload); |
shess | f7fcc45 | 2017-04-19 22:10:41 | [diff] [blame] | 539 | FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 540 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 541 | // Internal initialize function used by both Init and InitInMemory. The file |
| 542 | // name is always 8 bits since we want to use the 8-bit version of |
| 543 | // sqlite3_open. The string can also be sqlite's special ":memory:" string. |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 544 | // |
| 545 | // |retry_flag| controls retrying the open if the error callback |
| 546 | // addressed errors using RazeAndClose(). |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 547 | enum Retry { NO_RETRY = 0, RETRY_ON_POISON }; |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 548 | bool OpenInternal(const std::string& file_name, Retry retry_flag); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 549 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 550 | // Internal close function used by Close() and RazeAndClose(). |
| 551 | // |forced| indicates that orderly-shutdown checks should not apply. |
| 552 | void CloseInternal(bool forced); |
| 553 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 554 | // Check whether the current thread is allowed to make IO calls, but only |
| 555 | // if database wasn't open in memory. Function is inlined to be a no-op in |
| 556 | // official build. |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 557 | void AssertIOAllowed() const { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 558 | if (!in_memory_) |
Etienne Pierre-doray | a4195e59 | 2018-10-18 16:36:42 | [diff] [blame] | 559 | base::AssertBlockingAllowedDeprecated(); |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 560 | } |
| 561 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 562 | // Internal helper for Does*Exist() functions. |
| 563 | bool DoesSchemaItemExist(const char* name, const char* type) const; |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 564 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 565 | // Accessors for global error-expecter, for injecting behavior during tests. |
| 566 | // See test/scoped_error_expecter.h. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 567 | using ErrorExpecterCallback = base::RepeatingCallback<bool(int)>; |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 568 | static ErrorExpecterCallback* current_expecter_cb_; |
| 569 | static void SetErrorExpecter(ErrorExpecterCallback* expecter); |
| 570 | static void ResetErrorExpecter(); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 571 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 572 | // A StatementRef is a refcounted wrapper around a sqlite statement pointer. |
| 573 | // Refcounting allows us to give these statements out to sql::Statement |
| 574 | // objects while also optionally maintaining a cache of compiled statements |
| 575 | // by just keeping a refptr to these objects. |
| 576 | // |
| 577 | // A statement ref can be valid, in which case it can be used, or invalid to |
| 578 | // indicate that the statement hasn't been created yet, has an error, or has |
| 579 | // been destroyed. |
| 580 | // |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 581 | // The Database may revoke a StatementRef in some error cases, so callers |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 582 | // should always check validity before using. |
[email protected] | 601dc6a | 2011-11-12 01:14:23 | [diff] [blame] | 583 | class SQL_EXPORT StatementRef : public base::RefCounted<StatementRef> { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 584 | public: |
Victor Costan | 3b02cdf | 2018-07-18 00:39:56 | [diff] [blame] | 585 | REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE(); |
| 586 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 587 | // |database| is the sql::Database instance associated with |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 588 | // the statement, and is used for tracking outstanding statements |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 589 | // and for error handling. Set to nullptr for invalid or untracked |
| 590 | // refs. |stmt| is the actual statement, and should only be null |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 591 | // to create an invalid ref. |was_valid| indicates whether the |
| 592 | // statement should be considered valid for diagnistic purposes. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 593 | // |was_valid| can be true for a null |stmt| if the Database has |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 594 | // been forcibly closed by an error handler. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 595 | StatementRef(Database* database, sqlite3_stmt* stmt, bool was_valid); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 596 | |
| 597 | // When true, the statement can be used. |
| 598 | bool is_valid() const { return !!stmt_; } |
| 599 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 600 | // When true, the statement is either currently valid, or was |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 601 | // previously valid but the database was forcibly closed. Used |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 602 | // for diagnostic checks. |
| 603 | bool was_valid() const { return was_valid_; } |
| 604 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 605 | // If we've not been linked to a database, this will be null. |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 606 | // |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 607 | // TODO(shess): database_ can be nullptr in case of |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 608 | // GetUntrackedStatement(), which prevents Statement::OnError() from |
| 609 | // forwarding errors. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 610 | Database* database() const { return database_; } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 611 | |
| 612 | // Returns the sqlite statement if any. If the statement is not active, |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 613 | // this will return nullptr. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 614 | sqlite3_stmt* stmt() const { return stmt_; } |
| 615 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 616 | // Destroys the compiled statement and sets it to nullptr. The statement |
| 617 | // will no longer be active. |forced| is used to indicate if |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 618 | // orderly-shutdown checks should apply (see Database::RazeAndClose()). |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 619 | void Close(bool forced); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 620 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 621 | // Check whether the current thread is allowed to make IO calls, but only |
| 622 | // if database wasn't open in memory. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 623 | void AssertIOAllowed() const { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 624 | if (database_) |
| 625 | database_->AssertIOAllowed(); |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 626 | } |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 627 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 628 | private: |
[email protected] | 877d55d | 2009-11-05 21:53:08 | [diff] [blame] | 629 | friend class base::RefCounted<StatementRef>; |
| 630 | |
| 631 | ~StatementRef(); |
| 632 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 633 | Database* database_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 634 | sqlite3_stmt* stmt_; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 635 | bool was_valid_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 636 | |
| 637 | DISALLOW_COPY_AND_ASSIGN(StatementRef); |
| 638 | }; |
| 639 | friend class StatementRef; |
| 640 | |
| 641 | // Executes a rollback statement, ignoring all transaction state. Used |
| 642 | // internally in the transaction management code. |
| 643 | void DoRollback(); |
| 644 | |
| 645 | // Called by a StatementRef when it's being created or destroyed. See |
| 646 | // open_statements_ below. |
| 647 | void StatementRefCreated(StatementRef* ref); |
| 648 | void StatementRefDeleted(StatementRef* ref); |
| 649 | |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 650 | // Called when a sqlite function returns an error, which is passed |
| 651 | // as |err|. The return value is the error code to be reflected |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 652 | // back to client code. |stmt| is non-null if the error relates to |
| 653 | // an sql::Statement instance. |sql| is non-nullptr if the error |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 654 | // relates to non-statement sql code (Execute, for instance). Both |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 655 | // can be null, but both should never be set. |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 656 | // NOTE(shess): Originally, the return value was intended to allow |
| 657 | // error handlers to transparently convert errors into success. |
| 658 | // Unfortunately, transactions are not generally restartable, so |
| 659 | // this did not work out. |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 660 | int OnSqliteError(int err, Statement* stmt, const char* sql) const; |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 661 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 662 | // Like |Execute()|, but retries if the database is locked. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 663 | bool ExecuteWithTimeout(const char* sql, |
| 664 | base::TimeDelta ms_timeout) WARN_UNUSED_RESULT; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 665 | |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 666 | // Implementation helper for GetUniqueStatement() and GetUntrackedStatement(). |
| 667 | // |tracking_db| is the db the resulting ref should register with for |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 668 | // outstanding statement tracking, which should be |this| to track or null to |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 669 | // not track. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 670 | scoped_refptr<StatementRef> GetStatementImpl(sql::Database* tracking_db, |
| 671 | const char* sql) const; |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 672 | |
| 673 | // Helper for implementing const member functions. Like GetUniqueStatement(), |
| 674 | // except the StatementRef is not entered into |open_statements_|, so an |
| 675 | // outstanding StatementRef from this function can block closing the database. |
| 676 | // The StatementRef will not call OnSqliteError(), because that can call |
| 677 | // |error_callback_| which can close the database. |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 678 | scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const; |
| 679 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 680 | bool IntegrityCheckHelper(const char* pragma_sql, |
| 681 | std::vector<std::string>* messages) |
| 682 | WARN_UNUSED_RESULT; |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 683 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 684 | // Record time spent executing explicit COMMIT statements. |
| 685 | void RecordCommitTime(const base::TimeDelta& delta); |
| 686 | |
| 687 | // Record time in DML (Data Manipulation Language) statements such as INSERT |
| 688 | // or UPDATE outside of an explicit transaction. Due to implementation |
| 689 | // limitations time spent on DDL (Data Definition Language) statements such as |
| 690 | // ALTER and CREATE is not included. |
| 691 | void RecordAutoCommitTime(const base::TimeDelta& delta); |
| 692 | |
| 693 | // Record all time spent on updating the database. This includes CommitTime() |
| 694 | // and AutoCommitTime(), plus any time spent spilling to the journal if |
| 695 | // transactions do not fit in cache. |
| 696 | void RecordUpdateTime(const base::TimeDelta& delta); |
| 697 | |
| 698 | // Record all time spent running statements, including time spent doing |
| 699 | // updates and time spent on read-only queries. |
| 700 | void RecordQueryTime(const base::TimeDelta& delta); |
| 701 | |
| 702 | // Record |delta| as query time if |read_only| (from sqlite3_stmt_readonly) is |
| 703 | // true, autocommit time if the database is not in a transaction, or update |
| 704 | // time if the database is in a transaction. Also records change count to |
| 705 | // EVENT_CHANGES_AUTOCOMMIT or EVENT_CHANGES_COMMIT. |
| 706 | void RecordTimeAndChanges(const base::TimeDelta& delta, bool read_only); |
| 707 | |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 708 | // Release page-cache memory if memory-mapped I/O is enabled and the database |
| 709 | // was changed. Passing true for |implicit_change_performed| allows |
| 710 | // overriding the change detection for cases like DDL (CREATE, DROP, etc), |
| 711 | // which do not participate in the total-rows-changed tracking. |
| 712 | void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed); |
| 713 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 714 | // Returns the results of sqlite3_db_filename(), which should match the path |
| 715 | // passed to Open(). |
| 716 | base::FilePath DbPath() const; |
| 717 | |
| 718 | // Helper to prevent uploading too many diagnostic dumps for a given database, |
| 719 | // since every dump will likely show the same problem. Returns |true| if this |
| 720 | // function was not previously called for this database, and the persistent |
| 721 | // storage which tracks state was updated. |
| 722 | // |
| 723 | // |false| is returned if the function was previously called for this |
| 724 | // database, even across restarts. |false| is also returned if the persistent |
| 725 | // storage cannot be updated, possibly indicating problems requiring user or |
| 726 | // admin intervention, such as filesystem corruption or disk full. |false| is |
| 727 | // also returned if the persistent storage contains invalid data or is not |
| 728 | // readable. |
| 729 | // |
| 730 | // TODO(shess): It would make sense to reset the persistent state if the |
| 731 | // database is razed or recovered, or if the diagnostic code adds new |
| 732 | // capabilities. |
| 733 | bool RegisterIntentToUpload() const; |
| 734 | |
| 735 | // Helper to collect diagnostic info for a corrupt database. |
| 736 | std::string CollectCorruptionInfo(); |
| 737 | |
| 738 | // Helper to collect diagnostic info for errors. |
| 739 | std::string CollectErrorInfo(int error, Statement* stmt) const; |
| 740 | |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 741 | // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors |
| 742 | // can make it unsafe to map a file, so the file is read using regular I/O, |
| 743 | // with any errors causing 0 (don't map anything) to be returned. If the |
| 744 | // entire file is read without error, a large value is returned which will |
| 745 | // allow the entire file to be mapped in most cases. |
| 746 | // |
| 747 | // Results are recorded in the database's meta table for future reference, so |
| 748 | // the file should only be read through once. |
| 749 | size_t GetAppropriateMmapSize(); |
| 750 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 751 | // Helpers for GetAppropriateMmapSize(). |
| 752 | bool GetMmapAltStatus(int64_t* status); |
| 753 | bool SetMmapAltStatus(int64_t status); |
| 754 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 755 | // The actual sqlite database. Will be null before Init has been called or if |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 756 | // Init resulted in an error. |
| 757 | sqlite3* db_; |
| 758 | |
| 759 | // Parameters we'll configure in sqlite before doing anything else. Zero means |
| 760 | // use the default value. |
| 761 | int page_size_; |
| 762 | int cache_size_; |
| 763 | bool exclusive_locking_; |
| 764 | |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 765 | // Holds references to all cached statements so they remain active. |
| 766 | // |
| 767 | // flat_map is appropriate here because the codebase has ~400 cached |
| 768 | // statements, and each statement is at most one insertion in the map |
| 769 | // throughout a process' lifetime. |
| 770 | base::flat_map<StatementID, scoped_refptr<StatementRef>> statement_cache_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 771 | |
| 772 | // A list of all StatementRefs we've given out. Each ref must register with |
| 773 | // us when it's created or destroyed. This allows us to potentially close |
| 774 | // any open statements when we encounter an error. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 775 | std::set<StatementRef*> open_statements_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 776 | |
| 777 | // Number of currently-nested transactions. |
| 778 | int transaction_nesting_; |
| 779 | |
| 780 | // True if any of the currently nested transactions have been rolled back. |
| 781 | // When we get to the outermost transaction, this will determine if we do |
| 782 | // a rollback instead of a commit. |
| 783 | bool needs_rollback_; |
| 784 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 785 | // True if database is open with OpenInMemory(), False if database is open |
| 786 | // with Open(). |
| 787 | bool in_memory_; |
| 788 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 789 | // |true| if the Database was closed using RazeAndClose(). Used |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 790 | // to enable diagnostics to distinguish calls to never-opened |
| 791 | // databases (incorrect use of the API) from calls to once-valid |
| 792 | // databases. |
| 793 | bool poisoned_; |
| 794 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 795 | // |true| to use alternate storage for tracking mmap status. |
| 796 | bool mmap_alt_status_; |
| 797 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 798 | // |true| if SQLite memory-mapped I/O is not desired for this database. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 799 | bool mmap_disabled_; |
| 800 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 801 | // |true| if SQLite memory-mapped I/O was enabled for this database. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 802 | // Used by ReleaseCacheMemoryIfNeeded(). |
| 803 | bool mmap_enabled_; |
| 804 | |
| 805 | // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened |
| 806 | // since memory was last released. |
| 807 | int total_changes_at_last_release_; |
| 808 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 809 | ErrorCallback error_callback_; |
| 810 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 811 | // Tag for auxiliary histograms. |
| 812 | std::string histogram_tag_; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 813 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 814 | // Linear histogram for RecordEvent(). |
| 815 | base::HistogramBase* stats_histogram_; |
| 816 | |
| 817 | // Histogram for tracking time taken in commit. |
| 818 | base::HistogramBase* commit_time_histogram_; |
| 819 | |
| 820 | // Histogram for tracking time taken in autocommit updates. |
| 821 | base::HistogramBase* autocommit_time_histogram_; |
| 822 | |
| 823 | // Histogram for tracking time taken in updates (including commit and |
| 824 | // autocommit). |
| 825 | base::HistogramBase* update_time_histogram_; |
| 826 | |
| 827 | // Histogram for tracking time taken in all queries. |
| 828 | base::HistogramBase* query_time_histogram_; |
| 829 | |
| 830 | // Source for timing information, provided to allow tests to inject time |
| 831 | // changes. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 832 | std::unique_ptr<base::TickClock> clock_; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 833 | |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 834 | // Stores the dump provider object when db is open. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 835 | std::unique_ptr<DatabaseMemoryDumpProvider> memory_dump_provider_; |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 836 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 837 | DISALLOW_COPY_AND_ASSIGN(Database); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 838 | }; |
| 839 | |
| 840 | } // namespace sql |
| 841 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 842 | #endif // SQL_DATABASE_H_ |