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