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