Blink roll: 152400:152445.
[chromium-blink-merge.git] / sql / connection.cc
blob510d6a771b4b7598e4f83f6cba68ded7520b3cb0
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/file_util.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/metrics/sparse_histogram.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "sql/statement.h"
19 #include "third_party/sqlite/sqlite3.h"
21 namespace {
23 // Spin for up to a second waiting for the lock to clear when setting
24 // up the database.
25 // TODO(shess): Better story on this. http://crbug.com/56559
26 const int kBusyTimeoutSeconds = 1;
28 class ScopedBusyTimeout {
29 public:
30 explicit ScopedBusyTimeout(sqlite3* db)
31 : db_(db) {
33 ~ScopedBusyTimeout() {
34 sqlite3_busy_timeout(db_, 0);
37 int SetTimeout(base::TimeDelta timeout) {
38 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
39 return sqlite3_busy_timeout(db_,
40 static_cast<int>(timeout.InMilliseconds()));
43 private:
44 sqlite3* db_;
47 // Helper to "safely" enable writable_schema. No error checking
48 // because it is reasonable to just forge ahead in case of an error.
49 // If turning it on fails, then most likely nothing will work, whereas
50 // if turning it off fails, it only matters if some code attempts to
51 // continue working with the database and tries to modify the
52 // sqlite_master table (none of our code does this).
53 class ScopedWritableSchema {
54 public:
55 explicit ScopedWritableSchema(sqlite3* db)
56 : db_(db) {
57 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
59 ~ScopedWritableSchema() {
60 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
63 private:
64 sqlite3* db_;
67 } // namespace
69 namespace sql {
71 bool StatementID::operator<(const StatementID& other) const {
72 if (number_ != other.number_)
73 return number_ < other.number_;
74 return strcmp(str_, other.str_) < 0;
77 Connection::StatementRef::StatementRef(Connection* connection,
78 sqlite3_stmt* stmt,
79 bool was_valid)
80 : connection_(connection),
81 stmt_(stmt),
82 was_valid_(was_valid) {
83 if (connection)
84 connection_->StatementRefCreated(this);
87 Connection::StatementRef::~StatementRef() {
88 if (connection_)
89 connection_->StatementRefDeleted(this);
90 Close(false);
93 void Connection::StatementRef::Close(bool forced) {
94 if (stmt_) {
95 // Call to AssertIOAllowed() cannot go at the beginning of the function
96 // because Close() is called unconditionally from destructor to clean
97 // connection_. And if this is inactive statement this won't cause any
98 // disk access and destructor most probably will be called on thread
99 // not allowing disk access.
100 // TODO(paivanof@gmail.com): This should move to the beginning
101 // of the function. http://crbug.com/136655.
102 AssertIOAllowed();
103 sqlite3_finalize(stmt_);
104 stmt_ = NULL;
106 connection_ = NULL; // The connection may be getting deleted.
108 // Forced close is expected to happen from a statement error
109 // handler. In that case maintain the sense of |was_valid_| which
110 // previously held for this ref.
111 was_valid_ = was_valid_ && forced;
114 Connection::Connection()
115 : db_(NULL),
116 page_size_(0),
117 cache_size_(0),
118 exclusive_locking_(false),
119 transaction_nesting_(0),
120 needs_rollback_(false),
121 in_memory_(false),
122 poisoned_(false) {
125 Connection::~Connection() {
126 Close();
129 bool Connection::Open(const base::FilePath& path) {
130 if (!histogram_tag_.empty()) {
131 int64 size_64 = 0;
132 if (file_util::GetFileSize(path, &size_64)) {
133 size_t sample = static_cast<size_t>(size_64 / 1024);
134 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
135 base::HistogramBase* histogram =
136 base::Histogram::FactoryGet(
137 full_histogram_name, 1, 1000000, 50,
138 base::HistogramBase::kUmaTargetedHistogramFlag);
139 if (histogram)
140 histogram->Add(sample);
144 #if defined(OS_WIN)
145 return OpenInternal(WideToUTF8(path.value()));
146 #elif defined(OS_POSIX)
147 return OpenInternal(path.value());
148 #endif
151 bool Connection::OpenInMemory() {
152 in_memory_ = true;
153 return OpenInternal(":memory:");
156 void Connection::CloseInternal(bool forced) {
157 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
158 // will delete the -journal file. For ChromiumOS or other more
159 // embedded systems, this is probably not appropriate, whereas on
160 // desktop it might make some sense.
162 // sqlite3_close() needs all prepared statements to be finalized.
164 // Release cached statements.
165 statement_cache_.clear();
167 // With cached statements released, in-use statements will remain.
168 // Closing the database while statements are in use is an API
169 // violation, except for forced close (which happens from within a
170 // statement's error handler).
171 DCHECK(forced || open_statements_.empty());
173 // Deactivate any outstanding statements so sqlite3_close() works.
174 for (StatementRefSet::iterator i = open_statements_.begin();
175 i != open_statements_.end(); ++i)
176 (*i)->Close(forced);
177 open_statements_.clear();
179 if (db_) {
180 // Call to AssertIOAllowed() cannot go at the beginning of the function
181 // because Close() must be called from destructor to clean
182 // statement_cache_, it won't cause any disk access and it most probably
183 // will happen on thread not allowing disk access.
184 // TODO(paivanof@gmail.com): This should move to the beginning
185 // of the function. http://crbug.com/136655.
186 AssertIOAllowed();
187 // TODO(shess): Histogram for failure.
188 sqlite3_close(db_);
189 db_ = NULL;
193 void Connection::Close() {
194 // If the database was already closed by RazeAndClose(), then no
195 // need to close again. Clear the |poisoned_| bit so that incorrect
196 // API calls are caught.
197 if (poisoned_) {
198 poisoned_ = false;
199 return;
202 CloseInternal(false);
205 void Connection::Preload() {
206 AssertIOAllowed();
208 if (!db_) {
209 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
210 return;
213 // A statement must be open for the preload command to work. If the meta
214 // table doesn't exist, it probably means this is a new database and there
215 // is nothing to preload (so it's OK we do nothing).
216 if (!DoesTableExist("meta"))
217 return;
218 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
219 if (!dummy.Step())
220 return;
222 #if !defined(USE_SYSTEM_SQLITE)
223 // This function is only defined in Chromium's version of sqlite.
224 // Do not call it when using system sqlite.
225 sqlite3_preload(db_);
226 #endif
229 // Create an in-memory database with the existing database's page
230 // size, then backup that database over the existing database.
231 bool Connection::Raze() {
232 AssertIOAllowed();
234 if (!db_) {
235 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
236 return false;
239 if (transaction_nesting_ > 0) {
240 DLOG(FATAL) << "Cannot raze within a transaction";
241 return false;
244 sql::Connection null_db;
245 if (!null_db.OpenInMemory()) {
246 DLOG(FATAL) << "Unable to open in-memory database.";
247 return false;
250 if (page_size_) {
251 // Enforce SQLite restrictions on |page_size_|.
252 DCHECK(!(page_size_ & (page_size_ - 1)))
253 << " page_size_ " << page_size_ << " is not a power of two.";
254 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
255 DCHECK_LE(page_size_, kSqliteMaxPageSize);
256 const std::string sql =
257 base::StringPrintf("PRAGMA page_size=%d", page_size_);
258 if (!null_db.Execute(sql.c_str()))
259 return false;
262 #if defined(OS_ANDROID)
263 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
264 // in-memory databases do not respect this define.
265 // TODO(shess): Figure out a way to set this without using platform
266 // specific code. AFAICT from sqlite3.c, the only way to do it
267 // would be to create an actual filesystem database, which is
268 // unfortunate.
269 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
270 return false;
271 #endif
273 // The page size doesn't take effect until a database has pages, and
274 // at this point the null database has none. Changing the schema
275 // version will create the first page. This will not affect the
276 // schema version in the resulting database, as SQLite's backup
277 // implementation propagates the schema version from the original
278 // connection to the new version of the database, incremented by one
279 // so that other readers see the schema change and act accordingly.
280 if (!null_db.Execute("PRAGMA schema_version = 1"))
281 return false;
283 // SQLite tracks the expected number of database pages in the first
284 // page, and if it does not match the total retrieved from a
285 // filesystem call, treats the database as corrupt. This situation
286 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
287 // used to hint to SQLite to soldier on in that case, specifically
288 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
289 // sqlite3.c lockBtree().]
290 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
291 // page_size" can be used to query such a database.
292 ScopedWritableSchema writable_schema(db_);
294 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
295 null_db.db_, "main");
296 if (!backup) {
297 DLOG(FATAL) << "Unable to start sqlite3_backup().";
298 return false;
301 // -1 backs up the entire database.
302 int rc = sqlite3_backup_step(backup, -1);
303 int pages = sqlite3_backup_pagecount(backup);
304 sqlite3_backup_finish(backup);
306 // The destination database was locked.
307 if (rc == SQLITE_BUSY) {
308 return false;
311 // The entire database should have been backed up.
312 if (rc != SQLITE_DONE) {
313 DLOG(FATAL) << "Unable to copy entire null database.";
314 return false;
317 // Exactly one page should have been backed up. If this breaks,
318 // check this function to make sure assumptions aren't being broken.
319 DCHECK_EQ(pages, 1);
321 return true;
324 bool Connection::RazeWithTimout(base::TimeDelta timeout) {
325 if (!db_) {
326 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
327 return false;
330 ScopedBusyTimeout busy_timeout(db_);
331 busy_timeout.SetTimeout(timeout);
332 return Raze();
335 bool Connection::RazeAndClose() {
336 if (!db_) {
337 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
338 return false;
341 // Raze() cannot run in a transaction.
342 while (transaction_nesting_) {
343 RollbackTransaction();
346 bool result = Raze();
348 CloseInternal(true);
350 // Mark the database so that future API calls fail appropriately,
351 // but don't DCHECK (because after calling this function they are
352 // expected to fail).
353 poisoned_ = true;
355 return result;
358 bool Connection::BeginTransaction() {
359 if (needs_rollback_) {
360 DCHECK_GT(transaction_nesting_, 0);
362 // When we're going to rollback, fail on this begin and don't actually
363 // mark us as entering the nested transaction.
364 return false;
367 bool success = true;
368 if (!transaction_nesting_) {
369 needs_rollback_ = false;
371 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
372 if (!begin.Run())
373 return false;
375 transaction_nesting_++;
376 return success;
379 void Connection::RollbackTransaction() {
380 if (!transaction_nesting_) {
381 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
382 return;
385 transaction_nesting_--;
387 if (transaction_nesting_ > 0) {
388 // Mark the outermost transaction as needing rollback.
389 needs_rollback_ = true;
390 return;
393 DoRollback();
396 bool Connection::CommitTransaction() {
397 if (!transaction_nesting_) {
398 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
399 return false;
401 transaction_nesting_--;
403 if (transaction_nesting_ > 0) {
404 // Mark any nested transactions as failing after we've already got one.
405 return !needs_rollback_;
408 if (needs_rollback_) {
409 DoRollback();
410 return false;
413 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
414 return commit.Run();
417 int Connection::ExecuteAndReturnErrorCode(const char* sql) {
418 AssertIOAllowed();
419 if (!db_) {
420 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
421 return SQLITE_ERROR;
423 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
426 bool Connection::Execute(const char* sql) {
427 if (!db_) {
428 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
429 return false;
432 int error = ExecuteAndReturnErrorCode(sql);
433 if (error != SQLITE_OK)
434 error = OnSqliteError(error, NULL);
436 // This needs to be a FATAL log because the error case of arriving here is
437 // that there's a malformed SQL statement. This can arise in development if
438 // a change alters the schema but not all queries adjust.
439 if (error == SQLITE_ERROR)
440 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
441 return error == SQLITE_OK;
444 bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
445 if (!db_) {
446 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
447 return false;
450 ScopedBusyTimeout busy_timeout(db_);
451 busy_timeout.SetTimeout(timeout);
452 return Execute(sql);
455 bool Connection::HasCachedStatement(const StatementID& id) const {
456 return statement_cache_.find(id) != statement_cache_.end();
459 scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
460 const StatementID& id,
461 const char* sql) {
462 CachedStatementMap::iterator i = statement_cache_.find(id);
463 if (i != statement_cache_.end()) {
464 // Statement is in the cache. It should still be active (we're the only
465 // one invalidating cached statements, and we'll remove it from the cache
466 // if we do that. Make sure we reset it before giving out the cached one in
467 // case it still has some stuff bound.
468 DCHECK(i->second->is_valid());
469 sqlite3_reset(i->second->stmt());
470 return i->second;
473 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
474 if (statement->is_valid())
475 statement_cache_[id] = statement; // Only cache valid statements.
476 return statement;
479 scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
480 const char* sql) {
481 AssertIOAllowed();
483 // Return inactive statement.
484 if (!db_)
485 return new StatementRef(NULL, NULL, poisoned_);
487 sqlite3_stmt* stmt = NULL;
488 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
489 if (rc != SQLITE_OK) {
490 // This is evidence of a syntax error in the incoming SQL.
491 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
493 // It could also be database corruption.
494 OnSqliteError(rc, NULL);
495 return new StatementRef(NULL, NULL, false);
497 return new StatementRef(this, stmt, true);
500 scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
501 const char* sql) const {
502 // Return inactive statement.
503 if (!db_)
504 return new StatementRef(NULL, NULL, poisoned_);
506 sqlite3_stmt* stmt = NULL;
507 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
508 if (rc != SQLITE_OK) {
509 // This is evidence of a syntax error in the incoming SQL.
510 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
511 return new StatementRef(NULL, NULL, false);
513 return new StatementRef(NULL, stmt, true);
516 bool Connection::IsSQLValid(const char* sql) {
517 AssertIOAllowed();
518 if (!db_) {
519 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
520 return false;
523 sqlite3_stmt* stmt = NULL;
524 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
525 return false;
527 sqlite3_finalize(stmt);
528 return true;
531 bool Connection::DoesTableExist(const char* table_name) const {
532 return DoesTableOrIndexExist(table_name, "table");
535 bool Connection::DoesIndexExist(const char* index_name) const {
536 return DoesTableOrIndexExist(index_name, "index");
539 bool Connection::DoesTableOrIndexExist(
540 const char* name, const char* type) const {
541 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
542 Statement statement(GetUntrackedStatement(kSql));
543 statement.BindString(0, type);
544 statement.BindString(1, name);
546 return statement.Step(); // Table exists if any row was returned.
549 bool Connection::DoesColumnExist(const char* table_name,
550 const char* column_name) const {
551 std::string sql("PRAGMA TABLE_INFO(");
552 sql.append(table_name);
553 sql.append(")");
555 Statement statement(GetUntrackedStatement(sql.c_str()));
556 while (statement.Step()) {
557 if (!statement.ColumnString(1).compare(column_name))
558 return true;
560 return false;
563 int64 Connection::GetLastInsertRowId() const {
564 if (!db_) {
565 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
566 return 0;
568 return sqlite3_last_insert_rowid(db_);
571 int Connection::GetLastChangeCount() const {
572 if (!db_) {
573 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
574 return 0;
576 return sqlite3_changes(db_);
579 int Connection::GetErrorCode() const {
580 if (!db_)
581 return SQLITE_ERROR;
582 return sqlite3_errcode(db_);
585 int Connection::GetLastErrno() const {
586 if (!db_)
587 return -1;
589 int err = 0;
590 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
591 return -2;
593 return err;
596 const char* Connection::GetErrorMessage() const {
597 if (!db_)
598 return "sql::Connection has no connection.";
599 return sqlite3_errmsg(db_);
602 bool Connection::OpenInternal(const std::string& file_name) {
603 AssertIOAllowed();
605 if (db_) {
606 DLOG(FATAL) << "sql::Connection is already open.";
607 return false;
610 // If |poisoned_| is set, it means an error handler called
611 // RazeAndClose(). Until regular Close() is called, the caller
612 // should be treating the database as open, but is_open() currently
613 // only considers the sqlite3 handle's state.
614 // TODO(shess): Revise is_open() to consider poisoned_, and review
615 // to see if any non-testing code even depends on it.
616 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
618 int err = sqlite3_open(file_name.c_str(), &db_);
619 if (err != SQLITE_OK) {
620 // Histogram failures specific to initial open for debugging
621 // purposes.
622 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
624 OnSqliteError(err, NULL);
625 Close();
626 db_ = NULL;
627 return false;
630 // SQLite uses a lookaside buffer to improve performance of small mallocs.
631 // Chromium already depends on small mallocs being efficient, so we disable
632 // this to avoid the extra memory overhead.
633 // This must be called immediatly after opening the database before any SQL
634 // statements are run.
635 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
637 // sqlite3_open() does not actually read the database file (unless a
638 // hot journal is found). Successfully executing this pragma on an
639 // existing database requires a valid header on page 1.
640 // TODO(shess): For now, just probing to see what the lay of the
641 // land is. If it's mostly SQLITE_NOTADB, then the database should
642 // be razed.
643 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
644 if (err != SQLITE_OK)
645 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
647 // Enable extended result codes to provide more color on I/O errors.
648 // Not having extended result codes is not a fatal problem, as
649 // Chromium code does not attempt to handle I/O errors anyhow. The
650 // current implementation always returns SQLITE_OK, the DCHECK is to
651 // quickly notify someone if SQLite changes.
652 err = sqlite3_extended_result_codes(db_, 1);
653 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
655 // If indicated, lock up the database before doing anything else, so
656 // that the following code doesn't have to deal with locking.
657 // TODO(shess): This code is brittle. Find the cases where code
658 // doesn't request |exclusive_locking_| and audit that it does the
659 // right thing with SQLITE_BUSY, and that it doesn't make
660 // assumptions about who might change things in the database.
661 // http://crbug.com/56559
662 if (exclusive_locking_) {
663 // TODO(shess): This should probably be a full CHECK(). Code
664 // which requests exclusive locking but doesn't get it is almost
665 // certain to be ill-tested.
666 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
667 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
670 // http://www.sqlite.org/pragma.html#pragma_journal_mode
671 // DELETE (default) - delete -journal file to commit.
672 // TRUNCATE - truncate -journal file to commit.
673 // PERSIST - zero out header of -journal file to commit.
674 // journal_size_limit provides size to trim to in PERSIST.
675 // TODO(shess): Figure out if PERSIST and journal_size_limit really
676 // matter. In theory, it keeps pages pre-allocated, so if
677 // transactions usually fit, it should be faster.
678 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
679 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
681 const base::TimeDelta kBusyTimeout =
682 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
684 if (page_size_ != 0) {
685 // Enforce SQLite restrictions on |page_size_|.
686 DCHECK(!(page_size_ & (page_size_ - 1)))
687 << " page_size_ " << page_size_ << " is not a power of two.";
688 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
689 DCHECK_LE(page_size_, kSqliteMaxPageSize);
690 const std::string sql =
691 base::StringPrintf("PRAGMA page_size=%d", page_size_);
692 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
693 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
696 if (cache_size_ != 0) {
697 const std::string sql =
698 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
699 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
700 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
703 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
704 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
705 Close();
706 return false;
709 return true;
712 void Connection::DoRollback() {
713 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
714 rollback.Run();
715 needs_rollback_ = false;
718 void Connection::StatementRefCreated(StatementRef* ref) {
719 DCHECK(open_statements_.find(ref) == open_statements_.end());
720 open_statements_.insert(ref);
723 void Connection::StatementRefDeleted(StatementRef* ref) {
724 StatementRefSet::iterator i = open_statements_.find(ref);
725 if (i == open_statements_.end())
726 DLOG(FATAL) << "Could not find statement";
727 else
728 open_statements_.erase(i);
731 void Connection::AddTaggedHistogram(const std::string& name,
732 size_t sample) const {
733 if (histogram_tag_.empty())
734 return;
736 // TODO(shess): The histogram macros create a bit of static storage
737 // for caching the histogram object. This code shouldn't execute
738 // often enough for such caching to be crucial. If it becomes an
739 // issue, the object could be cached alongside histogram_prefix_.
740 std::string full_histogram_name = name + "." + histogram_tag_;
741 base::HistogramBase* histogram =
742 base::SparseHistogram::FactoryGet(
743 full_histogram_name,
744 base::HistogramBase::kUmaTargetedHistogramFlag);
745 if (histogram)
746 histogram->Add(sample);
749 int Connection::OnSqliteError(int err, sql::Statement *stmt) {
750 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
751 AddTaggedHistogram("Sqlite.Error", err);
753 // Always log the error.
754 LOG(ERROR) << "sqlite error " << err
755 << ", errno " << GetLastErrno()
756 << ": " << GetErrorMessage();
758 if (!error_callback_.is_null()) {
759 error_callback_.Run(err, stmt);
760 return err;
763 // The default handling is to assert on debug and to ignore on release.
764 DLOG(FATAL) << GetErrorMessage();
765 return err;
768 // TODO(shess): Allow specifying integrity_check versus quick_check.
769 // TODO(shess): Allow specifying maximum results (default 100 lines).
770 bool Connection::IntegrityCheck(std::vector<std::string>* messages) {
771 messages->clear();
773 // This has the side effect of setting SQLITE_RecoveryMode, which
774 // allows SQLite to process through certain cases of corruption.
775 // Failing to set this pragma probably means that the database is
776 // beyond recovery.
777 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
778 if (!Execute(kWritableSchema))
779 return false;
781 bool ret = false;
783 const char kSql[] = "PRAGMA integrity_check";
784 sql::Statement stmt(GetUniqueStatement(kSql));
786 // The pragma appears to return all results (up to 100 by default)
787 // as a single string. This doesn't appear to be an API contract,
788 // it could return separate lines, so loop _and_ split.
789 while (stmt.Step()) {
790 std::string result(stmt.ColumnString(0));
791 base::SplitString(result, '\n', messages);
793 ret = stmt.Succeeded();
796 // Best effort to put things back as they were before.
797 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
798 ignore_result(Execute(kNoWritableSchema));
800 return ret;
803 } // namespace sql