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