[email protected] | 6402104 | 2012-02-10 20:02:29 | [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 | #include "sql/database.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 6 | |
avi | 51ba3e69 | 2015-12-26 17:30:50 | [diff] [blame] | 7 | #include <limits.h> |
avi | 0b51920 | 2015-12-21 07:25:19 | [diff] [blame] | 8 | #include <stddef.h> |
| 9 | #include <stdint.h> |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 10 | #include <string.h> |
mostynb | d82cd995 | 2016-04-11 20:05:34 | [diff] [blame] | 11 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 12 | #include "base/feature_list.h" |
[email protected] | 5799981 | 2013-02-24 05:40:52 | [diff] [blame] | 13 | #include "base/files/file_path.h" |
thestig | 22dfc401 | 2014-09-05 08:29:44 | [diff] [blame] | 14 | #include "base/files/file_util.h" |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 15 | #include "base/format_macros.h" |
fdoray | 2dfa7645 | 2016-06-07 13:11:22 | [diff] [blame] | 16 | #include "base/location.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 17 | #include "base/logging.h" |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 18 | #include "base/metrics/histogram_functions.h" |
asvitkine | 3033081 | 2016-08-30 04:01:08 | [diff] [blame] | 19 | #include "base/metrics/histogram_macros.h" |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 20 | #include "base/metrics/sparse_histogram.h" |
Victor Costan | 3653df6 | 2018-02-08 21:38:16 | [diff] [blame] | 21 | #include "base/no_destructor.h" |
Will Harris | b869359 | 2018-08-28 22:58:44 | [diff] [blame] | 22 | #include "base/numerics/safe_conversions.h" |
fdoray | 2dfa7645 | 2016-06-07 13:11:22 | [diff] [blame] | 23 | #include "base/single_thread_task_runner.h" |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 24 | #include "base/strings/string_split.h" |
[email protected] | a4bbc1f9 | 2013-06-11 07:28:19 | [diff] [blame] | 25 | #include "base/strings/string_util.h" |
| 26 | #include "base/strings/stringprintf.h" |
[email protected] | 90626587 | 2013-06-07 22:40:45 | [diff] [blame] | 27 | #include "base/strings/utf_string_conversions.h" |
[email protected] | a7ec129 | 2013-07-22 22:02:18 | [diff] [blame] | 28 | #include "base/synchronization/lock.h" |
Etienne Pierre-Doray | 0400dfb6 | 2018-12-03 19:12:25 | [diff] [blame] | 29 | #include "base/threading/scoped_blocking_call.h" |
ssid | 9f8022f | 2015-10-12 17:49:03 | [diff] [blame] | 30 | #include "base/trace_event/memory_dump_manager.h" |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 31 | #include "base/trace_event/trace_event.h" |
Kevin Marshall | a9f05ec | 2017-07-14 02:10:05 | [diff] [blame] | 32 | #include "build/build_config.h" |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 33 | #include "sql/database_memory_dump_provider.h" |
Victor Costan | 3653df6 | 2018-02-08 21:38:16 | [diff] [blame] | 34 | #include "sql/initialization.h" |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 35 | #include "sql/meta_table.h" |
Victor Costan | 3ffd9a37 | 2019-05-22 00:46:54 | [diff] [blame] | 36 | #include "sql/sql_features.h" |
[email protected] | f0a54b2 | 2011-07-19 18:40:21 | [diff] [blame] | 37 | #include "sql/statement.h" |
shess | 5f2c344 | 2017-01-24 02:15:10 | [diff] [blame] | 38 | #include "sql/vfs_wrapper.h" |
[email protected] | e33cba4 | 2010-08-18 23:37:03 | [diff] [blame] | 39 | #include "third_party/sqlite/sqlite3.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 40 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 41 | namespace { |
| 42 | |
Ken Rockot | 0168742 | 2020-08-17 18:00:59 | [diff] [blame] | 43 | bool enable_mmap_by_default_ = true; |
| 44 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 45 | // Spin for up to a second waiting for the lock to clear when setting |
| 46 | // up the database. |
| 47 | // TODO(shess): Better story on this. http://crbug.com/56559 |
[email protected] | c68ce17 | 2011-11-24 22:30:27 | [diff] [blame] | 48 | const int kBusyTimeoutSeconds = 1; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 49 | |
| 50 | class ScopedBusyTimeout { |
| 51 | public: |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 52 | explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {} |
| 53 | ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); } |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 54 | |
| 55 | int SetTimeout(base::TimeDelta timeout) { |
| 56 | DCHECK_LT(timeout.InMilliseconds(), INT_MAX); |
| 57 | return sqlite3_busy_timeout(db_, |
| 58 | static_cast<int>(timeout.InMilliseconds())); |
| 59 | } |
| 60 | |
| 61 | private: |
| 62 | sqlite3* db_; |
| 63 | }; |
| 64 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 65 | // Helper to "safely" enable writable_schema. No error checking |
| 66 | // because it is reasonable to just forge ahead in case of an error. |
| 67 | // If turning it on fails, then most likely nothing will work, whereas |
| 68 | // if turning it off fails, it only matters if some code attempts to |
| 69 | // continue working with the database and tries to modify the |
| 70 | // sqlite_master table (none of our code does this). |
| 71 | class ScopedWritableSchema { |
| 72 | public: |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 73 | explicit ScopedWritableSchema(sqlite3* db) : db_(db) { |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 74 | sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr); |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 75 | } |
| 76 | ~ScopedWritableSchema() { |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 77 | sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr); |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 78 | } |
| 79 | |
| 80 | private: |
| 81 | sqlite3* db_; |
| 82 | }; |
| 83 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 84 | // Helper to wrap the sqlite3_backup_*() step of Raze(). Return |
| 85 | // SQLite error code from running the backup step. |
| 86 | int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) { |
| 87 | DCHECK_NE(src, dst); |
| 88 | sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name); |
| 89 | if (!backup) { |
| 90 | // Since this call only sets things up, this indicates a gross |
| 91 | // error in SQLite. |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 92 | DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst); |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 93 | return sqlite3_errcode(dst); |
| 94 | } |
| 95 | |
| 96 | // -1 backs up the entire database. |
| 97 | int rc = sqlite3_backup_step(backup, -1); |
| 98 | int pages = sqlite3_backup_pagecount(backup); |
| 99 | sqlite3_backup_finish(backup); |
| 100 | |
| 101 | // If successful, exactly one page should have been backed up. If |
| 102 | // this breaks, check this function to make sure assumptions aren't |
| 103 | // being broken. |
| 104 | if (rc == SQLITE_DONE) |
| 105 | DCHECK_EQ(pages, 1); |
| 106 | |
| 107 | return rc; |
| 108 | } |
| 109 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 110 | // Be very strict on attachment point. SQLite can handle a much wider |
| 111 | // character set with appropriate quoting, but Chromium code should |
| 112 | // just use clean names to start with. |
| 113 | bool ValidAttachmentPoint(const char* attachment_point) { |
| 114 | for (size_t i = 0; attachment_point[i]; ++i) { |
zhongyi | 2396034 | 2016-04-12 23:13:20 | [diff] [blame] | 115 | if (!(base::IsAsciiDigit(attachment_point[i]) || |
| 116 | base::IsAsciiAlpha(attachment_point[i]) || |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 117 | attachment_point[i] == '_')) { |
| 118 | return false; |
| 119 | } |
| 120 | } |
| 121 | return true; |
| 122 | } |
| 123 | |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 124 | // Helper to get the sqlite3_file* associated with the "main" database. |
| 125 | int GetSqlite3File(sqlite3* db, sqlite3_file** file) { |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 126 | *file = nullptr; |
| 127 | int rc = sqlite3_file_control(db, nullptr, SQLITE_FCNTL_FILE_POINTER, file); |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 128 | if (rc != SQLITE_OK) |
| 129 | return rc; |
| 130 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 131 | // TODO(shess): null in file->pMethods has been observed on android_dbg |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 132 | // content_unittests, even though it should not be possible. |
| 133 | // http://crbug.com/329982 |
| 134 | if (!*file || !(*file)->pMethods) |
| 135 | return SQLITE_ERROR; |
| 136 | |
| 137 | return rc; |
| 138 | } |
| 139 | |
shess | 5dac334f | 2015-11-05 20:47:42 | [diff] [blame] | 140 | // Convenience to get the sqlite3_file* and the size for the "main" database. |
| 141 | int GetSqlite3FileAndSize(sqlite3* db, |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 142 | sqlite3_file** file, |
| 143 | sqlite3_int64* db_size) { |
shess | 5dac334f | 2015-11-05 20:47:42 | [diff] [blame] | 144 | int rc = GetSqlite3File(db, file); |
| 145 | if (rc != SQLITE_OK) |
| 146 | return rc; |
| 147 | |
| 148 | return (*file)->pMethods->xFileSize(*file, db_size); |
| 149 | } |
| 150 | |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 151 | std::string AsUTF8ForSQL(const base::FilePath& path) { |
| 152 | #if defined(OS_WIN) |
Jan Wilken Dörrie | 9720dce | 2020-07-21 17:14:23 | [diff] [blame] | 153 | return base::WideToUTF8(path.value()); |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 154 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 155 | return path.value(); |
| 156 | #endif |
| 157 | } |
| 158 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 159 | } // namespace |
| 160 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 161 | namespace sql { |
| 162 | |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 163 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 164 | Database::ErrorExpecterCallback* Database::current_expecter_cb_ = nullptr; |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 165 | |
| 166 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 167 | bool Database::IsExpectedSqliteError(int error) { |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 168 | if (!current_expecter_cb_) |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 169 | return false; |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 170 | return current_expecter_cb_->Run(error); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 171 | } |
| 172 | |
| 173 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 174 | void Database::SetErrorExpecter(Database::ErrorExpecterCallback* cb) { |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 175 | CHECK(!current_expecter_cb_); |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 176 | current_expecter_cb_ = cb; |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 177 | } |
| 178 | |
| 179 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 180 | void Database::ResetErrorExpecter() { |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 181 | CHECK(current_expecter_cb_); |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 182 | current_expecter_cb_ = nullptr; |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 183 | } |
| 184 | |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 185 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 186 | base::FilePath Database::JournalPath(const base::FilePath& db_path) { |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 187 | return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal")); |
| 188 | } |
| 189 | |
| 190 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 191 | base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) { |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 192 | return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal")); |
| 193 | } |
| 194 | |
| 195 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 196 | base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) { |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 197 | return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm")); |
| 198 | } |
| 199 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 200 | Database::StatementRef::StatementRef(Database* database, |
| 201 | sqlite3_stmt* stmt, |
| 202 | bool was_valid) |
| 203 | : database_(database), stmt_(stmt), was_valid_(was_valid) { |
| 204 | if (database) |
| 205 | database_->StatementRefCreated(this); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 206 | } |
| 207 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 208 | Database::StatementRef::~StatementRef() { |
| 209 | if (database_) |
| 210 | database_->StatementRefDeleted(this); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 211 | Close(false); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 212 | } |
| 213 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 214 | void Database::StatementRef::Close(bool forced) { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 215 | if (stmt_) { |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 216 | // Call to InitScopedBlockingCall() cannot go at the beginning of the |
| 217 | // function because Close() is called unconditionally from destructor to |
| 218 | // clean database_. And if this is inactive statement this won't cause any |
| 219 | // disk access and destructor most probably will be called on thread not |
| 220 | // allowing disk access. |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 221 | // TODO([email protected]): This should move to the beginning |
| 222 | // of the function. http://crbug.com/136655. |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 223 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 224 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 225 | sqlite3_finalize(stmt_); |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 226 | stmt_ = nullptr; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 227 | } |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 228 | database_ = nullptr; // The Database may be getting deleted. |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 229 | |
| 230 | // Forced close is expected to happen from a statement error |
| 231 | // handler. In that case maintain the sense of |was_valid_| which |
| 232 | // previously held for this ref. |
| 233 | was_valid_ = was_valid_ && forced; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 234 | } |
| 235 | |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 236 | static_assert(DatabaseOptions::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE, |
| 237 | "DatabaseOptions::kDefaultPageSize must match the value " |
| 238 | "configured into SQLite"); |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 239 | |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 240 | Database::Database() : Database({.exclusive_locking = false}) {} |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 241 | |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 242 | Database::Database(DatabaseOptions options) |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 243 | : db_(nullptr), |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 244 | options_(options), |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 245 | transaction_nesting_(0), |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 246 | needs_rollback_(false), |
[email protected] | 49dc4f2 | 2012-10-17 17:41:16 | [diff] [blame] | 247 | in_memory_(false), |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 248 | poisoned_(false), |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 249 | mmap_alt_status_(false), |
Ken Rockot | 0168742 | 2020-08-17 18:00:59 | [diff] [blame] | 250 | mmap_disabled_(!enable_mmap_by_default_), |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 251 | mmap_enabled_(false), |
| 252 | total_changes_at_last_release_(0), |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 253 | stats_histogram_(nullptr) { |
| 254 | DCHECK_GE(options.page_size, 512); |
| 255 | DCHECK_LE(options.page_size, 65536); |
| 256 | DCHECK(!(options.page_size & (options.page_size - 1))) |
| 257 | << "page_size must be a power of two"; |
| 258 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 259 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 260 | Database::~Database() { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 261 | Close(); |
| 262 | } |
| 263 | |
Ken Rockot | 0168742 | 2020-08-17 18:00:59 | [diff] [blame] | 264 | void Database::DisableMmapByDefault() { |
| 265 | enable_mmap_by_default_ = false; |
| 266 | } |
| 267 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 268 | void Database::RecordEvent(Events event, size_t count) { |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 269 | for (size_t i = 0; i < count; ++i) { |
Victor Costan | b0e7fc0 | 2019-03-01 03:36:27 | [diff] [blame] | 270 | UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats2", event, EVENT_MAX_VALUE); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 271 | } |
| 272 | |
| 273 | if (stats_histogram_) { |
| 274 | for (size_t i = 0; i < count; ++i) { |
| 275 | stats_histogram_->Add(event); |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 280 | bool Database::Open(const base::FilePath& path) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 281 | TRACE_EVENT1("sql", "Database::Open", "path", path.MaybeAsASCII()); |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 282 | return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 283 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 284 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 285 | bool Database::OpenInMemory() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 286 | TRACE_EVENT0("sql", "Database::OpenInMemory"); |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 287 | in_memory_ = true; |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 288 | return OpenInternal(":memory:", NO_RETRY); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 289 | } |
| 290 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 291 | bool Database::OpenTemporary() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 292 | TRACE_EVENT0("sql", "Database::OpenTemporary"); |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 293 | return OpenInternal("", NO_RETRY); |
| 294 | } |
| 295 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 296 | void Database::CloseInternal(bool forced) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 297 | TRACE_EVENT0("sql", "Database::CloseInternal"); |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 298 | // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point |
| 299 | // will delete the -journal file. For ChromiumOS or other more |
| 300 | // embedded systems, this is probably not appropriate, whereas on |
| 301 | // desktop it might make some sense. |
| 302 | |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 303 | // sqlite3_close() needs all prepared statements to be finalized. |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 304 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 305 | // Release cached statements. |
| 306 | statement_cache_.clear(); |
| 307 | |
| 308 | // With cached statements released, in-use statements will remain. |
| 309 | // Closing the database while statements are in use is an API |
| 310 | // violation, except for forced close (which happens from within a |
| 311 | // statement's error handler). |
| 312 | DCHECK(forced || open_statements_.empty()); |
| 313 | |
| 314 | // Deactivate any outstanding statements so sqlite3_close() works. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 315 | for (StatementRef* statement_ref : open_statements_) |
| 316 | statement_ref->Close(forced); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 317 | open_statements_.clear(); |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 318 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 319 | if (db_) { |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 320 | // Call to InitScopedBlockingCall() cannot go at the beginning of the |
| 321 | // function because Close() must be called from destructor to clean |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 322 | // statement_cache_, it won't cause any disk access and it most probably |
| 323 | // will happen on thread not allowing disk access. |
| 324 | // TODO([email protected]): This should move to the beginning |
| 325 | // of the function. http://crbug.com/136655. |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 326 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 327 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 328 | |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 329 | // Resetting acquires a lock to ensure no dump is happening on the database |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 330 | // at the same time. Unregister takes ownership of provider and it is safe |
| 331 | // since the db is reset. memory_dump_provider_ could be null if db_ was |
| 332 | // poisoned. |
| 333 | if (memory_dump_provider_) { |
| 334 | memory_dump_provider_->ResetDatabase(); |
| 335 | base::trace_event::MemoryDumpManager::GetInstance() |
| 336 | ->UnregisterAndDeleteDumpProviderSoon( |
| 337 | std::move(memory_dump_provider_)); |
| 338 | } |
| 339 | |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 340 | int rc = sqlite3_close(db_); |
| 341 | if (rc != SQLITE_OK) { |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 342 | base::UmaHistogramSparse("Sqlite.CloseFailure", rc); |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 343 | DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage(); |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 344 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 345 | } |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 346 | db_ = nullptr; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 347 | } |
| 348 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 349 | void Database::Close() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 350 | TRACE_EVENT0("sql", "Database::Close"); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 351 | // If the database was already closed by RazeAndClose(), then no |
| 352 | // need to close again. Clear the |poisoned_| bit so that incorrect |
| 353 | // API calls are caught. |
| 354 | if (poisoned_) { |
| 355 | poisoned_ = false; |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | CloseInternal(false); |
| 360 | } |
| 361 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 362 | void Database::Preload() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 363 | TRACE_EVENT0("sql", "Database::Preload"); |
Victor Costan | 3ffd9a37 | 2019-05-22 00:46:54 | [diff] [blame] | 364 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 365 | if (!db_) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 366 | DCHECK(poisoned_) << "Cannot preload null db"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 367 | return; |
| 368 | } |
| 369 | |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 370 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 371 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 372 | |
Victor Costan | bcfeb5b | 2019-10-11 21:38:10 | [diff] [blame] | 373 | // Maximum number of bytes that will be prefetched from the database. |
| 374 | // |
| 375 | // This limit is very aggressive. Here are the trade-offs involved. |
| 376 | // 1) Accessing bytes that weren't preread is very expensive on |
| 377 | // performance-critical databases, so the limit must exceed the expected |
| 378 | // sizes of feature databases. |
| 379 | // 2) On some platforms (Windows 7 and, currently, macOS), base::PreReadFile() |
| 380 | // falls back to a synchronous read, and blocks until the entire file is |
| 381 | // read into memory. So, there's a tangible cost to reading data that would |
| 382 | // get evicted before base::PreReadFile() completes. This cost needs to be |
| 383 | // balanced with the benefit reading the entire database at once, and |
| 384 | // avoiding seeks on spinning disks. |
| 385 | constexpr int kPreReadSize = 128 * 1024 * 1024; // 128 MB |
| 386 | base::PreReadFile(DbPath(), /*is_executable=*/false, kPreReadSize); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 387 | } |
| 388 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 389 | // SQLite keeps unused pages associated with a database in a cache. It asks |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 390 | // the cache for pages by an id, and if the page is present and the database is |
| 391 | // unchanged, it considers the content of the page valid and doesn't read it |
| 392 | // from disk. When memory-mapped I/O is enabled, on read SQLite uses page |
| 393 | // structures created from the memory map data before consulting the cache. On |
| 394 | // write SQLite creates a new in-memory page structure, copies the data from the |
| 395 | // memory map, and later writes it, releasing the updated page back to the |
| 396 | // cache. |
| 397 | // |
| 398 | // This means that in memory-mapped mode, the contents of the cached pages are |
| 399 | // not re-used for reads, but they are re-used for writes if the re-written page |
| 400 | // is still in the cache. The implementation of sqlite3_db_release_memory() as |
| 401 | // of SQLite 3.8.7.4 frees all pages from pcaches associated with the |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 402 | // database, so it should free these pages. |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 403 | // |
| 404 | // Unfortunately, the zero page is also freed. That page is never accessed |
| 405 | // using memory-mapped I/O, and the cached copy can be re-used after verifying |
| 406 | // the file change counter on disk. Also, fresh pages from cache receive some |
| 407 | // pager-level initialization before they can be used. Since the information |
| 408 | // involved will immediately be accessed in various ways, it is unclear if the |
| 409 | // additional overhead is material, or just moving processor cache effects |
| 410 | // around. |
| 411 | // |
| 412 | // TODO(shess): It would be better to release the pages immediately when they |
| 413 | // are no longer needed. This would basically happen after SQLite commits a |
| 414 | // transaction. I had implemented a pcache wrapper to do this, but it involved |
| 415 | // layering violations, and it had to be setup before any other sqlite call, |
| 416 | // which was brittle. Also, for large files it would actually make sense to |
| 417 | // maintain the existing pcache behavior for blocks past the memory-mapped |
| 418 | // segment. I think drh would accept a reasonable implementation of the overall |
| 419 | // concept for upstreaming to SQLite core. |
| 420 | // |
| 421 | // TODO(shess): Another possibility would be to set the cache size small, which |
| 422 | // would keep the zero page around, plus some pre-initialized pages, and SQLite |
| 423 | // can manage things. The downside is that updates larger than the cache would |
| 424 | // spill to the journal. That could be compensated by setting cache_spill to |
| 425 | // false. The downside then is that it allows open-ended use of memory for |
| 426 | // large transactions. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 427 | void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 428 | TRACE_EVENT0("sql", "Database::ReleaseCacheMemoryIfNeeded"); |
shess | 644fc8a | 2016-02-26 18:15:58 | [diff] [blame] | 429 | // The database could have been closed during a transaction as part of error |
| 430 | // recovery. |
| 431 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 432 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
shess | 644fc8a | 2016-02-26 18:15:58 | [diff] [blame] | 433 | return; |
| 434 | } |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 435 | |
| 436 | // If memory-mapping is not enabled, the page cache helps performance. |
| 437 | if (!mmap_enabled_) |
| 438 | return; |
| 439 | |
| 440 | // On caller request, force the change comparison to fail. Done before the |
| 441 | // transaction-nesting test so that the signal can carry to transaction |
| 442 | // commit. |
| 443 | if (implicit_change_performed) |
| 444 | --total_changes_at_last_release_; |
| 445 | |
| 446 | // Cached pages may be re-used within the same transaction. |
| 447 | if (transaction_nesting()) |
| 448 | return; |
| 449 | |
| 450 | // If no changes have been made, skip flushing. This allows the first page of |
| 451 | // the database to remain in cache across multiple reads. |
| 452 | const int total_changes = sqlite3_total_changes(db_); |
| 453 | if (total_changes == total_changes_at_last_release_) |
| 454 | return; |
| 455 | |
| 456 | total_changes_at_last_release_ = total_changes; |
| 457 | sqlite3_db_release_memory(db_); |
| 458 | } |
| 459 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 460 | base::FilePath Database::DbPath() const { |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 461 | if (!is_open()) |
| 462 | return base::FilePath(); |
| 463 | |
| 464 | const char* path = sqlite3_db_filename(db_, "main"); |
| 465 | const base::StringPiece db_path(path); |
| 466 | #if defined(OS_WIN) |
Jan Wilken Dörrie | 9720dce | 2020-07-21 17:14:23 | [diff] [blame] | 467 | return base::FilePath(base::UTF8ToWide(db_path)); |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 468 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 469 | return base::FilePath(db_path); |
| 470 | #else |
| 471 | NOTREACHED(); |
| 472 | return base::FilePath(); |
| 473 | #endif |
| 474 | } |
| 475 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 476 | std::string Database::CollectErrorInfo(int error, Statement* stmt) const { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 477 | TRACE_EVENT0("sql", "Database::CollectErrorInfo"); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 478 | // Buffer for accumulating debugging info about the error. Place |
| 479 | // more-relevant information earlier, in case things overflow the |
| 480 | // fixed-size reporting buffer. |
| 481 | std::string debug_info; |
| 482 | |
| 483 | // The error message from the failed operation. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 484 | base::StringAppendF(&debug_info, "db error: %d/%s\n", GetErrorCode(), |
| 485 | GetErrorMessage()); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 486 | |
| 487 | // TODO(shess): |error| and |GetErrorCode()| should always be the same, but |
| 488 | // reading code does not entirely convince me. Remove if they turn out to be |
| 489 | // the same. |
| 490 | if (error != GetErrorCode()) |
| 491 | base::StringAppendF(&debug_info, "reported error: %d\n", error); |
| 492 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 493 | // System error information. Interpretation of Windows errors is different |
| 494 | // from posix. |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 495 | #if defined(OS_WIN) |
| 496 | base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno()); |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 497 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 498 | base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno()); |
| 499 | #else |
| 500 | NOTREACHED(); // Add appropriate log info. |
| 501 | #endif |
| 502 | |
| 503 | if (stmt) { |
| 504 | base::StringAppendF(&debug_info, "statement: %s\n", |
| 505 | stmt->GetSQLStatement()); |
| 506 | } else { |
| 507 | base::StringAppendF(&debug_info, "statement: NULL\n"); |
| 508 | } |
| 509 | |
| 510 | // SQLITE_ERROR often indicates some sort of mismatch between the statement |
| 511 | // and the schema, possibly due to a failed schema migration. |
| 512 | if (error == SQLITE_ERROR) { |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 513 | static const char kVersionSql[] = |
| 514 | "SELECT value FROM meta WHERE key='version'"; |
| 515 | sqlite3_stmt* sqlite_statement; |
| 516 | // When the number of bytes passed to sqlite3_prepare_v3() includes the null |
| 517 | // terminator, SQLite avoids a buffer copy. |
| 518 | int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql), |
| 519 | SQLITE_PREPARE_NO_VTAB, &sqlite_statement, |
| 520 | /* pzTail= */ nullptr); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 521 | if (rc == SQLITE_OK) { |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 522 | rc = sqlite3_step(sqlite_statement); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 523 | if (rc == SQLITE_ROW) { |
| 524 | base::StringAppendF(&debug_info, "version: %d\n", |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 525 | sqlite3_column_int(sqlite_statement, 0)); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 526 | } else if (rc == SQLITE_DONE) { |
| 527 | debug_info += "version: none\n"; |
| 528 | } else { |
| 529 | base::StringAppendF(&debug_info, "version: error %d\n", rc); |
| 530 | } |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 531 | sqlite3_finalize(sqlite_statement); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 532 | } else { |
| 533 | base::StringAppendF(&debug_info, "version: prepare error %d\n", rc); |
| 534 | } |
| 535 | |
| 536 | debug_info += "schema:\n"; |
| 537 | |
| 538 | // sqlite_master has columns: |
| 539 | // type - "index" or "table". |
| 540 | // name - name of created element. |
| 541 | // tbl_name - name of element, or target table in case of index. |
| 542 | // rootpage - root page of the element in database file. |
| 543 | // sql - SQL to create the element. |
| 544 | // In general, the |sql| column is sufficient to derive the other columns. |
| 545 | // |rootpage| is not interesting for debugging, without the contents of the |
| 546 | // database. The COALESCE is because certain automatic elements will have a |
| 547 | // |name| but no |sql|, |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 548 | static const char kSchemaSql[] = |
| 549 | "SELECT COALESCE(sql,name) FROM sqlite_master"; |
| 550 | rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql), |
| 551 | SQLITE_PREPARE_NO_VTAB, &sqlite_statement, |
| 552 | /* pzTail= */ nullptr); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 553 | if (rc == SQLITE_OK) { |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 554 | while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) { |
| 555 | base::StringAppendF(&debug_info, "%s\n", |
| 556 | sqlite3_column_text(sqlite_statement, 0)); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 557 | } |
| 558 | if (rc != SQLITE_DONE) |
| 559 | base::StringAppendF(&debug_info, "error %d\n", rc); |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 560 | sqlite3_finalize(sqlite_statement); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 561 | } else { |
| 562 | base::StringAppendF(&debug_info, "prepare error %d\n", rc); |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | return debug_info; |
| 567 | } |
| 568 | |
| 569 | // TODO(shess): Since this is only called in an error situation, it might be |
| 570 | // prudent to rewrite in terms of SQLite API calls, and mark the function const. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 571 | std::string Database::CollectCorruptionInfo() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 572 | TRACE_EVENT0("sql", "Database::CollectCorruptionInfo"); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 573 | // If the file cannot be accessed it is unlikely that an integrity check will |
| 574 | // turn up actionable information. |
| 575 | const base::FilePath db_path = DbPath(); |
avi | 0b51920 | 2015-12-21 07:25:19 | [diff] [blame] | 576 | int64_t db_size = -1; |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 577 | if (!base::GetFileSize(db_path, &db_size) || db_size < 0) |
| 578 | return std::string(); |
| 579 | |
| 580 | // Buffer for accumulating debugging info about the error. Place |
| 581 | // more-relevant information earlier, in case things overflow the |
| 582 | // fixed-size reporting buffer. |
| 583 | std::string debug_info; |
| 584 | base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n", |
| 585 | db_size); |
| 586 | |
| 587 | // Only check files up to 8M to keep things from blocking too long. |
avi | 0b51920 | 2015-12-21 07:25:19 | [diff] [blame] | 588 | const int64_t kMaxIntegrityCheckSize = 8192 * 1024; |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 589 | if (db_size > kMaxIntegrityCheckSize) { |
| 590 | debug_info += "integrity_check skipped due to size\n"; |
| 591 | } else { |
| 592 | std::vector<std::string> messages; |
| 593 | |
| 594 | // TODO(shess): FullIntegrityCheck() splits into a vector while this joins |
| 595 | // into a string. Probably should be refactored. |
| 596 | const base::TimeTicks before = base::TimeTicks::Now(); |
| 597 | FullIntegrityCheck(&messages); |
| 598 | base::StringAppendF( |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 599 | &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n", |
| 600 | (base::TimeTicks::Now() - before).InMilliseconds(), messages.size()); |
shess | c8cd2a16 | 2015-10-22 20:30:46 | [diff] [blame] | 601 | |
| 602 | // SQLite returns up to 100 messages by default, trim deeper to |
| 603 | // keep close to the 2000-character size limit for dumping. |
| 604 | const size_t kMaxMessages = 20; |
| 605 | for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) { |
| 606 | base::StringAppendF(&debug_info, "%s\n", messages[i].c_str()); |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | return debug_info; |
| 611 | } |
| 612 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 613 | bool Database::GetMmapAltStatus(int64_t* status) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 614 | TRACE_EVENT0("sql", "Database::GetMmapAltStatus"); |
| 615 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 616 | // The [meta] version uses a missing table as a signal for a fresh database. |
| 617 | // That will not work for the view, which would not exist in either a new or |
| 618 | // an existing database. A new database _should_ be only one page long, so |
| 619 | // just don't bother optimizing this case (start at offset 0). |
| 620 | // TODO(shess): Could the [meta] case also get simpler, then? |
| 621 | if (!DoesViewExist("MmapStatus")) { |
| 622 | *status = 0; |
| 623 | return true; |
| 624 | } |
| 625 | |
| 626 | const char* kMmapStatusSql = "SELECT * FROM MmapStatus"; |
| 627 | Statement s(GetUniqueStatement(kMmapStatusSql)); |
| 628 | if (s.Step()) |
| 629 | *status = s.ColumnInt64(0); |
| 630 | return s.Succeeded(); |
| 631 | } |
| 632 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 633 | bool Database::SetMmapAltStatus(int64_t status) { |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 634 | if (!BeginTransaction()) |
| 635 | return false; |
| 636 | |
| 637 | // View may not exist on first run. |
| 638 | if (!Execute("DROP VIEW IF EXISTS MmapStatus")) { |
| 639 | RollbackTransaction(); |
| 640 | return false; |
| 641 | } |
| 642 | |
| 643 | // Views live in the schema, so they cannot be parameterized. For an integer |
| 644 | // value, this construct should be safe from SQL injection, if the value |
| 645 | // becomes more complicated use "SELECT quote(?)" to generate a safe quoted |
| 646 | // value. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 647 | const std::string create_view_sql = base::StringPrintf( |
| 648 | "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status); |
| 649 | if (!Execute(create_view_sql.c_str())) { |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 650 | RollbackTransaction(); |
| 651 | return false; |
| 652 | } |
| 653 | |
| 654 | return CommitTransaction(); |
| 655 | } |
| 656 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 657 | size_t Database::GetAppropriateMmapSize() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 658 | TRACE_EVENT0("sql", "Database::GetAppropriateMmapSize"); |
| 659 | |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 660 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 661 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 662 | |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 663 | // How much to map if no errors are found. 50MB encompasses the 99th |
| 664 | // percentile of Chrome databases in the wild, so this should be good. |
| 665 | const size_t kMmapEverything = 256 * 1024 * 1024; |
| 666 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 667 | // Progress information is tracked in the [meta] table for databases which use |
| 668 | // sql::MetaTable, otherwise it is tracked in a special view. |
| 669 | // TODO(shess): Move all cases to the view implementation. |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 670 | int64_t mmap_ofs = 0; |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 671 | if (mmap_alt_status_) { |
| 672 | if (!GetMmapAltStatus(&mmap_ofs)) { |
| 673 | RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ); |
| 674 | return 0; |
| 675 | } |
| 676 | } else { |
| 677 | // If [meta] doesn't exist, yet, it's a new database, assume the best. |
| 678 | // sql::MetaTable::Init() will preload kMmapSuccess. |
| 679 | if (!MetaTable::DoesTableExist(this)) { |
| 680 | RecordOneEvent(EVENT_MMAP_META_MISSING); |
| 681 | return kMmapEverything; |
| 682 | } |
| 683 | |
| 684 | if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) { |
| 685 | RecordOneEvent(EVENT_MMAP_META_FAILURE_READ); |
| 686 | return 0; |
| 687 | } |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 688 | } |
| 689 | |
| 690 | // Database read failed in the past, don't memory map. |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 691 | if (mmap_ofs == MetaTable::kMmapFailure) { |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 692 | RecordOneEvent(EVENT_MMAP_FAILED); |
| 693 | return 0; |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 694 | } |
| 695 | |
| 696 | if (mmap_ofs != MetaTable::kMmapSuccess) { |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 697 | // Continue reading from previous offset. |
| 698 | DCHECK_GE(mmap_ofs, 0); |
| 699 | |
| 700 | // TODO(shess): Could this reading code be shared with Preload()? It would |
| 701 | // require locking twice (this code wouldn't be able to access |db_size| so |
| 702 | // the helper would have to return amount read). |
| 703 | |
| 704 | // Read more of the database looking for errors. The VFS interface is used |
| 705 | // to assure that the reads are valid for SQLite. |g_reads_allowed| is used |
| 706 | // to limit checking to 20MB per run of Chromium. |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 707 | sqlite3_file* file = nullptr; |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 708 | sqlite3_int64 db_size = 0; |
| 709 | if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) { |
| 710 | RecordOneEvent(EVENT_MMAP_VFS_FAILURE); |
| 711 | return 0; |
| 712 | } |
| 713 | |
| 714 | // Read the data left, or |g_reads_allowed|, whichever is smaller. |
| 715 | // |g_reads_allowed| limits the total amount of I/O to spend verifying data |
| 716 | // in a single Chromium run. |
| 717 | sqlite3_int64 amount = db_size - mmap_ofs; |
| 718 | if (amount < 0) |
| 719 | amount = 0; |
| 720 | if (amount > 0) { |
Victor Costan | 3653df6 | 2018-02-08 21:38:16 | [diff] [blame] | 721 | static base::NoDestructor<base::Lock> lock; |
| 722 | base::AutoLock auto_lock(*lock); |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 723 | static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024; |
| 724 | if (g_reads_allowed < amount) |
| 725 | amount = g_reads_allowed; |
| 726 | g_reads_allowed -= amount; |
| 727 | } |
| 728 | |
| 729 | // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the |
| 730 | // database was truncated after a previous pass. |
| 731 | if (amount <= 0 && mmap_ofs < db_size) { |
| 732 | DCHECK_EQ(0, amount); |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 733 | } else { |
| 734 | static const int kPageSize = 4096; |
| 735 | char buf[kPageSize]; |
| 736 | while (amount > 0) { |
| 737 | int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs); |
| 738 | if (rc == SQLITE_OK) { |
| 739 | mmap_ofs += sizeof(buf); |
| 740 | amount -= sizeof(buf); |
| 741 | } else if (rc == SQLITE_IOERR_SHORT_READ) { |
| 742 | // Reached EOF for a database with page size < |kPageSize|. |
| 743 | mmap_ofs = db_size; |
| 744 | break; |
| 745 | } else { |
| 746 | // TODO(shess): Consider calling OnSqliteError(). |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 747 | mmap_ofs = MetaTable::kMmapFailure; |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 748 | break; |
| 749 | } |
| 750 | } |
| 751 | |
| 752 | // Log these events after update to distinguish meta update failure. |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 753 | if (mmap_ofs >= db_size) { |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 754 | mmap_ofs = MetaTable::kMmapSuccess; |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 755 | } else { |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 756 | DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure); |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 757 | } |
| 758 | |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 759 | if (mmap_alt_status_) { |
| 760 | if (!SetMmapAltStatus(mmap_ofs)) { |
| 761 | RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE); |
| 762 | return 0; |
| 763 | } |
| 764 | } else { |
| 765 | if (!MetaTable::SetMmapStatus(this, mmap_ofs)) { |
| 766 | RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE); |
| 767 | return 0; |
| 768 | } |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 769 | } |
| 770 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 771 | if (mmap_ofs == MetaTable::kMmapFailure) |
| 772 | RecordOneEvent(EVENT_MMAP_FAILED_NEW); |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 773 | } |
| 774 | } |
| 775 | |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 776 | if (mmap_ofs == MetaTable::kMmapFailure) |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 777 | return 0; |
shess | 9bf2c67 | 2015-12-18 01:18:08 | [diff] [blame] | 778 | if (mmap_ofs == MetaTable::kMmapSuccess) |
| 779 | return kMmapEverything; |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 780 | return mmap_ofs; |
| 781 | } |
| 782 | |
Victor Costan | 52bef81 | 2018-12-05 07:41:49 | [diff] [blame] | 783 | void Database::TrimMemory() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 784 | TRACE_EVENT0("sql", "Database::TrimMemory"); |
| 785 | |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 786 | if (!db_) |
| 787 | return; |
| 788 | |
Victor Costan | 52bef81 | 2018-12-05 07:41:49 | [diff] [blame] | 789 | sqlite3_db_release_memory(db_); |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 790 | |
Victor Costan | 52bef81 | 2018-12-05 07:41:49 | [diff] [blame] | 791 | // It is tempting to use sqlite3_release_memory() here as well. However, the |
| 792 | // API is documented to be a no-op unless SQLite is built with |
| 793 | // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is |
| 794 | // incompatible with per-database page cache pools. Behind the scenes, |
| 795 | // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache |
| 796 | // pool, and sqlite3_release_memory() releases unused pages from this global |
| 797 | // pool. |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 798 | } |
| 799 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 800 | // Create an in-memory database with the existing database's page |
| 801 | // size, then backup that database over the existing database. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 802 | bool Database::Raze() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 803 | TRACE_EVENT0("sql", "Database::Raze"); |
| 804 | |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 805 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 806 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 807 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 808 | if (!db_) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 809 | DCHECK(poisoned_) << "Cannot raze null db"; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 810 | return false; |
| 811 | } |
| 812 | |
| 813 | if (transaction_nesting_ > 0) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 814 | DLOG(DCHECK) << "Cannot raze within a transaction"; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 815 | return false; |
| 816 | } |
| 817 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 818 | sql::Database null_db; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 819 | if (!null_db.OpenInMemory()) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 820 | DLOG(DCHECK) << "Unable to open in-memory database."; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 821 | return false; |
| 822 | } |
| 823 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 824 | const std::string page_size_sql = |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 825 | base::StringPrintf("PRAGMA page_size=%d", options_.page_size); |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 826 | if (!null_db.Execute(page_size_sql.c_str())) |
Victor Costan | 7f6abbbe | 2018-07-29 02:57:27 | [diff] [blame] | 827 | return false; |
[email protected] | 69c5845 | 2012-08-06 19:22:42 | [diff] [blame] | 828 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 829 | #if defined(OS_ANDROID) |
| 830 | // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately, |
| 831 | // in-memory databases do not respect this define. |
| 832 | // TODO(shess): Figure out a way to set this without using platform |
| 833 | // specific code. AFAICT from sqlite3.c, the only way to do it |
| 834 | // would be to create an actual filesystem database, which is |
| 835 | // unfortunate. |
| 836 | if (!null_db.Execute("PRAGMA auto_vacuum = 1")) |
| 837 | return false; |
| 838 | #endif |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 839 | |
| 840 | // The page size doesn't take effect until a database has pages, and |
| 841 | // at this point the null database has none. Changing the schema |
| 842 | // version will create the first page. This will not affect the |
| 843 | // schema version in the resulting database, as SQLite's backup |
| 844 | // implementation propagates the schema version from the original |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 845 | // database to the new version of the database, incremented by one |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 846 | // so that other readers see the schema change and act accordingly. |
| 847 | if (!null_db.Execute("PRAGMA schema_version = 1")) |
| 848 | return false; |
| 849 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 850 | // SQLite tracks the expected number of database pages in the first |
| 851 | // page, and if it does not match the total retrieved from a |
| 852 | // filesystem call, treats the database as corrupt. This situation |
| 853 | // breaks almost all SQLite calls. "PRAGMA writable_schema" can be |
| 854 | // used to hint to SQLite to soldier on in that case, specifically |
| 855 | // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in |
| 856 | // sqlite3.c lockBtree().] |
| 857 | // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA |
| 858 | // page_size" can be used to query such a database. |
| 859 | ScopedWritableSchema writable_schema(db_); |
| 860 | |
shess | 92a6fb2 | 2017-04-23 04:33:30 | [diff] [blame] | 861 | #if defined(OS_WIN) |
| 862 | // On Windows, truncate silently fails when applied to memory-mapped files. |
| 863 | // Disable memory-mapping so that the truncate succeeds. Note that other |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 864 | // Database connections may have memory-mapped the file, so this may not |
| 865 | // entirely prevent the problem. |
shess | 92a6fb2 | 2017-04-23 04:33:30 | [diff] [blame] | 866 | // [Source: <https://sqlite.org/mmap.html> plus experiments.] |
| 867 | ignore_result(Execute("PRAGMA mmap_size = 0")); |
| 868 | #endif |
| 869 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 870 | const char* kMain = "main"; |
| 871 | int rc = BackupDatabase(null_db.db_, db_, kMain); |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 872 | base::UmaHistogramSparse("Sqlite.RazeDatabase", rc); |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 873 | |
| 874 | // The destination database was locked. |
| 875 | if (rc == SQLITE_BUSY) { |
| 876 | return false; |
| 877 | } |
| 878 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 879 | // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not |
| 880 | // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_ |
| 881 | // isn't even big enough for one page. Either way, reach in and |
| 882 | // truncate it before trying again. |
| 883 | // TODO(shess): Maybe it would be worthwhile to just truncate from |
| 884 | // the get-go? |
| 885 | if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) { |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 886 | sqlite3_file* file = nullptr; |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 887 | rc = GetSqlite3File(db_, &file); |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 888 | if (rc != SQLITE_OK) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 889 | DLOG(DCHECK) << "Failure getting file handle."; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 890 | return false; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 891 | } |
| 892 | |
| 893 | rc = file->pMethods->xTruncate(file, 0); |
| 894 | if (rc != SQLITE_OK) { |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 895 | base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc); |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 896 | DLOG(DCHECK) << "Failed to truncate file."; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 897 | return false; |
| 898 | } |
| 899 | |
| 900 | rc = BackupDatabase(null_db.db_, db_, kMain); |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 901 | base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc); |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 902 | |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 903 | DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze()."; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 904 | } |
| 905 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 906 | // Page size of |db_| and |null_db| differ. |
| 907 | if (rc == SQLITE_READONLY) { |
| 908 | // Enter TRUNCATE mode to change page size. |
| 909 | // TODO([email protected]): Need a guarantee here that there is no other |
| 910 | // database connection open. |
| 911 | ignore_result(Execute("PRAGMA journal_mode=TRUNCATE;")); |
| 912 | if (!Execute(page_size_sql.c_str())) { |
| 913 | return false; |
| 914 | } |
| 915 | // Page size isn't changed until the database is vacuumed. |
| 916 | ignore_result(Execute("VACUUM")); |
| 917 | // Re-enter WAL mode. |
| 918 | if (UseWALMode()) { |
| 919 | ignore_result(Execute("PRAGMA journal_mode=WAL;")); |
| 920 | } |
| 921 | |
| 922 | rc = BackupDatabase(null_db.db_, db_, kMain); |
| 923 | base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc); |
| 924 | |
| 925 | DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze()."; |
| 926 | } |
| 927 | |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 928 | // TODO(shess): Figure out which other cases can happen. |
| 929 | DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database."; |
| 930 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 931 | // Checkpoint to propagate transactions to the database file and empty the WAL |
| 932 | // file. |
| 933 | // The database can still contain old data if the Checkpoint fails so fail the |
| 934 | // Raze. |
| 935 | if (!CheckpointDatabase()) { |
| 936 | return false; |
| 937 | } |
| 938 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 939 | // The entire database should have been backed up. |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 940 | return rc == SQLITE_DONE; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 941 | } |
| 942 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 943 | bool Database::RazeAndClose() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 944 | TRACE_EVENT0("sql", "Database::RazeAndClose"); |
| 945 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 946 | if (!db_) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 947 | DCHECK(poisoned_) << "Cannot raze null db"; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 948 | return false; |
| 949 | } |
| 950 | |
| 951 | // Raze() cannot run in a transaction. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 952 | RollbackAllTransactions(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 953 | |
| 954 | bool result = Raze(); |
| 955 | |
| 956 | CloseInternal(true); |
| 957 | |
| 958 | // Mark the database so that future API calls fail appropriately, |
| 959 | // but don't DCHECK (because after calling this function they are |
| 960 | // expected to fail). |
| 961 | poisoned_ = true; |
| 962 | |
| 963 | return result; |
| 964 | } |
| 965 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 966 | void Database::Poison() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 967 | TRACE_EVENT0("sql", "Database::Poison"); |
| 968 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 969 | if (!db_) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 970 | DCHECK(poisoned_) << "Cannot poison null db"; |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 971 | return; |
| 972 | } |
| 973 | |
| 974 | RollbackAllTransactions(); |
| 975 | CloseInternal(true); |
| 976 | |
| 977 | // Mark the database so that future API calls fail appropriately, |
| 978 | // but don't DCHECK (because after calling this function they are |
| 979 | // expected to fail). |
| 980 | poisoned_ = true; |
| 981 | } |
| 982 | |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 983 | // TODO(shess): To the extent possible, figure out the optimal |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 984 | // ordering for these deletes which will prevent other Database connections |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 985 | // from seeing odd behavior. For instance, it may be necessary to |
| 986 | // manually lock the main database file in a SQLite-compatible fashion |
| 987 | // (to prevent other processes from opening it), then delete the |
| 988 | // journal files, then delete the main database file. Another option |
| 989 | // might be to lock the main database file and poison the header with |
| 990 | // junk to prevent other processes from opening it successfully (like |
| 991 | // Gears "SQLite poison 3" trick). |
| 992 | // |
| 993 | // static |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 994 | bool Database::Delete(const base::FilePath& path) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 995 | TRACE_EVENT1("sql", "Database::Delete", "path", path.MaybeAsASCII()); |
| 996 | |
Etienne Bergeron | 436d4221 | 2019-02-26 17:15:12 | [diff] [blame] | 997 | base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, |
| 998 | base::BlockingType::MAY_BLOCK); |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 999 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1000 | base::FilePath journal_path = Database::JournalPath(path); |
| 1001 | base::FilePath wal_path = Database::WriteAheadLogPath(path); |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 1002 | |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1003 | std::string journal_str = AsUTF8ForSQL(journal_path); |
| 1004 | std::string wal_str = AsUTF8ForSQL(wal_path); |
| 1005 | std::string path_str = AsUTF8ForSQL(path); |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 1006 | |
Victor Costan | 3653df6 | 2018-02-08 21:38:16 | [diff] [blame] | 1007 | EnsureSqliteInitialized(); |
shess | 70246762 | 2015-09-16 19:04:55 | [diff] [blame] | 1008 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1009 | sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr); |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1010 | CHECK(vfs); |
| 1011 | CHECK(vfs->xDelete); |
| 1012 | CHECK(vfs->xAccess); |
| 1013 | |
Ken Rockot | 0168742 | 2020-08-17 18:00:59 | [diff] [blame] | 1014 | // We only work with the VFS implementations listed below. If you're trying to |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1015 | // use this code with any other VFS, you're not in a good place. |
| 1016 | CHECK(strncmp(vfs->zName, "unix", 4) == 0 || |
| 1017 | strncmp(vfs->zName, "win32", 5) == 0 || |
Ken Rockot | 0168742 | 2020-08-17 18:00:59 | [diff] [blame] | 1018 | strcmp(vfs->zName, "storage_service") == 0); |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1019 | |
| 1020 | vfs->xDelete(vfs, journal_str.c_str(), 0); |
| 1021 | vfs->xDelete(vfs, wal_str.c_str(), 0); |
| 1022 | vfs->xDelete(vfs, path_str.c_str(), 0); |
| 1023 | |
| 1024 | int journal_exists = 0; |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 1025 | vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists); |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1026 | |
| 1027 | int wal_exists = 0; |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 1028 | vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists); |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1029 | |
| 1030 | int path_exists = 0; |
Victor Costan | ce678e7 | 2018-07-24 10:25:00 | [diff] [blame] | 1031 | vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists); |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 1032 | |
| 1033 | return !journal_exists && !wal_exists && !path_exists; |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 1034 | } |
| 1035 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1036 | bool Database::BeginTransaction() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1037 | TRACE_EVENT0("sql", "Database::BeginTransaction"); |
| 1038 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1039 | if (needs_rollback_) { |
[email protected] | 88563f6 | 2011-03-13 22:13:33 | [diff] [blame] | 1040 | DCHECK_GT(transaction_nesting_, 0); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1041 | |
| 1042 | // When we're going to rollback, fail on this begin and don't actually |
| 1043 | // mark us as entering the nested transaction. |
| 1044 | return false; |
| 1045 | } |
| 1046 | |
| 1047 | bool success = true; |
| 1048 | if (!transaction_nesting_) { |
| 1049 | needs_rollback_ = false; |
| 1050 | |
| 1051 | Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION")); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1052 | if (!begin.Run()) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1053 | return false; |
| 1054 | } |
| 1055 | transaction_nesting_++; |
| 1056 | return success; |
| 1057 | } |
| 1058 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1059 | void Database::RollbackTransaction() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1060 | TRACE_EVENT0("sql", "Database::RollbackTransaction"); |
| 1061 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1062 | if (!transaction_nesting_) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 1063 | DCHECK(poisoned_) << "Rolling back a nonexistent transaction"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1064 | return; |
| 1065 | } |
| 1066 | |
| 1067 | transaction_nesting_--; |
| 1068 | |
| 1069 | if (transaction_nesting_ > 0) { |
| 1070 | // Mark the outermost transaction as needing rollback. |
| 1071 | needs_rollback_ = true; |
| 1072 | return; |
| 1073 | } |
| 1074 | |
| 1075 | DoRollback(); |
| 1076 | } |
| 1077 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1078 | bool Database::CommitTransaction() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1079 | TRACE_EVENT0("sql", "Database::CommitTransaction"); |
| 1080 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1081 | if (!transaction_nesting_) { |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 1082 | DCHECK(poisoned_) << "Committing a nonexistent transaction"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1083 | return false; |
| 1084 | } |
| 1085 | transaction_nesting_--; |
| 1086 | |
| 1087 | if (transaction_nesting_ > 0) { |
| 1088 | // Mark any nested transactions as failing after we've already got one. |
| 1089 | return !needs_rollback_; |
| 1090 | } |
| 1091 | |
| 1092 | if (needs_rollback_) { |
| 1093 | DoRollback(); |
| 1094 | return false; |
| 1095 | } |
| 1096 | |
| 1097 | Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT")); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1098 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1099 | bool succeeded = commit.Run(); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1100 | |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 1101 | // Release dirty cache pages after the transaction closes. |
| 1102 | ReleaseCacheMemoryIfNeeded(false); |
| 1103 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1104 | return succeeded; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1105 | } |
| 1106 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1107 | void Database::RollbackAllTransactions() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1108 | TRACE_EVENT0("sql", "Database::RollbackAllTransactions"); |
| 1109 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 1110 | if (transaction_nesting_ > 0) { |
| 1111 | transaction_nesting_ = 0; |
| 1112 | DoRollback(); |
| 1113 | } |
| 1114 | } |
| 1115 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1116 | bool Database::AttachDatabase(const base::FilePath& other_db_path, |
| 1117 | const char* attachment_point, |
| 1118 | InternalApiToken) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1119 | TRACE_EVENT0("sql", "Database::AttachDatabase"); |
| 1120 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 1121 | DCHECK(ValidAttachmentPoint(attachment_point)); |
| 1122 | |
| 1123 | Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?")); |
| 1124 | #if OS_WIN |
Jan Wilken Dörrie | 9720dce | 2020-07-21 17:14:23 | [diff] [blame] | 1125 | s.BindString16(0, base::AsStringPiece16(other_db_path.value())); |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 1126 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
Fabrice de Gans-Riberi | bd1301f | 2018-05-18 21:00:09 | [diff] [blame] | 1127 | s.BindString(0, other_db_path.value()); |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 1128 | #else |
| 1129 | #error Unsupported platform |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 1130 | #endif |
| 1131 | s.BindString(1, attachment_point); |
| 1132 | return s.Run(); |
| 1133 | } |
| 1134 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1135 | bool Database::DetachDatabase(const char* attachment_point, InternalApiToken) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1136 | TRACE_EVENT0("sql", "Database::DetachDatabase"); |
| 1137 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 1138 | DCHECK(ValidAttachmentPoint(attachment_point)); |
| 1139 | |
| 1140 | Statement s(GetUniqueStatement("DETACH DATABASE ?")); |
| 1141 | s.BindString(0, attachment_point); |
| 1142 | return s.Run(); |
| 1143 | } |
| 1144 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1145 | // TODO(shess): Consider changing this to execute exactly one statement. If a |
| 1146 | // caller wishes to execute multiple statements, that should be explicit, and |
| 1147 | // perhaps tucked into an explicit transaction with rollback in case of error. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1148 | int Database::ExecuteAndReturnErrorCode(const char* sql) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1149 | TRACE_EVENT0("sql", "Database::ExecuteAndReturnErrorCode"); |
| 1150 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1151 | DCHECK(sql); |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 1152 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1153 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1154 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1155 | return SQLITE_ERROR; |
| 1156 | } |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1157 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1158 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 1159 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1160 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1161 | int rc = SQLITE_OK; |
| 1162 | while ((rc == SQLITE_OK) && *sql) { |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1163 | sqlite3_stmt* sqlite_statement; |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1164 | const char* leftover_sql; |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1165 | rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0, |
| 1166 | &sqlite_statement, &leftover_sql); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1167 | // Stop if an error is encountered. |
| 1168 | if (rc != SQLITE_OK) |
| 1169 | break; |
| 1170 | |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1171 | sql = leftover_sql; |
| 1172 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1173 | // This happens if |sql| originally only contained comments or whitespace. |
| 1174 | // TODO(shess): Audit to see if this can become a DCHECK(). Having |
| 1175 | // extraneous comments and whitespace in the SQL statements increases |
| 1176 | // runtime cost and can easily be shifted out to the C++ layer. |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1177 | if (!sqlite_statement) |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1178 | continue; |
| 1179 | |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1180 | while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) { |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1181 | // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1182 | // is the only legitimate case for this. Previously recorded histograms |
| 1183 | // show significant use of this code path. |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1184 | } |
| 1185 | |
| 1186 | // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step() |
| 1187 | // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code. |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1188 | rc = sqlite3_finalize(sqlite_statement); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1189 | |
| 1190 | // sqlite3_exec() does this, presumably to avoid spinning the parser for |
| 1191 | // trailing whitespace. |
| 1192 | // TODO(shess): Audit to see if this can become a DCHECK. |
brettw | b341306 | 2015-06-24 00:39:02 | [diff] [blame] | 1193 | while (base::IsAsciiWhitespace(*sql)) { |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1194 | sql++; |
| 1195 | } |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1196 | } |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 1197 | |
| 1198 | // Most calls to Execute() modify the database. The main exceptions would be |
| 1199 | // calls such as CREATE TABLE IF NOT EXISTS which could modify the database |
| 1200 | // but sometimes don't. |
| 1201 | ReleaseCacheMemoryIfNeeded(true); |
| 1202 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1203 | return rc; |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1204 | } |
| 1205 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1206 | bool Database::Execute(const char* sql) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1207 | TRACE_EVENT1("sql", "Database::Execute", "query", TRACE_STR_COPY(sql)); |
| 1208 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1209 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1210 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1211 | return false; |
| 1212 | } |
| 1213 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1214 | int error = ExecuteAndReturnErrorCode(sql); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 1215 | if (error != SQLITE_OK) |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1216 | error = OnSqliteError(error, nullptr, sql); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 1217 | |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 1218 | // This needs to be a FATAL log because the error case of arriving here is |
| 1219 | // that there's a malformed SQL statement. This can arise in development if |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 1220 | // a change alters the schema but not all queries adjust. This can happen |
| 1221 | // in production if the schema is corrupted. |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 1222 | DCHECK_NE(error, SQLITE_ERROR) |
| 1223 | << "SQL Error in " << sql << ", " << GetErrorMessage(); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1224 | return error == SQLITE_OK; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1225 | } |
| 1226 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1227 | bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1228 | TRACE_EVENT0("sql", "Database::ExecuteWithTimeout"); |
| 1229 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1230 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1231 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1232 | return false; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1233 | } |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1234 | |
| 1235 | ScopedBusyTimeout busy_timeout(db_); |
| 1236 | busy_timeout.SetTimeout(timeout); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1237 | return Execute(sql); |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1238 | } |
| 1239 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1240 | scoped_refptr<Database::StatementRef> Database::GetCachedStatement( |
Victor Costan | 12daa3ac9 | 2018-07-19 01:05:58 | [diff] [blame] | 1241 | StatementID id, |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1242 | const char* sql) { |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 1243 | auto it = statement_cache_.find(id); |
| 1244 | if (it != statement_cache_.end()) { |
Victor Costan | 613b430 | 2018-11-20 05:32:43 | [diff] [blame] | 1245 | // Statement is in the cache. It should still be valid. We're the only |
| 1246 | // entity invalidating cached statements, and we remove them from the cache |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 1247 | // when we do that. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 1248 | DCHECK(it->second->is_valid()); |
Victor Costan | 613b430 | 2018-11-20 05:32:43 | [diff] [blame] | 1249 | DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql)) |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 1250 | << "GetCachedStatement used with same ID but different SQL"; |
| 1251 | |
| 1252 | // Reset the statement so it can be reused. |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 1253 | sqlite3_reset(it->second->stmt()); |
| 1254 | return it->second; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1255 | } |
| 1256 | |
| 1257 | scoped_refptr<StatementRef> statement = GetUniqueStatement(sql); |
Victor Costan | 613b430 | 2018-11-20 05:32:43 | [diff] [blame] | 1258 | if (statement->is_valid()) { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1259 | statement_cache_[id] = statement; // Only cache valid statements. |
Victor Costan | 613b430 | 2018-11-20 05:32:43 | [diff] [blame] | 1260 | DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql)) |
| 1261 | << "Input SQL does not match SQLite's normalized version"; |
| 1262 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1263 | return statement; |
| 1264 | } |
| 1265 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1266 | scoped_refptr<Database::StatementRef> Database::GetUniqueStatement( |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1267 | const char* sql) { |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 1268 | return GetStatementImpl(this, sql); |
| 1269 | } |
| 1270 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1271 | scoped_refptr<Database::StatementRef> Database::GetStatementImpl( |
| 1272 | sql::Database* tracking_db, |
| 1273 | const char* sql) const { |
shess | 9e77283d | 2016-06-13 23:53:20 | [diff] [blame] | 1274 | DCHECK(sql); |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 1275 | DCHECK(!tracking_db || tracking_db == this); |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 1276 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1277 | // Return inactive statement. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1278 | if (!db_) |
Victor Costan | 3b02cdf | 2018-07-18 00:39:56 | [diff] [blame] | 1279 | return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1280 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1281 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 1282 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1283 | |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1284 | // TODO(pwnall): Cached statements (but not unique statements) should be |
| 1285 | // prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT. |
| 1286 | sqlite3_stmt* sqlite_statement; |
| 1287 | int rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0, |
| 1288 | &sqlite_statement, /* pzTail= */ nullptr); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 1289 | if (rc != SQLITE_OK) { |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1290 | // This is evidence of a syntax error in the incoming SQL. |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 1291 | DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage(); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 1292 | |
| 1293 | // It could also be database corruption. |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1294 | OnSqliteError(rc, nullptr, sql); |
Victor Costan | 3b02cdf | 2018-07-18 00:39:56 | [diff] [blame] | 1295 | return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1296 | } |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1297 | return base::MakeRefCounted<StatementRef>(tracking_db, sqlite_statement, |
| 1298 | true); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1299 | } |
| 1300 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1301 | scoped_refptr<Database::StatementRef> Database::GetUntrackedStatement( |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 1302 | const char* sql) const { |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1303 | return GetStatementImpl(nullptr, sql); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 1304 | } |
| 1305 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1306 | std::string Database::GetSchema() const { |
[email protected] | 92cd00a | 2013-08-16 11:09:58 | [diff] [blame] | 1307 | // The ORDER BY should not be necessary, but relying on organic |
| 1308 | // order for something like this is questionable. |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 1309 | static const char kSql[] = |
[email protected] | 92cd00a | 2013-08-16 11:09:58 | [diff] [blame] | 1310 | "SELECT type, name, tbl_name, sql " |
| 1311 | "FROM sqlite_master ORDER BY 1, 2, 3, 4"; |
| 1312 | Statement statement(GetUntrackedStatement(kSql)); |
| 1313 | |
| 1314 | std::string schema; |
| 1315 | while (statement.Step()) { |
| 1316 | schema += statement.ColumnString(0); |
| 1317 | schema += '|'; |
| 1318 | schema += statement.ColumnString(1); |
| 1319 | schema += '|'; |
| 1320 | schema += statement.ColumnString(2); |
| 1321 | schema += '|'; |
| 1322 | schema += statement.ColumnString(3); |
| 1323 | schema += '\n'; |
| 1324 | } |
| 1325 | |
| 1326 | return schema; |
| 1327 | } |
| 1328 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1329 | bool Database::IsSQLValid(const char* sql) { |
Etienne Pierre-Doray | a71d7af | 2019-02-07 02:07:54 | [diff] [blame] | 1330 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 1331 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1332 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1333 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1334 | return false; |
| 1335 | } |
| 1336 | |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1337 | sqlite3_stmt* sqlite_statement = nullptr; |
| 1338 | if (sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0, |
| 1339 | &sqlite_statement, |
| 1340 | /* pzTail= */ nullptr) != SQLITE_OK) { |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1341 | return false; |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1342 | } |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1343 | |
Victor Costan | f37f7ae | 2019-04-11 19:26:12 | [diff] [blame] | 1344 | sqlite3_finalize(sqlite_statement); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1345 | return true; |
| 1346 | } |
| 1347 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1348 | bool Database::DoesIndexExist(const char* index_name) const { |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 1349 | return DoesSchemaItemExist(index_name, "index"); |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 1350 | } |
| 1351 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1352 | bool Database::DoesTableExist(const char* table_name) const { |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 1353 | return DoesSchemaItemExist(table_name, "table"); |
| 1354 | } |
| 1355 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1356 | bool Database::DoesViewExist(const char* view_name) const { |
shess | a62504d | 2016-11-07 19:26:12 | [diff] [blame] | 1357 | return DoesSchemaItemExist(view_name, "view"); |
| 1358 | } |
| 1359 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1360 | bool Database::DoesSchemaItemExist(const char* name, const char* type) const { |
Victor Costan | f85512e5 | 2019-04-10 20:51:36 | [diff] [blame] | 1361 | static const char kSql[] = |
| 1362 | "SELECT 1 FROM sqlite_master WHERE type=? AND name=?"; |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 1363 | Statement statement(GetUntrackedStatement(kSql)); |
shess | 92a2ab1 | 2015-04-09 01:59:47 | [diff] [blame] | 1364 | |
Victor Costan | f85512e5 | 2019-04-10 20:51:36 | [diff] [blame] | 1365 | if (!statement.is_valid()) { |
| 1366 | // The database is corrupt. |
shess | 92a2ab1 | 2015-04-09 01:59:47 | [diff] [blame] | 1367 | return false; |
Victor Costan | f85512e5 | 2019-04-10 20:51:36 | [diff] [blame] | 1368 | } |
shess | 92a2ab1 | 2015-04-09 01:59:47 | [diff] [blame] | 1369 | |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 1370 | statement.BindString(0, type); |
| 1371 | statement.BindString(1, name); |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 1372 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1373 | return statement.Step(); // Table exists if any row was returned. |
| 1374 | } |
| 1375 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1376 | bool Database::DoesColumnExist(const char* table_name, |
| 1377 | const char* column_name) const { |
Victor Costan | 1ff47e9 | 2018-12-07 11:10:43 | [diff] [blame] | 1378 | // sqlite3_table_column_metadata uses out-params to return column definition |
| 1379 | // details, such as the column type and whether it allows NULL values. These |
| 1380 | // aren't needed to compute the current method's result, so we pass in nullptr |
| 1381 | // for all the out-params. |
| 1382 | int error = sqlite3_table_column_metadata( |
| 1383 | db_, "main", table_name, column_name, /* pzDataType= */ nullptr, |
| 1384 | /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr, |
| 1385 | /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr); |
| 1386 | return error == SQLITE_OK; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1387 | } |
| 1388 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1389 | int64_t Database::GetLastInsertRowId() const { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1390 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1391 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1392 | return 0; |
| 1393 | } |
| 1394 | return sqlite3_last_insert_rowid(db_); |
| 1395 | } |
| 1396 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1397 | int Database::GetLastChangeCount() const { |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 1398 | if (!db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1399 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 1400 | return 0; |
| 1401 | } |
| 1402 | return sqlite3_changes(db_); |
| 1403 | } |
| 1404 | |
Victor Costan | d6e7325 | 2020-10-14 21:11:25 | [diff] [blame] | 1405 | int Database::GetMemoryUsage() { |
| 1406 | if (!db_) { |
| 1407 | DCHECK(poisoned_) << "Illegal use of Database without a db"; |
| 1408 | return 0; |
| 1409 | } |
| 1410 | |
| 1411 | int highwater_should_always_be_zero; |
| 1412 | int cache_memory = 0, schema_memory = 0, statement_memory = 0; |
| 1413 | |
| 1414 | int error = |
| 1415 | sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_memory, |
| 1416 | &highwater_should_always_be_zero, /*resetFlg=*/false); |
| 1417 | DCHECK_EQ(error, SQLITE_OK); |
| 1418 | |
| 1419 | error = |
| 1420 | sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_memory, |
| 1421 | &highwater_should_always_be_zero, /*resetFlg=*/false); |
| 1422 | DCHECK_EQ(error, SQLITE_OK); |
| 1423 | |
| 1424 | error = |
| 1425 | sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_memory, |
| 1426 | &highwater_should_always_be_zero, /*resetFlg=*/false); |
| 1427 | DCHECK_EQ(error, SQLITE_OK); |
| 1428 | |
| 1429 | return cache_memory + schema_memory + statement_memory; |
| 1430 | } |
| 1431 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1432 | int Database::GetErrorCode() const { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1433 | if (!db_) |
| 1434 | return SQLITE_ERROR; |
| 1435 | return sqlite3_errcode(db_); |
| 1436 | } |
| 1437 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1438 | int Database::GetLastErrno() const { |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 1439 | if (!db_) |
| 1440 | return -1; |
| 1441 | |
| 1442 | int err = 0; |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1443 | if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err)) |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 1444 | return -2; |
| 1445 | |
| 1446 | return err; |
| 1447 | } |
| 1448 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1449 | const char* Database::GetErrorMessage() const { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1450 | if (!db_) |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1451 | return "sql::Database is not opened."; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1452 | return sqlite3_errmsg(db_); |
| 1453 | } |
| 1454 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1455 | bool Database::OpenInternal(const std::string& file_name, |
| 1456 | Database::Retry retry_flag) { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1457 | TRACE_EVENT1("sql", "Database::OpenInternal", "path", file_name); |
| 1458 | |
[email protected] | 9cfbc92 | 2009-11-17 20:13:17 | [diff] [blame] | 1459 | if (db_) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1460 | DLOG(DCHECK) << "sql::Database is already open."; |
[email protected] | 9cfbc92 | 2009-11-17 20:13:17 | [diff] [blame] | 1461 | return false; |
| 1462 | } |
| 1463 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1464 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
Etienne Bergeron | e7681c7 | 2020-01-17 00:51:20 | [diff] [blame] | 1465 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1466 | |
Victor Costan | 3653df6 | 2018-02-08 21:38:16 | [diff] [blame] | 1467 | EnsureSqliteInitialized(); |
[email protected] | a7ec129 | 2013-07-22 22:02:18 | [diff] [blame] | 1468 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1469 | // Setup the stats histograms immediately rather than allocating lazily. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1470 | // Databases which won't exercise all of these probably shouldn't exist. |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1471 | if (!histogram_tag_.empty()) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1472 | stats_histogram_ = base::LinearHistogram::FactoryGet( |
Victor Costan | b0e7fc0 | 2019-03-01 03:36:27 | [diff] [blame] | 1473 | "Sqlite.Stats2." + histogram_tag_, 1, EVENT_MAX_VALUE, |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1474 | EVENT_MAX_VALUE + 1, base::HistogramBase::kUmaTargetedHistogramFlag); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1475 | } |
| 1476 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1477 | // If |poisoned_| is set, it means an error handler called |
| 1478 | // RazeAndClose(). Until regular Close() is called, the caller |
| 1479 | // should be treating the database as open, but is_open() currently |
| 1480 | // only considers the sqlite3 handle's state. |
| 1481 | // TODO(shess): Revise is_open() to consider poisoned_, and review |
| 1482 | // to see if any non-testing code even depends on it. |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1483 | DCHECK(!poisoned_) << "sql::Database is already open."; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 1484 | poisoned_ = false; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1485 | |
shess | 5f2c344 | 2017-01-24 02:15:10 | [diff] [blame] | 1486 | // Custom memory-mapping VFS which reads pages using regular I/O on first hit. |
| 1487 | sqlite3_vfs* vfs = VFSWrapper(); |
| 1488 | const char* vfs_name = (vfs ? vfs->zName : nullptr); |
Victor Costan | c6d3a86 | 2018-11-20 18:41:23 | [diff] [blame] | 1489 | |
| 1490 | // The flags are documented at https://www.sqlite.org/c3ref/open.html. |
| 1491 | // |
| 1492 | // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many |
| 1493 | // disparate features with their own databases, and having separate page |
| 1494 | // caches makes it easier to reason about each feature's performance in |
| 1495 | // isolation. |
| 1496 | int err = sqlite3_open_v2( |
| 1497 | file_name.c_str(), &db_, |
| 1498 | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_PRIVATECACHE, |
| 1499 | vfs_name); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1500 | if (err != SQLITE_OK) { |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 1501 | // Extended error codes cannot be enabled until a handle is |
| 1502 | // available, fetch manually. |
| 1503 | err = sqlite3_extended_errcode(db_); |
| 1504 | |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 1505 | // Histogram failures specific to initial open for debugging |
| 1506 | // purposes. |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 1507 | base::UmaHistogramSparse("Sqlite.OpenFailure", err); |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 1508 | |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1509 | OnSqliteError(err, nullptr, "-- sqlite3_open()"); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1510 | bool was_poisoned = poisoned_; |
[email protected] | 6402104 | 2012-02-10 20:02:29 | [diff] [blame] | 1511 | Close(); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1512 | |
| 1513 | if (was_poisoned && retry_flag == RETRY_ON_POISON) |
| 1514 | return OpenInternal(file_name, NO_RETRY); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1515 | return false; |
| 1516 | } |
| 1517 | |
Victor Costan | b223079 | 2020-10-09 08:35:14 | [diff] [blame] | 1518 | // If indicated, enable shared mode ("NORMAL") on the database, so it can be |
| 1519 | // opened by multiple processes. This needs to happen before WAL mode is |
| 1520 | // enabled. |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1521 | // |
Victor Costan | b223079 | 2020-10-09 08:35:14 | [diff] [blame] | 1522 | // TODO(crbug.com/1120969): Remove support for non-exclusive mode. |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 1523 | if (!options_.exclusive_locking) { |
Victor Costan | b223079 | 2020-10-09 08:35:14 | [diff] [blame] | 1524 | err = ExecuteAndReturnErrorCode("PRAGMA locking_mode=NORMAL"); |
| 1525 | if (err != SQLITE_OK) |
| 1526 | return false; |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1527 | } |
| 1528 | |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 1529 | // Enable extended result codes to provide more color on I/O errors. |
| 1530 | // Not having extended result codes is not a fatal problem, as |
| 1531 | // Chromium code does not attempt to handle I/O errors anyhow. The |
| 1532 | // current implementation always returns SQLITE_OK, the DCHECK is to |
| 1533 | // quickly notify someone if SQLite changes. |
| 1534 | err = sqlite3_extended_result_codes(db_, 1); |
| 1535 | DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes"; |
| 1536 | |
shess | bccd300e | 2016-08-20 00:06:56 | [diff] [blame] | 1537 | // sqlite3_open() does not actually read the database file (unless a hot |
| 1538 | // journal is found). Successfully executing this pragma on an existing |
| 1539 | // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to |
| 1540 | // get the error code before error callback (potentially) overwrites. |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 1541 | // TODO(shess): For now, just probing to see what the lay of the |
| 1542 | // land is. If it's mostly SQLITE_NOTADB, then the database should |
| 1543 | // be razed. |
| 1544 | err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum"); |
shess | bccd300e | 2016-08-20 00:06:56 | [diff] [blame] | 1545 | if (err != SQLITE_OK) { |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 1546 | base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err); |
shess | bccd300e | 2016-08-20 00:06:56 | [diff] [blame] | 1547 | OnSqliteError(err, nullptr, "PRAGMA auto_vacuum"); |
| 1548 | |
| 1549 | // Retry or bail out if the error handler poisoned the handle. |
Victor Costan | f1e9443b | 2018-12-05 04:35:53 | [diff] [blame] | 1550 | // TODO(shess): Move this handling to one place (see also sqlite3_open). |
| 1551 | // Possibly a wrapper function? |
shess | bccd300e | 2016-08-20 00:06:56 | [diff] [blame] | 1552 | if (poisoned_) { |
| 1553 | Close(); |
| 1554 | if (retry_flag == RETRY_ON_POISON) |
| 1555 | return OpenInternal(file_name, NO_RETRY); |
| 1556 | return false; |
| 1557 | } |
| 1558 | } |
[email protected] | 658f833 | 2010-09-18 04:40:43 | [diff] [blame] | 1559 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1560 | const base::TimeDelta kBusyTimeout = |
| 1561 | base::TimeDelta::FromSeconds(kBusyTimeoutSeconds); |
| 1562 | |
| 1563 | // Needs to happen before entering WAL mode. Will only work if this the first |
| 1564 | // time the database is being opened in WAL mode. |
| 1565 | const std::string page_size_sql = |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 1566 | base::StringPrintf("PRAGMA page_size=%d", options_.page_size); |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1567 | ignore_result(ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout)); |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1568 | |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 1569 | // http://www.sqlite.org/pragma.html#pragma_journal_mode |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1570 | // WAL - Use a write-ahead log instead of a journal file. |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 1571 | // DELETE (default) - delete -journal file to commit. |
| 1572 | // TRUNCATE - truncate -journal file to commit. |
| 1573 | // PERSIST - zero out header of -journal file to commit. |
shess | 2c21ecf | 2015-06-02 01:31:09 | [diff] [blame] | 1574 | // TRUNCATE should be faster than DELETE because it won't need directory |
| 1575 | // changes for each transaction. PERSIST may break the spirit of using |
| 1576 | // secure_delete. |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1577 | // |
| 1578 | // Needs to be performed after setting exclusive locking mode. Otherwise can |
| 1579 | // fail if underlying VFS doesn't support shared memory. |
| 1580 | if (UseWALMode()) { |
| 1581 | // Set the synchronous flag to NORMAL. This means that writers don't flush |
| 1582 | // the WAL file after every write. The WAL file is only flushed on a |
| 1583 | // checkpoint. In this case, transcations might lose durability on a power |
| 1584 | // loss (but still durable after an application crash). |
| 1585 | // TODO([email protected]): Evaluate if this loss of durability is a |
| 1586 | // concern. |
| 1587 | ignore_result(Execute("PRAGMA synchronous=NORMAL")); |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 1588 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1589 | // Opening the db in WAL mode can fail (eg if the underlying VFS doesn't |
| 1590 | // support shared memory and we are not in exclusive locking mode). |
| 1591 | // |
| 1592 | // TODO([email protected]): We should probably catch a failure here. |
| 1593 | ignore_result(Execute("PRAGMA journal_mode=WAL")); |
| 1594 | } else { |
| 1595 | ignore_result(Execute("PRAGMA journal_mode=TRUNCATE")); |
| 1596 | } |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1597 | |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 1598 | if (options_.cache_size != 0) { |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1599 | const std::string cache_size_sql = |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 1600 | base::StringPrintf("PRAGMA cache_size=%d", options_.cache_size); |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1601 | ignore_result(ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout)); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1602 | } |
| 1603 | |
Victor Costan | f1e9443b | 2018-12-05 04:35:53 | [diff] [blame] | 1604 | static_assert(SQLITE_SECURE_DELETE == 1, |
| 1605 | "Chrome assumes secure_delete is on by default."); |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 1606 | |
shess | 5dac334f | 2015-11-05 20:47:42 | [diff] [blame] | 1607 | // Set a reasonable chunk size for larger files. This reduces churn from |
| 1608 | // remapping memory on size changes. It also reduces filesystem |
| 1609 | // fragmentation. |
| 1610 | // TODO(shess): It may make sense to have this be hinted by the client. |
| 1611 | // Database sizes seem to be bimodal, some clients have consistently small |
| 1612 | // databases (<20k) while other clients have a broad distribution of sizes |
| 1613 | // (hundreds of kilobytes to many megabytes). |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1614 | sqlite3_file* file = nullptr; |
shess | 5dac334f | 2015-11-05 20:47:42 | [diff] [blame] | 1615 | sqlite3_int64 db_size = 0; |
| 1616 | int rc = GetSqlite3FileAndSize(db_, &file, &db_size); |
| 1617 | if (rc == SQLITE_OK && db_size > 16 * 1024) { |
| 1618 | int chunk_size = 4 * 1024; |
| 1619 | if (db_size > 128 * 1024) |
| 1620 | chunk_size = 32 * 1024; |
Victor Costan | bd62311 | 2018-07-18 04:17:27 | [diff] [blame] | 1621 | sqlite3_file_control(db_, nullptr, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size); |
shess | 5dac334f | 2015-11-05 20:47:42 | [diff] [blame] | 1622 | } |
| 1623 | |
shess | 2f3a814b | 2015-11-05 18:11:10 | [diff] [blame] | 1624 | // Enable memory-mapped access. The explicit-disable case is because SQLite |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 1625 | // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a |
| 1626 | // safe range to memory-map based on past regular I/O. This value will be |
| 1627 | // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and |
| 1628 | // 64-bit platforms. |
| 1629 | size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize(); |
| 1630 | std::string mmap_sql = |
Victor Costan | 4c2f3e92 | 2018-08-21 04:47:59 | [diff] [blame] | 1631 | base::StringPrintf("PRAGMA mmap_size=%" PRIuS, mmap_size); |
shess | d90aeea8 | 2015-11-13 02:24:31 | [diff] [blame] | 1632 | ignore_result(Execute(mmap_sql.c_str())); |
shess | 2f3a814b | 2015-11-05 18:11:10 | [diff] [blame] | 1633 | |
| 1634 | // Determine if memory-mapping has actually been enabled. The Execute() above |
| 1635 | // can succeed without changing the amount mapped. |
| 1636 | mmap_enabled_ = false; |
| 1637 | { |
| 1638 | Statement s(GetUniqueStatement("PRAGMA mmap_size")); |
| 1639 | if (s.Step() && s.ColumnInt64(0) > 0) |
| 1640 | mmap_enabled_ = true; |
| 1641 | } |
| 1642 | |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 1643 | DCHECK(!memory_dump_provider_); |
| 1644 | memory_dump_provider_.reset( |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1645 | new DatabaseMemoryDumpProvider(db_, histogram_tag_)); |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 1646 | base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1647 | memory_dump_provider_.get(), "sql::Database", nullptr); |
ssid | 3be5b1ec | 2016-01-13 14:21:57 | [diff] [blame] | 1648 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1649 | return true; |
| 1650 | } |
| 1651 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1652 | void Database::DoRollback() { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1653 | TRACE_EVENT0("sql", "Database::DoRollback"); |
| 1654 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1655 | Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK")); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1656 | |
Victor Costan | 5e785e3 | 2019-02-26 20:39:31 | [diff] [blame] | 1657 | rollback.Run(); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1658 | |
shess | 7dbd4dee | 2015-10-06 17:39:16 | [diff] [blame] | 1659 | // The cache may have been accumulating dirty pages for commit. Note that in |
| 1660 | // some cases sql::Transaction can fire rollback after a database is closed. |
| 1661 | if (is_open()) |
| 1662 | ReleaseCacheMemoryIfNeeded(false); |
| 1663 | |
[email protected] | 44ad7d90 | 2012-03-23 00:09:05 | [diff] [blame] | 1664 | needs_rollback_ = false; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1665 | } |
| 1666 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1667 | void Database::StatementRefCreated(StatementRef* ref) { |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 1668 | DCHECK(!open_statements_.count(ref)) |
| 1669 | << __func__ << " already called with this statement"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1670 | open_statements_.insert(ref); |
| 1671 | } |
| 1672 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1673 | void Database::StatementRefDeleted(StatementRef* ref) { |
Victor Costan | c7e7f2e | 2018-07-18 20:07:55 | [diff] [blame] | 1674 | DCHECK(open_statements_.count(ref)) |
| 1675 | << __func__ << " called with non-existing statement"; |
| 1676 | open_statements_.erase(ref); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1677 | } |
| 1678 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1679 | void Database::set_histogram_tag(const std::string& tag) { |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1680 | DCHECK(!is_open()); |
Victor Costan | 87cf8c7 | 2018-07-19 19:36:04 | [diff] [blame] | 1681 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1682 | histogram_tag_ = tag; |
| 1683 | } |
| 1684 | |
Will Harris | b869359 | 2018-08-28 22:58:44 | [diff] [blame] | 1685 | void Database::AddTaggedHistogram(const std::string& name, int sample) const { |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 1686 | if (histogram_tag_.empty()) |
| 1687 | return; |
| 1688 | |
| 1689 | // TODO(shess): The histogram macros create a bit of static storage |
| 1690 | // for caching the histogram object. This code shouldn't execute |
| 1691 | // often enough for such caching to be crucial. If it becomes an |
| 1692 | // issue, the object could be cached alongside histogram_prefix_. |
| 1693 | std::string full_histogram_name = name + "." + histogram_tag_; |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1694 | base::HistogramBase* histogram = base::SparseHistogram::FactoryGet( |
| 1695 | full_histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag); |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 1696 | if (histogram) |
| 1697 | histogram->Add(sample); |
| 1698 | } |
| 1699 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1700 | int Database::OnSqliteError(int err, |
| 1701 | sql::Statement* stmt, |
| 1702 | const char* sql) const { |
Etienne Bergeron | 6cb35c7 | 2020-02-12 18:09:48 | [diff] [blame] | 1703 | TRACE_EVENT0("sql", "Database::OnSqliteError"); |
| 1704 | |
Ilya Sherman | 1c811db | 2017-12-14 10:36:18 | [diff] [blame] | 1705 | base::UmaHistogramSparse("Sqlite.Error", err); |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 1706 | AddTaggedHistogram("Sqlite.Error", err); |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 1707 | |
| 1708 | // Always log the error. |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 1709 | if (!sql && stmt) |
| 1710 | sql = stmt->GetSQLStatement(); |
| 1711 | if (!sql) |
| 1712 | sql = "-- unknown"; |
shess | f7e988f | 2015-11-13 00:41:06 | [diff] [blame] | 1713 | |
| 1714 | std::string id = histogram_tag_; |
| 1715 | if (id.empty()) |
| 1716 | id = DbPath().BaseName().AsUTF8Unsafe(); |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1717 | LOG(ERROR) << id << " sqlite error " << err << ", errno " << GetLastErrno() |
| 1718 | << ": " << GetErrorMessage() << ", sql: " << sql; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 1719 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 1720 | if (!error_callback_.is_null()) { |
[email protected] | 98cf300 | 2013-07-12 01:38:56 | [diff] [blame] | 1721 | // Fire from a copy of the callback in case of reentry into |
| 1722 | // re/set_error_callback(). |
| 1723 | // TODO(shess): <http://crbug.com/254584> |
| 1724 | ErrorCallback(error_callback_).Run(err, stmt); |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 1725 | return err; |
| 1726 | } |
| 1727 | |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 1728 | // The default handling is to assert on debug and to ignore on release. |
shess | 97681440 | 2016-06-21 06:56:25 | [diff] [blame] | 1729 | if (!IsExpectedSqliteError(err)) |
Sigurdur Asgeirsson | 8d82bd0 | 2017-09-25 21:05:52 | [diff] [blame] | 1730 | DLOG(DCHECK) << GetErrorMessage(); |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 1731 | return err; |
| 1732 | } |
| 1733 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1734 | bool Database::FullIntegrityCheck(std::vector<std::string>* messages) { |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 1735 | return IntegrityCheckHelper("PRAGMA integrity_check", messages); |
| 1736 | } |
| 1737 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1738 | bool Database::QuickIntegrityCheck() { |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 1739 | std::vector<std::string> messages; |
| 1740 | if (!IntegrityCheckHelper("PRAGMA quick_check", &messages)) |
| 1741 | return false; |
| 1742 | return messages.size() == 1 && messages[0] == "ok"; |
| 1743 | } |
| 1744 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1745 | std::string Database::GetDiagnosticInfo(int extended_error, |
| 1746 | Statement* statement) { |
afakhry | 7c9abe7 | 2016-08-05 17:33:19 | [diff] [blame] | 1747 | // Prevent reentrant calls to the error callback. |
| 1748 | ErrorCallback original_callback = std::move(error_callback_); |
| 1749 | reset_error_callback(); |
| 1750 | |
| 1751 | // Trim extended error codes. |
| 1752 | const int error = (extended_error & 0xFF); |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1753 | // CollectCorruptionInfo() is implemented in terms of sql::Database, |
afakhry | 7c9abe7 | 2016-08-05 17:33:19 | [diff] [blame] | 1754 | // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite. |
| 1755 | std::string result = (error == SQLITE_CORRUPT) |
| 1756 | ? CollectCorruptionInfo() |
| 1757 | : CollectErrorInfo(extended_error, statement); |
| 1758 | |
| 1759 | // The following queries must be executed after CollectErrorInfo() above, so |
| 1760 | // if they result in their own errors, they don't interfere with |
| 1761 | // CollectErrorInfo(). |
| 1762 | const bool has_valid_header = |
| 1763 | (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK); |
| 1764 | const bool select_sqlite_master_result = |
| 1765 | (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") == |
| 1766 | SQLITE_OK); |
| 1767 | |
| 1768 | // Restore the original error callback. |
| 1769 | error_callback_ = std::move(original_callback); |
| 1770 | |
| 1771 | base::StringAppendF(&result, "Has valid header: %s\n", |
| 1772 | (has_valid_header ? "Yes" : "No")); |
| 1773 | base::StringAppendF(&result, "Has valid schema: %s\n", |
| 1774 | (select_sqlite_master_result ? "Yes" : "No")); |
| 1775 | |
| 1776 | return result; |
| 1777 | } |
| 1778 | |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1779 | // TODO(shess): Allow specifying maximum results (default 100 lines). |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1780 | bool Database::IntegrityCheckHelper(const char* pragma_sql, |
| 1781 | std::vector<std::string>* messages) { |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1782 | messages->clear(); |
| 1783 | |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1784 | // This has the side effect of setting SQLITE_RecoveryMode, which |
| 1785 | // allows SQLite to process through certain cases of corruption. |
| 1786 | // Failing to set this pragma probably means that the database is |
| 1787 | // beyond recovery. |
Victor Costan | 4c2f3e92 | 2018-08-21 04:47:59 | [diff] [blame] | 1788 | static const char kWritableSchemaSql[] = "PRAGMA writable_schema=ON"; |
Victor Costan | 1d86835 | 2018-06-26 19:06:48 | [diff] [blame] | 1789 | if (!Execute(kWritableSchemaSql)) |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1790 | return false; |
| 1791 | |
| 1792 | bool ret = false; |
| 1793 | { |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 1794 | sql::Statement stmt(GetUniqueStatement(pragma_sql)); |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1795 | |
| 1796 | // The pragma appears to return all results (up to 100 by default) |
| 1797 | // as a single string. This doesn't appear to be an API contract, |
| 1798 | // it could return separate lines, so loop _and_ split. |
| 1799 | while (stmt.Step()) { |
| 1800 | std::string result(stmt.ColumnString(0)); |
brettw | 83dc161 | 2015-08-12 07:31:18 | [diff] [blame] | 1801 | *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE, |
| 1802 | base::SPLIT_WANT_ALL); |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1803 | } |
| 1804 | ret = stmt.Succeeded(); |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1805 | } |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1806 | |
| 1807 | // Best effort to put things back as they were before. |
Victor Costan | 4c2f3e92 | 2018-08-21 04:47:59 | [diff] [blame] | 1808 | static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema=OFF"; |
Victor Costan | 1d86835 | 2018-06-26 19:06:48 | [diff] [blame] | 1809 | ignore_result(Execute(kNoWritableSchemaSql)); |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1810 | |
| 1811 | return ret; |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1812 | } |
| 1813 | |
Victor Costan | cfbfa60 | 2018-08-01 23:24:46 | [diff] [blame] | 1814 | bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd, |
| 1815 | const std::string& dump_name) { |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 1816 | return memory_dump_provider_ && |
ssid | 1f4e536 | 2016-12-08 20:41:38 | [diff] [blame] | 1817 | memory_dump_provider_->ReportMemoryUsage(pmd, dump_name); |
dskiba | b4199f8 | 2016-11-21 20:16:13 | [diff] [blame] | 1818 | } |
| 1819 | |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1820 | bool Database::UseWALMode() const { |
| 1821 | #if defined(OS_FUCHSIA) |
| 1822 | // WAL mode is only enabled on Fuchsia for databases with exclusive |
| 1823 | // locking, because this case does not require shared memory support. |
| 1824 | // At the time this was implemented (May 2020), Fuchsia's shared |
| 1825 | // memory support was insufficient for SQLite's needs. |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 1826 | return options_.wal_mode && options_.exclusive_locking; |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1827 | #else |
Shubham Aggarwal | 7b60fe6e | 2020-10-15 06:00:28 | [diff] [blame] | 1828 | return options_.wal_mode; |
Shubham Aggarwal | be4f97ce | 2020-06-19 15:58:57 | [diff] [blame] | 1829 | #endif // defined(OS_FUCHSIA) |
| 1830 | } |
| 1831 | |
| 1832 | bool Database::CheckpointDatabase() { |
| 1833 | base::Optional<base::ScopedBlockingCall> scoped_blocking_call; |
| 1834 | InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); |
| 1835 | |
| 1836 | static const char* kMainDb = "main"; |
| 1837 | int rc = sqlite3_wal_checkpoint_v2(db_, kMainDb, SQLITE_CHECKPOINT_PASSIVE, |
| 1838 | /*pnLog=*/nullptr, |
| 1839 | /*pnCkpt=*/nullptr); |
| 1840 | |
| 1841 | return rc == SQLITE_OK; |
| 1842 | } |
| 1843 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1844 | } // namespace sql |