[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 | |
| 7 | #include <string.h> |
| 8 | |
[email protected] | 5799981 | 2013-02-24 05:40:52 | [diff] [blame] | 9 | #include "base/files/file_path.h" |
thestig | 22dfc401 | 2014-09-05 08:29:44 | [diff] [blame] | 10 | #include "base/files/file_util.h" |
[email protected] | a7ec129 | 2013-07-22 22:02:18 | [diff] [blame] | 11 | #include "base/lazy_instance.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 12 | #include "base/logging.h" |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 13 | #include "base/metrics/histogram.h" |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 14 | #include "base/metrics/sparse_histogram.h" |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 15 | #include "base/strings/string_split.h" |
[email protected] | a4bbc1f9 | 2013-06-11 07:28:19 | [diff] [blame] | 16 | #include "base/strings/string_util.h" |
| 17 | #include "base/strings/stringprintf.h" |
[email protected] | 90626587 | 2013-06-07 22:40:45 | [diff] [blame] | 18 | #include "base/strings/utf_string_conversions.h" |
[email protected] | a7ec129 | 2013-07-22 22:02:18 | [diff] [blame] | 19 | #include "base/synchronization/lock.h" |
[email protected] | f0a54b2 | 2011-07-19 18:40:21 | [diff] [blame] | 20 | #include "sql/statement.h" |
[email protected] | e33cba4 | 2010-08-18 23:37:03 | [diff] [blame] | 21 | #include "third_party/sqlite/sqlite3.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 22 | |
[email protected] | 2e1cee76 | 2013-07-09 14:40:00 | [diff] [blame] | 23 | #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE) |
| 24 | #include "third_party/sqlite/src/ext/icu/sqliteicu.h" |
| 25 | #endif |
| 26 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 27 | namespace { |
| 28 | |
| 29 | // Spin for up to a second waiting for the lock to clear when setting |
| 30 | // up the database. |
| 31 | // TODO(shess): Better story on this. http://crbug.com/56559 |
[email protected] | c68ce17 | 2011-11-24 22:30:27 | [diff] [blame] | 32 | const int kBusyTimeoutSeconds = 1; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 33 | |
| 34 | class ScopedBusyTimeout { |
| 35 | public: |
| 36 | explicit ScopedBusyTimeout(sqlite3* db) |
| 37 | : db_(db) { |
| 38 | } |
| 39 | ~ScopedBusyTimeout() { |
| 40 | sqlite3_busy_timeout(db_, 0); |
| 41 | } |
| 42 | |
| 43 | int SetTimeout(base::TimeDelta timeout) { |
| 44 | DCHECK_LT(timeout.InMilliseconds(), INT_MAX); |
| 45 | return sqlite3_busy_timeout(db_, |
| 46 | static_cast<int>(timeout.InMilliseconds())); |
| 47 | } |
| 48 | |
| 49 | private: |
| 50 | sqlite3* db_; |
| 51 | }; |
| 52 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 53 | // Helper to "safely" enable writable_schema. No error checking |
| 54 | // because it is reasonable to just forge ahead in case of an error. |
| 55 | // If turning it on fails, then most likely nothing will work, whereas |
| 56 | // if turning it off fails, it only matters if some code attempts to |
| 57 | // continue working with the database and tries to modify the |
| 58 | // sqlite_master table (none of our code does this). |
| 59 | class ScopedWritableSchema { |
| 60 | public: |
| 61 | explicit ScopedWritableSchema(sqlite3* db) |
| 62 | : db_(db) { |
| 63 | sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL); |
| 64 | } |
| 65 | ~ScopedWritableSchema() { |
| 66 | sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL); |
| 67 | } |
| 68 | |
| 69 | private: |
| 70 | sqlite3* db_; |
| 71 | }; |
| 72 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 73 | // Helper to wrap the sqlite3_backup_*() step of Raze(). Return |
| 74 | // SQLite error code from running the backup step. |
| 75 | int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) { |
| 76 | DCHECK_NE(src, dst); |
| 77 | sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name); |
| 78 | if (!backup) { |
| 79 | // Since this call only sets things up, this indicates a gross |
| 80 | // error in SQLite. |
| 81 | DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst); |
| 82 | return sqlite3_errcode(dst); |
| 83 | } |
| 84 | |
| 85 | // -1 backs up the entire database. |
| 86 | int rc = sqlite3_backup_step(backup, -1); |
| 87 | int pages = sqlite3_backup_pagecount(backup); |
| 88 | sqlite3_backup_finish(backup); |
| 89 | |
| 90 | // If successful, exactly one page should have been backed up. If |
| 91 | // this breaks, check this function to make sure assumptions aren't |
| 92 | // being broken. |
| 93 | if (rc == SQLITE_DONE) |
| 94 | DCHECK_EQ(pages, 1); |
| 95 | |
| 96 | return rc; |
| 97 | } |
| 98 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 99 | // Be very strict on attachment point. SQLite can handle a much wider |
| 100 | // character set with appropriate quoting, but Chromium code should |
| 101 | // just use clean names to start with. |
| 102 | bool ValidAttachmentPoint(const char* attachment_point) { |
| 103 | for (size_t i = 0; attachment_point[i]; ++i) { |
| 104 | if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') || |
| 105 | (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') || |
| 106 | (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') || |
| 107 | attachment_point[i] == '_')) { |
| 108 | return false; |
| 109 | } |
| 110 | } |
| 111 | return true; |
| 112 | } |
| 113 | |
[email protected] | a7ec129 | 2013-07-22 22:02:18 | [diff] [blame] | 114 | // SQLite automatically calls sqlite3_initialize() lazily, but |
| 115 | // sqlite3_initialize() uses double-checked locking and thus can have |
| 116 | // data races. |
| 117 | // |
| 118 | // TODO(shess): Another alternative would be to have |
| 119 | // sqlite3_initialize() called as part of process bring-up. If this |
| 120 | // is changed, remove the dynamic_annotations dependency in sql.gyp. |
| 121 | base::LazyInstance<base::Lock>::Leaky |
| 122 | g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER; |
| 123 | void InitializeSqlite() { |
| 124 | base::AutoLock lock(g_sqlite_init_lock.Get()); |
| 125 | sqlite3_initialize(); |
| 126 | } |
| 127 | |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 128 | // Helper to get the sqlite3_file* associated with the "main" database. |
| 129 | int GetSqlite3File(sqlite3* db, sqlite3_file** file) { |
| 130 | *file = NULL; |
| 131 | int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file); |
| 132 | if (rc != SQLITE_OK) |
| 133 | return rc; |
| 134 | |
| 135 | // TODO(shess): NULL in file->pMethods has been observed on android_dbg |
| 136 | // content_unittests, even though it should not be possible. |
| 137 | // http://crbug.com/329982 |
| 138 | if (!*file || !(*file)->pMethods) |
| 139 | return SQLITE_ERROR; |
| 140 | |
| 141 | return rc; |
| 142 | } |
| 143 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 144 | // This should match UMA_HISTOGRAM_MEDIUM_TIMES(). |
| 145 | base::HistogramBase* GetMediumTimeHistogram(const std::string& name) { |
| 146 | return base::Histogram::FactoryTimeGet( |
| 147 | name, |
| 148 | base::TimeDelta::FromMilliseconds(10), |
| 149 | base::TimeDelta::FromMinutes(3), |
| 150 | 50, |
| 151 | base::HistogramBase::kUmaTargetedHistogramFlag); |
| 152 | } |
| 153 | |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 154 | std::string AsUTF8ForSQL(const base::FilePath& path) { |
| 155 | #if defined(OS_WIN) |
| 156 | return base::WideToUTF8(path.value()); |
| 157 | #elif defined(OS_POSIX) |
| 158 | return path.value(); |
| 159 | #endif |
| 160 | } |
| 161 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 162 | } // namespace |
| 163 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 164 | namespace sql { |
| 165 | |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 166 | // static |
| 167 | Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL; |
| 168 | |
| 169 | // static |
[email protected] | 74cdede | 2013-09-25 05:39:57 | [diff] [blame] | 170 | bool Connection::ShouldIgnoreSqliteError(int error) { |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 171 | if (!current_ignorer_cb_) |
| 172 | return false; |
| 173 | return current_ignorer_cb_->Run(error); |
| 174 | } |
| 175 | |
| 176 | // static |
| 177 | void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) { |
| 178 | CHECK(current_ignorer_cb_ == NULL); |
| 179 | current_ignorer_cb_ = cb; |
| 180 | } |
| 181 | |
| 182 | // static |
| 183 | void Connection::ResetErrorIgnorer() { |
| 184 | CHECK(current_ignorer_cb_); |
| 185 | current_ignorer_cb_ = NULL; |
| 186 | } |
| 187 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 188 | bool StatementID::operator<(const StatementID& other) const { |
| 189 | if (number_ != other.number_) |
| 190 | return number_ < other.number_; |
| 191 | return strcmp(str_, other.str_) < 0; |
| 192 | } |
| 193 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 194 | Connection::StatementRef::StatementRef(Connection* connection, |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 195 | sqlite3_stmt* stmt, |
| 196 | bool was_valid) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 197 | : connection_(connection), |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 198 | stmt_(stmt), |
| 199 | was_valid_(was_valid) { |
| 200 | if (connection) |
| 201 | connection_->StatementRefCreated(this); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 202 | } |
| 203 | |
| 204 | Connection::StatementRef::~StatementRef() { |
| 205 | if (connection_) |
| 206 | connection_->StatementRefDeleted(this); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 207 | Close(false); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 208 | } |
| 209 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 210 | void Connection::StatementRef::Close(bool forced) { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 211 | if (stmt_) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 212 | // Call to AssertIOAllowed() cannot go at the beginning of the function |
| 213 | // because Close() is called unconditionally from destructor to clean |
| 214 | // connection_. And if this is inactive statement this won't cause any |
| 215 | // disk access and destructor most probably will be called on thread |
| 216 | // not allowing disk access. |
| 217 | // TODO([email protected]): This should move to the beginning |
| 218 | // of the function. http://crbug.com/136655. |
| 219 | AssertIOAllowed(); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 220 | sqlite3_finalize(stmt_); |
| 221 | stmt_ = NULL; |
| 222 | } |
| 223 | connection_ = NULL; // The connection may be getting deleted. |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 224 | |
| 225 | // Forced close is expected to happen from a statement error |
| 226 | // handler. In that case maintain the sense of |was_valid_| which |
| 227 | // previously held for this ref. |
| 228 | was_valid_ = was_valid_ && forced; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 229 | } |
| 230 | |
| 231 | Connection::Connection() |
| 232 | : db_(NULL), |
| 233 | page_size_(0), |
| 234 | cache_size_(0), |
| 235 | exclusive_locking_(false), |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame] | 236 | restrict_to_user_(false), |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 237 | transaction_nesting_(0), |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 238 | needs_rollback_(false), |
[email protected] | 49dc4f2 | 2012-10-17 17:41:16 | [diff] [blame] | 239 | in_memory_(false), |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 240 | poisoned_(false), |
| 241 | stats_histogram_(NULL), |
| 242 | commit_time_histogram_(NULL), |
| 243 | autocommit_time_histogram_(NULL), |
| 244 | update_time_histogram_(NULL), |
| 245 | query_time_histogram_(NULL), |
| 246 | clock_(new TimeSource()) { |
[email protected] | 526b466 | 2013-06-14 04:09:12 | [diff] [blame] | 247 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 248 | |
| 249 | Connection::~Connection() { |
| 250 | Close(); |
| 251 | } |
| 252 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 253 | void Connection::RecordEvent(Events event, size_t count) { |
| 254 | for (size_t i = 0; i < count; ++i) { |
| 255 | UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE); |
| 256 | } |
| 257 | |
| 258 | if (stats_histogram_) { |
| 259 | for (size_t i = 0; i < count; ++i) { |
| 260 | stats_histogram_->Add(event); |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | void Connection::RecordCommitTime(const base::TimeDelta& delta) { |
| 266 | RecordUpdateTime(delta); |
| 267 | UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta); |
| 268 | if (commit_time_histogram_) |
| 269 | commit_time_histogram_->AddTime(delta); |
| 270 | } |
| 271 | |
| 272 | void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) { |
| 273 | RecordUpdateTime(delta); |
| 274 | UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta); |
| 275 | if (autocommit_time_histogram_) |
| 276 | autocommit_time_histogram_->AddTime(delta); |
| 277 | } |
| 278 | |
| 279 | void Connection::RecordUpdateTime(const base::TimeDelta& delta) { |
| 280 | RecordQueryTime(delta); |
| 281 | UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta); |
| 282 | if (update_time_histogram_) |
| 283 | update_time_histogram_->AddTime(delta); |
| 284 | } |
| 285 | |
| 286 | void Connection::RecordQueryTime(const base::TimeDelta& delta) { |
| 287 | UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta); |
| 288 | if (query_time_histogram_) |
| 289 | query_time_histogram_->AddTime(delta); |
| 290 | } |
| 291 | |
| 292 | void Connection::RecordTimeAndChanges( |
| 293 | const base::TimeDelta& delta, bool read_only) { |
| 294 | if (read_only) { |
| 295 | RecordQueryTime(delta); |
| 296 | } else { |
| 297 | const int changes = sqlite3_changes(db_); |
| 298 | if (sqlite3_get_autocommit(db_)) { |
| 299 | RecordAutoCommitTime(delta); |
| 300 | RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes); |
| 301 | } else { |
| 302 | RecordUpdateTime(delta); |
| 303 | RecordEvent(EVENT_CHANGES, changes); |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 308 | bool Connection::Open(const base::FilePath& path) { |
[email protected] | 348ac8f5 | 2013-05-21 03:27:02 | [diff] [blame] | 309 | if (!histogram_tag_.empty()) { |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 310 | int64_t size_64 = 0; |
[email protected] | 5628570 | 2013-12-04 18:22:49 | [diff] [blame] | 311 | if (base::GetFileSize(path, &size_64)) { |
[email protected] | 348ac8f5 | 2013-05-21 03:27:02 | [diff] [blame] | 312 | size_t sample = static_cast<size_t>(size_64 / 1024); |
| 313 | std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_; |
| 314 | base::HistogramBase* histogram = |
| 315 | base::Histogram::FactoryGet( |
| 316 | full_histogram_name, 1, 1000000, 50, |
| 317 | base::HistogramBase::kUmaTargetedHistogramFlag); |
| 318 | if (histogram) |
| 319 | histogram->Add(sample); |
| 320 | } |
| 321 | } |
| 322 | |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 323 | return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 324 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 325 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 326 | bool Connection::OpenInMemory() { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 327 | in_memory_ = true; |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 328 | return OpenInternal(":memory:", NO_RETRY); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 329 | } |
| 330 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 331 | bool Connection::OpenTemporary() { |
| 332 | return OpenInternal("", NO_RETRY); |
| 333 | } |
| 334 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 335 | void Connection::CloseInternal(bool forced) { |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 336 | // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point |
| 337 | // will delete the -journal file. For ChromiumOS or other more |
| 338 | // embedded systems, this is probably not appropriate, whereas on |
| 339 | // desktop it might make some sense. |
| 340 | |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 341 | // sqlite3_close() needs all prepared statements to be finalized. |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 342 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 343 | // Release cached statements. |
| 344 | statement_cache_.clear(); |
| 345 | |
| 346 | // With cached statements released, in-use statements will remain. |
| 347 | // Closing the database while statements are in use is an API |
| 348 | // violation, except for forced close (which happens from within a |
| 349 | // statement's error handler). |
| 350 | DCHECK(forced || open_statements_.empty()); |
| 351 | |
| 352 | // Deactivate any outstanding statements so sqlite3_close() works. |
| 353 | for (StatementRefSet::iterator i = open_statements_.begin(); |
| 354 | i != open_statements_.end(); ++i) |
| 355 | (*i)->Close(forced); |
| 356 | open_statements_.clear(); |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 357 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 358 | if (db_) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 359 | // Call to AssertIOAllowed() cannot go at the beginning of the function |
| 360 | // because Close() must be called from destructor to clean |
| 361 | // statement_cache_, it won't cause any disk access and it most probably |
| 362 | // will happen on thread not allowing disk access. |
| 363 | // TODO([email protected]): This should move to the beginning |
| 364 | // of the function. http://crbug.com/136655. |
| 365 | AssertIOAllowed(); |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 366 | |
| 367 | int rc = sqlite3_close(db_); |
| 368 | if (rc != SQLITE_OK) { |
| 369 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc); |
| 370 | DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage(); |
| 371 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 372 | } |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 373 | db_ = NULL; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 374 | } |
| 375 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 376 | void Connection::Close() { |
| 377 | // If the database was already closed by RazeAndClose(), then no |
| 378 | // need to close again. Clear the |poisoned_| bit so that incorrect |
| 379 | // API calls are caught. |
| 380 | if (poisoned_) { |
| 381 | poisoned_ = false; |
| 382 | return; |
| 383 | } |
| 384 | |
| 385 | CloseInternal(false); |
| 386 | } |
| 387 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 388 | void Connection::Preload() { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 389 | AssertIOAllowed(); |
| 390 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 391 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 392 | DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 393 | return; |
| 394 | } |
| 395 | |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 396 | // Use local settings if provided, otherwise use documented defaults. The |
| 397 | // actual results could be fetching via PRAGMA calls. |
| 398 | const int page_size = page_size_ ? page_size_ : 1024; |
| 399 | sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000); |
| 400 | if (preload_size < 1) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 401 | return; |
| 402 | |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 403 | sqlite3_file* file = NULL; |
| 404 | int rc = GetSqlite3File(db_, &file); |
| 405 | if (rc != SQLITE_OK) |
| 406 | return; |
| 407 | |
| 408 | sqlite3_int64 file_size = 0; |
| 409 | rc = file->pMethods->xFileSize(file, &file_size); |
| 410 | if (rc != SQLITE_OK) |
| 411 | return; |
| 412 | |
| 413 | // Don't preload more than the file contains. |
| 414 | if (preload_size > file_size) |
| 415 | preload_size = file_size; |
| 416 | |
| 417 | scoped_ptr<char[]> buf(new char[page_size]); |
shess | de60c5f1 | 2015-04-21 17:34:46 | [diff] [blame] | 418 | for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) { |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 419 | rc = file->pMethods->xRead(file, buf.get(), page_size, pos); |
| 420 | if (rc != SQLITE_OK) |
| 421 | return; |
| 422 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 423 | } |
| 424 | |
[email protected] | be7995f1 | 2013-07-18 18:49:14 | [diff] [blame] | 425 | void Connection::TrimMemory(bool aggressively) { |
| 426 | if (!db_) |
| 427 | return; |
| 428 | |
| 429 | // TODO(shess): investigate using sqlite3_db_release_memory() when possible. |
| 430 | int original_cache_size; |
| 431 | { |
| 432 | Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size")); |
| 433 | if (!sql_get_original.Step()) { |
| 434 | DLOG(WARNING) << "Could not get cache size " << GetErrorMessage(); |
| 435 | return; |
| 436 | } |
| 437 | original_cache_size = sql_get_original.ColumnInt(0); |
| 438 | } |
| 439 | int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2); |
| 440 | |
| 441 | // Force sqlite to try to reduce page cache usage. |
| 442 | const std::string sql_shrink = |
| 443 | base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size); |
| 444 | if (!Execute(sql_shrink.c_str())) |
| 445 | DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage(); |
| 446 | |
| 447 | // Restore cache size. |
| 448 | const std::string sql_restore = |
| 449 | base::StringPrintf("PRAGMA cache_size=%d", original_cache_size); |
| 450 | if (!Execute(sql_restore.c_str())) |
| 451 | DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage(); |
| 452 | } |
| 453 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 454 | // Create an in-memory database with the existing database's page |
| 455 | // size, then backup that database over the existing database. |
| 456 | bool Connection::Raze() { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 457 | AssertIOAllowed(); |
| 458 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 459 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 460 | DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db"; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 461 | return false; |
| 462 | } |
| 463 | |
| 464 | if (transaction_nesting_ > 0) { |
| 465 | DLOG(FATAL) << "Cannot raze within a transaction"; |
| 466 | return false; |
| 467 | } |
| 468 | |
| 469 | sql::Connection null_db; |
| 470 | if (!null_db.OpenInMemory()) { |
| 471 | DLOG(FATAL) << "Unable to open in-memory database."; |
| 472 | return false; |
| 473 | } |
| 474 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 475 | if (page_size_) { |
| 476 | // Enforce SQLite restrictions on |page_size_|. |
| 477 | DCHECK(!(page_size_ & (page_size_ - 1))) |
| 478 | << " page_size_ " << page_size_ << " is not a power of two."; |
| 479 | const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h |
| 480 | DCHECK_LE(page_size_, kSqliteMaxPageSize); |
[email protected] | 7d3cbc9 | 2013-03-18 22:33:04 | [diff] [blame] | 481 | const std::string sql = |
| 482 | base::StringPrintf("PRAGMA page_size=%d", page_size_); |
[email protected] | 69c5845 | 2012-08-06 19:22:42 | [diff] [blame] | 483 | if (!null_db.Execute(sql.c_str())) |
| 484 | return false; |
| 485 | } |
| 486 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 487 | #if defined(OS_ANDROID) |
| 488 | // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately, |
| 489 | // in-memory databases do not respect this define. |
| 490 | // TODO(shess): Figure out a way to set this without using platform |
| 491 | // specific code. AFAICT from sqlite3.c, the only way to do it |
| 492 | // would be to create an actual filesystem database, which is |
| 493 | // unfortunate. |
| 494 | if (!null_db.Execute("PRAGMA auto_vacuum = 1")) |
| 495 | return false; |
| 496 | #endif |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 497 | |
| 498 | // The page size doesn't take effect until a database has pages, and |
| 499 | // at this point the null database has none. Changing the schema |
| 500 | // version will create the first page. This will not affect the |
| 501 | // schema version in the resulting database, as SQLite's backup |
| 502 | // implementation propagates the schema version from the original |
| 503 | // connection to the new version of the database, incremented by one |
| 504 | // so that other readers see the schema change and act accordingly. |
| 505 | if (!null_db.Execute("PRAGMA schema_version = 1")) |
| 506 | return false; |
| 507 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 508 | // SQLite tracks the expected number of database pages in the first |
| 509 | // page, and if it does not match the total retrieved from a |
| 510 | // filesystem call, treats the database as corrupt. This situation |
| 511 | // breaks almost all SQLite calls. "PRAGMA writable_schema" can be |
| 512 | // used to hint to SQLite to soldier on in that case, specifically |
| 513 | // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in |
| 514 | // sqlite3.c lockBtree().] |
| 515 | // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA |
| 516 | // page_size" can be used to query such a database. |
| 517 | ScopedWritableSchema writable_schema(db_); |
| 518 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 519 | const char* kMain = "main"; |
| 520 | int rc = BackupDatabase(null_db.db_, db_, kMain); |
| 521 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc); |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 522 | |
| 523 | // The destination database was locked. |
| 524 | if (rc == SQLITE_BUSY) { |
| 525 | return false; |
| 526 | } |
| 527 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 528 | // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not |
| 529 | // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_ |
| 530 | // isn't even big enough for one page. Either way, reach in and |
| 531 | // truncate it before trying again. |
| 532 | // TODO(shess): Maybe it would be worthwhile to just truncate from |
| 533 | // the get-go? |
| 534 | if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) { |
| 535 | sqlite3_file* file = NULL; |
[email protected] | 8ada10f | 2013-12-21 00:42:34 | [diff] [blame] | 536 | rc = GetSqlite3File(db_, &file); |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 537 | if (rc != SQLITE_OK) { |
| 538 | DLOG(FATAL) << "Failure getting file handle."; |
| 539 | return false; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 540 | } |
| 541 | |
| 542 | rc = file->pMethods->xTruncate(file, 0); |
| 543 | if (rc != SQLITE_OK) { |
| 544 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc); |
| 545 | DLOG(FATAL) << "Failed to truncate file."; |
| 546 | return false; |
| 547 | } |
| 548 | |
| 549 | rc = BackupDatabase(null_db.db_, db_, kMain); |
| 550 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc); |
| 551 | |
| 552 | if (rc != SQLITE_DONE) { |
| 553 | DLOG(FATAL) << "Failed retrying Raze()."; |
| 554 | } |
| 555 | } |
| 556 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 557 | // The entire database should have been backed up. |
| 558 | if (rc != SQLITE_DONE) { |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 559 | // TODO(shess): Figure out which other cases can happen. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 560 | DLOG(FATAL) << "Unable to copy entire null database."; |
| 561 | return false; |
| 562 | } |
| 563 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 564 | return true; |
| 565 | } |
| 566 | |
| 567 | bool Connection::RazeWithTimout(base::TimeDelta timeout) { |
| 568 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 569 | DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db"; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 570 | return false; |
| 571 | } |
| 572 | |
| 573 | ScopedBusyTimeout busy_timeout(db_); |
| 574 | busy_timeout.SetTimeout(timeout); |
| 575 | return Raze(); |
| 576 | } |
| 577 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 578 | bool Connection::RazeAndClose() { |
| 579 | if (!db_) { |
| 580 | DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db"; |
| 581 | return false; |
| 582 | } |
| 583 | |
| 584 | // Raze() cannot run in a transaction. |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 585 | RollbackAllTransactions(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 586 | |
| 587 | bool result = Raze(); |
| 588 | |
| 589 | CloseInternal(true); |
| 590 | |
| 591 | // Mark the database so that future API calls fail appropriately, |
| 592 | // but don't DCHECK (because after calling this function they are |
| 593 | // expected to fail). |
| 594 | poisoned_ = true; |
| 595 | |
| 596 | return result; |
| 597 | } |
| 598 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 599 | void Connection::Poison() { |
| 600 | if (!db_) { |
| 601 | DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db"; |
| 602 | return; |
| 603 | } |
| 604 | |
| 605 | RollbackAllTransactions(); |
| 606 | CloseInternal(true); |
| 607 | |
| 608 | // Mark the database so that future API calls fail appropriately, |
| 609 | // but don't DCHECK (because after calling this function they are |
| 610 | // expected to fail). |
| 611 | poisoned_ = true; |
| 612 | } |
| 613 | |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 614 | // TODO(shess): To the extent possible, figure out the optimal |
| 615 | // ordering for these deletes which will prevent other connections |
| 616 | // from seeing odd behavior. For instance, it may be necessary to |
| 617 | // manually lock the main database file in a SQLite-compatible fashion |
| 618 | // (to prevent other processes from opening it), then delete the |
| 619 | // journal files, then delete the main database file. Another option |
| 620 | // might be to lock the main database file and poison the header with |
| 621 | // junk to prevent other processes from opening it successfully (like |
| 622 | // Gears "SQLite poison 3" trick). |
| 623 | // |
| 624 | // static |
| 625 | bool Connection::Delete(const base::FilePath& path) { |
| 626 | base::ThreadRestrictions::AssertIOAllowed(); |
| 627 | |
| 628 | base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal")); |
| 629 | base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal")); |
| 630 | |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 631 | std::string journal_str = AsUTF8ForSQL(journal_path); |
| 632 | std::string wal_str = AsUTF8ForSQL(wal_path); |
| 633 | std::string path_str = AsUTF8ForSQL(path); |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 634 | |
erg | 102ceb41 | 2015-06-20 01:38:13 | [diff] [blame] | 635 | sqlite3_vfs* vfs = sqlite3_vfs_find(NULL); |
| 636 | CHECK(vfs); |
| 637 | CHECK(vfs->xDelete); |
| 638 | CHECK(vfs->xAccess); |
| 639 | |
| 640 | // We only work with unix, win32 and mojo filesystems. If you're trying to |
| 641 | // use this code with any other VFS, you're not in a good place. |
| 642 | CHECK(strncmp(vfs->zName, "unix", 4) == 0 || |
| 643 | strncmp(vfs->zName, "win32", 5) == 0 || |
| 644 | strcmp(vfs->zName, "mojo") == 0); |
| 645 | |
| 646 | vfs->xDelete(vfs, journal_str.c_str(), 0); |
| 647 | vfs->xDelete(vfs, wal_str.c_str(), 0); |
| 648 | vfs->xDelete(vfs, path_str.c_str(), 0); |
| 649 | |
| 650 | int journal_exists = 0; |
| 651 | vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, |
| 652 | &journal_exists); |
| 653 | |
| 654 | int wal_exists = 0; |
| 655 | vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, |
| 656 | &wal_exists); |
| 657 | |
| 658 | int path_exists = 0; |
| 659 | vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, |
| 660 | &path_exists); |
| 661 | |
| 662 | return !journal_exists && !wal_exists && !path_exists; |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 663 | } |
| 664 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 665 | bool Connection::BeginTransaction() { |
| 666 | if (needs_rollback_) { |
[email protected] | 88563f6 | 2011-03-13 22:13:33 | [diff] [blame] | 667 | DCHECK_GT(transaction_nesting_, 0); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 668 | |
| 669 | // When we're going to rollback, fail on this begin and don't actually |
| 670 | // mark us as entering the nested transaction. |
| 671 | return false; |
| 672 | } |
| 673 | |
| 674 | bool success = true; |
| 675 | if (!transaction_nesting_) { |
| 676 | needs_rollback_ = false; |
| 677 | |
| 678 | Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION")); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 679 | RecordOneEvent(EVENT_BEGIN); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 680 | if (!begin.Run()) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 681 | return false; |
| 682 | } |
| 683 | transaction_nesting_++; |
| 684 | return success; |
| 685 | } |
| 686 | |
| 687 | void Connection::RollbackTransaction() { |
| 688 | if (!transaction_nesting_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 689 | DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 690 | return; |
| 691 | } |
| 692 | |
| 693 | transaction_nesting_--; |
| 694 | |
| 695 | if (transaction_nesting_ > 0) { |
| 696 | // Mark the outermost transaction as needing rollback. |
| 697 | needs_rollback_ = true; |
| 698 | return; |
| 699 | } |
| 700 | |
| 701 | DoRollback(); |
| 702 | } |
| 703 | |
| 704 | bool Connection::CommitTransaction() { |
| 705 | if (!transaction_nesting_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 706 | DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 707 | return false; |
| 708 | } |
| 709 | transaction_nesting_--; |
| 710 | |
| 711 | if (transaction_nesting_ > 0) { |
| 712 | // Mark any nested transactions as failing after we've already got one. |
| 713 | return !needs_rollback_; |
| 714 | } |
| 715 | |
| 716 | if (needs_rollback_) { |
| 717 | DoRollback(); |
| 718 | return false; |
| 719 | } |
| 720 | |
| 721 | Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT")); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 722 | |
| 723 | // Collect the commit time manually, sql::Statement would register it as query |
| 724 | // time only. |
| 725 | const base::TimeTicks before = Now(); |
| 726 | bool ret = commit.RunWithoutTimers(); |
| 727 | const base::TimeDelta delta = Now() - before; |
| 728 | |
| 729 | RecordCommitTime(delta); |
| 730 | RecordOneEvent(EVENT_COMMIT); |
| 731 | |
| 732 | return ret; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 733 | } |
| 734 | |
[email protected] | 8d40941 | 2013-07-19 18:25:30 | [diff] [blame] | 735 | void Connection::RollbackAllTransactions() { |
| 736 | if (transaction_nesting_ > 0) { |
| 737 | transaction_nesting_ = 0; |
| 738 | DoRollback(); |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | bool Connection::AttachDatabase(const base::FilePath& other_db_path, |
| 743 | const char* attachment_point) { |
| 744 | DCHECK(ValidAttachmentPoint(attachment_point)); |
| 745 | |
| 746 | Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?")); |
| 747 | #if OS_WIN |
| 748 | s.BindString16(0, other_db_path.value()); |
| 749 | #else |
| 750 | s.BindString(0, other_db_path.value()); |
| 751 | #endif |
| 752 | s.BindString(1, attachment_point); |
| 753 | return s.Run(); |
| 754 | } |
| 755 | |
| 756 | bool Connection::DetachDatabase(const char* attachment_point) { |
| 757 | DCHECK(ValidAttachmentPoint(attachment_point)); |
| 758 | |
| 759 | Statement s(GetUniqueStatement("DETACH DATABASE ?")); |
| 760 | s.BindString(0, attachment_point); |
| 761 | return s.Run(); |
| 762 | } |
| 763 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 764 | // TODO(shess): Consider changing this to execute exactly one statement. If a |
| 765 | // caller wishes to execute multiple statements, that should be explicit, and |
| 766 | // perhaps tucked into an explicit transaction with rollback in case of error. |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 767 | int Connection::ExecuteAndReturnErrorCode(const char* sql) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 768 | AssertIOAllowed(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 769 | if (!db_) { |
| 770 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
| 771 | return SQLITE_ERROR; |
| 772 | } |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 773 | DCHECK(sql); |
| 774 | |
| 775 | RecordOneEvent(EVENT_EXECUTE); |
| 776 | int rc = SQLITE_OK; |
| 777 | while ((rc == SQLITE_OK) && *sql) { |
| 778 | sqlite3_stmt *stmt = NULL; |
| 779 | const char *leftover_sql; |
| 780 | |
| 781 | const base::TimeTicks before = Now(); |
| 782 | rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql); |
| 783 | sql = leftover_sql; |
| 784 | |
| 785 | // Stop if an error is encountered. |
| 786 | if (rc != SQLITE_OK) |
| 787 | break; |
| 788 | |
| 789 | // This happens if |sql| originally only contained comments or whitespace. |
| 790 | // TODO(shess): Audit to see if this can become a DCHECK(). Having |
| 791 | // extraneous comments and whitespace in the SQL statements increases |
| 792 | // runtime cost and can easily be shifted out to the C++ layer. |
| 793 | if (!stmt) |
| 794 | continue; |
| 795 | |
| 796 | // Save for use after statement is finalized. |
| 797 | const bool read_only = !!sqlite3_stmt_readonly(stmt); |
| 798 | |
| 799 | RecordOneEvent(Connection::EVENT_STATEMENT_RUN); |
| 800 | while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { |
| 801 | // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA |
| 802 | // is the only legitimate case for this. |
| 803 | RecordOneEvent(Connection::EVENT_STATEMENT_ROWS); |
| 804 | } |
| 805 | |
| 806 | // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step() |
| 807 | // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code. |
| 808 | rc = sqlite3_finalize(stmt); |
| 809 | if (rc == SQLITE_OK) |
| 810 | RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS); |
| 811 | |
| 812 | // sqlite3_exec() does this, presumably to avoid spinning the parser for |
| 813 | // trailing whitespace. |
| 814 | // TODO(shess): Audit to see if this can become a DCHECK. |
brettw | b341306 | 2015-06-24 00:39:02 | [diff] [blame] | 815 | while (base::IsAsciiWhitespace(*sql)) { |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 816 | sql++; |
| 817 | } |
| 818 | |
| 819 | const base::TimeDelta delta = Now() - before; |
| 820 | RecordTimeAndChanges(delta, read_only); |
| 821 | } |
| 822 | return rc; |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 823 | } |
| 824 | |
| 825 | bool Connection::Execute(const char* sql) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 826 | if (!db_) { |
| 827 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
| 828 | return false; |
| 829 | } |
| 830 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 831 | int error = ExecuteAndReturnErrorCode(sql); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 832 | if (error != SQLITE_OK) |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 833 | error = OnSqliteError(error, NULL, sql); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 834 | |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 835 | // This needs to be a FATAL log because the error case of arriving here is |
| 836 | // that there's a malformed SQL statement. This can arise in development if |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 837 | // a change alters the schema but not all queries adjust. This can happen |
| 838 | // in production if the schema is corrupted. |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 839 | if (error == SQLITE_ERROR) |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 840 | DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage(); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 841 | return error == SQLITE_OK; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 842 | } |
| 843 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 844 | bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 845 | if (!db_) { |
| 846 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 847 | return false; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 848 | } |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 849 | |
| 850 | ScopedBusyTimeout busy_timeout(db_); |
| 851 | busy_timeout.SetTimeout(timeout); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 852 | return Execute(sql); |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 853 | } |
| 854 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 855 | bool Connection::HasCachedStatement(const StatementID& id) const { |
| 856 | return statement_cache_.find(id) != statement_cache_.end(); |
| 857 | } |
| 858 | |
| 859 | scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement( |
| 860 | const StatementID& id, |
| 861 | const char* sql) { |
| 862 | CachedStatementMap::iterator i = statement_cache_.find(id); |
| 863 | if (i != statement_cache_.end()) { |
| 864 | // Statement is in the cache. It should still be active (we're the only |
| 865 | // one invalidating cached statements, and we'll remove it from the cache |
| 866 | // if we do that. Make sure we reset it before giving out the cached one in |
| 867 | // case it still has some stuff bound. |
| 868 | DCHECK(i->second->is_valid()); |
| 869 | sqlite3_reset(i->second->stmt()); |
| 870 | return i->second; |
| 871 | } |
| 872 | |
| 873 | scoped_refptr<StatementRef> statement = GetUniqueStatement(sql); |
| 874 | if (statement->is_valid()) |
| 875 | statement_cache_[id] = statement; // Only cache valid statements. |
| 876 | return statement; |
| 877 | } |
| 878 | |
| 879 | scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement( |
| 880 | const char* sql) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 881 | AssertIOAllowed(); |
| 882 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 883 | // Return inactive statement. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 884 | if (!db_) |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 885 | return new StatementRef(NULL, NULL, poisoned_); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 886 | |
| 887 | sqlite3_stmt* stmt = NULL; |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 888 | int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL); |
| 889 | if (rc != SQLITE_OK) { |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 890 | // This is evidence of a syntax error in the incoming SQL. |
shess | 193bfb62 | 2015-04-10 22:30:02 | [diff] [blame] | 891 | if (!ShouldIgnoreSqliteError(rc)) |
| 892 | DLOG(FATAL) << "SQL compile error " << GetErrorMessage(); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 893 | |
| 894 | // It could also be database corruption. |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 895 | OnSqliteError(rc, NULL, sql); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 896 | return new StatementRef(NULL, NULL, false); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 897 | } |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 898 | return new StatementRef(this, stmt, true); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 899 | } |
| 900 | |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 901 | scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement( |
| 902 | const char* sql) const { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 903 | // Return inactive statement. |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 904 | if (!db_) |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 905 | return new StatementRef(NULL, NULL, poisoned_); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 906 | |
| 907 | sqlite3_stmt* stmt = NULL; |
| 908 | int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL); |
| 909 | if (rc != SQLITE_OK) { |
| 910 | // This is evidence of a syntax error in the incoming SQL. |
shess | 193bfb62 | 2015-04-10 22:30:02 | [diff] [blame] | 911 | if (!ShouldIgnoreSqliteError(rc)) |
| 912 | DLOG(FATAL) << "SQL compile error " << GetErrorMessage(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 913 | return new StatementRef(NULL, NULL, false); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 914 | } |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 915 | return new StatementRef(NULL, stmt, true); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 916 | } |
| 917 | |
[email protected] | 92cd00a | 2013-08-16 11:09:58 | [diff] [blame] | 918 | std::string Connection::GetSchema() const { |
| 919 | // The ORDER BY should not be necessary, but relying on organic |
| 920 | // order for something like this is questionable. |
| 921 | const char* kSql = |
| 922 | "SELECT type, name, tbl_name, sql " |
| 923 | "FROM sqlite_master ORDER BY 1, 2, 3, 4"; |
| 924 | Statement statement(GetUntrackedStatement(kSql)); |
| 925 | |
| 926 | std::string schema; |
| 927 | while (statement.Step()) { |
| 928 | schema += statement.ColumnString(0); |
| 929 | schema += '|'; |
| 930 | schema += statement.ColumnString(1); |
| 931 | schema += '|'; |
| 932 | schema += statement.ColumnString(2); |
| 933 | schema += '|'; |
| 934 | schema += statement.ColumnString(3); |
| 935 | schema += '\n'; |
| 936 | } |
| 937 | |
| 938 | return schema; |
| 939 | } |
| 940 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 941 | bool Connection::IsSQLValid(const char* sql) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 942 | AssertIOAllowed(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 943 | if (!db_) { |
| 944 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
| 945 | return false; |
| 946 | } |
| 947 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 948 | sqlite3_stmt* stmt = NULL; |
| 949 | if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK) |
| 950 | return false; |
| 951 | |
| 952 | sqlite3_finalize(stmt); |
| 953 | return true; |
| 954 | } |
| 955 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 956 | bool Connection::DoesTableExist(const char* table_name) const { |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 957 | return DoesTableOrIndexExist(table_name, "table"); |
| 958 | } |
| 959 | |
| 960 | bool Connection::DoesIndexExist(const char* index_name) const { |
| 961 | return DoesTableOrIndexExist(index_name, "index"); |
| 962 | } |
| 963 | |
| 964 | bool Connection::DoesTableOrIndexExist( |
| 965 | const char* name, const char* type) const { |
shess | 92a2ab1 | 2015-04-09 01:59:47 | [diff] [blame] | 966 | const char* kSql = |
| 967 | "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE"; |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 968 | Statement statement(GetUntrackedStatement(kSql)); |
shess | 92a2ab1 | 2015-04-09 01:59:47 | [diff] [blame] | 969 | |
| 970 | // This can happen if the database is corrupt and the error is being ignored |
| 971 | // for testing purposes. |
| 972 | if (!statement.is_valid()) |
| 973 | return false; |
| 974 | |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 975 | statement.BindString(0, type); |
| 976 | statement.BindString(1, name); |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 977 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 978 | return statement.Step(); // Table exists if any row was returned. |
| 979 | } |
| 980 | |
| 981 | bool Connection::DoesColumnExist(const char* table_name, |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 982 | const char* column_name) const { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 983 | std::string sql("PRAGMA TABLE_INFO("); |
| 984 | sql.append(table_name); |
| 985 | sql.append(")"); |
| 986 | |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 987 | Statement statement(GetUntrackedStatement(sql.c_str())); |
shess | 92a2ab1 | 2015-04-09 01:59:47 | [diff] [blame] | 988 | |
| 989 | // This can happen if the database is corrupt and the error is being ignored |
| 990 | // for testing purposes. |
| 991 | if (!statement.is_valid()) |
| 992 | return false; |
| 993 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 994 | while (statement.Step()) { |
brettw | 8a80090 | 2015-07-10 18:28:33 | [diff] [blame^] | 995 | if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1), |
| 996 | column_name)) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 997 | return true; |
| 998 | } |
| 999 | return false; |
| 1000 | } |
| 1001 | |
tfarina | 720d4f3 | 2015-05-11 22:31:26 | [diff] [blame] | 1002 | int64_t Connection::GetLastInsertRowId() const { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1003 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1004 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1005 | return 0; |
| 1006 | } |
| 1007 | return sqlite3_last_insert_rowid(db_); |
| 1008 | } |
| 1009 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 1010 | int Connection::GetLastChangeCount() const { |
| 1011 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1012 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 1013 | return 0; |
| 1014 | } |
| 1015 | return sqlite3_changes(db_); |
| 1016 | } |
| 1017 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1018 | int Connection::GetErrorCode() const { |
| 1019 | if (!db_) |
| 1020 | return SQLITE_ERROR; |
| 1021 | return sqlite3_errcode(db_); |
| 1022 | } |
| 1023 | |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 1024 | int Connection::GetLastErrno() const { |
| 1025 | if (!db_) |
| 1026 | return -1; |
| 1027 | |
| 1028 | int err = 0; |
| 1029 | if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err)) |
| 1030 | return -2; |
| 1031 | |
| 1032 | return err; |
| 1033 | } |
| 1034 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1035 | const char* Connection::GetErrorMessage() const { |
| 1036 | if (!db_) |
| 1037 | return "sql::Connection has no connection."; |
| 1038 | return sqlite3_errmsg(db_); |
| 1039 | } |
| 1040 | |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1041 | bool Connection::OpenInternal(const std::string& file_name, |
| 1042 | Connection::Retry retry_flag) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 1043 | AssertIOAllowed(); |
| 1044 | |
[email protected] | 9cfbc92 | 2009-11-17 20:13:17 | [diff] [blame] | 1045 | if (db_) { |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1046 | DLOG(FATAL) << "sql::Connection is already open."; |
[email protected] | 9cfbc92 | 2009-11-17 20:13:17 | [diff] [blame] | 1047 | return false; |
| 1048 | } |
| 1049 | |
[email protected] | a7ec129 | 2013-07-22 22:02:18 | [diff] [blame] | 1050 | // Make sure sqlite3_initialize() is called before anything else. |
| 1051 | InitializeSqlite(); |
| 1052 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1053 | // Setup the stats histograms immediately rather than allocating lazily. |
| 1054 | // Connections which won't exercise all of these probably shouldn't exist. |
| 1055 | if (!histogram_tag_.empty()) { |
| 1056 | stats_histogram_ = |
| 1057 | base::LinearHistogram::FactoryGet( |
| 1058 | "Sqlite.Stats." + histogram_tag_, |
| 1059 | 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1, |
| 1060 | base::HistogramBase::kUmaTargetedHistogramFlag); |
| 1061 | |
| 1062 | // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an |
| 1063 | // unreasonable time for any single operation, so there is not much value to |
| 1064 | // knowing if it was 3 minutes or 5 minutes. In reality at that point |
| 1065 | // things are entirely busted. |
| 1066 | commit_time_histogram_ = |
| 1067 | GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_); |
| 1068 | |
| 1069 | autocommit_time_histogram_ = |
| 1070 | GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_); |
| 1071 | |
| 1072 | update_time_histogram_ = |
| 1073 | GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_); |
| 1074 | |
| 1075 | query_time_histogram_ = |
| 1076 | GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_); |
| 1077 | } |
| 1078 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1079 | // If |poisoned_| is set, it means an error handler called |
| 1080 | // RazeAndClose(). Until regular Close() is called, the caller |
| 1081 | // should be treating the database as open, but is_open() currently |
| 1082 | // only considers the sqlite3 handle's state. |
| 1083 | // TODO(shess): Revise is_open() to consider poisoned_, and review |
| 1084 | // to see if any non-testing code even depends on it. |
| 1085 | DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open."; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 1086 | poisoned_ = false; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 1087 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1088 | int err = sqlite3_open(file_name.c_str(), &db_); |
| 1089 | if (err != SQLITE_OK) { |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 1090 | // Extended error codes cannot be enabled until a handle is |
| 1091 | // available, fetch manually. |
| 1092 | err = sqlite3_extended_errcode(db_); |
| 1093 | |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 1094 | // Histogram failures specific to initial open for debugging |
| 1095 | // purposes. |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 1096 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err); |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 1097 | |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 1098 | OnSqliteError(err, NULL, "-- sqlite3_open()"); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1099 | bool was_poisoned = poisoned_; |
[email protected] | 6402104 | 2012-02-10 20:02:29 | [diff] [blame] | 1100 | Close(); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1101 | |
| 1102 | if (was_poisoned && retry_flag == RETRY_ON_POISON) |
| 1103 | return OpenInternal(file_name, NO_RETRY); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1104 | return false; |
| 1105 | } |
| 1106 | |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame] | 1107 | // TODO(shess): OS_WIN support? |
| 1108 | #if defined(OS_POSIX) |
| 1109 | if (restrict_to_user_) { |
| 1110 | DCHECK_NE(file_name, std::string(":memory")); |
| 1111 | base::FilePath file_path(file_name); |
| 1112 | int mode = 0; |
| 1113 | // TODO(shess): Arguably, failure to retrieve and change |
| 1114 | // permissions should be fatal if the file exists. |
[email protected] | b264eab | 2013-11-27 23:22:08 | [diff] [blame] | 1115 | if (base::GetPosixFilePermissions(file_path, &mode)) { |
| 1116 | mode &= base::FILE_PERMISSION_USER_MASK; |
| 1117 | base::SetPosixFilePermissions(file_path, mode); |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame] | 1118 | |
| 1119 | // SQLite sets the permissions on these files from the main |
| 1120 | // database on create. Set them here in case they already exist |
| 1121 | // at this point. Failure to set these permissions should not |
| 1122 | // be fatal unless the file doesn't exist. |
| 1123 | base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal")); |
| 1124 | base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal")); |
[email protected] | b264eab | 2013-11-27 23:22:08 | [diff] [blame] | 1125 | base::SetPosixFilePermissions(journal_path, mode); |
| 1126 | base::SetPosixFilePermissions(wal_path, mode); |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame] | 1127 | } |
| 1128 | } |
| 1129 | #endif // defined(OS_POSIX) |
| 1130 | |
[email protected] | affa2da | 2013-06-06 22:20:34 | [diff] [blame] | 1131 | // SQLite uses a lookaside buffer to improve performance of small mallocs. |
| 1132 | // Chromium already depends on small mallocs being efficient, so we disable |
| 1133 | // this to avoid the extra memory overhead. |
| 1134 | // This must be called immediatly after opening the database before any SQL |
| 1135 | // statements are run. |
| 1136 | sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0); |
| 1137 | |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 1138 | // Enable extended result codes to provide more color on I/O errors. |
| 1139 | // Not having extended result codes is not a fatal problem, as |
| 1140 | // Chromium code does not attempt to handle I/O errors anyhow. The |
| 1141 | // current implementation always returns SQLITE_OK, the DCHECK is to |
| 1142 | // quickly notify someone if SQLite changes. |
| 1143 | err = sqlite3_extended_result_codes(db_, 1); |
| 1144 | DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes"; |
| 1145 | |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 1146 | // sqlite3_open() does not actually read the database file (unless a |
| 1147 | // hot journal is found). Successfully executing this pragma on an |
| 1148 | // existing database requires a valid header on page 1. |
| 1149 | // TODO(shess): For now, just probing to see what the lay of the |
| 1150 | // land is. If it's mostly SQLITE_NOTADB, then the database should |
| 1151 | // be razed. |
| 1152 | err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum"); |
| 1153 | if (err != SQLITE_OK) |
[email protected] | 73fb8d5 | 2013-07-24 05:04:28 | [diff] [blame] | 1154 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err); |
[email protected] | 658f833 | 2010-09-18 04:40:43 | [diff] [blame] | 1155 | |
[email protected] | 2e1cee76 | 2013-07-09 14:40:00 | [diff] [blame] | 1156 | #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE) |
| 1157 | // The version of SQLite shipped with iOS doesn't enable ICU, which includes |
| 1158 | // REGEXP support. Add it in dynamically. |
| 1159 | err = sqlite3IcuInit(db_); |
| 1160 | DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support"; |
| 1161 | #endif // OS_IOS && USE_SYSTEM_SQLITE |
| 1162 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1163 | // If indicated, lock up the database before doing anything else, so |
| 1164 | // that the following code doesn't have to deal with locking. |
| 1165 | // TODO(shess): This code is brittle. Find the cases where code |
| 1166 | // doesn't request |exclusive_locking_| and audit that it does the |
| 1167 | // right thing with SQLITE_BUSY, and that it doesn't make |
| 1168 | // assumptions about who might change things in the database. |
| 1169 | // http://crbug.com/56559 |
| 1170 | if (exclusive_locking_) { |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 1171 | // TODO(shess): This should probably be a failure. Code which |
| 1172 | // requests exclusive locking but doesn't get it is almost certain |
| 1173 | // to be ill-tested. |
| 1174 | ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE")); |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1175 | } |
| 1176 | |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 1177 | // http://www.sqlite.org/pragma.html#pragma_journal_mode |
| 1178 | // DELETE (default) - delete -journal file to commit. |
| 1179 | // TRUNCATE - truncate -journal file to commit. |
| 1180 | // PERSIST - zero out header of -journal file to commit. |
shess | 2c21ecf | 2015-06-02 01:31:09 | [diff] [blame] | 1181 | // TRUNCATE should be faster than DELETE because it won't need directory |
| 1182 | // changes for each transaction. PERSIST may break the spirit of using |
| 1183 | // secure_delete. |
| 1184 | ignore_result(Execute("PRAGMA journal_mode = TRUNCATE")); |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 1185 | |
[email protected] | c68ce17 | 2011-11-24 22:30:27 | [diff] [blame] | 1186 | const base::TimeDelta kBusyTimeout = |
| 1187 | base::TimeDelta::FromSeconds(kBusyTimeoutSeconds); |
| 1188 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1189 | if (page_size_ != 0) { |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1190 | // Enforce SQLite restrictions on |page_size_|. |
| 1191 | DCHECK(!(page_size_ & (page_size_ - 1))) |
| 1192 | << " page_size_ " << page_size_ << " is not a power of two."; |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 1193 | const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 1194 | DCHECK_LE(page_size_, kSqliteMaxPageSize); |
[email protected] | 7d3cbc9 | 2013-03-18 22:33:04 | [diff] [blame] | 1195 | const std::string sql = |
| 1196 | base::StringPrintf("PRAGMA page_size=%d", page_size_); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 1197 | ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout)); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1198 | } |
| 1199 | |
| 1200 | if (cache_size_ != 0) { |
[email protected] | 7d3cbc9 | 2013-03-18 22:33:04 | [diff] [blame] | 1201 | const std::string sql = |
| 1202 | base::StringPrintf("PRAGMA cache_size=%d", cache_size_); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 1203 | ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout)); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1204 | } |
| 1205 | |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 1206 | if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) { |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1207 | bool was_poisoned = poisoned_; |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 1208 | Close(); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 1209 | if (was_poisoned && retry_flag == RETRY_ON_POISON) |
| 1210 | return OpenInternal(file_name, NO_RETRY); |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 1211 | return false; |
| 1212 | } |
| 1213 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 1214 | return true; |
| 1215 | } |
| 1216 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1217 | void Connection::DoRollback() { |
| 1218 | Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK")); |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1219 | |
| 1220 | // Collect the rollback time manually, sql::Statement would register it as |
| 1221 | // query time only. |
| 1222 | const base::TimeTicks before = Now(); |
| 1223 | rollback.RunWithoutTimers(); |
| 1224 | const base::TimeDelta delta = Now() - before; |
| 1225 | |
| 1226 | RecordUpdateTime(delta); |
| 1227 | RecordOneEvent(EVENT_ROLLBACK); |
| 1228 | |
[email protected] | 44ad7d90 | 2012-03-23 00:09:05 | [diff] [blame] | 1229 | needs_rollback_ = false; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1230 | } |
| 1231 | |
| 1232 | void Connection::StatementRefCreated(StatementRef* ref) { |
| 1233 | DCHECK(open_statements_.find(ref) == open_statements_.end()); |
| 1234 | open_statements_.insert(ref); |
| 1235 | } |
| 1236 | |
| 1237 | void Connection::StatementRefDeleted(StatementRef* ref) { |
| 1238 | StatementRefSet::iterator i = open_statements_.find(ref); |
| 1239 | if (i == open_statements_.end()) |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 1240 | DLOG(FATAL) << "Could not find statement"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1241 | else |
| 1242 | open_statements_.erase(i); |
| 1243 | } |
| 1244 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1245 | void Connection::set_histogram_tag(const std::string& tag) { |
| 1246 | DCHECK(!is_open()); |
| 1247 | histogram_tag_ = tag; |
| 1248 | } |
| 1249 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 1250 | void Connection::AddTaggedHistogram(const std::string& name, |
| 1251 | size_t sample) const { |
| 1252 | if (histogram_tag_.empty()) |
| 1253 | return; |
| 1254 | |
| 1255 | // TODO(shess): The histogram macros create a bit of static storage |
| 1256 | // for caching the histogram object. This code shouldn't execute |
| 1257 | // often enough for such caching to be crucial. If it becomes an |
| 1258 | // issue, the object could be cached alongside histogram_prefix_. |
| 1259 | std::string full_histogram_name = name + "." + histogram_tag_; |
| 1260 | base::HistogramBase* histogram = |
| 1261 | base::SparseHistogram::FactoryGet( |
| 1262 | full_histogram_name, |
| 1263 | base::HistogramBase::kUmaTargetedHistogramFlag); |
| 1264 | if (histogram) |
| 1265 | histogram->Add(sample); |
| 1266 | } |
| 1267 | |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 1268 | int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) { |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 1269 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err); |
| 1270 | AddTaggedHistogram("Sqlite.Error", err); |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 1271 | |
| 1272 | // Always log the error. |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 1273 | if (!sql && stmt) |
| 1274 | sql = stmt->GetSQLStatement(); |
| 1275 | if (!sql) |
| 1276 | sql = "-- unknown"; |
| 1277 | LOG(ERROR) << histogram_tag_ << " sqlite error " << err |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 1278 | << ", errno " << GetLastErrno() |
[email protected] | 2f496b4 | 2013-09-26 18:36:58 | [diff] [blame] | 1279 | << ": " << GetErrorMessage() |
| 1280 | << ", sql: " << sql; |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 1281 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 1282 | if (!error_callback_.is_null()) { |
[email protected] | 98cf300 | 2013-07-12 01:38:56 | [diff] [blame] | 1283 | // Fire from a copy of the callback in case of reentry into |
| 1284 | // re/set_error_callback(). |
| 1285 | // TODO(shess): <http://crbug.com/254584> |
| 1286 | ErrorCallback(error_callback_).Run(err, stmt); |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 1287 | return err; |
| 1288 | } |
| 1289 | |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 1290 | // The default handling is to assert on debug and to ignore on release. |
[email protected] | 74cdede | 2013-09-25 05:39:57 | [diff] [blame] | 1291 | if (!ShouldIgnoreSqliteError(err)) |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 1292 | DLOG(FATAL) << GetErrorMessage(); |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 1293 | return err; |
| 1294 | } |
| 1295 | |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 1296 | bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) { |
| 1297 | return IntegrityCheckHelper("PRAGMA integrity_check", messages); |
| 1298 | } |
| 1299 | |
| 1300 | bool Connection::QuickIntegrityCheck() { |
| 1301 | std::vector<std::string> messages; |
| 1302 | if (!IntegrityCheckHelper("PRAGMA quick_check", &messages)) |
| 1303 | return false; |
| 1304 | return messages.size() == 1 && messages[0] == "ok"; |
| 1305 | } |
| 1306 | |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1307 | // TODO(shess): Allow specifying maximum results (default 100 lines). |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 1308 | bool Connection::IntegrityCheckHelper( |
| 1309 | const char* pragma_sql, |
| 1310 | std::vector<std::string>* messages) { |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1311 | messages->clear(); |
| 1312 | |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1313 | // This has the side effect of setting SQLITE_RecoveryMode, which |
| 1314 | // allows SQLite to process through certain cases of corruption. |
| 1315 | // Failing to set this pragma probably means that the database is |
| 1316 | // beyond recovery. |
| 1317 | const char kWritableSchema[] = "PRAGMA writable_schema = ON"; |
| 1318 | if (!Execute(kWritableSchema)) |
| 1319 | return false; |
| 1320 | |
| 1321 | bool ret = false; |
| 1322 | { |
[email protected] | 579446c | 2013-12-16 18:36:52 | [diff] [blame] | 1323 | sql::Statement stmt(GetUniqueStatement(pragma_sql)); |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1324 | |
| 1325 | // The pragma appears to return all results (up to 100 by default) |
| 1326 | // as a single string. This doesn't appear to be an API contract, |
| 1327 | // it could return separate lines, so loop _and_ split. |
| 1328 | while (stmt.Step()) { |
| 1329 | std::string result(stmt.ColumnString(0)); |
| 1330 | base::SplitString(result, '\n', messages); |
| 1331 | } |
| 1332 | ret = stmt.Succeeded(); |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1333 | } |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 1334 | |
| 1335 | // Best effort to put things back as they were before. |
| 1336 | const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF"; |
| 1337 | ignore_result(Execute(kNoWritableSchema)); |
| 1338 | |
| 1339 | return ret; |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 1340 | } |
| 1341 | |
shess | 58b8df8 | 2015-06-03 00:19:32 | [diff] [blame] | 1342 | base::TimeTicks TimeSource::Now() { |
| 1343 | return base::TimeTicks::Now(); |
| 1344 | } |
| 1345 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 1346 | } // namespace sql |