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