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