Add a missing dependency to //extensions/extensions_renderer_resources
[chromium-blink-merge.git] / sql / connection.cc
blobc196073ebfb549d39340316e4437e7f2c7cb61b5
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sql/connection.h"
7 #include <string.h>
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/sparse_histogram.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/synchronization/lock.h"
20 #include "sql/statement.h"
21 #include "third_party/sqlite/sqlite3.h"
23 #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
24 #include "third_party/sqlite/src/ext/icu/sqliteicu.h"
25 #endif
27 namespace {
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
32 const int kBusyTimeoutSeconds = 1;
34 class ScopedBusyTimeout {
35 public:
36 explicit ScopedBusyTimeout(sqlite3* db)
37 : db_(db) {
39 ~ScopedBusyTimeout() {
40 sqlite3_busy_timeout(db_, 0);
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()));
49 private:
50 sqlite3* db_;
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);
65 ~ScopedWritableSchema() {
66 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
69 private:
70 sqlite3* db_;
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);
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);
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);
96 return rc;
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;
111 return true;
114 // SQLite automatically calls sqlite3_initialize() lazily, but
115 // sqlite3_initialize() uses double-checked locking and thus can have
116 // data races.
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();
128 // Helper to get the sqlite3_file* associated with the "main" database.
129 int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
130 *file = NULL;
131 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
132 if (rc != SQLITE_OK)
133 return rc;
135 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
136 // content_unittests, even though it should not be possible.
137 // http://crbug.com/329982
138 if (!*file || !(*file)->pMethods)
139 return SQLITE_ERROR;
141 return rc;
144 // This should match UMA_HISTOGRAM_MEDIUM_TIMES().
145 base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
146 return base::Histogram::FactoryTimeGet(
147 name,
148 base::TimeDelta::FromMilliseconds(10),
149 base::TimeDelta::FromMinutes(3),
151 base::HistogramBase::kUmaTargetedHistogramFlag);
154 } // namespace
156 namespace sql {
158 // static
159 Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
161 // static
162 bool Connection::ShouldIgnoreSqliteError(int error) {
163 if (!current_ignorer_cb_)
164 return false;
165 return current_ignorer_cb_->Run(error);
168 // static
169 void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
170 CHECK(current_ignorer_cb_ == NULL);
171 current_ignorer_cb_ = cb;
174 // static
175 void Connection::ResetErrorIgnorer() {
176 CHECK(current_ignorer_cb_);
177 current_ignorer_cb_ = NULL;
180 bool StatementID::operator<(const StatementID& other) const {
181 if (number_ != other.number_)
182 return number_ < other.number_;
183 return strcmp(str_, other.str_) < 0;
186 Connection::StatementRef::StatementRef(Connection* connection,
187 sqlite3_stmt* stmt,
188 bool was_valid)
189 : connection_(connection),
190 stmt_(stmt),
191 was_valid_(was_valid) {
192 if (connection)
193 connection_->StatementRefCreated(this);
196 Connection::StatementRef::~StatementRef() {
197 if (connection_)
198 connection_->StatementRefDeleted(this);
199 Close(false);
202 void Connection::StatementRef::Close(bool forced) {
203 if (stmt_) {
204 // Call to AssertIOAllowed() cannot go at the beginning of the function
205 // because Close() is called unconditionally from destructor to clean
206 // connection_. And if this is inactive statement this won't cause any
207 // disk access and destructor most probably will be called on thread
208 // not allowing disk access.
209 // TODO(paivanof@gmail.com): This should move to the beginning
210 // of the function. http://crbug.com/136655.
211 AssertIOAllowed();
212 sqlite3_finalize(stmt_);
213 stmt_ = NULL;
215 connection_ = NULL; // The connection may be getting deleted.
217 // Forced close is expected to happen from a statement error
218 // handler. In that case maintain the sense of |was_valid_| which
219 // previously held for this ref.
220 was_valid_ = was_valid_ && forced;
223 Connection::Connection()
224 : db_(NULL),
225 page_size_(0),
226 cache_size_(0),
227 exclusive_locking_(false),
228 restrict_to_user_(false),
229 transaction_nesting_(0),
230 needs_rollback_(false),
231 in_memory_(false),
232 poisoned_(false),
233 stats_histogram_(NULL),
234 commit_time_histogram_(NULL),
235 autocommit_time_histogram_(NULL),
236 update_time_histogram_(NULL),
237 query_time_histogram_(NULL),
238 clock_(new TimeSource()) {
241 Connection::~Connection() {
242 Close();
245 void Connection::RecordEvent(Events event, size_t count) {
246 for (size_t i = 0; i < count; ++i) {
247 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
250 if (stats_histogram_) {
251 for (size_t i = 0; i < count; ++i) {
252 stats_histogram_->Add(event);
257 void Connection::RecordCommitTime(const base::TimeDelta& delta) {
258 RecordUpdateTime(delta);
259 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
260 if (commit_time_histogram_)
261 commit_time_histogram_->AddTime(delta);
264 void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
265 RecordUpdateTime(delta);
266 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
267 if (autocommit_time_histogram_)
268 autocommit_time_histogram_->AddTime(delta);
271 void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
272 RecordQueryTime(delta);
273 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
274 if (update_time_histogram_)
275 update_time_histogram_->AddTime(delta);
278 void Connection::RecordQueryTime(const base::TimeDelta& delta) {
279 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
280 if (query_time_histogram_)
281 query_time_histogram_->AddTime(delta);
284 void Connection::RecordTimeAndChanges(
285 const base::TimeDelta& delta, bool read_only) {
286 if (read_only) {
287 RecordQueryTime(delta);
288 } else {
289 const int changes = sqlite3_changes(db_);
290 if (sqlite3_get_autocommit(db_)) {
291 RecordAutoCommitTime(delta);
292 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
293 } else {
294 RecordUpdateTime(delta);
295 RecordEvent(EVENT_CHANGES, changes);
300 bool Connection::Open(const base::FilePath& path) {
301 if (!histogram_tag_.empty()) {
302 int64_t size_64 = 0;
303 if (base::GetFileSize(path, &size_64)) {
304 size_t sample = static_cast<size_t>(size_64 / 1024);
305 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
306 base::HistogramBase* histogram =
307 base::Histogram::FactoryGet(
308 full_histogram_name, 1, 1000000, 50,
309 base::HistogramBase::kUmaTargetedHistogramFlag);
310 if (histogram)
311 histogram->Add(sample);
315 #if defined(OS_WIN)
316 return OpenInternal(base::WideToUTF8(path.value()), RETRY_ON_POISON);
317 #elif defined(OS_POSIX)
318 return OpenInternal(path.value(), RETRY_ON_POISON);
319 #endif
322 bool Connection::OpenInMemory() {
323 in_memory_ = true;
324 return OpenInternal(":memory:", NO_RETRY);
327 bool Connection::OpenTemporary() {
328 return OpenInternal("", NO_RETRY);
331 void Connection::CloseInternal(bool forced) {
332 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
333 // will delete the -journal file. For ChromiumOS or other more
334 // embedded systems, this is probably not appropriate, whereas on
335 // desktop it might make some sense.
337 // sqlite3_close() needs all prepared statements to be finalized.
339 // Release cached statements.
340 statement_cache_.clear();
342 // With cached statements released, in-use statements will remain.
343 // Closing the database while statements are in use is an API
344 // violation, except for forced close (which happens from within a
345 // statement's error handler).
346 DCHECK(forced || open_statements_.empty());
348 // Deactivate any outstanding statements so sqlite3_close() works.
349 for (StatementRefSet::iterator i = open_statements_.begin();
350 i != open_statements_.end(); ++i)
351 (*i)->Close(forced);
352 open_statements_.clear();
354 if (db_) {
355 // Call to AssertIOAllowed() cannot go at the beginning of the function
356 // because Close() must be called from destructor to clean
357 // statement_cache_, it won't cause any disk access and it most probably
358 // will happen on thread not allowing disk access.
359 // TODO(paivanof@gmail.com): This should move to the beginning
360 // of the function. http://crbug.com/136655.
361 AssertIOAllowed();
363 int rc = sqlite3_close(db_);
364 if (rc != SQLITE_OK) {
365 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
366 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
369 db_ = NULL;
372 void Connection::Close() {
373 // If the database was already closed by RazeAndClose(), then no
374 // need to close again. Clear the |poisoned_| bit so that incorrect
375 // API calls are caught.
376 if (poisoned_) {
377 poisoned_ = false;
378 return;
381 CloseInternal(false);
384 void Connection::Preload() {
385 AssertIOAllowed();
387 if (!db_) {
388 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
389 return;
392 // Use local settings if provided, otherwise use documented defaults. The
393 // actual results could be fetching via PRAGMA calls.
394 const int page_size = page_size_ ? page_size_ : 1024;
395 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
396 if (preload_size < 1)
397 return;
399 sqlite3_file* file = NULL;
400 int rc = GetSqlite3File(db_, &file);
401 if (rc != SQLITE_OK)
402 return;
404 sqlite3_int64 file_size = 0;
405 rc = file->pMethods->xFileSize(file, &file_size);
406 if (rc != SQLITE_OK)
407 return;
409 // Don't preload more than the file contains.
410 if (preload_size > file_size)
411 preload_size = file_size;
413 scoped_ptr<char[]> buf(new char[page_size]);
414 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
415 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
416 if (rc != SQLITE_OK)
417 return;
421 void Connection::TrimMemory(bool aggressively) {
422 if (!db_)
423 return;
425 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
426 int original_cache_size;
428 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
429 if (!sql_get_original.Step()) {
430 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
431 return;
433 original_cache_size = sql_get_original.ColumnInt(0);
435 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
437 // Force sqlite to try to reduce page cache usage.
438 const std::string sql_shrink =
439 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
440 if (!Execute(sql_shrink.c_str()))
441 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
443 // Restore cache size.
444 const std::string sql_restore =
445 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
446 if (!Execute(sql_restore.c_str()))
447 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
450 // Create an in-memory database with the existing database's page
451 // size, then backup that database over the existing database.
452 bool Connection::Raze() {
453 AssertIOAllowed();
455 if (!db_) {
456 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
457 return false;
460 if (transaction_nesting_ > 0) {
461 DLOG(FATAL) << "Cannot raze within a transaction";
462 return false;
465 sql::Connection null_db;
466 if (!null_db.OpenInMemory()) {
467 DLOG(FATAL) << "Unable to open in-memory database.";
468 return false;
471 if (page_size_) {
472 // Enforce SQLite restrictions on |page_size_|.
473 DCHECK(!(page_size_ & (page_size_ - 1)))
474 << " page_size_ " << page_size_ << " is not a power of two.";
475 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
476 DCHECK_LE(page_size_, kSqliteMaxPageSize);
477 const std::string sql =
478 base::StringPrintf("PRAGMA page_size=%d", page_size_);
479 if (!null_db.Execute(sql.c_str()))
480 return false;
483 #if defined(OS_ANDROID)
484 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
485 // in-memory databases do not respect this define.
486 // TODO(shess): Figure out a way to set this without using platform
487 // specific code. AFAICT from sqlite3.c, the only way to do it
488 // would be to create an actual filesystem database, which is
489 // unfortunate.
490 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
491 return false;
492 #endif
494 // The page size doesn't take effect until a database has pages, and
495 // at this point the null database has none. Changing the schema
496 // version will create the first page. This will not affect the
497 // schema version in the resulting database, as SQLite's backup
498 // implementation propagates the schema version from the original
499 // connection to the new version of the database, incremented by one
500 // so that other readers see the schema change and act accordingly.
501 if (!null_db.Execute("PRAGMA schema_version = 1"))
502 return false;
504 // SQLite tracks the expected number of database pages in the first
505 // page, and if it does not match the total retrieved from a
506 // filesystem call, treats the database as corrupt. This situation
507 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
508 // used to hint to SQLite to soldier on in that case, specifically
509 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
510 // sqlite3.c lockBtree().]
511 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
512 // page_size" can be used to query such a database.
513 ScopedWritableSchema writable_schema(db_);
515 const char* kMain = "main";
516 int rc = BackupDatabase(null_db.db_, db_, kMain);
517 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
519 // The destination database was locked.
520 if (rc == SQLITE_BUSY) {
521 return false;
524 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
525 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
526 // isn't even big enough for one page. Either way, reach in and
527 // truncate it before trying again.
528 // TODO(shess): Maybe it would be worthwhile to just truncate from
529 // the get-go?
530 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
531 sqlite3_file* file = NULL;
532 rc = GetSqlite3File(db_, &file);
533 if (rc != SQLITE_OK) {
534 DLOG(FATAL) << "Failure getting file handle.";
535 return false;
538 rc = file->pMethods->xTruncate(file, 0);
539 if (rc != SQLITE_OK) {
540 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
541 DLOG(FATAL) << "Failed to truncate file.";
542 return false;
545 rc = BackupDatabase(null_db.db_, db_, kMain);
546 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
548 if (rc != SQLITE_DONE) {
549 DLOG(FATAL) << "Failed retrying Raze().";
553 // The entire database should have been backed up.
554 if (rc != SQLITE_DONE) {
555 // TODO(shess): Figure out which other cases can happen.
556 DLOG(FATAL) << "Unable to copy entire null database.";
557 return false;
560 return true;
563 bool Connection::RazeWithTimout(base::TimeDelta timeout) {
564 if (!db_) {
565 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
566 return false;
569 ScopedBusyTimeout busy_timeout(db_);
570 busy_timeout.SetTimeout(timeout);
571 return Raze();
574 bool Connection::RazeAndClose() {
575 if (!db_) {
576 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
577 return false;
580 // Raze() cannot run in a transaction.
581 RollbackAllTransactions();
583 bool result = Raze();
585 CloseInternal(true);
587 // Mark the database so that future API calls fail appropriately,
588 // but don't DCHECK (because after calling this function they are
589 // expected to fail).
590 poisoned_ = true;
592 return result;
595 void Connection::Poison() {
596 if (!db_) {
597 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
598 return;
601 RollbackAllTransactions();
602 CloseInternal(true);
604 // Mark the database so that future API calls fail appropriately,
605 // but don't DCHECK (because after calling this function they are
606 // expected to fail).
607 poisoned_ = true;
610 // TODO(shess): To the extent possible, figure out the optimal
611 // ordering for these deletes which will prevent other connections
612 // from seeing odd behavior. For instance, it may be necessary to
613 // manually lock the main database file in a SQLite-compatible fashion
614 // (to prevent other processes from opening it), then delete the
615 // journal files, then delete the main database file. Another option
616 // might be to lock the main database file and poison the header with
617 // junk to prevent other processes from opening it successfully (like
618 // Gears "SQLite poison 3" trick).
620 // static
621 bool Connection::Delete(const base::FilePath& path) {
622 base::ThreadRestrictions::AssertIOAllowed();
624 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
625 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
627 base::DeleteFile(journal_path, false);
628 base::DeleteFile(wal_path, false);
629 base::DeleteFile(path, false);
631 return !base::PathExists(journal_path) &&
632 !base::PathExists(wal_path) &&
633 !base::PathExists(path);
636 bool Connection::BeginTransaction() {
637 if (needs_rollback_) {
638 DCHECK_GT(transaction_nesting_, 0);
640 // When we're going to rollback, fail on this begin and don't actually
641 // mark us as entering the nested transaction.
642 return false;
645 bool success = true;
646 if (!transaction_nesting_) {
647 needs_rollback_ = false;
649 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
650 RecordOneEvent(EVENT_BEGIN);
651 if (!begin.Run())
652 return false;
654 transaction_nesting_++;
655 return success;
658 void Connection::RollbackTransaction() {
659 if (!transaction_nesting_) {
660 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
661 return;
664 transaction_nesting_--;
666 if (transaction_nesting_ > 0) {
667 // Mark the outermost transaction as needing rollback.
668 needs_rollback_ = true;
669 return;
672 DoRollback();
675 bool Connection::CommitTransaction() {
676 if (!transaction_nesting_) {
677 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
678 return false;
680 transaction_nesting_--;
682 if (transaction_nesting_ > 0) {
683 // Mark any nested transactions as failing after we've already got one.
684 return !needs_rollback_;
687 if (needs_rollback_) {
688 DoRollback();
689 return false;
692 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
694 // Collect the commit time manually, sql::Statement would register it as query
695 // time only.
696 const base::TimeTicks before = Now();
697 bool ret = commit.RunWithoutTimers();
698 const base::TimeDelta delta = Now() - before;
700 RecordCommitTime(delta);
701 RecordOneEvent(EVENT_COMMIT);
703 return ret;
706 void Connection::RollbackAllTransactions() {
707 if (transaction_nesting_ > 0) {
708 transaction_nesting_ = 0;
709 DoRollback();
713 bool Connection::AttachDatabase(const base::FilePath& other_db_path,
714 const char* attachment_point) {
715 DCHECK(ValidAttachmentPoint(attachment_point));
717 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
718 #if OS_WIN
719 s.BindString16(0, other_db_path.value());
720 #else
721 s.BindString(0, other_db_path.value());
722 #endif
723 s.BindString(1, attachment_point);
724 return s.Run();
727 bool Connection::DetachDatabase(const char* attachment_point) {
728 DCHECK(ValidAttachmentPoint(attachment_point));
730 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
731 s.BindString(0, attachment_point);
732 return s.Run();
735 // TODO(shess): Consider changing this to execute exactly one statement. If a
736 // caller wishes to execute multiple statements, that should be explicit, and
737 // perhaps tucked into an explicit transaction with rollback in case of error.
738 int Connection::ExecuteAndReturnErrorCode(const char* sql) {
739 AssertIOAllowed();
740 if (!db_) {
741 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
742 return SQLITE_ERROR;
744 DCHECK(sql);
746 RecordOneEvent(EVENT_EXECUTE);
747 int rc = SQLITE_OK;
748 while ((rc == SQLITE_OK) && *sql) {
749 sqlite3_stmt *stmt = NULL;
750 const char *leftover_sql;
752 const base::TimeTicks before = Now();
753 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
754 sql = leftover_sql;
756 // Stop if an error is encountered.
757 if (rc != SQLITE_OK)
758 break;
760 // This happens if |sql| originally only contained comments or whitespace.
761 // TODO(shess): Audit to see if this can become a DCHECK(). Having
762 // extraneous comments and whitespace in the SQL statements increases
763 // runtime cost and can easily be shifted out to the C++ layer.
764 if (!stmt)
765 continue;
767 // Save for use after statement is finalized.
768 const bool read_only = !!sqlite3_stmt_readonly(stmt);
770 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
771 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
772 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
773 // is the only legitimate case for this.
774 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
777 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
778 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
779 rc = sqlite3_finalize(stmt);
780 if (rc == SQLITE_OK)
781 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
783 // sqlite3_exec() does this, presumably to avoid spinning the parser for
784 // trailing whitespace.
785 // TODO(shess): Audit to see if this can become a DCHECK.
786 while (IsAsciiWhitespace(*sql)) {
787 sql++;
790 const base::TimeDelta delta = Now() - before;
791 RecordTimeAndChanges(delta, read_only);
793 return rc;
796 bool Connection::Execute(const char* sql) {
797 if (!db_) {
798 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
799 return false;
802 int error = ExecuteAndReturnErrorCode(sql);
803 if (error != SQLITE_OK)
804 error = OnSqliteError(error, NULL, sql);
806 // This needs to be a FATAL log because the error case of arriving here is
807 // that there's a malformed SQL statement. This can arise in development if
808 // a change alters the schema but not all queries adjust. This can happen
809 // in production if the schema is corrupted.
810 if (error == SQLITE_ERROR)
811 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
812 return error == SQLITE_OK;
815 bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
816 if (!db_) {
817 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
818 return false;
821 ScopedBusyTimeout busy_timeout(db_);
822 busy_timeout.SetTimeout(timeout);
823 return Execute(sql);
826 bool Connection::HasCachedStatement(const StatementID& id) const {
827 return statement_cache_.find(id) != statement_cache_.end();
830 scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
831 const StatementID& id,
832 const char* sql) {
833 CachedStatementMap::iterator i = statement_cache_.find(id);
834 if (i != statement_cache_.end()) {
835 // Statement is in the cache. It should still be active (we're the only
836 // one invalidating cached statements, and we'll remove it from the cache
837 // if we do that. Make sure we reset it before giving out the cached one in
838 // case it still has some stuff bound.
839 DCHECK(i->second->is_valid());
840 sqlite3_reset(i->second->stmt());
841 return i->second;
844 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
845 if (statement->is_valid())
846 statement_cache_[id] = statement; // Only cache valid statements.
847 return statement;
850 scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
851 const char* sql) {
852 AssertIOAllowed();
854 // Return inactive statement.
855 if (!db_)
856 return new StatementRef(NULL, NULL, poisoned_);
858 sqlite3_stmt* stmt = NULL;
859 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
860 if (rc != SQLITE_OK) {
861 // This is evidence of a syntax error in the incoming SQL.
862 if (!ShouldIgnoreSqliteError(rc))
863 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
865 // It could also be database corruption.
866 OnSqliteError(rc, NULL, sql);
867 return new StatementRef(NULL, NULL, false);
869 return new StatementRef(this, stmt, true);
872 scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
873 const char* sql) const {
874 // Return inactive statement.
875 if (!db_)
876 return new StatementRef(NULL, NULL, poisoned_);
878 sqlite3_stmt* stmt = NULL;
879 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
880 if (rc != SQLITE_OK) {
881 // This is evidence of a syntax error in the incoming SQL.
882 if (!ShouldIgnoreSqliteError(rc))
883 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
884 return new StatementRef(NULL, NULL, false);
886 return new StatementRef(NULL, stmt, true);
889 std::string Connection::GetSchema() const {
890 // The ORDER BY should not be necessary, but relying on organic
891 // order for something like this is questionable.
892 const char* kSql =
893 "SELECT type, name, tbl_name, sql "
894 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
895 Statement statement(GetUntrackedStatement(kSql));
897 std::string schema;
898 while (statement.Step()) {
899 schema += statement.ColumnString(0);
900 schema += '|';
901 schema += statement.ColumnString(1);
902 schema += '|';
903 schema += statement.ColumnString(2);
904 schema += '|';
905 schema += statement.ColumnString(3);
906 schema += '\n';
909 return schema;
912 bool Connection::IsSQLValid(const char* sql) {
913 AssertIOAllowed();
914 if (!db_) {
915 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
916 return false;
919 sqlite3_stmt* stmt = NULL;
920 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
921 return false;
923 sqlite3_finalize(stmt);
924 return true;
927 bool Connection::DoesTableExist(const char* table_name) const {
928 return DoesTableOrIndexExist(table_name, "table");
931 bool Connection::DoesIndexExist(const char* index_name) const {
932 return DoesTableOrIndexExist(index_name, "index");
935 bool Connection::DoesTableOrIndexExist(
936 const char* name, const char* type) const {
937 const char* kSql =
938 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
939 Statement statement(GetUntrackedStatement(kSql));
941 // This can happen if the database is corrupt and the error is being ignored
942 // for testing purposes.
943 if (!statement.is_valid())
944 return false;
946 statement.BindString(0, type);
947 statement.BindString(1, name);
949 return statement.Step(); // Table exists if any row was returned.
952 bool Connection::DoesColumnExist(const char* table_name,
953 const char* column_name) const {
954 std::string sql("PRAGMA TABLE_INFO(");
955 sql.append(table_name);
956 sql.append(")");
958 Statement statement(GetUntrackedStatement(sql.c_str()));
960 // This can happen if the database is corrupt and the error is being ignored
961 // for testing purposes.
962 if (!statement.is_valid())
963 return false;
965 while (statement.Step()) {
966 if (!base::strcasecmp(statement.ColumnString(1).c_str(), column_name))
967 return true;
969 return false;
972 int64_t Connection::GetLastInsertRowId() const {
973 if (!db_) {
974 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
975 return 0;
977 return sqlite3_last_insert_rowid(db_);
980 int Connection::GetLastChangeCount() const {
981 if (!db_) {
982 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
983 return 0;
985 return sqlite3_changes(db_);
988 int Connection::GetErrorCode() const {
989 if (!db_)
990 return SQLITE_ERROR;
991 return sqlite3_errcode(db_);
994 int Connection::GetLastErrno() const {
995 if (!db_)
996 return -1;
998 int err = 0;
999 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1000 return -2;
1002 return err;
1005 const char* Connection::GetErrorMessage() const {
1006 if (!db_)
1007 return "sql::Connection has no connection.";
1008 return sqlite3_errmsg(db_);
1011 bool Connection::OpenInternal(const std::string& file_name,
1012 Connection::Retry retry_flag) {
1013 AssertIOAllowed();
1015 if (db_) {
1016 DLOG(FATAL) << "sql::Connection is already open.";
1017 return false;
1020 // Make sure sqlite3_initialize() is called before anything else.
1021 InitializeSqlite();
1023 // Setup the stats histograms immediately rather than allocating lazily.
1024 // Connections which won't exercise all of these probably shouldn't exist.
1025 if (!histogram_tag_.empty()) {
1026 stats_histogram_ =
1027 base::LinearHistogram::FactoryGet(
1028 "Sqlite.Stats." + histogram_tag_,
1029 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1030 base::HistogramBase::kUmaTargetedHistogramFlag);
1032 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1033 // unreasonable time for any single operation, so there is not much value to
1034 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1035 // things are entirely busted.
1036 commit_time_histogram_ =
1037 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1039 autocommit_time_histogram_ =
1040 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1042 update_time_histogram_ =
1043 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1045 query_time_histogram_ =
1046 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1049 // If |poisoned_| is set, it means an error handler called
1050 // RazeAndClose(). Until regular Close() is called, the caller
1051 // should be treating the database as open, but is_open() currently
1052 // only considers the sqlite3 handle's state.
1053 // TODO(shess): Revise is_open() to consider poisoned_, and review
1054 // to see if any non-testing code even depends on it.
1055 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
1056 poisoned_ = false;
1058 int err = sqlite3_open(file_name.c_str(), &db_);
1059 if (err != SQLITE_OK) {
1060 // Extended error codes cannot be enabled until a handle is
1061 // available, fetch manually.
1062 err = sqlite3_extended_errcode(db_);
1064 // Histogram failures specific to initial open for debugging
1065 // purposes.
1066 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
1068 OnSqliteError(err, NULL, "-- sqlite3_open()");
1069 bool was_poisoned = poisoned_;
1070 Close();
1072 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1073 return OpenInternal(file_name, NO_RETRY);
1074 return false;
1077 // TODO(shess): OS_WIN support?
1078 #if defined(OS_POSIX)
1079 if (restrict_to_user_) {
1080 DCHECK_NE(file_name, std::string(":memory"));
1081 base::FilePath file_path(file_name);
1082 int mode = 0;
1083 // TODO(shess): Arguably, failure to retrieve and change
1084 // permissions should be fatal if the file exists.
1085 if (base::GetPosixFilePermissions(file_path, &mode)) {
1086 mode &= base::FILE_PERMISSION_USER_MASK;
1087 base::SetPosixFilePermissions(file_path, mode);
1089 // SQLite sets the permissions on these files from the main
1090 // database on create. Set them here in case they already exist
1091 // at this point. Failure to set these permissions should not
1092 // be fatal unless the file doesn't exist.
1093 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1094 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
1095 base::SetPosixFilePermissions(journal_path, mode);
1096 base::SetPosixFilePermissions(wal_path, mode);
1099 #endif // defined(OS_POSIX)
1101 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1102 // Chromium already depends on small mallocs being efficient, so we disable
1103 // this to avoid the extra memory overhead.
1104 // This must be called immediatly after opening the database before any SQL
1105 // statements are run.
1106 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1108 // Enable extended result codes to provide more color on I/O errors.
1109 // Not having extended result codes is not a fatal problem, as
1110 // Chromium code does not attempt to handle I/O errors anyhow. The
1111 // current implementation always returns SQLITE_OK, the DCHECK is to
1112 // quickly notify someone if SQLite changes.
1113 err = sqlite3_extended_result_codes(db_, 1);
1114 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1116 // sqlite3_open() does not actually read the database file (unless a
1117 // hot journal is found). Successfully executing this pragma on an
1118 // existing database requires a valid header on page 1.
1119 // TODO(shess): For now, just probing to see what the lay of the
1120 // land is. If it's mostly SQLITE_NOTADB, then the database should
1121 // be razed.
1122 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1123 if (err != SQLITE_OK)
1124 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
1126 #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1127 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1128 // REGEXP support. Add it in dynamically.
1129 err = sqlite3IcuInit(db_);
1130 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1131 #endif // OS_IOS && USE_SYSTEM_SQLITE
1133 // If indicated, lock up the database before doing anything else, so
1134 // that the following code doesn't have to deal with locking.
1135 // TODO(shess): This code is brittle. Find the cases where code
1136 // doesn't request |exclusive_locking_| and audit that it does the
1137 // right thing with SQLITE_BUSY, and that it doesn't make
1138 // assumptions about who might change things in the database.
1139 // http://crbug.com/56559
1140 if (exclusive_locking_) {
1141 // TODO(shess): This should probably be a failure. Code which
1142 // requests exclusive locking but doesn't get it is almost certain
1143 // to be ill-tested.
1144 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
1147 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1148 // DELETE (default) - delete -journal file to commit.
1149 // TRUNCATE - truncate -journal file to commit.
1150 // PERSIST - zero out header of -journal file to commit.
1151 // TRUNCATE should be faster than DELETE because it won't need directory
1152 // changes for each transaction. PERSIST may break the spirit of using
1153 // secure_delete.
1154 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
1156 const base::TimeDelta kBusyTimeout =
1157 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1159 if (page_size_ != 0) {
1160 // Enforce SQLite restrictions on |page_size_|.
1161 DCHECK(!(page_size_ & (page_size_ - 1)))
1162 << " page_size_ " << page_size_ << " is not a power of two.";
1163 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1164 DCHECK_LE(page_size_, kSqliteMaxPageSize);
1165 const std::string sql =
1166 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1167 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
1170 if (cache_size_ != 0) {
1171 const std::string sql =
1172 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
1173 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
1176 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
1177 bool was_poisoned = poisoned_;
1178 Close();
1179 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1180 return OpenInternal(file_name, NO_RETRY);
1181 return false;
1184 return true;
1187 void Connection::DoRollback() {
1188 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
1190 // Collect the rollback time manually, sql::Statement would register it as
1191 // query time only.
1192 const base::TimeTicks before = Now();
1193 rollback.RunWithoutTimers();
1194 const base::TimeDelta delta = Now() - before;
1196 RecordUpdateTime(delta);
1197 RecordOneEvent(EVENT_ROLLBACK);
1199 needs_rollback_ = false;
1202 void Connection::StatementRefCreated(StatementRef* ref) {
1203 DCHECK(open_statements_.find(ref) == open_statements_.end());
1204 open_statements_.insert(ref);
1207 void Connection::StatementRefDeleted(StatementRef* ref) {
1208 StatementRefSet::iterator i = open_statements_.find(ref);
1209 if (i == open_statements_.end())
1210 DLOG(FATAL) << "Could not find statement";
1211 else
1212 open_statements_.erase(i);
1215 void Connection::set_histogram_tag(const std::string& tag) {
1216 DCHECK(!is_open());
1217 histogram_tag_ = tag;
1220 void Connection::AddTaggedHistogram(const std::string& name,
1221 size_t sample) const {
1222 if (histogram_tag_.empty())
1223 return;
1225 // TODO(shess): The histogram macros create a bit of static storage
1226 // for caching the histogram object. This code shouldn't execute
1227 // often enough for such caching to be crucial. If it becomes an
1228 // issue, the object could be cached alongside histogram_prefix_.
1229 std::string full_histogram_name = name + "." + histogram_tag_;
1230 base::HistogramBase* histogram =
1231 base::SparseHistogram::FactoryGet(
1232 full_histogram_name,
1233 base::HistogramBase::kUmaTargetedHistogramFlag);
1234 if (histogram)
1235 histogram->Add(sample);
1238 int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
1239 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1240 AddTaggedHistogram("Sqlite.Error", err);
1242 // Always log the error.
1243 if (!sql && stmt)
1244 sql = stmt->GetSQLStatement();
1245 if (!sql)
1246 sql = "-- unknown";
1247 LOG(ERROR) << histogram_tag_ << " sqlite error " << err
1248 << ", errno " << GetLastErrno()
1249 << ": " << GetErrorMessage()
1250 << ", sql: " << sql;
1252 if (!error_callback_.is_null()) {
1253 // Fire from a copy of the callback in case of reentry into
1254 // re/set_error_callback().
1255 // TODO(shess): <http://crbug.com/254584>
1256 ErrorCallback(error_callback_).Run(err, stmt);
1257 return err;
1260 // The default handling is to assert on debug and to ignore on release.
1261 if (!ShouldIgnoreSqliteError(err))
1262 DLOG(FATAL) << GetErrorMessage();
1263 return err;
1266 bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1267 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1270 bool Connection::QuickIntegrityCheck() {
1271 std::vector<std::string> messages;
1272 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1273 return false;
1274 return messages.size() == 1 && messages[0] == "ok";
1277 // TODO(shess): Allow specifying maximum results (default 100 lines).
1278 bool Connection::IntegrityCheckHelper(
1279 const char* pragma_sql,
1280 std::vector<std::string>* messages) {
1281 messages->clear();
1283 // This has the side effect of setting SQLITE_RecoveryMode, which
1284 // allows SQLite to process through certain cases of corruption.
1285 // Failing to set this pragma probably means that the database is
1286 // beyond recovery.
1287 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1288 if (!Execute(kWritableSchema))
1289 return false;
1291 bool ret = false;
1293 sql::Statement stmt(GetUniqueStatement(pragma_sql));
1295 // The pragma appears to return all results (up to 100 by default)
1296 // as a single string. This doesn't appear to be an API contract,
1297 // it could return separate lines, so loop _and_ split.
1298 while (stmt.Step()) {
1299 std::string result(stmt.ColumnString(0));
1300 base::SplitString(result, '\n', messages);
1302 ret = stmt.Succeeded();
1305 // Best effort to put things back as they were before.
1306 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1307 ignore_result(Execute(kNoWritableSchema));
1309 return ret;
1312 base::TimeTicks TimeSource::Now() {
1313 return base::TimeTicks::Now();
1316 } // namespace sql