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/string_util.h"
13 #include "base/stringprintf.h"
14 #include "base/utf_string_conversions.h"
15 #include "sql/statement.h"
16 #include "third_party/sqlite/sqlite3.h"
20 // Spin for up to a second waiting for the lock to clear when setting
22 // TODO(shess): Better story on this. http://crbug.com/56559
23 const int kBusyTimeoutSeconds
= 1;
25 class ScopedBusyTimeout
{
27 explicit ScopedBusyTimeout(sqlite3
* db
)
30 ~ScopedBusyTimeout() {
31 sqlite3_busy_timeout(db_
, 0);
34 int SetTimeout(base::TimeDelta timeout
) {
35 DCHECK_LT(timeout
.InMilliseconds(), INT_MAX
);
36 return sqlite3_busy_timeout(db_
,
37 static_cast<int>(timeout
.InMilliseconds()));
44 // Helper to "safely" enable writable_schema. No error checking
45 // because it is reasonable to just forge ahead in case of an error.
46 // If turning it on fails, then most likely nothing will work, whereas
47 // if turning it off fails, it only matters if some code attempts to
48 // continue working with the database and tries to modify the
49 // sqlite_master table (none of our code does this).
50 class ScopedWritableSchema
{
52 explicit ScopedWritableSchema(sqlite3
* db
)
54 sqlite3_exec(db_
, "PRAGMA writable_schema=1", NULL
, NULL
, NULL
);
56 ~ScopedWritableSchema() {
57 sqlite3_exec(db_
, "PRAGMA writable_schema=0", NULL
, NULL
, NULL
);
68 bool StatementID::operator<(const StatementID
& other
) const {
69 if (number_
!= other
.number_
)
70 return number_
< other
.number_
;
71 return strcmp(str_
, other
.str_
) < 0;
74 ErrorDelegate::~ErrorDelegate() {
77 Connection::StatementRef::StatementRef(Connection
* connection
,
80 : connection_(connection
),
82 was_valid_(was_valid
) {
84 connection_
->StatementRefCreated(this);
87 Connection::StatementRef::~StatementRef() {
89 connection_
->StatementRefDeleted(this);
93 void Connection::StatementRef::Close(bool forced
) {
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.
103 sqlite3_finalize(stmt_
);
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()
118 exclusive_locking_(false),
119 transaction_nesting_(0),
120 needs_rollback_(false),
123 error_delegate_(NULL
) {
126 Connection::~Connection() {
130 bool Connection::Open(const base::FilePath
& path
) {
132 return OpenInternal(WideToUTF8(path
.value()));
133 #elif defined(OS_POSIX)
134 return OpenInternal(path
.value());
138 bool Connection::OpenInMemory() {
140 return OpenInternal(":memory:");
143 void Connection::CloseInternal(bool forced
) {
144 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
145 // will delete the -journal file. For ChromiumOS or other more
146 // embedded systems, this is probably not appropriate, whereas on
147 // desktop it might make some sense.
149 // sqlite3_close() needs all prepared statements to be finalized.
151 // Release cached statements.
152 statement_cache_
.clear();
154 // With cached statements released, in-use statements will remain.
155 // Closing the database while statements are in use is an API
156 // violation, except for forced close (which happens from within a
157 // statement's error handler).
158 DCHECK(forced
|| open_statements_
.empty());
160 // Deactivate any outstanding statements so sqlite3_close() works.
161 for (StatementRefSet::iterator i
= open_statements_
.begin();
162 i
!= open_statements_
.end(); ++i
)
164 open_statements_
.clear();
167 // Call to AssertIOAllowed() cannot go at the beginning of the function
168 // because Close() must be called from destructor to clean
169 // statement_cache_, it won't cause any disk access and it most probably
170 // will happen on thread not allowing disk access.
171 // TODO(paivanof@gmail.com): This should move to the beginning
172 // of the function. http://crbug.com/136655.
174 // TODO(shess): Histogram for failure.
180 void Connection::Close() {
181 // If the database was already closed by RazeAndClose(), then no
182 // need to close again. Clear the |poisoned_| bit so that incorrect
183 // API calls are caught.
189 CloseInternal(false);
192 void Connection::Preload() {
196 DLOG_IF(FATAL
, !poisoned_
) << "Cannot preload null db";
200 // A statement must be open for the preload command to work. If the meta
201 // table doesn't exist, it probably means this is a new database and there
202 // is nothing to preload (so it's OK we do nothing).
203 if (!DoesTableExist("meta"))
205 Statement
dummy(GetUniqueStatement("SELECT * FROM meta"));
209 #if !defined(USE_SYSTEM_SQLITE)
210 // This function is only defined in Chromium's version of sqlite.
211 // Do not call it when using system sqlite.
212 sqlite3_preload(db_
);
216 // Create an in-memory database with the existing database's page
217 // size, then backup that database over the existing database.
218 bool Connection::Raze() {
222 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
226 if (transaction_nesting_
> 0) {
227 DLOG(FATAL
) << "Cannot raze within a transaction";
231 sql::Connection null_db
;
232 if (!null_db
.OpenInMemory()) {
233 DLOG(FATAL
) << "Unable to open in-memory database.";
238 // Enforce SQLite restrictions on |page_size_|.
239 DCHECK(!(page_size_
& (page_size_
- 1)))
240 << " page_size_ " << page_size_
<< " is not a power of two.";
241 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
242 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
243 const std::string sql
= StringPrintf("PRAGMA page_size=%d", page_size_
);
244 if (!null_db
.Execute(sql
.c_str()))
248 #if defined(OS_ANDROID)
249 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
250 // in-memory databases do not respect this define.
251 // TODO(shess): Figure out a way to set this without using platform
252 // specific code. AFAICT from sqlite3.c, the only way to do it
253 // would be to create an actual filesystem database, which is
255 if (!null_db
.Execute("PRAGMA auto_vacuum = 1"))
259 // The page size doesn't take effect until a database has pages, and
260 // at this point the null database has none. Changing the schema
261 // version will create the first page. This will not affect the
262 // schema version in the resulting database, as SQLite's backup
263 // implementation propagates the schema version from the original
264 // connection to the new version of the database, incremented by one
265 // so that other readers see the schema change and act accordingly.
266 if (!null_db
.Execute("PRAGMA schema_version = 1"))
269 // SQLite tracks the expected number of database pages in the first
270 // page, and if it does not match the total retrieved from a
271 // filesystem call, treats the database as corrupt. This situation
272 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
273 // used to hint to SQLite to soldier on in that case, specifically
274 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
275 // sqlite3.c lockBtree().]
276 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
277 // page_size" can be used to query such a database.
278 ScopedWritableSchema
writable_schema(db_
);
280 sqlite3_backup
* backup
= sqlite3_backup_init(db_
, "main",
281 null_db
.db_
, "main");
283 DLOG(FATAL
) << "Unable to start sqlite3_backup().";
287 // -1 backs up the entire database.
288 int rc
= sqlite3_backup_step(backup
, -1);
289 int pages
= sqlite3_backup_pagecount(backup
);
290 sqlite3_backup_finish(backup
);
292 // The destination database was locked.
293 if (rc
== SQLITE_BUSY
) {
297 // The entire database should have been backed up.
298 if (rc
!= SQLITE_DONE
) {
299 DLOG(FATAL
) << "Unable to copy entire null database.";
303 // Exactly one page should have been backed up. If this breaks,
304 // check this function to make sure assumptions aren't being broken.
310 bool Connection::RazeWithTimout(base::TimeDelta timeout
) {
312 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
316 ScopedBusyTimeout
busy_timeout(db_
);
317 busy_timeout
.SetTimeout(timeout
);
321 bool Connection::RazeAndClose() {
323 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
327 // Raze() cannot run in a transaction.
328 while (transaction_nesting_
) {
329 RollbackTransaction();
332 bool result
= Raze();
336 // Mark the database so that future API calls fail appropriately,
337 // but don't DCHECK (because after calling this function they are
338 // expected to fail).
344 bool Connection::BeginTransaction() {
345 if (needs_rollback_
) {
346 DCHECK_GT(transaction_nesting_
, 0);
348 // When we're going to rollback, fail on this begin and don't actually
349 // mark us as entering the nested transaction.
354 if (!transaction_nesting_
) {
355 needs_rollback_
= false;
357 Statement
begin(GetCachedStatement(SQL_FROM_HERE
, "BEGIN TRANSACTION"));
361 transaction_nesting_
++;
365 void Connection::RollbackTransaction() {
366 if (!transaction_nesting_
) {
367 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
371 transaction_nesting_
--;
373 if (transaction_nesting_
> 0) {
374 // Mark the outermost transaction as needing rollback.
375 needs_rollback_
= true;
382 bool Connection::CommitTransaction() {
383 if (!transaction_nesting_
) {
384 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
387 transaction_nesting_
--;
389 if (transaction_nesting_
> 0) {
390 // Mark any nested transactions as failing after we've already got one.
391 return !needs_rollback_
;
394 if (needs_rollback_
) {
399 Statement
commit(GetCachedStatement(SQL_FROM_HERE
, "COMMIT"));
403 int Connection::ExecuteAndReturnErrorCode(const char* sql
) {
406 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
409 return sqlite3_exec(db_
, sql
, NULL
, NULL
, NULL
);
412 bool Connection::Execute(const char* sql
) {
414 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
418 int error
= ExecuteAndReturnErrorCode(sql
);
419 if (error
!= SQLITE_OK
)
420 error
= OnSqliteError(error
, NULL
);
422 // This needs to be a FATAL log because the error case of arriving here is
423 // that there's a malformed SQL statement. This can arise in development if
424 // a change alters the schema but not all queries adjust.
425 if (error
== SQLITE_ERROR
)
426 DLOG(FATAL
) << "SQL Error in " << sql
<< ", " << GetErrorMessage();
427 return error
== SQLITE_OK
;
430 bool Connection::ExecuteWithTimeout(const char* sql
, base::TimeDelta timeout
) {
432 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
436 ScopedBusyTimeout
busy_timeout(db_
);
437 busy_timeout
.SetTimeout(timeout
);
441 bool Connection::HasCachedStatement(const StatementID
& id
) const {
442 return statement_cache_
.find(id
) != statement_cache_
.end();
445 scoped_refptr
<Connection::StatementRef
> Connection::GetCachedStatement(
446 const StatementID
& id
,
448 CachedStatementMap::iterator i
= statement_cache_
.find(id
);
449 if (i
!= statement_cache_
.end()) {
450 // Statement is in the cache. It should still be active (we're the only
451 // one invalidating cached statements, and we'll remove it from the cache
452 // if we do that. Make sure we reset it before giving out the cached one in
453 // case it still has some stuff bound.
454 DCHECK(i
->second
->is_valid());
455 sqlite3_reset(i
->second
->stmt());
459 scoped_refptr
<StatementRef
> statement
= GetUniqueStatement(sql
);
460 if (statement
->is_valid())
461 statement_cache_
[id
] = statement
; // Only cache valid statements.
465 scoped_refptr
<Connection::StatementRef
> Connection::GetUniqueStatement(
469 // Return inactive statement.
471 return new StatementRef(NULL
, NULL
, poisoned_
);
473 sqlite3_stmt
* stmt
= NULL
;
474 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
475 if (rc
!= SQLITE_OK
) {
476 // This is evidence of a syntax error in the incoming SQL.
477 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
479 // It could also be database corruption.
480 OnSqliteError(rc
, NULL
);
481 return new StatementRef(NULL
, NULL
, false);
483 return new StatementRef(this, stmt
, true);
486 scoped_refptr
<Connection::StatementRef
> Connection::GetUntrackedStatement(
487 const char* sql
) const {
488 // Return inactive statement.
490 return new StatementRef(NULL
, NULL
, poisoned_
);
492 sqlite3_stmt
* stmt
= NULL
;
493 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
494 if (rc
!= SQLITE_OK
) {
495 // This is evidence of a syntax error in the incoming SQL.
496 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
497 return new StatementRef(NULL
, NULL
, false);
499 return new StatementRef(NULL
, stmt
, true);
502 bool Connection::IsSQLValid(const char* sql
) {
505 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
509 sqlite3_stmt
* stmt
= NULL
;
510 if (sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
) != SQLITE_OK
)
513 sqlite3_finalize(stmt
);
517 bool Connection::DoesTableExist(const char* table_name
) const {
518 return DoesTableOrIndexExist(table_name
, "table");
521 bool Connection::DoesIndexExist(const char* index_name
) const {
522 return DoesTableOrIndexExist(index_name
, "index");
525 bool Connection::DoesTableOrIndexExist(
526 const char* name
, const char* type
) const {
527 const char* kSql
= "SELECT name FROM sqlite_master WHERE type=? AND name=?";
528 Statement
statement(GetUntrackedStatement(kSql
));
529 statement
.BindString(0, type
);
530 statement
.BindString(1, name
);
532 return statement
.Step(); // Table exists if any row was returned.
535 bool Connection::DoesColumnExist(const char* table_name
,
536 const char* column_name
) const {
537 std::string
sql("PRAGMA TABLE_INFO(");
538 sql
.append(table_name
);
541 Statement
statement(GetUntrackedStatement(sql
.c_str()));
542 while (statement
.Step()) {
543 if (!statement
.ColumnString(1).compare(column_name
))
549 int64
Connection::GetLastInsertRowId() const {
551 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
554 return sqlite3_last_insert_rowid(db_
);
557 int Connection::GetLastChangeCount() const {
559 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
562 return sqlite3_changes(db_
);
565 int Connection::GetErrorCode() const {
568 return sqlite3_errcode(db_
);
571 int Connection::GetLastErrno() const {
576 if (SQLITE_OK
!= sqlite3_file_control(db_
, NULL
, SQLITE_LAST_ERRNO
, &err
))
582 const char* Connection::GetErrorMessage() const {
584 return "sql::Connection has no connection.";
585 return sqlite3_errmsg(db_
);
588 bool Connection::OpenInternal(const std::string
& file_name
) {
592 DLOG(FATAL
) << "sql::Connection is already open.";
596 // If |poisoned_| is set, it means an error handler called
597 // RazeAndClose(). Until regular Close() is called, the caller
598 // should be treating the database as open, but is_open() currently
599 // only considers the sqlite3 handle's state.
600 // TODO(shess): Revise is_open() to consider poisoned_, and review
601 // to see if any non-testing code even depends on it.
602 DLOG_IF(FATAL
, poisoned_
) << "sql::Connection is already open.";
604 int err
= sqlite3_open(file_name
.c_str(), &db_
);
605 if (err
!= SQLITE_OK
) {
606 // Histogram failures specific to initial open for debugging
608 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err
& 0xff, 50);
610 OnSqliteError(err
, NULL
);
616 // sqlite3_open() does not actually read the database file (unless a
617 // hot journal is found). Successfully executing this pragma on an
618 // existing database requires a valid header on page 1.
619 // TODO(shess): For now, just probing to see what the lay of the
620 // land is. If it's mostly SQLITE_NOTADB, then the database should
622 err
= ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
623 if (err
!= SQLITE_OK
)
624 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err
& 0xff, 50);
626 // Enable extended result codes to provide more color on I/O errors.
627 // Not having extended result codes is not a fatal problem, as
628 // Chromium code does not attempt to handle I/O errors anyhow. The
629 // current implementation always returns SQLITE_OK, the DCHECK is to
630 // quickly notify someone if SQLite changes.
631 err
= sqlite3_extended_result_codes(db_
, 1);
632 DCHECK_EQ(err
, SQLITE_OK
) << "Could not enable extended result codes";
634 // If indicated, lock up the database before doing anything else, so
635 // that the following code doesn't have to deal with locking.
636 // TODO(shess): This code is brittle. Find the cases where code
637 // doesn't request |exclusive_locking_| and audit that it does the
638 // right thing with SQLITE_BUSY, and that it doesn't make
639 // assumptions about who might change things in the database.
640 // http://crbug.com/56559
641 if (exclusive_locking_
) {
642 // TODO(shess): This should probably be a full CHECK(). Code
643 // which requests exclusive locking but doesn't get it is almost
644 // certain to be ill-tested.
645 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
646 DLOG(FATAL
) << "Could not set locking mode: " << GetErrorMessage();
649 // http://www.sqlite.org/pragma.html#pragma_journal_mode
650 // DELETE (default) - delete -journal file to commit.
651 // TRUNCATE - truncate -journal file to commit.
652 // PERSIST - zero out header of -journal file to commit.
653 // journal_size_limit provides size to trim to in PERSIST.
654 // TODO(shess): Figure out if PERSIST and journal_size_limit really
655 // matter. In theory, it keeps pages pre-allocated, so if
656 // transactions usually fit, it should be faster.
657 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
658 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
660 const base::TimeDelta kBusyTimeout
=
661 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds
);
663 if (page_size_
!= 0) {
664 // Enforce SQLite restrictions on |page_size_|.
665 DCHECK(!(page_size_
& (page_size_
- 1)))
666 << " page_size_ " << page_size_
<< " is not a power of two.";
667 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
668 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
669 const std::string sql
= StringPrintf("PRAGMA page_size=%d", page_size_
);
670 if (!ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
))
671 DLOG(FATAL
) << "Could not set page size: " << GetErrorMessage();
674 if (cache_size_
!= 0) {
675 const std::string sql
= StringPrintf("PRAGMA cache_size=%d", cache_size_
);
676 if (!ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
))
677 DLOG(FATAL
) << "Could not set cache size: " << GetErrorMessage();
680 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout
)) {
681 DLOG(FATAL
) << "Could not enable secure_delete: " << GetErrorMessage();
689 void Connection::DoRollback() {
690 Statement
rollback(GetCachedStatement(SQL_FROM_HERE
, "ROLLBACK"));
692 needs_rollback_
= false;
695 void Connection::StatementRefCreated(StatementRef
* ref
) {
696 DCHECK(open_statements_
.find(ref
) == open_statements_
.end());
697 open_statements_
.insert(ref
);
700 void Connection::StatementRefDeleted(StatementRef
* ref
) {
701 StatementRefSet::iterator i
= open_statements_
.find(ref
);
702 if (i
== open_statements_
.end())
703 DLOG(FATAL
) << "Could not find statement";
705 open_statements_
.erase(i
);
708 int Connection::OnSqliteError(int err
, sql::Statement
*stmt
) {
709 // Strip extended error codes.
710 int base_err
= err
&0xff;
712 static size_t kSqliteErrorMax
= 50;
713 UMA_HISTOGRAM_ENUMERATION("Sqlite.Error", base_err
, kSqliteErrorMax
);
714 if (!error_histogram_name_
.empty()) {
715 // TODO(shess): The histogram macros create a bit of static
716 // storage for caching the histogram object. Since SQLite is
717 // being used for I/O, generally without error, this code
718 // shouldn't execute often enough for such caching to be crucial.
719 // If it becomes an issue, the object could be cached alongside
720 // error_histogram_name_.
721 base::HistogramBase
* histogram
=
722 base::LinearHistogram::FactoryGet(
723 error_histogram_name_
, 1, kSqliteErrorMax
, kSqliteErrorMax
+ 1,
724 base::HistogramBase::kUmaTargetedHistogramFlag
);
726 histogram
->Add(base_err
);
729 // Always log the error.
730 LOG(ERROR
) << "sqlite error " << err
731 << ", errno " << GetLastErrno()
732 << ": " << GetErrorMessage();
734 if (error_delegate_
.get())
735 return error_delegate_
->OnError(err
, this, stmt
);
737 // The default handling is to assert on debug and to ignore on release.
738 DLOG(FATAL
) << GetErrorMessage();