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