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