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"
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/sparse_histogram.h"
13 #include "base/string_util.h"
14 #include "base/stringprintf.h"
15 #include "base/utf_string_conversions.h"
16 #include "sql/statement.h"
17 #include "third_party/sqlite/sqlite3.h"
21 // Spin for up to a second waiting for the lock to clear when setting
23 // TODO(shess): Better story on this. http://crbug.com/56559
24 const int kBusyTimeoutSeconds
= 1;
26 class ScopedBusyTimeout
{
28 explicit ScopedBusyTimeout(sqlite3
* db
)
31 ~ScopedBusyTimeout() {
32 sqlite3_busy_timeout(db_
, 0);
35 int SetTimeout(base::TimeDelta timeout
) {
36 DCHECK_LT(timeout
.InMilliseconds(), INT_MAX
);
37 return sqlite3_busy_timeout(db_
,
38 static_cast<int>(timeout
.InMilliseconds()));
45 // Helper to "safely" enable writable_schema. No error checking
46 // because it is reasonable to just forge ahead in case of an error.
47 // If turning it on fails, then most likely nothing will work, whereas
48 // if turning it off fails, it only matters if some code attempts to
49 // continue working with the database and tries to modify the
50 // sqlite_master table (none of our code does this).
51 class ScopedWritableSchema
{
53 explicit ScopedWritableSchema(sqlite3
* db
)
55 sqlite3_exec(db_
, "PRAGMA writable_schema=1", NULL
, NULL
, NULL
);
57 ~ScopedWritableSchema() {
58 sqlite3_exec(db_
, "PRAGMA writable_schema=0", NULL
, NULL
, NULL
);
69 bool StatementID::operator<(const StatementID
& other
) const {
70 if (number_
!= other
.number_
)
71 return number_
< other
.number_
;
72 return strcmp(str_
, other
.str_
) < 0;
75 ErrorDelegate::~ErrorDelegate() {
78 Connection::StatementRef::StatementRef(Connection
* connection
,
81 : connection_(connection
),
83 was_valid_(was_valid
) {
85 connection_
->StatementRefCreated(this);
88 Connection::StatementRef::~StatementRef() {
90 connection_
->StatementRefDeleted(this);
94 void Connection::StatementRef::Close(bool forced
) {
96 // Call to AssertIOAllowed() cannot go at the beginning of the function
97 // because Close() is called unconditionally from destructor to clean
98 // connection_. And if this is inactive statement this won't cause any
99 // disk access and destructor most probably will be called on thread
100 // not allowing disk access.
101 // TODO(paivanof@gmail.com): This should move to the beginning
102 // of the function. http://crbug.com/136655.
104 sqlite3_finalize(stmt_
);
107 connection_
= NULL
; // The connection may be getting deleted.
109 // Forced close is expected to happen from a statement error
110 // handler. In that case maintain the sense of |was_valid_| which
111 // previously held for this ref.
112 was_valid_
= was_valid_
&& forced
;
115 Connection::Connection()
119 exclusive_locking_(false),
120 transaction_nesting_(0),
121 needs_rollback_(false),
124 error_delegate_(NULL
) {
127 Connection::~Connection() {
131 bool Connection::Open(const base::FilePath
& path
) {
133 return OpenInternal(WideToUTF8(path
.value()));
134 #elif defined(OS_POSIX)
135 return OpenInternal(path
.value());
139 bool Connection::OpenInMemory() {
141 return OpenInternal(":memory:");
144 void Connection::CloseInternal(bool forced
) {
145 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
146 // will delete the -journal file. For ChromiumOS or other more
147 // embedded systems, this is probably not appropriate, whereas on
148 // desktop it might make some sense.
150 // sqlite3_close() needs all prepared statements to be finalized.
152 // Release cached statements.
153 statement_cache_
.clear();
155 // With cached statements released, in-use statements will remain.
156 // Closing the database while statements are in use is an API
157 // violation, except for forced close (which happens from within a
158 // statement's error handler).
159 DCHECK(forced
|| open_statements_
.empty());
161 // Deactivate any outstanding statements so sqlite3_close() works.
162 for (StatementRefSet::iterator i
= open_statements_
.begin();
163 i
!= open_statements_
.end(); ++i
)
165 open_statements_
.clear();
168 // Call to AssertIOAllowed() cannot go at the beginning of the function
169 // because Close() must be called from destructor to clean
170 // statement_cache_, it won't cause any disk access and it most probably
171 // will happen on thread not allowing disk access.
172 // TODO(paivanof@gmail.com): This should move to the beginning
173 // of the function. http://crbug.com/136655.
175 // TODO(shess): Histogram for failure.
181 void Connection::Close() {
182 // If the database was already closed by RazeAndClose(), then no
183 // need to close again. Clear the |poisoned_| bit so that incorrect
184 // API calls are caught.
190 CloseInternal(false);
193 void Connection::Preload() {
197 DLOG_IF(FATAL
, !poisoned_
) << "Cannot preload null db";
201 // A statement must be open for the preload command to work. If the meta
202 // table doesn't exist, it probably means this is a new database and there
203 // is nothing to preload (so it's OK we do nothing).
204 if (!DoesTableExist("meta"))
206 Statement
dummy(GetUniqueStatement("SELECT * FROM meta"));
210 #if !defined(USE_SYSTEM_SQLITE)
211 // This function is only defined in Chromium's version of sqlite.
212 // Do not call it when using system sqlite.
213 sqlite3_preload(db_
);
217 // Create an in-memory database with the existing database's page
218 // size, then backup that database over the existing database.
219 bool Connection::Raze() {
223 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
227 if (transaction_nesting_
> 0) {
228 DLOG(FATAL
) << "Cannot raze within a transaction";
232 sql::Connection null_db
;
233 if (!null_db
.OpenInMemory()) {
234 DLOG(FATAL
) << "Unable to open in-memory database.";
239 // Enforce SQLite restrictions on |page_size_|.
240 DCHECK(!(page_size_
& (page_size_
- 1)))
241 << " page_size_ " << page_size_
<< " is not a power of two.";
242 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
243 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
244 const std::string sql
=
245 base::StringPrintf("PRAGMA page_size=%d", page_size_
);
246 if (!null_db
.Execute(sql
.c_str()))
250 #if defined(OS_ANDROID)
251 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
252 // in-memory databases do not respect this define.
253 // TODO(shess): Figure out a way to set this without using platform
254 // specific code. AFAICT from sqlite3.c, the only way to do it
255 // would be to create an actual filesystem database, which is
257 if (!null_db
.Execute("PRAGMA auto_vacuum = 1"))
261 // The page size doesn't take effect until a database has pages, and
262 // at this point the null database has none. Changing the schema
263 // version will create the first page. This will not affect the
264 // schema version in the resulting database, as SQLite's backup
265 // implementation propagates the schema version from the original
266 // connection to the new version of the database, incremented by one
267 // so that other readers see the schema change and act accordingly.
268 if (!null_db
.Execute("PRAGMA schema_version = 1"))
271 // SQLite tracks the expected number of database pages in the first
272 // page, and if it does not match the total retrieved from a
273 // filesystem call, treats the database as corrupt. This situation
274 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
275 // used to hint to SQLite to soldier on in that case, specifically
276 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
277 // sqlite3.c lockBtree().]
278 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
279 // page_size" can be used to query such a database.
280 ScopedWritableSchema
writable_schema(db_
);
282 sqlite3_backup
* backup
= sqlite3_backup_init(db_
, "main",
283 null_db
.db_
, "main");
285 DLOG(FATAL
) << "Unable to start sqlite3_backup().";
289 // -1 backs up the entire database.
290 int rc
= sqlite3_backup_step(backup
, -1);
291 int pages
= sqlite3_backup_pagecount(backup
);
292 sqlite3_backup_finish(backup
);
294 // The destination database was locked.
295 if (rc
== SQLITE_BUSY
) {
299 // The entire database should have been backed up.
300 if (rc
!= SQLITE_DONE
) {
301 DLOG(FATAL
) << "Unable to copy entire null database.";
305 // Exactly one page should have been backed up. If this breaks,
306 // check this function to make sure assumptions aren't being broken.
312 bool Connection::RazeWithTimout(base::TimeDelta timeout
) {
314 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
318 ScopedBusyTimeout
busy_timeout(db_
);
319 busy_timeout
.SetTimeout(timeout
);
323 bool Connection::RazeAndClose() {
325 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
329 // Raze() cannot run in a transaction.
330 while (transaction_nesting_
) {
331 RollbackTransaction();
334 bool result
= Raze();
338 // Mark the database so that future API calls fail appropriately,
339 // but don't DCHECK (because after calling this function they are
340 // expected to fail).
346 bool Connection::BeginTransaction() {
347 if (needs_rollback_
) {
348 DCHECK_GT(transaction_nesting_
, 0);
350 // When we're going to rollback, fail on this begin and don't actually
351 // mark us as entering the nested transaction.
356 if (!transaction_nesting_
) {
357 needs_rollback_
= false;
359 Statement
begin(GetCachedStatement(SQL_FROM_HERE
, "BEGIN TRANSACTION"));
363 transaction_nesting_
++;
367 void Connection::RollbackTransaction() {
368 if (!transaction_nesting_
) {
369 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
373 transaction_nesting_
--;
375 if (transaction_nesting_
> 0) {
376 // Mark the outermost transaction as needing rollback.
377 needs_rollback_
= true;
384 bool Connection::CommitTransaction() {
385 if (!transaction_nesting_
) {
386 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
389 transaction_nesting_
--;
391 if (transaction_nesting_
> 0) {
392 // Mark any nested transactions as failing after we've already got one.
393 return !needs_rollback_
;
396 if (needs_rollback_
) {
401 Statement
commit(GetCachedStatement(SQL_FROM_HERE
, "COMMIT"));
405 int Connection::ExecuteAndReturnErrorCode(const char* sql
) {
408 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
411 return sqlite3_exec(db_
, sql
, NULL
, NULL
, NULL
);
414 bool Connection::Execute(const char* sql
) {
416 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
420 int error
= ExecuteAndReturnErrorCode(sql
);
421 if (error
!= SQLITE_OK
)
422 error
= OnSqliteError(error
, NULL
);
424 // This needs to be a FATAL log because the error case of arriving here is
425 // that there's a malformed SQL statement. This can arise in development if
426 // a change alters the schema but not all queries adjust.
427 if (error
== SQLITE_ERROR
)
428 DLOG(FATAL
) << "SQL Error in " << sql
<< ", " << GetErrorMessage();
429 return error
== SQLITE_OK
;
432 bool Connection::ExecuteWithTimeout(const char* sql
, base::TimeDelta timeout
) {
434 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
438 ScopedBusyTimeout
busy_timeout(db_
);
439 busy_timeout
.SetTimeout(timeout
);
443 bool Connection::HasCachedStatement(const StatementID
& id
) const {
444 return statement_cache_
.find(id
) != statement_cache_
.end();
447 scoped_refptr
<Connection::StatementRef
> Connection::GetCachedStatement(
448 const StatementID
& id
,
450 CachedStatementMap::iterator i
= statement_cache_
.find(id
);
451 if (i
!= statement_cache_
.end()) {
452 // Statement is in the cache. It should still be active (we're the only
453 // one invalidating cached statements, and we'll remove it from the cache
454 // if we do that. Make sure we reset it before giving out the cached one in
455 // case it still has some stuff bound.
456 DCHECK(i
->second
->is_valid());
457 sqlite3_reset(i
->second
->stmt());
461 scoped_refptr
<StatementRef
> statement
= GetUniqueStatement(sql
);
462 if (statement
->is_valid())
463 statement_cache_
[id
] = statement
; // Only cache valid statements.
467 scoped_refptr
<Connection::StatementRef
> Connection::GetUniqueStatement(
471 // Return inactive statement.
473 return new StatementRef(NULL
, NULL
, poisoned_
);
475 sqlite3_stmt
* stmt
= NULL
;
476 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
477 if (rc
!= SQLITE_OK
) {
478 // This is evidence of a syntax error in the incoming SQL.
479 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
481 // It could also be database corruption.
482 OnSqliteError(rc
, NULL
);
483 return new StatementRef(NULL
, NULL
, false);
485 return new StatementRef(this, stmt
, true);
488 scoped_refptr
<Connection::StatementRef
> Connection::GetUntrackedStatement(
489 const char* sql
) const {
490 // Return inactive statement.
492 return new StatementRef(NULL
, NULL
, poisoned_
);
494 sqlite3_stmt
* stmt
= NULL
;
495 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
496 if (rc
!= SQLITE_OK
) {
497 // This is evidence of a syntax error in the incoming SQL.
498 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
499 return new StatementRef(NULL
, NULL
, false);
501 return new StatementRef(NULL
, stmt
, true);
504 bool Connection::IsSQLValid(const char* sql
) {
507 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
511 sqlite3_stmt
* stmt
= NULL
;
512 if (sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
) != SQLITE_OK
)
515 sqlite3_finalize(stmt
);
519 bool Connection::DoesTableExist(const char* table_name
) const {
520 return DoesTableOrIndexExist(table_name
, "table");
523 bool Connection::DoesIndexExist(const char* index_name
) const {
524 return DoesTableOrIndexExist(index_name
, "index");
527 bool Connection::DoesTableOrIndexExist(
528 const char* name
, const char* type
) const {
529 const char* kSql
= "SELECT name FROM sqlite_master WHERE type=? AND name=?";
530 Statement
statement(GetUntrackedStatement(kSql
));
531 statement
.BindString(0, type
);
532 statement
.BindString(1, name
);
534 return statement
.Step(); // Table exists if any row was returned.
537 bool Connection::DoesColumnExist(const char* table_name
,
538 const char* column_name
) const {
539 std::string
sql("PRAGMA TABLE_INFO(");
540 sql
.append(table_name
);
543 Statement
statement(GetUntrackedStatement(sql
.c_str()));
544 while (statement
.Step()) {
545 if (!statement
.ColumnString(1).compare(column_name
))
551 int64
Connection::GetLastInsertRowId() const {
553 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
556 return sqlite3_last_insert_rowid(db_
);
559 int Connection::GetLastChangeCount() const {
561 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
564 return sqlite3_changes(db_
);
567 int Connection::GetErrorCode() const {
570 return sqlite3_errcode(db_
);
573 int Connection::GetLastErrno() const {
578 if (SQLITE_OK
!= sqlite3_file_control(db_
, NULL
, SQLITE_LAST_ERRNO
, &err
))
584 const char* Connection::GetErrorMessage() const {
586 return "sql::Connection has no connection.";
587 return sqlite3_errmsg(db_
);
590 bool Connection::OpenInternal(const std::string
& file_name
) {
594 DLOG(FATAL
) << "sql::Connection is already open.";
598 // If |poisoned_| is set, it means an error handler called
599 // RazeAndClose(). Until regular Close() is called, the caller
600 // should be treating the database as open, but is_open() currently
601 // only considers the sqlite3 handle's state.
602 // TODO(shess): Revise is_open() to consider poisoned_, and review
603 // to see if any non-testing code even depends on it.
604 DLOG_IF(FATAL
, poisoned_
) << "sql::Connection is already open.";
606 int err
= sqlite3_open(file_name
.c_str(), &db_
);
607 if (err
!= SQLITE_OK
) {
608 // Histogram failures specific to initial open for debugging
610 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err
& 0xff, 50);
612 OnSqliteError(err
, NULL
);
618 // sqlite3_open() does not actually read the database file (unless a
619 // hot journal is found). Successfully executing this pragma on an
620 // existing database requires a valid header on page 1.
621 // TODO(shess): For now, just probing to see what the lay of the
622 // land is. If it's mostly SQLITE_NOTADB, then the database should
624 err
= ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
625 if (err
!= SQLITE_OK
)
626 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err
& 0xff, 50);
628 // Enable extended result codes to provide more color on I/O errors.
629 // Not having extended result codes is not a fatal problem, as
630 // Chromium code does not attempt to handle I/O errors anyhow. The
631 // current implementation always returns SQLITE_OK, the DCHECK is to
632 // quickly notify someone if SQLite changes.
633 err
= sqlite3_extended_result_codes(db_
, 1);
634 DCHECK_EQ(err
, SQLITE_OK
) << "Could not enable extended result codes";
636 // If indicated, lock up the database before doing anything else, so
637 // that the following code doesn't have to deal with locking.
638 // TODO(shess): This code is brittle. Find the cases where code
639 // doesn't request |exclusive_locking_| and audit that it does the
640 // right thing with SQLITE_BUSY, and that it doesn't make
641 // assumptions about who might change things in the database.
642 // http://crbug.com/56559
643 if (exclusive_locking_
) {
644 // TODO(shess): This should probably be a full CHECK(). Code
645 // which requests exclusive locking but doesn't get it is almost
646 // certain to be ill-tested.
647 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
648 DLOG(FATAL
) << "Could not set locking mode: " << GetErrorMessage();
651 // http://www.sqlite.org/pragma.html#pragma_journal_mode
652 // DELETE (default) - delete -journal file to commit.
653 // TRUNCATE - truncate -journal file to commit.
654 // PERSIST - zero out header of -journal file to commit.
655 // journal_size_limit provides size to trim to in PERSIST.
656 // TODO(shess): Figure out if PERSIST and journal_size_limit really
657 // matter. In theory, it keeps pages pre-allocated, so if
658 // transactions usually fit, it should be faster.
659 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
660 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
662 const base::TimeDelta kBusyTimeout
=
663 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds
);
665 if (page_size_
!= 0) {
666 // Enforce SQLite restrictions on |page_size_|.
667 DCHECK(!(page_size_
& (page_size_
- 1)))
668 << " page_size_ " << page_size_
<< " is not a power of two.";
669 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
670 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
671 const std::string sql
=
672 base::StringPrintf("PRAGMA page_size=%d", page_size_
);
673 if (!ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
))
674 DLOG(FATAL
) << "Could not set page size: " << GetErrorMessage();
677 if (cache_size_
!= 0) {
678 const std::string sql
=
679 base::StringPrintf("PRAGMA cache_size=%d", cache_size_
);
680 if (!ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
))
681 DLOG(FATAL
) << "Could not set cache size: " << GetErrorMessage();
684 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout
)) {
685 DLOG(FATAL
) << "Could not enable secure_delete: " << GetErrorMessage();
693 void Connection::DoRollback() {
694 Statement
rollback(GetCachedStatement(SQL_FROM_HERE
, "ROLLBACK"));
696 needs_rollback_
= false;
699 void Connection::StatementRefCreated(StatementRef
* ref
) {
700 DCHECK(open_statements_
.find(ref
) == open_statements_
.end());
701 open_statements_
.insert(ref
);
704 void Connection::StatementRefDeleted(StatementRef
* ref
) {
705 StatementRefSet::iterator i
= open_statements_
.find(ref
);
706 if (i
== open_statements_
.end())
707 DLOG(FATAL
) << "Could not find statement";
709 open_statements_
.erase(i
);
712 void Connection::AddTaggedHistogram(const std::string
& name
,
713 size_t sample
) const {
714 if (histogram_tag_
.empty())
717 // TODO(shess): The histogram macros create a bit of static storage
718 // for caching the histogram object. This code shouldn't execute
719 // often enough for such caching to be crucial. If it becomes an
720 // issue, the object could be cached alongside histogram_prefix_.
721 std::string full_histogram_name
= name
+ "." + histogram_tag_
;
722 base::HistogramBase
* histogram
=
723 base::SparseHistogram::FactoryGet(
725 base::HistogramBase::kUmaTargetedHistogramFlag
);
727 histogram
->Add(sample
);
730 int Connection::OnSqliteError(int err
, sql::Statement
*stmt
) {
731 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err
);
732 AddTaggedHistogram("Sqlite.Error", err
);
734 // Always log the error.
735 LOG(ERROR
) << "sqlite error " << err
736 << ", errno " << GetLastErrno()
737 << ": " << GetErrorMessage();
739 if (!error_callback_
.is_null()) {
740 error_callback_
.Run(err
, stmt
);
744 // TODO(shess): Remove |error_delegate_| once everything is
745 // converted to |error_callback_|.
746 if (error_delegate_
.get())
747 return error_delegate_
->OnError(err
, this, stmt
);
749 // The default handling is to assert on debug and to ignore on release.
750 DLOG(FATAL
) << GetErrorMessage();