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/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"
29 // Spin for up to a second waiting for the lock to clear when setting
31 // TODO(shess): Better story on this. http://crbug.com/56559
32 const int kBusyTimeoutSeconds
= 1;
34 class ScopedBusyTimeout
{
36 explicit ScopedBusyTimeout(sqlite3
* 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()));
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
{
61 explicit ScopedWritableSchema(sqlite3
* 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
);
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
) {
77 sqlite3_backup
* backup
= sqlite3_backup_init(dst
, db_name
, src
, db_name
);
79 // Since this call only sets things up, this indicates a gross
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
93 if (rc
== SQLITE_DONE
)
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
] == '_')) {
114 // SQLite automatically calls sqlite3_initialize() lazily, but
115 // sqlite3_initialize() uses double-checked locking and thus can have
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
) {
131 int rc
= sqlite3_file_control(db
, NULL
, SQLITE_FCNTL_FILE_POINTER
, file
);
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
)
149 Connection::ErrorIgnorerCallback
* Connection::current_ignorer_cb_
= NULL
;
152 bool Connection::ShouldIgnoreSqliteError(int error
) {
153 if (!current_ignorer_cb_
)
155 return current_ignorer_cb_
->Run(error
);
159 void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback
* cb
) {
160 CHECK(current_ignorer_cb_
== NULL
);
161 current_ignorer_cb_
= cb
;
165 void Connection::ResetErrorIgnorer() {
166 CHECK(current_ignorer_cb_
);
167 current_ignorer_cb_
= NULL
;
170 bool StatementID::operator<(const StatementID
& other
) const {
171 if (number_
!= other
.number_
)
172 return number_
< other
.number_
;
173 return strcmp(str_
, other
.str_
) < 0;
176 Connection::StatementRef::StatementRef(Connection
* connection
,
179 : connection_(connection
),
181 was_valid_(was_valid
) {
183 connection_
->StatementRefCreated(this);
186 Connection::StatementRef::~StatementRef() {
188 connection_
->StatementRefDeleted(this);
192 void Connection::StatementRef::Close(bool forced
) {
194 // Call to AssertIOAllowed() cannot go at the beginning of the function
195 // because Close() is called unconditionally from destructor to clean
196 // connection_. And if this is inactive statement this won't cause any
197 // disk access and destructor most probably will be called on thread
198 // not allowing disk access.
199 // TODO(paivanof@gmail.com): This should move to the beginning
200 // of the function. http://crbug.com/136655.
202 sqlite3_finalize(stmt_
);
205 connection_
= NULL
; // The connection may be getting deleted.
207 // Forced close is expected to happen from a statement error
208 // handler. In that case maintain the sense of |was_valid_| which
209 // previously held for this ref.
210 was_valid_
= was_valid_
&& forced
;
213 Connection::Connection()
217 exclusive_locking_(false),
218 restrict_to_user_(false),
219 transaction_nesting_(0),
220 needs_rollback_(false),
225 Connection::~Connection() {
229 bool Connection::Open(const base::FilePath
& path
) {
230 if (!histogram_tag_
.empty()) {
232 if (base::GetFileSize(path
, &size_64
)) {
233 size_t sample
= static_cast<size_t>(size_64
/ 1024);
234 std::string full_histogram_name
= "Sqlite.SizeKB." + histogram_tag_
;
235 base::HistogramBase
* histogram
=
236 base::Histogram::FactoryGet(
237 full_histogram_name
, 1, 1000000, 50,
238 base::HistogramBase::kUmaTargetedHistogramFlag
);
240 histogram
->Add(sample
);
245 return OpenInternal(base::WideToUTF8(path
.value()), RETRY_ON_POISON
);
246 #elif defined(OS_POSIX)
247 return OpenInternal(path
.value(), RETRY_ON_POISON
);
251 bool Connection::OpenInMemory() {
253 return OpenInternal(":memory:", NO_RETRY
);
256 bool Connection::OpenTemporary() {
257 return OpenInternal("", NO_RETRY
);
260 void Connection::CloseInternal(bool forced
) {
261 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
262 // will delete the -journal file. For ChromiumOS or other more
263 // embedded systems, this is probably not appropriate, whereas on
264 // desktop it might make some sense.
266 // sqlite3_close() needs all prepared statements to be finalized.
268 // Release cached statements.
269 statement_cache_
.clear();
271 // With cached statements released, in-use statements will remain.
272 // Closing the database while statements are in use is an API
273 // violation, except for forced close (which happens from within a
274 // statement's error handler).
275 DCHECK(forced
|| open_statements_
.empty());
277 // Deactivate any outstanding statements so sqlite3_close() works.
278 for (StatementRefSet::iterator i
= open_statements_
.begin();
279 i
!= open_statements_
.end(); ++i
)
281 open_statements_
.clear();
284 // Call to AssertIOAllowed() cannot go at the beginning of the function
285 // because Close() must be called from destructor to clean
286 // statement_cache_, it won't cause any disk access and it most probably
287 // will happen on thread not allowing disk access.
288 // TODO(paivanof@gmail.com): This should move to the beginning
289 // of the function. http://crbug.com/136655.
292 int rc
= sqlite3_close(db_
);
293 if (rc
!= SQLITE_OK
) {
294 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc
);
295 DLOG(FATAL
) << "sqlite3_close failed: " << GetErrorMessage();
301 void Connection::Close() {
302 // If the database was already closed by RazeAndClose(), then no
303 // need to close again. Clear the |poisoned_| bit so that incorrect
304 // API calls are caught.
310 CloseInternal(false);
313 void Connection::Preload() {
317 DLOG_IF(FATAL
, !poisoned_
) << "Cannot preload null db";
321 // Use local settings if provided, otherwise use documented defaults. The
322 // actual results could be fetching via PRAGMA calls.
323 const int page_size
= page_size_
? page_size_
: 1024;
324 sqlite3_int64 preload_size
= page_size
* (cache_size_
? cache_size_
: 2000);
325 if (preload_size
< 1)
328 sqlite3_file
* file
= NULL
;
329 int rc
= GetSqlite3File(db_
, &file
);
333 sqlite3_int64 file_size
= 0;
334 rc
= file
->pMethods
->xFileSize(file
, &file_size
);
338 // Don't preload more than the file contains.
339 if (preload_size
> file_size
)
340 preload_size
= file_size
;
342 scoped_ptr
<char[]> buf(new char[page_size
]);
343 for (sqlite3_int64 pos
= 0; pos
< file_size
; pos
+= page_size
) {
344 rc
= file
->pMethods
->xRead(file
, buf
.get(), page_size
, pos
);
350 void Connection::TrimMemory(bool aggressively
) {
354 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
355 int original_cache_size
;
357 Statement
sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
358 if (!sql_get_original
.Step()) {
359 DLOG(WARNING
) << "Could not get cache size " << GetErrorMessage();
362 original_cache_size
= sql_get_original
.ColumnInt(0);
364 int shrink_cache_size
= aggressively
? 1 : (original_cache_size
/ 2);
366 // Force sqlite to try to reduce page cache usage.
367 const std::string sql_shrink
=
368 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size
);
369 if (!Execute(sql_shrink
.c_str()))
370 DLOG(WARNING
) << "Could not shrink cache size: " << GetErrorMessage();
372 // Restore cache size.
373 const std::string sql_restore
=
374 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size
);
375 if (!Execute(sql_restore
.c_str()))
376 DLOG(WARNING
) << "Could not restore cache size: " << GetErrorMessage();
379 // Create an in-memory database with the existing database's page
380 // size, then backup that database over the existing database.
381 bool Connection::Raze() {
385 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
389 if (transaction_nesting_
> 0) {
390 DLOG(FATAL
) << "Cannot raze within a transaction";
394 sql::Connection null_db
;
395 if (!null_db
.OpenInMemory()) {
396 DLOG(FATAL
) << "Unable to open in-memory database.";
401 // Enforce SQLite restrictions on |page_size_|.
402 DCHECK(!(page_size_
& (page_size_
- 1)))
403 << " page_size_ " << page_size_
<< " is not a power of two.";
404 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
405 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
406 const std::string sql
=
407 base::StringPrintf("PRAGMA page_size=%d", page_size_
);
408 if (!null_db
.Execute(sql
.c_str()))
412 #if defined(OS_ANDROID)
413 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
414 // in-memory databases do not respect this define.
415 // TODO(shess): Figure out a way to set this without using platform
416 // specific code. AFAICT from sqlite3.c, the only way to do it
417 // would be to create an actual filesystem database, which is
419 if (!null_db
.Execute("PRAGMA auto_vacuum = 1"))
423 // The page size doesn't take effect until a database has pages, and
424 // at this point the null database has none. Changing the schema
425 // version will create the first page. This will not affect the
426 // schema version in the resulting database, as SQLite's backup
427 // implementation propagates the schema version from the original
428 // connection to the new version of the database, incremented by one
429 // so that other readers see the schema change and act accordingly.
430 if (!null_db
.Execute("PRAGMA schema_version = 1"))
433 // SQLite tracks the expected number of database pages in the first
434 // page, and if it does not match the total retrieved from a
435 // filesystem call, treats the database as corrupt. This situation
436 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
437 // used to hint to SQLite to soldier on in that case, specifically
438 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
439 // sqlite3.c lockBtree().]
440 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
441 // page_size" can be used to query such a database.
442 ScopedWritableSchema
writable_schema(db_
);
444 const char* kMain
= "main";
445 int rc
= BackupDatabase(null_db
.db_
, db_
, kMain
);
446 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc
);
448 // The destination database was locked.
449 if (rc
== SQLITE_BUSY
) {
453 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
454 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
455 // isn't even big enough for one page. Either way, reach in and
456 // truncate it before trying again.
457 // TODO(shess): Maybe it would be worthwhile to just truncate from
459 if (rc
== SQLITE_NOTADB
|| rc
== SQLITE_IOERR_SHORT_READ
) {
460 sqlite3_file
* file
= NULL
;
461 rc
= GetSqlite3File(db_
, &file
);
462 if (rc
!= SQLITE_OK
) {
463 DLOG(FATAL
) << "Failure getting file handle.";
467 rc
= file
->pMethods
->xTruncate(file
, 0);
468 if (rc
!= SQLITE_OK
) {
469 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc
);
470 DLOG(FATAL
) << "Failed to truncate file.";
474 rc
= BackupDatabase(null_db
.db_
, db_
, kMain
);
475 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc
);
477 if (rc
!= SQLITE_DONE
) {
478 DLOG(FATAL
) << "Failed retrying Raze().";
482 // The entire database should have been backed up.
483 if (rc
!= SQLITE_DONE
) {
484 // TODO(shess): Figure out which other cases can happen.
485 DLOG(FATAL
) << "Unable to copy entire null database.";
492 bool Connection::RazeWithTimout(base::TimeDelta timeout
) {
494 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
498 ScopedBusyTimeout
busy_timeout(db_
);
499 busy_timeout
.SetTimeout(timeout
);
503 bool Connection::RazeAndClose() {
505 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
509 // Raze() cannot run in a transaction.
510 RollbackAllTransactions();
512 bool result
= Raze();
516 // Mark the database so that future API calls fail appropriately,
517 // but don't DCHECK (because after calling this function they are
518 // expected to fail).
524 void Connection::Poison() {
526 DLOG_IF(FATAL
, !poisoned_
) << "Cannot poison null db";
530 RollbackAllTransactions();
533 // Mark the database so that future API calls fail appropriately,
534 // but don't DCHECK (because after calling this function they are
535 // expected to fail).
539 // TODO(shess): To the extent possible, figure out the optimal
540 // ordering for these deletes which will prevent other connections
541 // from seeing odd behavior. For instance, it may be necessary to
542 // manually lock the main database file in a SQLite-compatible fashion
543 // (to prevent other processes from opening it), then delete the
544 // journal files, then delete the main database file. Another option
545 // might be to lock the main database file and poison the header with
546 // junk to prevent other processes from opening it successfully (like
547 // Gears "SQLite poison 3" trick).
550 bool Connection::Delete(const base::FilePath
& path
) {
551 base::ThreadRestrictions::AssertIOAllowed();
553 base::FilePath
journal_path(path
.value() + FILE_PATH_LITERAL("-journal"));
554 base::FilePath
wal_path(path
.value() + FILE_PATH_LITERAL("-wal"));
556 base::DeleteFile(journal_path
, false);
557 base::DeleteFile(wal_path
, false);
558 base::DeleteFile(path
, false);
560 return !base::PathExists(journal_path
) &&
561 !base::PathExists(wal_path
) &&
562 !base::PathExists(path
);
565 bool Connection::BeginTransaction() {
566 if (needs_rollback_
) {
567 DCHECK_GT(transaction_nesting_
, 0);
569 // When we're going to rollback, fail on this begin and don't actually
570 // mark us as entering the nested transaction.
575 if (!transaction_nesting_
) {
576 needs_rollback_
= false;
578 Statement
begin(GetCachedStatement(SQL_FROM_HERE
, "BEGIN TRANSACTION"));
582 transaction_nesting_
++;
586 void Connection::RollbackTransaction() {
587 if (!transaction_nesting_
) {
588 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
592 transaction_nesting_
--;
594 if (transaction_nesting_
> 0) {
595 // Mark the outermost transaction as needing rollback.
596 needs_rollback_
= true;
603 bool Connection::CommitTransaction() {
604 if (!transaction_nesting_
) {
605 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
608 transaction_nesting_
--;
610 if (transaction_nesting_
> 0) {
611 // Mark any nested transactions as failing after we've already got one.
612 return !needs_rollback_
;
615 if (needs_rollback_
) {
620 Statement
commit(GetCachedStatement(SQL_FROM_HERE
, "COMMIT"));
624 void Connection::RollbackAllTransactions() {
625 if (transaction_nesting_
> 0) {
626 transaction_nesting_
= 0;
631 bool Connection::AttachDatabase(const base::FilePath
& other_db_path
,
632 const char* attachment_point
) {
633 DCHECK(ValidAttachmentPoint(attachment_point
));
635 Statement
s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
637 s
.BindString16(0, other_db_path
.value());
639 s
.BindString(0, other_db_path
.value());
641 s
.BindString(1, attachment_point
);
645 bool Connection::DetachDatabase(const char* attachment_point
) {
646 DCHECK(ValidAttachmentPoint(attachment_point
));
648 Statement
s(GetUniqueStatement("DETACH DATABASE ?"));
649 s
.BindString(0, attachment_point
);
653 int Connection::ExecuteAndReturnErrorCode(const char* sql
) {
656 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
659 return sqlite3_exec(db_
, sql
, NULL
, NULL
, NULL
);
662 bool Connection::Execute(const char* sql
) {
664 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
668 int error
= ExecuteAndReturnErrorCode(sql
);
669 if (error
!= SQLITE_OK
)
670 error
= OnSqliteError(error
, NULL
, sql
);
672 // This needs to be a FATAL log because the error case of arriving here is
673 // that there's a malformed SQL statement. This can arise in development if
674 // a change alters the schema but not all queries adjust. This can happen
675 // in production if the schema is corrupted.
676 if (error
== SQLITE_ERROR
)
677 DLOG(FATAL
) << "SQL Error in " << sql
<< ", " << GetErrorMessage();
678 return error
== SQLITE_OK
;
681 bool Connection::ExecuteWithTimeout(const char* sql
, base::TimeDelta timeout
) {
683 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
687 ScopedBusyTimeout
busy_timeout(db_
);
688 busy_timeout
.SetTimeout(timeout
);
692 bool Connection::HasCachedStatement(const StatementID
& id
) const {
693 return statement_cache_
.find(id
) != statement_cache_
.end();
696 scoped_refptr
<Connection::StatementRef
> Connection::GetCachedStatement(
697 const StatementID
& id
,
699 CachedStatementMap::iterator i
= statement_cache_
.find(id
);
700 if (i
!= statement_cache_
.end()) {
701 // Statement is in the cache. It should still be active (we're the only
702 // one invalidating cached statements, and we'll remove it from the cache
703 // if we do that. Make sure we reset it before giving out the cached one in
704 // case it still has some stuff bound.
705 DCHECK(i
->second
->is_valid());
706 sqlite3_reset(i
->second
->stmt());
710 scoped_refptr
<StatementRef
> statement
= GetUniqueStatement(sql
);
711 if (statement
->is_valid())
712 statement_cache_
[id
] = statement
; // Only cache valid statements.
716 scoped_refptr
<Connection::StatementRef
> Connection::GetUniqueStatement(
720 // Return inactive statement.
722 return new StatementRef(NULL
, NULL
, poisoned_
);
724 sqlite3_stmt
* stmt
= NULL
;
725 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
726 if (rc
!= SQLITE_OK
) {
727 // This is evidence of a syntax error in the incoming SQL.
728 if (!ShouldIgnoreSqliteError(rc
))
729 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
731 // It could also be database corruption.
732 OnSqliteError(rc
, NULL
, sql
);
733 return new StatementRef(NULL
, NULL
, false);
735 return new StatementRef(this, stmt
, true);
738 scoped_refptr
<Connection::StatementRef
> Connection::GetUntrackedStatement(
739 const char* sql
) const {
740 // Return inactive statement.
742 return new StatementRef(NULL
, NULL
, poisoned_
);
744 sqlite3_stmt
* stmt
= NULL
;
745 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
746 if (rc
!= SQLITE_OK
) {
747 // This is evidence of a syntax error in the incoming SQL.
748 if (!ShouldIgnoreSqliteError(rc
))
749 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
750 return new StatementRef(NULL
, NULL
, false);
752 return new StatementRef(NULL
, stmt
, true);
755 std::string
Connection::GetSchema() const {
756 // The ORDER BY should not be necessary, but relying on organic
757 // order for something like this is questionable.
759 "SELECT type, name, tbl_name, sql "
760 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
761 Statement
statement(GetUntrackedStatement(kSql
));
764 while (statement
.Step()) {
765 schema
+= statement
.ColumnString(0);
767 schema
+= statement
.ColumnString(1);
769 schema
+= statement
.ColumnString(2);
771 schema
+= statement
.ColumnString(3);
778 bool Connection::IsSQLValid(const char* sql
) {
781 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
785 sqlite3_stmt
* stmt
= NULL
;
786 if (sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
) != SQLITE_OK
)
789 sqlite3_finalize(stmt
);
793 bool Connection::DoesTableExist(const char* table_name
) const {
794 return DoesTableOrIndexExist(table_name
, "table");
797 bool Connection::DoesIndexExist(const char* index_name
) const {
798 return DoesTableOrIndexExist(index_name
, "index");
801 bool Connection::DoesTableOrIndexExist(
802 const char* name
, const char* type
) const {
804 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
805 Statement
statement(GetUntrackedStatement(kSql
));
807 // This can happen if the database is corrupt and the error is being ignored
808 // for testing purposes.
809 if (!statement
.is_valid())
812 statement
.BindString(0, type
);
813 statement
.BindString(1, name
);
815 return statement
.Step(); // Table exists if any row was returned.
818 bool Connection::DoesColumnExist(const char* table_name
,
819 const char* column_name
) const {
820 std::string
sql("PRAGMA TABLE_INFO(");
821 sql
.append(table_name
);
824 Statement
statement(GetUntrackedStatement(sql
.c_str()));
826 // This can happen if the database is corrupt and the error is being ignored
827 // for testing purposes.
828 if (!statement
.is_valid())
831 while (statement
.Step()) {
832 if (!base::strcasecmp(statement
.ColumnString(1).c_str(), column_name
))
838 int64
Connection::GetLastInsertRowId() const {
840 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
843 return sqlite3_last_insert_rowid(db_
);
846 int Connection::GetLastChangeCount() const {
848 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
851 return sqlite3_changes(db_
);
854 int Connection::GetErrorCode() const {
857 return sqlite3_errcode(db_
);
860 int Connection::GetLastErrno() const {
865 if (SQLITE_OK
!= sqlite3_file_control(db_
, NULL
, SQLITE_LAST_ERRNO
, &err
))
871 const char* Connection::GetErrorMessage() const {
873 return "sql::Connection has no connection.";
874 return sqlite3_errmsg(db_
);
877 bool Connection::OpenInternal(const std::string
& file_name
,
878 Connection::Retry retry_flag
) {
882 DLOG(FATAL
) << "sql::Connection is already open.";
886 // Make sure sqlite3_initialize() is called before anything else.
889 // If |poisoned_| is set, it means an error handler called
890 // RazeAndClose(). Until regular Close() is called, the caller
891 // should be treating the database as open, but is_open() currently
892 // only considers the sqlite3 handle's state.
893 // TODO(shess): Revise is_open() to consider poisoned_, and review
894 // to see if any non-testing code even depends on it.
895 DLOG_IF(FATAL
, poisoned_
) << "sql::Connection is already open.";
898 int err
= sqlite3_open(file_name
.c_str(), &db_
);
899 if (err
!= SQLITE_OK
) {
900 // Extended error codes cannot be enabled until a handle is
901 // available, fetch manually.
902 err
= sqlite3_extended_errcode(db_
);
904 // Histogram failures specific to initial open for debugging
906 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err
);
908 OnSqliteError(err
, NULL
, "-- sqlite3_open()");
909 bool was_poisoned
= poisoned_
;
912 if (was_poisoned
&& retry_flag
== RETRY_ON_POISON
)
913 return OpenInternal(file_name
, NO_RETRY
);
917 // TODO(shess): OS_WIN support?
918 #if defined(OS_POSIX)
919 if (restrict_to_user_
) {
920 DCHECK_NE(file_name
, std::string(":memory"));
921 base::FilePath
file_path(file_name
);
923 // TODO(shess): Arguably, failure to retrieve and change
924 // permissions should be fatal if the file exists.
925 if (base::GetPosixFilePermissions(file_path
, &mode
)) {
926 mode
&= base::FILE_PERMISSION_USER_MASK
;
927 base::SetPosixFilePermissions(file_path
, mode
);
929 // SQLite sets the permissions on these files from the main
930 // database on create. Set them here in case they already exist
931 // at this point. Failure to set these permissions should not
932 // be fatal unless the file doesn't exist.
933 base::FilePath
journal_path(file_name
+ FILE_PATH_LITERAL("-journal"));
934 base::FilePath
wal_path(file_name
+ FILE_PATH_LITERAL("-wal"));
935 base::SetPosixFilePermissions(journal_path
, mode
);
936 base::SetPosixFilePermissions(wal_path
, mode
);
939 #endif // defined(OS_POSIX)
941 // SQLite uses a lookaside buffer to improve performance of small mallocs.
942 // Chromium already depends on small mallocs being efficient, so we disable
943 // this to avoid the extra memory overhead.
944 // This must be called immediatly after opening the database before any SQL
945 // statements are run.
946 sqlite3_db_config(db_
, SQLITE_DBCONFIG_LOOKASIDE
, NULL
, 0, 0);
948 // Enable extended result codes to provide more color on I/O errors.
949 // Not having extended result codes is not a fatal problem, as
950 // Chromium code does not attempt to handle I/O errors anyhow. The
951 // current implementation always returns SQLITE_OK, the DCHECK is to
952 // quickly notify someone if SQLite changes.
953 err
= sqlite3_extended_result_codes(db_
, 1);
954 DCHECK_EQ(err
, SQLITE_OK
) << "Could not enable extended result codes";
956 // sqlite3_open() does not actually read the database file (unless a
957 // hot journal is found). Successfully executing this pragma on an
958 // existing database requires a valid header on page 1.
959 // TODO(shess): For now, just probing to see what the lay of the
960 // land is. If it's mostly SQLITE_NOTADB, then the database should
962 err
= ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
963 if (err
!= SQLITE_OK
)
964 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err
);
966 #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
967 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
968 // REGEXP support. Add it in dynamically.
969 err
= sqlite3IcuInit(db_
);
970 DCHECK_EQ(err
, SQLITE_OK
) << "Could not enable ICU support";
971 #endif // OS_IOS && USE_SYSTEM_SQLITE
973 // If indicated, lock up the database before doing anything else, so
974 // that the following code doesn't have to deal with locking.
975 // TODO(shess): This code is brittle. Find the cases where code
976 // doesn't request |exclusive_locking_| and audit that it does the
977 // right thing with SQLITE_BUSY, and that it doesn't make
978 // assumptions about who might change things in the database.
979 // http://crbug.com/56559
980 if (exclusive_locking_
) {
981 // TODO(shess): This should probably be a failure. Code which
982 // requests exclusive locking but doesn't get it is almost certain
984 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
987 // http://www.sqlite.org/pragma.html#pragma_journal_mode
988 // DELETE (default) - delete -journal file to commit.
989 // TRUNCATE - truncate -journal file to commit.
990 // PERSIST - zero out header of -journal file to commit.
991 // journal_size_limit provides size to trim to in PERSIST.
992 // TODO(shess): Figure out if PERSIST and journal_size_limit really
993 // matter. In theory, it keeps pages pre-allocated, so if
994 // transactions usually fit, it should be faster.
995 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
996 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
998 const base::TimeDelta kBusyTimeout
=
999 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds
);
1001 if (page_size_
!= 0) {
1002 // Enforce SQLite restrictions on |page_size_|.
1003 DCHECK(!(page_size_
& (page_size_
- 1)))
1004 << " page_size_ " << page_size_
<< " is not a power of two.";
1005 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
1006 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
1007 const std::string sql
=
1008 base::StringPrintf("PRAGMA page_size=%d", page_size_
);
1009 ignore_result(ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
));
1012 if (cache_size_
!= 0) {
1013 const std::string sql
=
1014 base::StringPrintf("PRAGMA cache_size=%d", cache_size_
);
1015 ignore_result(ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
));
1018 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout
)) {
1019 bool was_poisoned
= poisoned_
;
1021 if (was_poisoned
&& retry_flag
== RETRY_ON_POISON
)
1022 return OpenInternal(file_name
, NO_RETRY
);
1029 void Connection::DoRollback() {
1030 Statement
rollback(GetCachedStatement(SQL_FROM_HERE
, "ROLLBACK"));
1032 needs_rollback_
= false;
1035 void Connection::StatementRefCreated(StatementRef
* ref
) {
1036 DCHECK(open_statements_
.find(ref
) == open_statements_
.end());
1037 open_statements_
.insert(ref
);
1040 void Connection::StatementRefDeleted(StatementRef
* ref
) {
1041 StatementRefSet::iterator i
= open_statements_
.find(ref
);
1042 if (i
== open_statements_
.end())
1043 DLOG(FATAL
) << "Could not find statement";
1045 open_statements_
.erase(i
);
1048 void Connection::AddTaggedHistogram(const std::string
& name
,
1049 size_t sample
) const {
1050 if (histogram_tag_
.empty())
1053 // TODO(shess): The histogram macros create a bit of static storage
1054 // for caching the histogram object. This code shouldn't execute
1055 // often enough for such caching to be crucial. If it becomes an
1056 // issue, the object could be cached alongside histogram_prefix_.
1057 std::string full_histogram_name
= name
+ "." + histogram_tag_
;
1058 base::HistogramBase
* histogram
=
1059 base::SparseHistogram::FactoryGet(
1060 full_histogram_name
,
1061 base::HistogramBase::kUmaTargetedHistogramFlag
);
1063 histogram
->Add(sample
);
1066 int Connection::OnSqliteError(int err
, sql::Statement
*stmt
, const char* sql
) {
1067 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err
);
1068 AddTaggedHistogram("Sqlite.Error", err
);
1070 // Always log the error.
1072 sql
= stmt
->GetSQLStatement();
1075 LOG(ERROR
) << histogram_tag_
<< " sqlite error " << err
1076 << ", errno " << GetLastErrno()
1077 << ": " << GetErrorMessage()
1078 << ", sql: " << sql
;
1080 if (!error_callback_
.is_null()) {
1081 // Fire from a copy of the callback in case of reentry into
1082 // re/set_error_callback().
1083 // TODO(shess): <http://crbug.com/254584>
1084 ErrorCallback(error_callback_
).Run(err
, stmt
);
1088 // The default handling is to assert on debug and to ignore on release.
1089 if (!ShouldIgnoreSqliteError(err
))
1090 DLOG(FATAL
) << GetErrorMessage();
1094 bool Connection::FullIntegrityCheck(std::vector
<std::string
>* messages
) {
1095 return IntegrityCheckHelper("PRAGMA integrity_check", messages
);
1098 bool Connection::QuickIntegrityCheck() {
1099 std::vector
<std::string
> messages
;
1100 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages
))
1102 return messages
.size() == 1 && messages
[0] == "ok";
1105 // TODO(shess): Allow specifying maximum results (default 100 lines).
1106 bool Connection::IntegrityCheckHelper(
1107 const char* pragma_sql
,
1108 std::vector
<std::string
>* messages
) {
1111 // This has the side effect of setting SQLITE_RecoveryMode, which
1112 // allows SQLite to process through certain cases of corruption.
1113 // Failing to set this pragma probably means that the database is
1115 const char kWritableSchema
[] = "PRAGMA writable_schema = ON";
1116 if (!Execute(kWritableSchema
))
1121 sql::Statement
stmt(GetUniqueStatement(pragma_sql
));
1123 // The pragma appears to return all results (up to 100 by default)
1124 // as a single string. This doesn't appear to be an API contract,
1125 // it could return separate lines, so loop _and_ split.
1126 while (stmt
.Step()) {
1127 std::string
result(stmt
.ColumnString(0));
1128 base::SplitString(result
, '\n', messages
);
1130 ret
= stmt
.Succeeded();
1133 // Best effort to put things back as they were before.
1134 const char kNoWritableSchema
[] = "PRAGMA writable_schema = OFF";
1135 ignore_result(Execute(kNoWritableSchema
));