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