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