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