[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" |
[email protected] | 348ac8f5 | 2013-05-21 03:27:02 | [diff] [blame] | 10 | #include "base/file_util.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 11 | #include "base/logging.h" |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 12 | #include "base/metrics/histogram.h" |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 13 | #include "base/metrics/sparse_histogram.h" |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 14 | #include "base/strings/string_split.h" |
[email protected] | a4bbc1f9 | 2013-06-11 07:28:19 | [diff] [blame] | 15 | #include "base/strings/string_util.h" |
| 16 | #include "base/strings/stringprintf.h" |
[email protected] | 90626587 | 2013-06-07 22:40:45 | [diff] [blame] | 17 | #include "base/strings/utf_string_conversions.h" |
[email protected] | f0a54b2 | 2011-07-19 18:40:21 | [diff] [blame] | 18 | #include "sql/statement.h" |
[email protected] | e33cba4 | 2010-08-18 23:37:03 | [diff] [blame] | 19 | #include "third_party/sqlite/sqlite3.h" |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 20 | |
[email protected] | 2e1cee76 | 2013-07-09 14:40:00 | [diff] [blame] | 21 | #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE) |
| 22 | #include "third_party/sqlite/src/ext/icu/sqliteicu.h" |
| 23 | #endif |
| 24 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 25 | namespace { |
| 26 | |
| 27 | // Spin for up to a second waiting for the lock to clear when setting |
| 28 | // up the database. |
| 29 | // TODO(shess): Better story on this. http://crbug.com/56559 |
[email protected] | c68ce17 | 2011-11-24 22:30:27 | [diff] [blame] | 30 | const int kBusyTimeoutSeconds = 1; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 31 | |
| 32 | class ScopedBusyTimeout { |
| 33 | public: |
| 34 | explicit ScopedBusyTimeout(sqlite3* db) |
| 35 | : db_(db) { |
| 36 | } |
| 37 | ~ScopedBusyTimeout() { |
| 38 | sqlite3_busy_timeout(db_, 0); |
| 39 | } |
| 40 | |
| 41 | int SetTimeout(base::TimeDelta timeout) { |
| 42 | DCHECK_LT(timeout.InMilliseconds(), INT_MAX); |
| 43 | return sqlite3_busy_timeout(db_, |
| 44 | static_cast<int>(timeout.InMilliseconds())); |
| 45 | } |
| 46 | |
| 47 | private: |
| 48 | sqlite3* db_; |
| 49 | }; |
| 50 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 51 | // Helper to "safely" enable writable_schema. No error checking |
| 52 | // because it is reasonable to just forge ahead in case of an error. |
| 53 | // If turning it on fails, then most likely nothing will work, whereas |
| 54 | // if turning it off fails, it only matters if some code attempts to |
| 55 | // continue working with the database and tries to modify the |
| 56 | // sqlite_master table (none of our code does this). |
| 57 | class ScopedWritableSchema { |
| 58 | public: |
| 59 | explicit ScopedWritableSchema(sqlite3* db) |
| 60 | : db_(db) { |
| 61 | sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL); |
| 62 | } |
| 63 | ~ScopedWritableSchema() { |
| 64 | sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL); |
| 65 | } |
| 66 | |
| 67 | private: |
| 68 | sqlite3* db_; |
| 69 | }; |
| 70 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 71 | // Helper to wrap the sqlite3_backup_*() step of Raze(). Return |
| 72 | // SQLite error code from running the backup step. |
| 73 | int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) { |
| 74 | DCHECK_NE(src, dst); |
| 75 | sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name); |
| 76 | if (!backup) { |
| 77 | // Since this call only sets things up, this indicates a gross |
| 78 | // error in SQLite. |
| 79 | DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst); |
| 80 | return sqlite3_errcode(dst); |
| 81 | } |
| 82 | |
| 83 | // -1 backs up the entire database. |
| 84 | int rc = sqlite3_backup_step(backup, -1); |
| 85 | int pages = sqlite3_backup_pagecount(backup); |
| 86 | sqlite3_backup_finish(backup); |
| 87 | |
| 88 | // If successful, exactly one page should have been backed up. If |
| 89 | // this breaks, check this function to make sure assumptions aren't |
| 90 | // being broken. |
| 91 | if (rc == SQLITE_DONE) |
| 92 | DCHECK_EQ(pages, 1); |
| 93 | |
| 94 | return rc; |
| 95 | } |
| 96 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 97 | } // namespace |
| 98 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 99 | namespace sql { |
| 100 | |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 101 | // static |
| 102 | Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL; |
| 103 | |
| 104 | // static |
| 105 | bool Connection::ShouldIgnore(int error) { |
| 106 | if (!current_ignorer_cb_) |
| 107 | return false; |
| 108 | return current_ignorer_cb_->Run(error); |
| 109 | } |
| 110 | |
| 111 | // static |
| 112 | void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) { |
| 113 | CHECK(current_ignorer_cb_ == NULL); |
| 114 | current_ignorer_cb_ = cb; |
| 115 | } |
| 116 | |
| 117 | // static |
| 118 | void Connection::ResetErrorIgnorer() { |
| 119 | CHECK(current_ignorer_cb_); |
| 120 | current_ignorer_cb_ = NULL; |
| 121 | } |
| 122 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 123 | bool StatementID::operator<(const StatementID& other) const { |
| 124 | if (number_ != other.number_) |
| 125 | return number_ < other.number_; |
| 126 | return strcmp(str_, other.str_) < 0; |
| 127 | } |
| 128 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 129 | Connection::StatementRef::StatementRef(Connection* connection, |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 130 | sqlite3_stmt* stmt, |
| 131 | bool was_valid) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 132 | : connection_(connection), |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 133 | stmt_(stmt), |
| 134 | was_valid_(was_valid) { |
| 135 | if (connection) |
| 136 | connection_->StatementRefCreated(this); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 137 | } |
| 138 | |
| 139 | Connection::StatementRef::~StatementRef() { |
| 140 | if (connection_) |
| 141 | connection_->StatementRefDeleted(this); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 142 | Close(false); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 143 | } |
| 144 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 145 | void Connection::StatementRef::Close(bool forced) { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 146 | if (stmt_) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 147 | // Call to AssertIOAllowed() cannot go at the beginning of the function |
| 148 | // because Close() is called unconditionally from destructor to clean |
| 149 | // connection_. And if this is inactive statement this won't cause any |
| 150 | // disk access and destructor most probably will be called on thread |
| 151 | // not allowing disk access. |
| 152 | // TODO([email protected]): This should move to the beginning |
| 153 | // of the function. http://crbug.com/136655. |
| 154 | AssertIOAllowed(); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 155 | sqlite3_finalize(stmt_); |
| 156 | stmt_ = NULL; |
| 157 | } |
| 158 | connection_ = NULL; // The connection may be getting deleted. |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 159 | |
| 160 | // Forced close is expected to happen from a statement error |
| 161 | // handler. In that case maintain the sense of |was_valid_| which |
| 162 | // previously held for this ref. |
| 163 | was_valid_ = was_valid_ && forced; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 164 | } |
| 165 | |
| 166 | Connection::Connection() |
| 167 | : db_(NULL), |
| 168 | page_size_(0), |
| 169 | cache_size_(0), |
| 170 | exclusive_locking_(false), |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame^] | 171 | restrict_to_user_(false), |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 172 | transaction_nesting_(0), |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 173 | needs_rollback_(false), |
[email protected] | 49dc4f2 | 2012-10-17 17:41:16 | [diff] [blame] | 174 | in_memory_(false), |
[email protected] | 526b466 | 2013-06-14 04:09:12 | [diff] [blame] | 175 | poisoned_(false) { |
| 176 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 177 | |
| 178 | Connection::~Connection() { |
| 179 | Close(); |
| 180 | } |
| 181 | |
[email protected] | a3ef483 | 2013-02-02 05:12:33 | [diff] [blame] | 182 | bool Connection::Open(const base::FilePath& path) { |
[email protected] | 348ac8f5 | 2013-05-21 03:27:02 | [diff] [blame] | 183 | if (!histogram_tag_.empty()) { |
| 184 | int64 size_64 = 0; |
| 185 | if (file_util::GetFileSize(path, &size_64)) { |
| 186 | size_t sample = static_cast<size_t>(size_64 / 1024); |
| 187 | std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_; |
| 188 | base::HistogramBase* histogram = |
| 189 | base::Histogram::FactoryGet( |
| 190 | full_histogram_name, 1, 1000000, 50, |
| 191 | base::HistogramBase::kUmaTargetedHistogramFlag); |
| 192 | if (histogram) |
| 193 | histogram->Add(sample); |
| 194 | } |
| 195 | } |
| 196 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 197 | #if defined(OS_WIN) |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 198 | return OpenInternal(WideToUTF8(path.value()), RETRY_ON_POISON); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 199 | #elif defined(OS_POSIX) |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 200 | return OpenInternal(path.value(), RETRY_ON_POISON); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 201 | #endif |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 202 | } |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 203 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 204 | bool Connection::OpenInMemory() { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 205 | in_memory_ = true; |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 206 | return OpenInternal(":memory:", NO_RETRY); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 207 | } |
| 208 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 209 | void Connection::CloseInternal(bool forced) { |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 210 | // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point |
| 211 | // will delete the -journal file. For ChromiumOS or other more |
| 212 | // embedded systems, this is probably not appropriate, whereas on |
| 213 | // desktop it might make some sense. |
| 214 | |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 215 | // sqlite3_close() needs all prepared statements to be finalized. |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 216 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 217 | // Release cached statements. |
| 218 | statement_cache_.clear(); |
| 219 | |
| 220 | // With cached statements released, in-use statements will remain. |
| 221 | // Closing the database while statements are in use is an API |
| 222 | // violation, except for forced close (which happens from within a |
| 223 | // statement's error handler). |
| 224 | DCHECK(forced || open_statements_.empty()); |
| 225 | |
| 226 | // Deactivate any outstanding statements so sqlite3_close() works. |
| 227 | for (StatementRefSet::iterator i = open_statements_.begin(); |
| 228 | i != open_statements_.end(); ++i) |
| 229 | (*i)->Close(forced); |
| 230 | open_statements_.clear(); |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 231 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 232 | if (db_) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 233 | // Call to AssertIOAllowed() cannot go at the beginning of the function |
| 234 | // because Close() must be called from destructor to clean |
| 235 | // statement_cache_, it won't cause any disk access and it most probably |
| 236 | // will happen on thread not allowing disk access. |
| 237 | // TODO([email protected]): This should move to the beginning |
| 238 | // of the function. http://crbug.com/136655. |
| 239 | AssertIOAllowed(); |
[email protected] | 4b35005 | 2012-02-24 20:40:48 | [diff] [blame] | 240 | // TODO(shess): Histogram for failure. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 241 | sqlite3_close(db_); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 242 | } |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 243 | db_ = NULL; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 244 | } |
| 245 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 246 | void Connection::Close() { |
| 247 | // If the database was already closed by RazeAndClose(), then no |
| 248 | // need to close again. Clear the |poisoned_| bit so that incorrect |
| 249 | // API calls are caught. |
| 250 | if (poisoned_) { |
| 251 | poisoned_ = false; |
| 252 | return; |
| 253 | } |
| 254 | |
| 255 | CloseInternal(false); |
| 256 | } |
| 257 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 258 | void Connection::Preload() { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 259 | AssertIOAllowed(); |
| 260 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 261 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 262 | DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 263 | return; |
| 264 | } |
| 265 | |
| 266 | // A statement must be open for the preload command to work. If the meta |
| 267 | // table doesn't exist, it probably means this is a new database and there |
| 268 | // is nothing to preload (so it's OK we do nothing). |
| 269 | if (!DoesTableExist("meta")) |
| 270 | return; |
| 271 | Statement dummy(GetUniqueStatement("SELECT * FROM meta")); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 272 | if (!dummy.Step()) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 273 | return; |
| 274 | |
[email protected] | 4176eee4b | 2011-01-26 14:33:32 | [diff] [blame] | 275 | #if !defined(USE_SYSTEM_SQLITE) |
| 276 | // This function is only defined in Chromium's version of sqlite. |
| 277 | // Do not call it when using system sqlite. |
[email protected] | 67361b3 | 2011-04-12 20:13:06 | [diff] [blame] | 278 | sqlite3_preload(db_); |
[email protected] | 4176eee4b | 2011-01-26 14:33:32 | [diff] [blame] | 279 | #endif |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 280 | } |
| 281 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 282 | // Create an in-memory database with the existing database's page |
| 283 | // size, then backup that database over the existing database. |
| 284 | bool Connection::Raze() { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 285 | AssertIOAllowed(); |
| 286 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 287 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 288 | DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db"; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 289 | return false; |
| 290 | } |
| 291 | |
| 292 | if (transaction_nesting_ > 0) { |
| 293 | DLOG(FATAL) << "Cannot raze within a transaction"; |
| 294 | return false; |
| 295 | } |
| 296 | |
| 297 | sql::Connection null_db; |
| 298 | if (!null_db.OpenInMemory()) { |
| 299 | DLOG(FATAL) << "Unable to open in-memory database."; |
| 300 | return false; |
| 301 | } |
| 302 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 303 | if (page_size_) { |
| 304 | // Enforce SQLite restrictions on |page_size_|. |
| 305 | DCHECK(!(page_size_ & (page_size_ - 1))) |
| 306 | << " page_size_ " << page_size_ << " is not a power of two."; |
| 307 | const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h |
| 308 | DCHECK_LE(page_size_, kSqliteMaxPageSize); |
[email protected] | 7d3cbc9 | 2013-03-18 22:33:04 | [diff] [blame] | 309 | const std::string sql = |
| 310 | base::StringPrintf("PRAGMA page_size=%d", page_size_); |
[email protected] | 69c5845 | 2012-08-06 19:22:42 | [diff] [blame] | 311 | if (!null_db.Execute(sql.c_str())) |
| 312 | return false; |
| 313 | } |
| 314 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 315 | #if defined(OS_ANDROID) |
| 316 | // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately, |
| 317 | // in-memory databases do not respect this define. |
| 318 | // TODO(shess): Figure out a way to set this without using platform |
| 319 | // specific code. AFAICT from sqlite3.c, the only way to do it |
| 320 | // would be to create an actual filesystem database, which is |
| 321 | // unfortunate. |
| 322 | if (!null_db.Execute("PRAGMA auto_vacuum = 1")) |
| 323 | return false; |
| 324 | #endif |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 325 | |
| 326 | // The page size doesn't take effect until a database has pages, and |
| 327 | // at this point the null database has none. Changing the schema |
| 328 | // version will create the first page. This will not affect the |
| 329 | // schema version in the resulting database, as SQLite's backup |
| 330 | // implementation propagates the schema version from the original |
| 331 | // connection to the new version of the database, incremented by one |
| 332 | // so that other readers see the schema change and act accordingly. |
| 333 | if (!null_db.Execute("PRAGMA schema_version = 1")) |
| 334 | return false; |
| 335 | |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 336 | // SQLite tracks the expected number of database pages in the first |
| 337 | // page, and if it does not match the total retrieved from a |
| 338 | // filesystem call, treats the database as corrupt. This situation |
| 339 | // breaks almost all SQLite calls. "PRAGMA writable_schema" can be |
| 340 | // used to hint to SQLite to soldier on in that case, specifically |
| 341 | // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in |
| 342 | // sqlite3.c lockBtree().] |
| 343 | // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA |
| 344 | // page_size" can be used to query such a database. |
| 345 | ScopedWritableSchema writable_schema(db_); |
| 346 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 347 | const char* kMain = "main"; |
| 348 | int rc = BackupDatabase(null_db.db_, db_, kMain); |
| 349 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc); |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 350 | |
| 351 | // The destination database was locked. |
| 352 | if (rc == SQLITE_BUSY) { |
| 353 | return false; |
| 354 | } |
| 355 | |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 356 | // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not |
| 357 | // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_ |
| 358 | // isn't even big enough for one page. Either way, reach in and |
| 359 | // truncate it before trying again. |
| 360 | // TODO(shess): Maybe it would be worthwhile to just truncate from |
| 361 | // the get-go? |
| 362 | if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) { |
| 363 | sqlite3_file* file = NULL; |
| 364 | rc = sqlite3_file_control(db_, "main", SQLITE_FCNTL_FILE_POINTER, &file); |
| 365 | if (rc != SQLITE_OK) { |
| 366 | DLOG(FATAL) << "Failure getting file handle."; |
| 367 | return false; |
| 368 | } else if (!file) { |
| 369 | DLOG(FATAL) << "File handle is empty."; |
| 370 | return false; |
| 371 | } |
| 372 | |
| 373 | rc = file->pMethods->xTruncate(file, 0); |
| 374 | if (rc != SQLITE_OK) { |
| 375 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc); |
| 376 | DLOG(FATAL) << "Failed to truncate file."; |
| 377 | return false; |
| 378 | } |
| 379 | |
| 380 | rc = BackupDatabase(null_db.db_, db_, kMain); |
| 381 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc); |
| 382 | |
| 383 | if (rc != SQLITE_DONE) { |
| 384 | DLOG(FATAL) << "Failed retrying Raze()."; |
| 385 | } |
| 386 | } |
| 387 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 388 | // The entire database should have been backed up. |
| 389 | if (rc != SQLITE_DONE) { |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 390 | // TODO(shess): Figure out which other cases can happen. |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 391 | DLOG(FATAL) << "Unable to copy entire null database."; |
| 392 | return false; |
| 393 | } |
| 394 | |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 395 | return true; |
| 396 | } |
| 397 | |
| 398 | bool Connection::RazeWithTimout(base::TimeDelta timeout) { |
| 399 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 400 | DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db"; |
[email protected] | 8e0c0128 | 2012-04-06 19:36:49 | [diff] [blame] | 401 | return false; |
| 402 | } |
| 403 | |
| 404 | ScopedBusyTimeout busy_timeout(db_); |
| 405 | busy_timeout.SetTimeout(timeout); |
| 406 | return Raze(); |
| 407 | } |
| 408 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 409 | bool Connection::RazeAndClose() { |
| 410 | if (!db_) { |
| 411 | DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db"; |
| 412 | return false; |
| 413 | } |
| 414 | |
| 415 | // Raze() cannot run in a transaction. |
| 416 | while (transaction_nesting_) { |
| 417 | RollbackTransaction(); |
| 418 | } |
| 419 | |
| 420 | bool result = Raze(); |
| 421 | |
| 422 | CloseInternal(true); |
| 423 | |
| 424 | // Mark the database so that future API calls fail appropriately, |
| 425 | // but don't DCHECK (because after calling this function they are |
| 426 | // expected to fail). |
| 427 | poisoned_ = true; |
| 428 | |
| 429 | return result; |
| 430 | } |
| 431 | |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 432 | // TODO(shess): To the extent possible, figure out the optimal |
| 433 | // ordering for these deletes which will prevent other connections |
| 434 | // from seeing odd behavior. For instance, it may be necessary to |
| 435 | // manually lock the main database file in a SQLite-compatible fashion |
| 436 | // (to prevent other processes from opening it), then delete the |
| 437 | // journal files, then delete the main database file. Another option |
| 438 | // might be to lock the main database file and poison the header with |
| 439 | // junk to prevent other processes from opening it successfully (like |
| 440 | // Gears "SQLite poison 3" trick). |
| 441 | // |
| 442 | // static |
| 443 | bool Connection::Delete(const base::FilePath& path) { |
| 444 | base::ThreadRestrictions::AssertIOAllowed(); |
| 445 | |
| 446 | base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal")); |
| 447 | base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal")); |
| 448 | |
[email protected] | dd3aa79 | 2013-07-16 19:10:23 | [diff] [blame] | 449 | base::DeleteFile(journal_path, false); |
| 450 | base::DeleteFile(wal_path, false); |
| 451 | base::DeleteFile(path, false); |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 452 | |
[email protected] | 756748414 | 2013-07-11 17:36:07 | [diff] [blame] | 453 | return !base::PathExists(journal_path) && |
| 454 | !base::PathExists(wal_path) && |
| 455 | !base::PathExists(path); |
[email protected] | 8d2e39e | 2013-06-24 05:55:08 | [diff] [blame] | 456 | } |
| 457 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 458 | bool Connection::BeginTransaction() { |
| 459 | if (needs_rollback_) { |
[email protected] | 88563f6 | 2011-03-13 22:13:33 | [diff] [blame] | 460 | DCHECK_GT(transaction_nesting_, 0); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 461 | |
| 462 | // When we're going to rollback, fail on this begin and don't actually |
| 463 | // mark us as entering the nested transaction. |
| 464 | return false; |
| 465 | } |
| 466 | |
| 467 | bool success = true; |
| 468 | if (!transaction_nesting_) { |
| 469 | needs_rollback_ = false; |
| 470 | |
| 471 | Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION")); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 472 | if (!begin.Run()) |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 473 | return false; |
| 474 | } |
| 475 | transaction_nesting_++; |
| 476 | return success; |
| 477 | } |
| 478 | |
| 479 | void Connection::RollbackTransaction() { |
| 480 | if (!transaction_nesting_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 481 | DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 482 | return; |
| 483 | } |
| 484 | |
| 485 | transaction_nesting_--; |
| 486 | |
| 487 | if (transaction_nesting_ > 0) { |
| 488 | // Mark the outermost transaction as needing rollback. |
| 489 | needs_rollback_ = true; |
| 490 | return; |
| 491 | } |
| 492 | |
| 493 | DoRollback(); |
| 494 | } |
| 495 | |
| 496 | bool Connection::CommitTransaction() { |
| 497 | if (!transaction_nesting_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 498 | DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 499 | return false; |
| 500 | } |
| 501 | transaction_nesting_--; |
| 502 | |
| 503 | if (transaction_nesting_ > 0) { |
| 504 | // Mark any nested transactions as failing after we've already got one. |
| 505 | return !needs_rollback_; |
| 506 | } |
| 507 | |
| 508 | if (needs_rollback_) { |
| 509 | DoRollback(); |
| 510 | return false; |
| 511 | } |
| 512 | |
| 513 | Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT")); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 514 | return commit.Run(); |
| 515 | } |
| 516 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 517 | int Connection::ExecuteAndReturnErrorCode(const char* sql) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 518 | AssertIOAllowed(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 519 | if (!db_) { |
| 520 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
| 521 | return SQLITE_ERROR; |
| 522 | } |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 523 | return sqlite3_exec(db_, sql, NULL, NULL, NULL); |
| 524 | } |
| 525 | |
| 526 | bool Connection::Execute(const char* sql) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 527 | if (!db_) { |
| 528 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
| 529 | return false; |
| 530 | } |
| 531 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 532 | int error = ExecuteAndReturnErrorCode(sql); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 533 | if (error != SQLITE_OK) |
| 534 | error = OnSqliteError(error, NULL); |
| 535 | |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 536 | // This needs to be a FATAL log because the error case of arriving here is |
| 537 | // that there's a malformed SQL statement. This can arise in development if |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 538 | // a change alters the schema but not all queries adjust. This can happen |
| 539 | // in production if the schema is corrupted. |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 540 | if (error == SQLITE_ERROR) |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 541 | DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage(); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 542 | return error == SQLITE_OK; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 543 | } |
| 544 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 545 | bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 546 | if (!db_) { |
| 547 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 548 | return false; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 549 | } |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 550 | |
| 551 | ScopedBusyTimeout busy_timeout(db_); |
| 552 | busy_timeout.SetTimeout(timeout); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 553 | return Execute(sql); |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 554 | } |
| 555 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 556 | bool Connection::HasCachedStatement(const StatementID& id) const { |
| 557 | return statement_cache_.find(id) != statement_cache_.end(); |
| 558 | } |
| 559 | |
| 560 | scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement( |
| 561 | const StatementID& id, |
| 562 | const char* sql) { |
| 563 | CachedStatementMap::iterator i = statement_cache_.find(id); |
| 564 | if (i != statement_cache_.end()) { |
| 565 | // Statement is in the cache. It should still be active (we're the only |
| 566 | // one invalidating cached statements, and we'll remove it from the cache |
| 567 | // if we do that. Make sure we reset it before giving out the cached one in |
| 568 | // case it still has some stuff bound. |
| 569 | DCHECK(i->second->is_valid()); |
| 570 | sqlite3_reset(i->second->stmt()); |
| 571 | return i->second; |
| 572 | } |
| 573 | |
| 574 | scoped_refptr<StatementRef> statement = GetUniqueStatement(sql); |
| 575 | if (statement->is_valid()) |
| 576 | statement_cache_[id] = statement; // Only cache valid statements. |
| 577 | return statement; |
| 578 | } |
| 579 | |
| 580 | scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement( |
| 581 | const char* sql) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 582 | AssertIOAllowed(); |
| 583 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 584 | // Return inactive statement. |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 585 | if (!db_) |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 586 | return new StatementRef(NULL, NULL, poisoned_); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 587 | |
| 588 | sqlite3_stmt* stmt = NULL; |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 589 | int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL); |
| 590 | if (rc != SQLITE_OK) { |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 591 | // This is evidence of a syntax error in the incoming SQL. |
| 592 | DLOG(FATAL) << "SQL compile error " << GetErrorMessage(); |
[email protected] | 473ad79 | 2012-11-10 00:55:00 | [diff] [blame] | 593 | |
| 594 | // It could also be database corruption. |
| 595 | OnSqliteError(rc, NULL); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 596 | return new StatementRef(NULL, NULL, false); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 597 | } |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 598 | return new StatementRef(this, stmt, true); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 599 | } |
| 600 | |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 601 | scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement( |
| 602 | const char* sql) const { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 603 | // Return inactive statement. |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 604 | if (!db_) |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 605 | return new StatementRef(NULL, NULL, poisoned_); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 606 | |
| 607 | sqlite3_stmt* stmt = NULL; |
| 608 | int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL); |
| 609 | if (rc != SQLITE_OK) { |
| 610 | // This is evidence of a syntax error in the incoming SQL. |
| 611 | DLOG(FATAL) << "SQL compile error " << GetErrorMessage(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 612 | return new StatementRef(NULL, NULL, false); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 613 | } |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 614 | return new StatementRef(NULL, stmt, true); |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 615 | } |
| 616 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 617 | bool Connection::IsSQLValid(const char* sql) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 618 | AssertIOAllowed(); |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 619 | if (!db_) { |
| 620 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
| 621 | return false; |
| 622 | } |
| 623 | |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 624 | sqlite3_stmt* stmt = NULL; |
| 625 | if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK) |
| 626 | return false; |
| 627 | |
| 628 | sqlite3_finalize(stmt); |
| 629 | return true; |
| 630 | } |
| 631 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 632 | bool Connection::DoesTableExist(const char* table_name) const { |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 633 | return DoesTableOrIndexExist(table_name, "table"); |
| 634 | } |
| 635 | |
| 636 | bool Connection::DoesIndexExist(const char* index_name) const { |
| 637 | return DoesTableOrIndexExist(index_name, "index"); |
| 638 | } |
| 639 | |
| 640 | bool Connection::DoesTableOrIndexExist( |
| 641 | const char* name, const char* type) const { |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 642 | const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?"; |
| 643 | Statement statement(GetUntrackedStatement(kSql)); |
[email protected] | e2cadec8 | 2011-12-13 02:00:53 | [diff] [blame] | 644 | statement.BindString(0, type); |
| 645 | statement.BindString(1, name); |
[email protected] | 28fe0ff | 2012-02-25 00:40:33 | [diff] [blame] | 646 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 647 | return statement.Step(); // Table exists if any row was returned. |
| 648 | } |
| 649 | |
| 650 | bool Connection::DoesColumnExist(const char* table_name, |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 651 | const char* column_name) const { |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 652 | std::string sql("PRAGMA TABLE_INFO("); |
| 653 | sql.append(table_name); |
| 654 | sql.append(")"); |
| 655 | |
[email protected] | 2eec0a2 | 2012-07-24 01:59:58 | [diff] [blame] | 656 | Statement statement(GetUntrackedStatement(sql.c_str())); |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 657 | while (statement.Step()) { |
| 658 | if (!statement.ColumnString(1).compare(column_name)) |
| 659 | return true; |
| 660 | } |
| 661 | return false; |
| 662 | } |
| 663 | |
| 664 | int64 Connection::GetLastInsertRowId() const { |
| 665 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 666 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 667 | return 0; |
| 668 | } |
| 669 | return sqlite3_last_insert_rowid(db_); |
| 670 | } |
| 671 | |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 672 | int Connection::GetLastChangeCount() const { |
| 673 | if (!db_) { |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 674 | DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db"; |
[email protected] | 1ed78a3 | 2009-09-15 20:24:17 | [diff] [blame] | 675 | return 0; |
| 676 | } |
| 677 | return sqlite3_changes(db_); |
| 678 | } |
| 679 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 680 | int Connection::GetErrorCode() const { |
| 681 | if (!db_) |
| 682 | return SQLITE_ERROR; |
| 683 | return sqlite3_errcode(db_); |
| 684 | } |
| 685 | |
[email protected] | 767718e5 | 2010-09-21 23:18:49 | [diff] [blame] | 686 | int Connection::GetLastErrno() const { |
| 687 | if (!db_) |
| 688 | return -1; |
| 689 | |
| 690 | int err = 0; |
| 691 | if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err)) |
| 692 | return -2; |
| 693 | |
| 694 | return err; |
| 695 | } |
| 696 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 697 | const char* Connection::GetErrorMessage() const { |
| 698 | if (!db_) |
| 699 | return "sql::Connection has no connection."; |
| 700 | return sqlite3_errmsg(db_); |
| 701 | } |
| 702 | |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 703 | bool Connection::OpenInternal(const std::string& file_name, |
| 704 | Connection::Retry retry_flag) { |
[email protected] | 35f7e539 | 2012-07-27 19:54:50 | [diff] [blame] | 705 | AssertIOAllowed(); |
| 706 | |
[email protected] | 9cfbc92 | 2009-11-17 20:13:17 | [diff] [blame] | 707 | if (db_) { |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 708 | DLOG(FATAL) << "sql::Connection is already open."; |
[email protected] | 9cfbc92 | 2009-11-17 20:13:17 | [diff] [blame] | 709 | return false; |
| 710 | } |
| 711 | |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 712 | // If |poisoned_| is set, it means an error handler called |
| 713 | // RazeAndClose(). Until regular Close() is called, the caller |
| 714 | // should be treating the database as open, but is_open() currently |
| 715 | // only considers the sqlite3 handle's state. |
| 716 | // TODO(shess): Revise is_open() to consider poisoned_, and review |
| 717 | // to see if any non-testing code even depends on it. |
| 718 | DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open."; |
[email protected] | 7bae574 | 2013-07-10 20:46:16 | [diff] [blame] | 719 | poisoned_ = false; |
[email protected] | 41a97c81 | 2013-02-07 02:35:38 | [diff] [blame] | 720 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 721 | int err = sqlite3_open(file_name.c_str(), &db_); |
| 722 | if (err != SQLITE_OK) { |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 723 | // Histogram failures specific to initial open for debugging |
| 724 | // purposes. |
| 725 | UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50); |
| 726 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 727 | OnSqliteError(err, NULL); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 728 | bool was_poisoned = poisoned_; |
[email protected] | 6402104 | 2012-02-10 20:02:29 | [diff] [blame] | 729 | Close(); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 730 | |
| 731 | if (was_poisoned && retry_flag == RETRY_ON_POISON) |
| 732 | return OpenInternal(file_name, NO_RETRY); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 733 | return false; |
| 734 | } |
| 735 | |
[email protected] | 81a2a60 | 2013-07-17 19:10:36 | [diff] [blame^] | 736 | // TODO(shess): OS_WIN support? |
| 737 | #if defined(OS_POSIX) |
| 738 | if (restrict_to_user_) { |
| 739 | DCHECK_NE(file_name, std::string(":memory")); |
| 740 | base::FilePath file_path(file_name); |
| 741 | int mode = 0; |
| 742 | // TODO(shess): Arguably, failure to retrieve and change |
| 743 | // permissions should be fatal if the file exists. |
| 744 | if (file_util::GetPosixFilePermissions(file_path, &mode)) { |
| 745 | mode &= file_util::FILE_PERMISSION_USER_MASK; |
| 746 | file_util::SetPosixFilePermissions(file_path, mode); |
| 747 | |
| 748 | // SQLite sets the permissions on these files from the main |
| 749 | // database on create. Set them here in case they already exist |
| 750 | // at this point. Failure to set these permissions should not |
| 751 | // be fatal unless the file doesn't exist. |
| 752 | base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal")); |
| 753 | base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal")); |
| 754 | file_util::SetPosixFilePermissions(journal_path, mode); |
| 755 | file_util::SetPosixFilePermissions(wal_path, mode); |
| 756 | } |
| 757 | } |
| 758 | #endif // defined(OS_POSIX) |
| 759 | |
[email protected] | affa2da | 2013-06-06 22:20:34 | [diff] [blame] | 760 | // SQLite uses a lookaside buffer to improve performance of small mallocs. |
| 761 | // Chromium already depends on small mallocs being efficient, so we disable |
| 762 | // this to avoid the extra memory overhead. |
| 763 | // This must be called immediatly after opening the database before any SQL |
| 764 | // statements are run. |
| 765 | sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0); |
| 766 | |
[email protected] | bd2ccdb4a | 2012-12-07 22:14:50 | [diff] [blame] | 767 | // sqlite3_open() does not actually read the database file (unless a |
| 768 | // hot journal is found). Successfully executing this pragma on an |
| 769 | // existing database requires a valid header on page 1. |
| 770 | // TODO(shess): For now, just probing to see what the lay of the |
| 771 | // land is. If it's mostly SQLITE_NOTADB, then the database should |
| 772 | // be razed. |
| 773 | err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum"); |
| 774 | if (err != SQLITE_OK) |
| 775 | UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50); |
| 776 | |
[email protected] | 658f833 | 2010-09-18 04:40:43 | [diff] [blame] | 777 | // Enable extended result codes to provide more color on I/O errors. |
| 778 | // Not having extended result codes is not a fatal problem, as |
| 779 | // Chromium code does not attempt to handle I/O errors anyhow. The |
| 780 | // current implementation always returns SQLITE_OK, the DCHECK is to |
| 781 | // quickly notify someone if SQLite changes. |
| 782 | err = sqlite3_extended_result_codes(db_, 1); |
| 783 | DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes"; |
| 784 | |
[email protected] | 2e1cee76 | 2013-07-09 14:40:00 | [diff] [blame] | 785 | #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE) |
| 786 | // The version of SQLite shipped with iOS doesn't enable ICU, which includes |
| 787 | // REGEXP support. Add it in dynamically. |
| 788 | err = sqlite3IcuInit(db_); |
| 789 | DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support"; |
| 790 | #endif // OS_IOS && USE_SYSTEM_SQLITE |
| 791 | |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 792 | // If indicated, lock up the database before doing anything else, so |
| 793 | // that the following code doesn't have to deal with locking. |
| 794 | // TODO(shess): This code is brittle. Find the cases where code |
| 795 | // doesn't request |exclusive_locking_| and audit that it does the |
| 796 | // right thing with SQLITE_BUSY, and that it doesn't make |
| 797 | // assumptions about who might change things in the database. |
| 798 | // http://crbug.com/56559 |
| 799 | if (exclusive_locking_) { |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 800 | // TODO(shess): This should probably be a failure. Code which |
| 801 | // requests exclusive locking but doesn't get it is almost certain |
| 802 | // to be ill-tested. |
| 803 | ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE")); |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 804 | } |
| 805 | |
[email protected] | 4e179ba | 2012-03-17 16:06:47 | [diff] [blame] | 806 | // http://www.sqlite.org/pragma.html#pragma_journal_mode |
| 807 | // DELETE (default) - delete -journal file to commit. |
| 808 | // TRUNCATE - truncate -journal file to commit. |
| 809 | // PERSIST - zero out header of -journal file to commit. |
| 810 | // journal_size_limit provides size to trim to in PERSIST. |
| 811 | // TODO(shess): Figure out if PERSIST and journal_size_limit really |
| 812 | // matter. In theory, it keeps pages pre-allocated, so if |
| 813 | // transactions usually fit, it should be faster. |
| 814 | ignore_result(Execute("PRAGMA journal_mode = PERSIST")); |
| 815 | ignore_result(Execute("PRAGMA journal_size_limit = 16384")); |
| 816 | |
[email protected] | c68ce17 | 2011-11-24 22:30:27 | [diff] [blame] | 817 | const base::TimeDelta kBusyTimeout = |
| 818 | base::TimeDelta::FromSeconds(kBusyTimeoutSeconds); |
| 819 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 820 | if (page_size_ != 0) { |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 821 | // Enforce SQLite restrictions on |page_size_|. |
| 822 | DCHECK(!(page_size_ & (page_size_ - 1))) |
| 823 | << " page_size_ " << page_size_ << " is not a power of two."; |
[email protected] | 6d42f15 | 2012-11-10 00:38:24 | [diff] [blame] | 824 | const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h |
[email protected] | 5b96f377 | 2010-09-28 16:30:57 | [diff] [blame] | 825 | DCHECK_LE(page_size_, kSqliteMaxPageSize); |
[email protected] | 7d3cbc9 | 2013-03-18 22:33:04 | [diff] [blame] | 826 | const std::string sql = |
| 827 | base::StringPrintf("PRAGMA page_size=%d", page_size_); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 828 | ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout)); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 829 | } |
| 830 | |
| 831 | if (cache_size_ != 0) { |
[email protected] | 7d3cbc9 | 2013-03-18 22:33:04 | [diff] [blame] | 832 | const std::string sql = |
| 833 | base::StringPrintf("PRAGMA cache_size=%d", cache_size_); |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 834 | ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout)); |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 835 | } |
| 836 | |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 837 | if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) { |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 838 | bool was_poisoned = poisoned_; |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 839 | Close(); |
[email protected] | fed734a | 2013-07-17 04:45:13 | [diff] [blame] | 840 | if (was_poisoned && retry_flag == RETRY_ON_POISON) |
| 841 | return OpenInternal(file_name, NO_RETRY); |
[email protected] | 6e0b144 | 2011-08-09 23:23:58 | [diff] [blame] | 842 | return false; |
| 843 | } |
| 844 | |
[email protected] | 765b4450 | 2009-10-02 05:01:42 | [diff] [blame] | 845 | return true; |
| 846 | } |
| 847 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 848 | void Connection::DoRollback() { |
| 849 | Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK")); |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 850 | rollback.Run(); |
[email protected] | 44ad7d90 | 2012-03-23 00:09:05 | [diff] [blame] | 851 | needs_rollback_ = false; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 852 | } |
| 853 | |
| 854 | void Connection::StatementRefCreated(StatementRef* ref) { |
| 855 | DCHECK(open_statements_.find(ref) == open_statements_.end()); |
| 856 | open_statements_.insert(ref); |
| 857 | } |
| 858 | |
| 859 | void Connection::StatementRefDeleted(StatementRef* ref) { |
| 860 | StatementRefSet::iterator i = open_statements_.find(ref); |
| 861 | if (i == open_statements_.end()) |
[email protected] | eff1fa52 | 2011-12-12 23:50:59 | [diff] [blame] | 862 | DLOG(FATAL) << "Could not find statement"; |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 863 | else |
| 864 | open_statements_.erase(i); |
| 865 | } |
| 866 | |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 867 | void Connection::AddTaggedHistogram(const std::string& name, |
| 868 | size_t sample) const { |
| 869 | if (histogram_tag_.empty()) |
| 870 | return; |
| 871 | |
| 872 | // TODO(shess): The histogram macros create a bit of static storage |
| 873 | // for caching the histogram object. This code shouldn't execute |
| 874 | // often enough for such caching to be crucial. If it becomes an |
| 875 | // issue, the object could be cached alongside histogram_prefix_. |
| 876 | std::string full_histogram_name = name + "." + histogram_tag_; |
| 877 | base::HistogramBase* histogram = |
| 878 | base::SparseHistogram::FactoryGet( |
| 879 | full_histogram_name, |
| 880 | base::HistogramBase::kUmaTargetedHistogramFlag); |
| 881 | if (histogram) |
| 882 | histogram->Add(sample); |
| 883 | } |
| 884 | |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 885 | int Connection::OnSqliteError(int err, sql::Statement *stmt) { |
[email protected] | 210ce0af | 2013-05-15 09:10:39 | [diff] [blame] | 886 | UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err); |
| 887 | AddTaggedHistogram("Sqlite.Error", err); |
[email protected] | c088e3a3 | 2013-01-03 23:59:14 | [diff] [blame] | 888 | |
| 889 | // Always log the error. |
| 890 | LOG(ERROR) << "sqlite error " << err |
| 891 | << ", errno " << GetLastErrno() |
| 892 | << ": " << GetErrorMessage(); |
| 893 | |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 894 | if (!error_callback_.is_null()) { |
[email protected] | 98cf300 | 2013-07-12 01:38:56 | [diff] [blame] | 895 | // Fire from a copy of the callback in case of reentry into |
| 896 | // re/set_error_callback(). |
| 897 | // TODO(shess): <http://crbug.com/254584> |
| 898 | ErrorCallback(error_callback_).Run(err, stmt); |
[email protected] | c3881b37 | 2013-05-17 08:39:46 | [diff] [blame] | 899 | return err; |
| 900 | } |
| 901 | |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 902 | // The default handling is to assert on debug and to ignore on release. |
[email protected] | 4350e32 | 2013-06-18 22:18:10 | [diff] [blame] | 903 | if (!ShouldIgnore(err)) |
| 904 | DLOG(FATAL) << GetErrorMessage(); |
[email protected] | faa604e | 2009-09-25 22:38:59 | [diff] [blame] | 905 | return err; |
| 906 | } |
| 907 | |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 908 | // TODO(shess): Allow specifying integrity_check versus quick_check. |
| 909 | // TODO(shess): Allow specifying maximum results (default 100 lines). |
| 910 | bool Connection::IntegrityCheck(std::vector<std::string>* messages) { |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 911 | messages->clear(); |
| 912 | |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 913 | // This has the side effect of setting SQLITE_RecoveryMode, which |
| 914 | // allows SQLite to process through certain cases of corruption. |
| 915 | // Failing to set this pragma probably means that the database is |
| 916 | // beyond recovery. |
| 917 | const char kWritableSchema[] = "PRAGMA writable_schema = ON"; |
| 918 | if (!Execute(kWritableSchema)) |
| 919 | return false; |
| 920 | |
| 921 | bool ret = false; |
| 922 | { |
| 923 | const char kSql[] = "PRAGMA integrity_check"; |
| 924 | sql::Statement stmt(GetUniqueStatement(kSql)); |
| 925 | |
| 926 | // The pragma appears to return all results (up to 100 by default) |
| 927 | // as a single string. This doesn't appear to be an API contract, |
| 928 | // it could return separate lines, so loop _and_ split. |
| 929 | while (stmt.Step()) { |
| 930 | std::string result(stmt.ColumnString(0)); |
| 931 | base::SplitString(result, '\n', messages); |
| 932 | } |
| 933 | ret = stmt.Succeeded(); |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 934 | } |
[email protected] | 4658e2a0 | 2013-06-06 23:05:00 | [diff] [blame] | 935 | |
| 936 | // Best effort to put things back as they were before. |
| 937 | const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF"; |
| 938 | ignore_result(Execute(kNoWritableSchema)); |
| 939 | |
| 940 | return ret; |
[email protected] | 80abf15 | 2013-05-22 12:42:42 | [diff] [blame] | 941 | } |
| 942 | |
[email protected] | e5ffd0e4 | 2009-09-11 21:30:56 | [diff] [blame] | 943 | } // namespace sql |