[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" |
Victor Costan | e56cc68 | 2018-12-27 01:53:46 | [diff] [blame] | 18 | #include "base/component_export.h" |
Dmitry Skiba | a9ad8fe4 | 2017-08-16 21:02:48 | [diff] [blame] | 19 | #include "base/containers/flat_map.h" |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 20 | #include "base/gtest_prod_util.h" |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 21 | #include "base/macros.h" |
[email protected] | 3b63f8f4 | 2011-03-28 01:54:15 | [diff] [blame] | 22 | #include "base/memory/ref_counted.h" |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 23 | #include "base/optional.h" |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 24 | #include "base/sequence_checker.h" |
Etienne Pierre-Doray | 0400dfb6 | 2018-12-03 19:12:25 | [diff] [blame] | 25 | #include "base/threading/scoped_blocking_call.h" |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 26 | #include "sql/internal_api_token.h" |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 27 | #include "sql/statement_id.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 28 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 29 | struct sqlite3; |
| 30 | struct sqlite3_stmt; |
| 31 | |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 32 | namespace base { |
| 33 | class FilePath; |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 34 | class HistogramBase; |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 35 | namespace trace_event { |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 36 | class ProcessMemoryDump; |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 37 | } // namespace trace_event |
| 38 | } // namespace base |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 39 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 40 | namespace sql { |
| 41 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 42 | class DatabaseMemoryDumpProvider; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 43 | class Statement; |
| 44 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 45 | namespace test { |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 46 | class ScopedErrorExpecter; |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 47 | } // namespace test |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 48 | |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 49 | // Handle to an open SQLite database. |
| 50 | // |
| 51 | // Instances of this class are thread-unsafe and DCHECK that they are accessed |
| 52 | // on the same sequence. |
Victor Costan | e56cc68 | 2018-12-27 01:53:46 | [diff] [blame] | 53 | class COMPONENT_EXPORT(SQL) Database { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 54 | private: |
| 55 | class StatementRef; // Forward declaration, see real one below. |
| 56 | |
| 57 | public: |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 58 | // The database is opened by calling Open[InMemory](). Any uncommitted |
| 59 | // transactions will be rolled back when this object is deleted. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 60 | Database(); |
| 61 | ~Database(); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 62 | |
Ken Rockot | 0168742 | 2020-08-17 18:00:59 | [diff] [blame] | 63 | // Allows mmapping to be disabled globally by default in the calling process. |
| 64 | // Must be called before any threads attempt to create a Database. |
| 65 | // |
| 66 | // TODO(crbug.com/1117049): Remove this global configuration. |
| 67 | static void DisableMmapByDefault(); |
| 68 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 69 | // Pre-init configuration ---------------------------------------------------- |
| 70 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 71 | // 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] | 72 | // must be called before Init(), and will only have an effect on new |
| 73 | // databases. |
| 74 | // |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 75 | // 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] | 76 | void set_page_size(int page_size) { |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 77 | DCHECK_GE(page_size, 512); |
| 78 | DCHECK_LE(page_size, 65536); |
| 79 | DCHECK(!(page_size & (page_size - 1))) |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 80 | << "page_size must be a power of two"; |
| 81 | |
| 82 | page_size_ = page_size; |
| 83 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 84 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 85 | // The page size that will be used when creating a new database. |
| 86 | int page_size() const { return page_size_; } |
| 87 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 88 | // Sets the number of pages that will be cached in memory by sqlite. The |
| 89 | // 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] | 90 | // called before Open() to have an effect. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 91 | void set_cache_size(int cache_size) { |
| 92 | DCHECK_GE(cache_size, 0); |
| 93 | |
| 94 | cache_size_ = cache_size; |
| 95 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 96 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 97 | // Returns whether a database will be opened in WAL mode. |
| 98 | bool UseWALMode() const; |
| 99 | |
| 100 | // Enables/disables WAL mode (https://www.sqlite.org/wal.html) when |
| 101 | // opening a new database. |
| 102 | // |
| 103 | // WAL mode is currently not fully supported on FuchsiaOS. It will only be |
| 104 | // turned on if the database is also using exclusive locking mode. |
| 105 | // (https://crbug.com/1082059) |
| 106 | // |
| 107 | // Note: Changing page size is not supported when in WAL mode. So running |
| 108 | // 'PRAGMA page_size = <new-size>' or using set_page_size will result in |
| 109 | // no-ops. |
| 110 | // |
| 111 | // This must be called before Open() to have an effect. |
| 112 | void want_wal_mode(bool enabled) { want_wal_mode_ = enabled; } |
| 113 | |
Victor Costan | b223079 | 2020-10-09 08:35:14 | [diff] [blame] | 114 | // Makes database accessible by only one process at a time. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 115 | // |
Victor Costan | b223079 | 2020-10-09 08:35:14 | [diff] [blame] | 116 | // TODO(https://crbug.com/1120969): This should be the default mode. The |
| 117 | // "NORMAL" mode should be opt-in. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 118 | // |
Victor Costan | b223079 | 2020-10-09 08:35:14 | [diff] [blame] | 119 | // SQLite supports a locking protocol that allows multiple processes to safely |
| 120 | // operate on the same database at the same time. The locking protocol is used |
| 121 | // on every transaction, and comes with a small performance penalty. |
| 122 | // |
| 123 | // Calling this method causes the locking protocol to be used once, when the |
| 124 | // database is opened. No other process will be able to access the database at |
| 125 | // the same time. |
| 126 | // |
| 127 | // This method must be called before Open() to have an effect. |
| 128 | // |
| 129 | // More details at https://www.sqlite.org/pragma.html#pragma_locking_mode |
| 130 | // |
| 131 | // SQLite's locking protocol is summarized at |
| 132 | // https://www.sqlite.org/c3ref/io_methods.html |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 133 | void set_exclusive_locking() { exclusive_locking_ = true; } |
| 134 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 135 | // Call to use alternative status-tracking for mmap. Usually this is tracked |
| 136 | // in the meta table, but some databases have no meta table. |
| 137 | // TODO(shess): Maybe just have all databases use the alt option? |
| 138 | void set_mmap_alt_status() { mmap_alt_status_ = true; } |
| 139 | |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 140 | // Opt out of memory-mapped file I/O. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 141 | void set_mmap_disabled() { mmap_disabled_ = true; } |
| 142 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 143 | // Set an error-handling callback. On errors, the error number (and |
| 144 | // statement, if available) will be passed to the callback. |
| 145 | // |
| 146 | // If no callback is set, the default action is to crash in debug |
| 147 | // mode or return failure in release mode. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 148 | using ErrorCallback = base::RepeatingCallback<void(int, Statement*)>; |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 149 | void set_error_callback(const ErrorCallback& callback) { |
| 150 | error_callback_ = callback; |
| 151 | } |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 152 | bool has_error_callback() const { return !error_callback_.is_null(); } |
| 153 | void reset_error_callback() { error_callback_.Reset(); } |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 154 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 155 | // Set this to enable additional per-database histogramming. Must be called |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 156 | // before Open(). |
| 157 | void set_histogram_tag(const std::string& tag); |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 158 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 159 | // Record a sparse UMA histogram sample under |
| 160 | // |name|+"."+|histogram_tag_|. If |histogram_tag_| is empty, no |
| 161 | // histogram is recorded. |
Will Harris | b869359 | 2018-08-28 22:58:44 | [diff] [blame] | 162 | void AddTaggedHistogram(const std::string& name, int sample) const; |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 163 | |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 164 | // Track various API calls and results. Values correspond to UMA |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 165 | // histograms, do not modify, or add or delete other than directly |
| 166 | // before EVENT_MAX_VALUE. |
| 167 | enum Events { |
| 168 | // Number of statements run, either with sql::Statement or Execute*(). |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 169 | EVENT_STATEMENT_RUN_DEPRECATED = 0, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 170 | |
| 171 | // Number of rows returned by statements run. |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 172 | EVENT_STATEMENT_ROWS_DEPRECATED, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 173 | |
| 174 | // Number of statements successfully run (all steps returned SQLITE_DONE or |
| 175 | // SQLITE_ROW). |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 176 | EVENT_STATEMENT_SUCCESS_DEPRECATED, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 177 | |
| 178 | // Number of statements run by Execute() or ExecuteAndReturnErrorCode(). |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 179 | EVENT_EXECUTE_DEPRECATED, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 180 | |
| 181 | // Number of rows changed by autocommit statements. |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 182 | EVENT_CHANGES_AUTOCOMMIT_DEPRECATED, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 183 | |
| 184 | // Number of rows changed by statements in transactions. |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 185 | EVENT_CHANGES_DEPRECATED, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 186 | |
| 187 | // Count actual SQLite transaction statements (not including nesting). |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 188 | EVENT_BEGIN_DEPRECATED, |
| 189 | EVENT_COMMIT_DEPRECATED, |
| 190 | EVENT_ROLLBACK_DEPRECATED, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 191 | |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 192 | // Track success and failure in GetAppropriateMmapSize(). |
| 193 | // GetAppropriateMmapSize() should record at most one of these per run. The |
| 194 | // case of mapping everything is not recorded. |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 195 | EVENT_MMAP_META_MISSING, // No meta table present. |
| 196 | EVENT_MMAP_META_FAILURE_READ, // Failed reading meta table. |
| 197 | EVENT_MMAP_META_FAILURE_UPDATE, // Failed updating meta table. |
| 198 | EVENT_MMAP_VFS_FAILURE, // Failed to access VFS. |
| 199 | EVENT_MMAP_FAILED, // Failure from past run. |
| 200 | EVENT_MMAP_FAILED_NEW, // Read error in this run. |
| 201 | EVENT_MMAP_SUCCESS_NEW_DEPRECATED, // Read to EOF in this run. |
| 202 | EVENT_MMAP_SUCCESS_PARTIAL_DEPRECATED, // Read but did not reach EOF. |
| 203 | EVENT_MMAP_SUCCESS_NO_PROGRESS_DEPRECATED, // Read quota exhausted. |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 204 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 205 | EVENT_MMAP_STATUS_FAILURE_READ, // Failure reading MmapStatus view. |
| 206 | EVENT_MMAP_STATUS_FAILURE_UPDATE, // Failure updating MmapStatus view. |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 207 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 208 | // Leave this at the end. |
| 209 | // TODO(shess): |EVENT_MAX| causes compile fail on Windows. |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 210 | EVENT_MAX_VALUE, |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 211 | }; |
| 212 | void RecordEvent(Events event, size_t count); |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 213 | void RecordOneEvent(Events event) { RecordEvent(event, 1); } |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 214 | |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 215 | // Run "PRAGMA integrity_check" and post each line of |
| 216 | // results into |messages|. Returns the success of running the |
| 217 | // statement - per the SQLite documentation, if no errors are found the |
| 218 | // call should succeed, and a single value "ok" should be in messages. |
| 219 | bool FullIntegrityCheck(std::vector<std::string>* messages); |
| 220 | |
| 221 | // Runs "PRAGMA quick_check" and, unlike the FullIntegrityCheck method, |
| 222 | // interprets the results returning true if the the statement executes |
| 223 | // without error and results in a single "ok" value. |
| 224 | bool QuickIntegrityCheck() WARN_UNUSED_RESULT; |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 225 | |
afakhry | 7c9abe7 | 2016-08-05 17:33:19 | [diff] [blame] | 226 | // Meant to be called from a client error callback so that it's able to |
| 227 | // get diagnostic information about the database. |
| 228 | std::string GetDiagnosticInfo(int extended_error, Statement* statement); |
| 229 | |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 230 | // Reports memory usage into provided memory dump with the given name. |
| 231 | bool ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd, |
| 232 | const std::string& dump_name); |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 233 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 234 | // Initialization ------------------------------------------------------------ |
| 235 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 236 | // Initializes the SQL database for the given file, returning true if the |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 237 | // file could be opened. You can call this or OpenInMemory. |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 238 | bool Open(const base::FilePath& path) WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 239 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 240 | // Initializes the SQL database for a temporary in-memory database. There |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 241 | // will be no associated file on disk, and the initial database will be |
[email protected] | 35f2094c | 2009-12-29 22:46:55 | [diff] [blame] | 242 | // empty. You can call this or Open. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 243 | bool OpenInMemory() WARN_UNUSED_RESULT; |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 244 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 245 | // Create a temporary on-disk database. The database will be |
| 246 | // deleted after close. This kind of database is similar to |
| 247 | // OpenInMemory() for small databases, but can page to disk if the |
| 248 | // database becomes large. |
| 249 | bool OpenTemporary() WARN_UNUSED_RESULT; |
| 250 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 251 | // Returns true if the database has been successfully opened. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 252 | bool is_open() const { return static_cast<bool>(db_); } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 253 | |
| 254 | // Closes the database. This is automatically performed on destruction for |
| 255 | // you, but this allows you to close the database early. You must not call |
| 256 | // any other functions after closing it. It is permissable to call Close on |
| 257 | // an uninitialized or already-closed database. |
| 258 | void Close(); |
| 259 | |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 260 | // Reads the first <cache-size>*<page-size> bytes of the file to prime the |
| 261 | // filesystem cache. This can be more efficient than faulting pages |
| 262 | // individually. Since this involves blocking I/O, it should only be used if |
| 263 | // the caller will immediately read a substantial amount of data from the |
| 264 | // database. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 265 | // |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 266 | // TODO(shess): Design a set of histograms or an experiment to inform this |
| 267 | // decision. Preloading should almost always improve later performance |
| 268 | // numbers for this database simply because it pulls operations forward, but |
| 269 | // if the data isn't actually used soon then preloading just slows down |
| 270 | // everything else. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 271 | void Preload(); |
| 272 | |
Victor Costan | 52bef81 | 2018-12-05 07:41:49 | [diff] [blame] | 273 | // Release all non-essential memory associated with this database connection. |
| 274 | void TrimMemory(); |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 275 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 276 | // Raze the database to the ground. This approximates creating a |
| 277 | // fresh database from scratch, within the constraints of SQLite's |
| 278 | // locking protocol (locks and open handles can make doing this with |
| 279 | // filesystem operations problematic). Returns true if the database |
| 280 | // was razed. |
| 281 | // |
| 282 | // false is returned if the database is locked by some other |
Carlos Knippschild | 46800c9f | 2017-09-02 02:21:43 | [diff] [blame] | 283 | // process. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 284 | // |
| 285 | // NOTE(shess): Raze() will DCHECK in the following situations: |
| 286 | // - database is not open. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 287 | // - the database has a transaction open. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 288 | // - a SQLite issue occurs which is structural in nature (like the |
| 289 | // statements used are broken). |
| 290 | // Since Raze() is expected to be called in unexpected situations, |
| 291 | // these all return false, since it is unlikely that the caller |
| 292 | // could fix them. |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 293 | // |
| 294 | // The database's page size is taken from |page_size_|. The |
| 295 | // existing database's |auto_vacuum| setting is lost (the |
| 296 | // possibility of corruption makes it unreliable to pull it from the |
| 297 | // existing database). To re-enable on the empty database requires |
| 298 | // running "PRAGMA auto_vacuum = 1;" then "VACUUM". |
| 299 | // |
| 300 | // NOTE(shess): For Android, SQLITE_DEFAULT_AUTOVACUUM is set to 1, |
| 301 | // so Raze() sets auto_vacuum to 1. |
| 302 | // |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 303 | // TODO(shess): Raze() needs a database so cannot clear SQLITE_NOTADB. |
| 304 | // TODO(shess): Bake auto_vacuum into Database's API so it can |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 305 | // just pick up the default. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 306 | bool Raze(); |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 307 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 308 | // Breaks all outstanding transactions (as initiated by |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 309 | // BeginTransaction()), closes the SQLite database, and poisons the |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 310 | // object so that all future operations against the Database (or |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 311 | // its Statements) fail safely, without side effects. |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 312 | // |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 313 | // This is intended as an alternative to Close() in error callbacks. |
| 314 | // Close() should still be called at some point. |
| 315 | void Poison(); |
| 316 | |
| 317 | // Raze() the database and Poison() the handle. Returns the return |
| 318 | // value from Raze(). |
| 319 | // TODO(shess): Rename to RazeAndPoison(). |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 320 | bool RazeAndClose(); |
| 321 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 322 | // Delete the underlying database files associated with |path|. This should be |
| 323 | // used on a database which is not opened by any Database instance. Open |
| 324 | // Database instances pointing to the database can cause odd results or |
| 325 | // corruption (for instance if a hot journal is deleted but the associated |
| 326 | // database is not). |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 327 | // |
| 328 | // Returns true if the database file and associated journals no |
| 329 | // longer exist, false otherwise. If the database has never |
| 330 | // existed, this will return true. |
| 331 | static bool Delete(const base::FilePath& path); |
| 332 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 333 | // Transactions -------------------------------------------------------------- |
| 334 | |
| 335 | // Transaction management. We maintain a virtual transaction stack to emulate |
| 336 | // nested transactions since sqlite can't do nested transactions. The |
| 337 | // limitation is you can't roll back a sub transaction: if any transaction |
| 338 | // fails, all transactions open will also be rolled back. Any nested |
| 339 | // transactions after one has rolled back will return fail for Begin(). If |
| 340 | // Begin() fails, you must not call Commit or Rollback(). |
| 341 | // |
| 342 | // Normally you should use sql::Transaction to manage a transaction, which |
| 343 | // will scope it to a C++ context. |
| 344 | bool BeginTransaction(); |
| 345 | void RollbackTransaction(); |
| 346 | bool CommitTransaction(); |
| 347 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 348 | // Rollback all outstanding transactions. Use with care, there may |
| 349 | // be scoped transactions on the stack. |
| 350 | void RollbackAllTransactions(); |
| 351 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 352 | // Returns the current transaction nesting, which will be 0 if there are |
| 353 | // no open transactions. |
| 354 | int transaction_nesting() const { return transaction_nesting_; } |
| 355 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 356 | // Attached databases--------------------------------------------------------- |
| 357 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 358 | // SQLite supports attaching multiple database files to a single connection. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 359 | // |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 360 | // Attach the database in |other_db_path| to the current connection under |
| 361 | // |attachment_point|. |attachment_point| must only contain characters from |
| 362 | // [a-zA-Z0-9_]. |
Victor Costan | 8a87f7e5 | 2017-11-10 01:29:30 | [diff] [blame] | 363 | // |
| 364 | // On the SQLite version shipped with Chrome (3.21+, Oct 2017), databases can |
| 365 | // be attached while a transaction is opened. However, these databases cannot |
Victor Costan | 70bedf2 | 2018-07-18 21:21:14 | [diff] [blame] | 366 | // be detached until the transaction is committed or aborted. |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 367 | // |
| 368 | // These APIs are only exposed for use in recovery. They are extremely subtle |
| 369 | // and are not useful for features built on top of //sql. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 370 | bool AttachDatabase(const base::FilePath& other_db_path, |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 371 | const char* attachment_point, |
| 372 | InternalApiToken); |
| 373 | bool DetachDatabase(const char* attachment_point, InternalApiToken); |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 374 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 375 | // Statements ---------------------------------------------------------------- |
| 376 | |
| 377 | // Executes the given SQL string, returning true on success. This is |
| 378 | // normally used for simple, 1-off statements that don't take any bound |
| 379 | // parameters and don't return any data (e.g. CREATE TABLE). |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 380 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 381 | // This will DCHECK if the |sql| contains errors. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 382 | // |
| 383 | // Do not use ignore_result() to ignore all errors. Use |
| 384 | // ExecuteAndReturnErrorCode() and ignore only specific errors. |
| 385 | bool Execute(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 386 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 387 | // Like Execute(), but returns the error code given by SQLite. |
[email protected] | 9fe3755 | 2011-12-23 17:07:20 | [diff] [blame] | 388 | int ExecuteAndReturnErrorCode(const char* sql) WARN_UNUSED_RESULT; |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 389 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 390 | // Returns a statement for the given SQL using the statement cache. It can |
| 391 | // take a nontrivial amount of work to parse and compile a statement, so |
| 392 | // keeping commonly-used ones around for future use is important for |
| 393 | // performance. |
| 394 | // |
Victor Costan | 613b430 | 2018-11-20 05:32:43 | [diff] [blame] | 395 | // The SQL_FROM_HERE macro is the recommended way of generating a StatementID. |
| 396 | // Code that generates custom IDs must ensure that a StatementID is never used |
| 397 | // for different SQL statements. Failing to meet this requirement results in |
| 398 | // incorrect behavior, and should be caught by a DCHECK. |
| 399 | // |
| 400 | // The SQL statement passed in |sql| must match the SQL statement reported |
| 401 | // back by SQLite. Mismatches are caught by a DCHECK, so any code that has |
| 402 | // automated test coverage or that was manually tested on a DCHECK build will |
| 403 | // not exhibit this problem. Mismatches generally imply that the statement |
| 404 | // passed in has extra whitespace or comments surrounding it, which waste |
| 405 | // storage and CPU cycles. |
| 406 | // |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 407 | // If the |sql| has an error, an invalid, inert StatementRef is returned (and |
| 408 | // the code will crash in debug). The caller must deal with this eventuality, |
| 409 | // either by checking validity of the |sql| before calling, by correctly |
| 410 | // handling the return of an inert statement, or both. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 411 | // |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 412 | // Example: |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 413 | // sql::Statement stmt(database_.GetCachedStatement( |
[email protected] | 3273dce | 2010-01-27 16:08:08 | [diff] [blame] | 414 | // SQL_FROM_HERE, "SELECT * FROM foo")); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 415 | // if (!stmt) |
| 416 | // return false; // Error creating statement. |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 417 | scoped_refptr<StatementRef> GetCachedStatement(StatementID id, |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 418 | const char* sql); |
| 419 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 420 | // Used to check a |sql| statement for syntactic validity. If the statement is |
| 421 | // valid SQL, returns true. |
| 422 | bool IsSQLValid(const char* sql); |
| 423 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 424 | // Returns a non-cached statement for the given SQL. Use this for SQL that |
| 425 | // is only executed once or only rarely (there is overhead associated with |
| 426 | // keeping a statement cached). |
| 427 | // |
| 428 | // See GetCachedStatement above for examples and error information. |
| 429 | scoped_refptr<StatementRef> GetUniqueStatement(const char* sql); |
| 430 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 431 | // Performs a passive checkpoint on the main attached database if it is in |
| 432 | // WAL mode. Returns true if the checkpoint was successful and false in case |
| 433 | // of an error. It is a no-op if the database is not in WAL mode. |
| 434 | // |
| 435 | // Note: Checkpointing is a very slow operation and will block any writes |
| 436 | // until it is finished. Please use with care. |
| 437 | bool CheckpointDatabase(); |
| 438 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 439 | // Info querying ------------------------------------------------------------- |
| 440 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 441 | // Returns true if the given structure exists. Instead of test-then-create, |
| 442 | // callers should almost always prefer the "IF NOT EXISTS" version of the |
| 443 | // CREATE statement. |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 444 | bool DoesIndexExist(const char* index_name) const; |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 445 | bool DoesTableExist(const char* table_name) const; |
| 446 | bool DoesViewExist(const char* table_name) const; |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 447 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 448 | // Returns true if a column with the given name exists in the given table. |
Victor Costan | 1ff47e9 | 2018-12-07 11:10:43 | [diff] [blame] | 449 | // |
| 450 | // Calling this method on a VIEW returns an unspecified result. |
| 451 | // |
| 452 | // This should only be used by migration code for legacy features that do not |
| 453 | // use MetaTable, and need an alternative way of figuring out the database's |
| 454 | // current version. |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 455 | bool DoesColumnExist(const char* table_name, const char* column_name) const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 456 | |
| 457 | // Returns sqlite's internal ID for the last inserted row. Valid only |
| 458 | // immediately after an insert. |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 459 | int64_t GetLastInsertRowId() const; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 460 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 461 | // Returns sqlite's count of the number of rows modified by the last |
| 462 | // statement executed. Will be 0 if no statement has executed or the database |
| 463 | // is closed. |
| 464 | int GetLastChangeCount() const; |
| 465 | |
Victor Costan | d6e7325 | 2020-10-14 21:11:25 | [diff] [blame^] | 466 | // Approximates the amount of memory used by SQLite for this database. |
| 467 | // |
| 468 | // This measures the memory used for the page cache (most likely the biggest |
| 469 | // consumer), database schema, and prepared statements. |
| 470 | // |
| 471 | // The memory used by the page cache can be recovered by calling TrimMemory(), |
| 472 | // which will cause SQLite to drop the page cache. |
| 473 | int GetMemoryUsage(); |
| 474 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 475 | // Errors -------------------------------------------------------------------- |
| 476 | |
| 477 | // Returns the error code associated with the last sqlite operation. |
| 478 | int GetErrorCode() const; |
| 479 | |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 480 | // Returns the errno associated with GetErrorCode(). See |
| 481 | // SQLITE_LAST_ERRNO in SQLite documentation. |
| 482 | int GetLastErrno() const; |
| 483 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 484 | // Returns a pointer to a statically allocated string associated with the |
| 485 | // last sqlite operation. |
| 486 | const char* GetErrorMessage() const; |
| 487 | |
[email protected] | 92cd00a | 2013-08-16 11:09:58 | [diff] [blame] | 488 | // Return a reproducible representation of the schema equivalent to |
| 489 | // running the following statement at a sqlite3 command-line: |
| 490 | // SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY 1, 2, 3, 4; |
| 491 | std::string GetSchema() const; |
| 492 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 493 | // Returns |true| if there is an error expecter (see SetErrorExpecter), and |
| 494 | // that expecter returns |true| when passed |error|. Clients which provide an |
| 495 | // |error_callback| should use IsExpectedSqliteError() to check for unexpected |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 496 | // errors; if one is detected, DLOG(DCHECK) is generally appropriate (see |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 497 | // OnSqliteError implementation). |
| 498 | static bool IsExpectedSqliteError(int error); |
[email protected] | 74cdede | 2013-09-25 05:39:57 | [diff] [blame] | 499 | |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 500 | // Computes the path of a database's rollback journal. |
| 501 | // |
| 502 | // The journal file is created at the beginning of the database's first |
| 503 | // transaction. The file may be removed and re-created between transactions, |
| 504 | // depending on whether the database is opened in exclusive mode, and on |
| 505 | // configuration options. The journal file does not exist when the database |
| 506 | // operates in WAL mode. |
| 507 | // |
| 508 | // This is intended for internal use and tests. To preserve our ability to |
| 509 | // iterate on our SQLite configuration, features must avoid relying on |
| 510 | // the existence of specific files. |
| 511 | static base::FilePath JournalPath(const base::FilePath& db_path); |
| 512 | |
| 513 | // Computes the path of a database's write-ahead log (WAL). |
| 514 | // |
| 515 | // The WAL file exists while a database is opened in WAL mode. |
| 516 | // |
| 517 | // This is intended for internal use and tests. To preserve our ability to |
| 518 | // iterate on our SQLite configuration, features must avoid relying on |
| 519 | // the existence of specific files. |
| 520 | static base::FilePath WriteAheadLogPath(const base::FilePath& db_path); |
| 521 | |
| 522 | // Computes the path of a database's shared memory (SHM) file. |
| 523 | // |
| 524 | // The SHM file is used to coordinate between multiple processes using the |
| 525 | // same database in WAL mode. Thus, this file only exists for databases using |
| 526 | // WAL and not opened in exclusive mode. |
| 527 | // |
| 528 | // This is intended for internal use and tests. To preserve our ability to |
| 529 | // iterate on our SQLite configuration, features must avoid relying on |
| 530 | // the existence of specific files. |
| 531 | static base::FilePath SharedMemoryFilePath(const base::FilePath& db_path); |
| 532 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 533 | // Default page size for newly created databases. |
| 534 | // |
| 535 | // Guaranteed to match SQLITE_DEFAULT_PAGE_SIZE. |
| 536 | static constexpr int kDefaultPageSize = 4096; |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 537 | |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 538 | // Internal state accessed by other classes in //sql. |
| 539 | sqlite3* db(InternalApiToken) const { return db_; } |
| 540 | bool poisoned(InternalApiToken) const { return poisoned_; } |
| 541 | |
| 542 | private: |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 543 | // Allow test-support code to set/reset error expecter. |
| 544 | friend class test::ScopedErrorExpecter; |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 545 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 546 | // Statement accesses StatementRef which we don't want to expose to everybody |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 547 | // (they should go through Statement). |
| 548 | friend class Statement; |
| 549 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 550 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CachedStatement); |
| 551 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, CollectDiagnosticInfo); |
| 552 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSize); |
| 553 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, GetAppropriateMmapSizeAltStatus); |
| 554 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, OnMemoryDump); |
| 555 | FRIEND_TEST_ALL_PREFIXES(SQLDatabaseTest, RegisterIntentToUpload); |
shess | f7fcc45 | 2017-04-19 22:10:41 | [diff] [blame] | 556 | FRIEND_TEST_ALL_PREFIXES(SQLiteFeaturesTest, WALNoClose); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 557 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 558 | // Internal initialize function used by both Init and InitInMemory. The file |
| 559 | // name is always 8 bits since we want to use the 8-bit version of |
| 560 | // sqlite3_open. The string can also be sqlite's special ":memory:" string. |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 561 | // |
| 562 | // |retry_flag| controls retrying the open if the error callback |
| 563 | // addressed errors using RazeAndClose(). |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 564 | enum Retry { NO_RETRY = 0, RETRY_ON_POISON }; |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 565 | bool OpenInternal(const std::string& file_name, Retry retry_flag); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 566 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 567 | // Internal close function used by Close() and RazeAndClose(). |
| 568 | // |forced| indicates that orderly-shutdown checks should not apply. |
| 569 | void CloseInternal(bool forced); |
| 570 | |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 571 | // Construct a ScopedBlockingCall to annotate IO calls, but only if |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 572 | // database wasn't open in memory. ScopedBlockingCall uses |from_here| to |
| 573 | // declare its blocking execution scope (see https://www.crbug/934302). |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 574 | void InitScopedBlockingCall( |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 575 | const base::Location& from_here, |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 576 | base::Optional<base::ScopedBlockingCall>* scoped_blocking_call) const { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 577 | if (!in_memory_) |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 578 | scoped_blocking_call->emplace(from_here, base::BlockingType::MAY_BLOCK); |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 579 | } |
| 580 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 581 | // Internal helper for Does*Exist() functions. |
| 582 | bool DoesSchemaItemExist(const char* name, const char* type) const; |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 583 | |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 584 | // Accessors for global error-expecter, for injecting behavior during tests. |
| 585 | // See test/scoped_error_expecter.h. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 586 | using ErrorExpecterCallback = base::RepeatingCallback<bool(int)>; |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 587 | static ErrorExpecterCallback* current_expecter_cb_; |
| 588 | static void SetErrorExpecter(ErrorExpecterCallback* expecter); |
| 589 | static void ResetErrorExpecter(); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 590 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 591 | // A StatementRef is a refcounted wrapper around a sqlite statement pointer. |
| 592 | // Refcounting allows us to give these statements out to sql::Statement |
| 593 | // objects while also optionally maintaining a cache of compiled statements |
| 594 | // by just keeping a refptr to these objects. |
| 595 | // |
| 596 | // A statement ref can be valid, in which case it can be used, or invalid to |
| 597 | // indicate that the statement hasn't been created yet, has an error, or has |
| 598 | // been destroyed. |
| 599 | // |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 600 | // The Database may revoke a StatementRef in some error cases, so callers |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 601 | // should always check validity before using. |
Victor Costan | e56cc68 | 2018-12-27 01:53:46 | [diff] [blame] | 602 | class COMPONENT_EXPORT(SQL) StatementRef |
| 603 | : public base::RefCounted<StatementRef> { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 604 | public: |
Victor Costan | 3b02cdf | 2018-07-18 00:39:56 | [diff] [blame] | 605 | REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE(); |
| 606 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 607 | // |database| is the sql::Database instance associated with |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 608 | // the statement, and is used for tracking outstanding statements |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 609 | // and for error handling. Set to nullptr for invalid or untracked |
| 610 | // refs. |stmt| is the actual statement, and should only be null |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 611 | // to create an invalid ref. |was_valid| indicates whether the |
Etienne Bergeron | 95a01c2a | 2019-02-26 21:32:50 | [diff] [blame] | 612 | // statement should be considered valid for diagnostic purposes. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 613 | // |was_valid| can be true for a null |stmt| if the Database has |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 614 | // been forcibly closed by an error handler. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 615 | StatementRef(Database* database, sqlite3_stmt* stmt, bool was_valid); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 616 | |
| 617 | // When true, the statement can be used. |
| 618 | bool is_valid() const { return !!stmt_; } |
| 619 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 620 | // When true, the statement is either currently valid, or was |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 621 | // previously valid but the database was forcibly closed. Used |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 622 | // for diagnostic checks. |
| 623 | bool was_valid() const { return was_valid_; } |
| 624 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 625 | // If we've not been linked to a database, this will be null. |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 626 | // |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 627 | // TODO(shess): database_ can be nullptr in case of |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 628 | // GetUntrackedStatement(), which prevents Statement::OnError() from |
| 629 | // forwarding errors. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 630 | Database* database() const { return database_; } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 631 | |
| 632 | // Returns the sqlite statement if any. If the statement is not active, |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 633 | // this will return nullptr. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 634 | sqlite3_stmt* stmt() const { return stmt_; } |
| 635 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 636 | // Destroys the compiled statement and sets it to nullptr. The statement |
| 637 | // will no longer be active. |forced| is used to indicate if |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 638 | // orderly-shutdown checks should apply (see Database::RazeAndClose()). |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 639 | void Close(bool forced); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 640 | |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 641 | // Construct a ScopedBlockingCall to annotate IO calls, but only if |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 642 | // database wasn't open in memory. ScopedBlockingCall uses |from_here| to |
| 643 | // declare its blocking execution scope (see https://www.crbug/934302). |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 644 | void InitScopedBlockingCall( |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 645 | const base::Location& from_here, |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 646 | base::Optional<base::ScopedBlockingCall>* scoped_blocking_call) const { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 647 | if (database_) |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 648 | database_->InitScopedBlockingCall(from_here, scoped_blocking_call); |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 649 | } |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 650 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 651 | private: |
[email protected] | 877d55d | 2009-11-05 21:53:08 | [diff] [blame] | 652 | friend class base::RefCounted<StatementRef>; |
| 653 | |
| 654 | ~StatementRef(); |
| 655 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 656 | Database* database_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 657 | sqlite3_stmt* stmt_; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 658 | bool was_valid_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 659 | |
| 660 | DISALLOW_COPY_AND_ASSIGN(StatementRef); |
| 661 | }; |
| 662 | friend class StatementRef; |
| 663 | |
| 664 | // Executes a rollback statement, ignoring all transaction state. Used |
| 665 | // internally in the transaction management code. |
| 666 | void DoRollback(); |
| 667 | |
| 668 | // Called by a StatementRef when it's being created or destroyed. See |
| 669 | // open_statements_ below. |
| 670 | void StatementRefCreated(StatementRef* ref); |
| 671 | void StatementRefDeleted(StatementRef* ref); |
| 672 | |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 673 | // Called when a sqlite function returns an error, which is passed |
| 674 | // as |err|. The return value is the error code to be reflected |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 675 | // back to client code. |stmt| is non-null if the error relates to |
| 676 | // an sql::Statement instance. |sql| is non-nullptr if the error |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 677 | // relates to non-statement sql code (Execute, for instance). Both |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 678 | // can be null, but both should never be set. |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 679 | // NOTE(shess): Originally, the return value was intended to allow |
| 680 | // error handlers to transparently convert errors into success. |
| 681 | // Unfortunately, transactions are not generally restartable, so |
| 682 | // this did not work out. |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 683 | int OnSqliteError(int err, Statement* stmt, const char* sql) const; |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 684 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 685 | // Like |Execute()|, but retries if the database is locked. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 686 | bool ExecuteWithTimeout(const char* sql, |
| 687 | base::TimeDelta ms_timeout) WARN_UNUSED_RESULT; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 688 | |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 689 | // Implementation helper for GetUniqueStatement() and GetUntrackedStatement(). |
| 690 | // |tracking_db| is the db the resulting ref should register with for |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 691 | // outstanding statement tracking, which should be |this| to track or null to |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 692 | // not track. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 693 | scoped_refptr<StatementRef> GetStatementImpl(sql::Database* tracking_db, |
| 694 | const char* sql) const; |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 695 | |
| 696 | // Helper for implementing const member functions. Like GetUniqueStatement(), |
| 697 | // except the StatementRef is not entered into |open_statements_|, so an |
| 698 | // outstanding StatementRef from this function can block closing the database. |
| 699 | // The StatementRef will not call OnSqliteError(), because that can call |
| 700 | // |error_callback_| which can close the database. |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 701 | scoped_refptr<StatementRef> GetUntrackedStatement(const char* sql) const; |
| 702 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 703 | bool IntegrityCheckHelper(const char* pragma_sql, |
| 704 | std::vector<std::string>* messages) |
| 705 | WARN_UNUSED_RESULT; |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 706 | |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 707 | // Release page-cache memory if memory-mapped I/O is enabled and the database |
| 708 | // was changed. Passing true for |implicit_change_performed| allows |
| 709 | // overriding the change detection for cases like DDL (CREATE, DROP, etc), |
| 710 | // which do not participate in the total-rows-changed tracking. |
| 711 | void ReleaseCacheMemoryIfNeeded(bool implicit_change_performed); |
| 712 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 713 | // Returns the results of sqlite3_db_filename(), which should match the path |
| 714 | // passed to Open(). |
| 715 | base::FilePath DbPath() const; |
| 716 | |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 717 | // Helper to collect diagnostic info for a corrupt database. |
| 718 | std::string CollectCorruptionInfo(); |
| 719 | |
| 720 | // Helper to collect diagnostic info for errors. |
| 721 | std::string CollectErrorInfo(int error, Statement* stmt) const; |
| 722 | |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 723 | // Calculates a value appropriate to pass to "PRAGMA mmap_size = ". So errors |
| 724 | // can make it unsafe to map a file, so the file is read using regular I/O, |
| 725 | // with any errors causing 0 (don't map anything) to be returned. If the |
| 726 | // entire file is read without error, a large value is returned which will |
| 727 | // allow the entire file to be mapped in most cases. |
| 728 | // |
| 729 | // Results are recorded in the database's meta table for future reference, so |
| 730 | // the file should only be read through once. |
| 731 | size_t GetAppropriateMmapSize(); |
| 732 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 733 | // Helpers for GetAppropriateMmapSize(). |
| 734 | bool GetMmapAltStatus(int64_t* status); |
| 735 | bool SetMmapAltStatus(int64_t status); |
| 736 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 737 | // 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] | 738 | // Init resulted in an error. |
| 739 | sqlite3* db_; |
| 740 | |
| 741 | // Parameters we'll configure in sqlite before doing anything else. Zero means |
| 742 | // use the default value. |
| 743 | int page_size_; |
| 744 | int cache_size_; |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 745 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 746 | bool exclusive_locking_; |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 747 | bool want_wal_mode_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 748 | |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 749 | // Holds references to all cached statements so they remain active. |
| 750 | // |
| 751 | // flat_map is appropriate here because the codebase has ~400 cached |
| 752 | // statements, and each statement is at most one insertion in the map |
| 753 | // throughout a process' lifetime. |
| 754 | base::flat_map<StatementID, scoped_refptr<StatementRef>> statement_cache_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 755 | |
| 756 | // A list of all StatementRefs we've given out. Each ref must register with |
| 757 | // us when it's created or destroyed. This allows us to potentially close |
| 758 | // any open statements when we encounter an error. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 759 | std::set<StatementRef*> open_statements_; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 760 | |
| 761 | // Number of currently-nested transactions. |
| 762 | int transaction_nesting_; |
| 763 | |
| 764 | // True if any of the currently nested transactions have been rolled back. |
| 765 | // When we get to the outermost transaction, this will determine if we do |
| 766 | // a rollback instead of a commit. |
| 767 | bool needs_rollback_; |
| 768 | |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 769 | // True if database is open with OpenInMemory(), False if database is open |
| 770 | // with Open(). |
| 771 | bool in_memory_; |
| 772 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 773 | // |true| if the Database was closed using RazeAndClose(). Used |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 774 | // to enable diagnostics to distinguish calls to never-opened |
| 775 | // databases (incorrect use of the API) from calls to once-valid |
| 776 | // databases. |
| 777 | bool poisoned_; |
| 778 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 779 | // |true| to use alternate storage for tracking mmap status. |
| 780 | bool mmap_alt_status_; |
| 781 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 782 | // |true| if SQLite memory-mapped I/O is not desired for this database. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 783 | bool mmap_disabled_; |
| 784 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 785 | // |true| if SQLite memory-mapped I/O was enabled for this database. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 786 | // Used by ReleaseCacheMemoryIfNeeded(). |
| 787 | bool mmap_enabled_; |
| 788 | |
| 789 | // Used by ReleaseCacheMemoryIfNeeded() to track if new changes have happened |
| 790 | // since memory was last released. |
| 791 | int total_changes_at_last_release_; |
| 792 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 793 | ErrorCallback error_callback_; |
| 794 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 795 | // Tag for auxiliary histograms. |
| 796 | std::string histogram_tag_; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 797 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 798 | // Linear histogram for RecordEvent(). |
| 799 | base::HistogramBase* stats_histogram_; |
| 800 | |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 801 | // Stores the dump provider object when db is open. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 802 | std::unique_ptr<DatabaseMemoryDumpProvider> memory_dump_provider_; |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 803 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 804 | DISALLOW_COPY_AND_ASSIGN(Database); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 805 | }; |
| 806 | |
| 807 | } // namespace sql |
| 808 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 809 | #endif // SQL_DATABASE_H_ |