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