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