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"
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/histogram.h"
16 #include "base/metrics/sparse_histogram.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/synchronization/lock.h"
22 #include "sql/statement.h"
23 #include "third_party/sqlite/sqlite3.h"
25 #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
26 #include "third_party/sqlite/src/ext/icu/sqliteicu.h"
31 // Spin for up to a second waiting for the lock to clear when setting
33 // TODO(shess): Better story on this. http://crbug.com/56559
34 const int kBusyTimeoutSeconds
= 1;
36 class ScopedBusyTimeout
{
38 explicit ScopedBusyTimeout(sqlite3
* db
)
41 ~ScopedBusyTimeout() {
42 sqlite3_busy_timeout(db_
, 0);
45 int SetTimeout(base::TimeDelta timeout
) {
46 DCHECK_LT(timeout
.InMilliseconds(), INT_MAX
);
47 return sqlite3_busy_timeout(db_
,
48 static_cast<int>(timeout
.InMilliseconds()));
55 // Helper to "safely" enable writable_schema. No error checking
56 // because it is reasonable to just forge ahead in case of an error.
57 // If turning it on fails, then most likely nothing will work, whereas
58 // if turning it off fails, it only matters if some code attempts to
59 // continue working with the database and tries to modify the
60 // sqlite_master table (none of our code does this).
61 class ScopedWritableSchema
{
63 explicit ScopedWritableSchema(sqlite3
* db
)
65 sqlite3_exec(db_
, "PRAGMA writable_schema=1", NULL
, NULL
, NULL
);
67 ~ScopedWritableSchema() {
68 sqlite3_exec(db_
, "PRAGMA writable_schema=0", NULL
, NULL
, NULL
);
75 // Helper to wrap the sqlite3_backup_*() step of Raze(). Return
76 // SQLite error code from running the backup step.
77 int BackupDatabase(sqlite3
* src
, sqlite3
* dst
, const char* db_name
) {
79 sqlite3_backup
* backup
= sqlite3_backup_init(dst
, db_name
, src
, db_name
);
81 // Since this call only sets things up, this indicates a gross
83 DLOG(FATAL
) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst
);
84 return sqlite3_errcode(dst
);
87 // -1 backs up the entire database.
88 int rc
= sqlite3_backup_step(backup
, -1);
89 int pages
= sqlite3_backup_pagecount(backup
);
90 sqlite3_backup_finish(backup
);
92 // If successful, exactly one page should have been backed up. If
93 // this breaks, check this function to make sure assumptions aren't
95 if (rc
== SQLITE_DONE
)
101 // Be very strict on attachment point. SQLite can handle a much wider
102 // character set with appropriate quoting, but Chromium code should
103 // just use clean names to start with.
104 bool ValidAttachmentPoint(const char* attachment_point
) {
105 for (size_t i
= 0; attachment_point
[i
]; ++i
) {
106 if (!((attachment_point
[i
] >= '0' && attachment_point
[i
] <= '9') ||
107 (attachment_point
[i
] >= 'a' && attachment_point
[i
] <= 'z') ||
108 (attachment_point
[i
] >= 'A' && attachment_point
[i
] <= 'Z') ||
109 attachment_point
[i
] == '_')) {
116 void RecordSqliteMemory10Min() {
117 const int64 used
= sqlite3_memory_used();
118 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used
/ 1024);
121 void RecordSqliteMemoryHour() {
122 const int64 used
= sqlite3_memory_used();
123 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used
/ 1024);
126 void RecordSqliteMemoryDay() {
127 const int64 used
= sqlite3_memory_used();
128 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used
/ 1024);
131 // SQLite automatically calls sqlite3_initialize() lazily, but
132 // sqlite3_initialize() uses double-checked locking and thus can have
135 // TODO(shess): Another alternative would be to have
136 // sqlite3_initialize() called as part of process bring-up. If this
137 // is changed, remove the dynamic_annotations dependency in sql.gyp.
138 base::LazyInstance
<base::Lock
>::Leaky
139 g_sqlite_init_lock
= LAZY_INSTANCE_INITIALIZER
;
140 void InitializeSqlite() {
141 base::AutoLock
lock(g_sqlite_init_lock
.Get());
142 static bool first_call
= true;
144 sqlite3_initialize();
146 // Schedule callback to record memory footprint histograms at 10m, 1h, and
147 // 1d. There may not be a message loop in tests.
148 if (base::MessageLoop::current()) {
149 base::MessageLoop::current()->PostDelayedTask(
150 FROM_HERE
, base::Bind(&RecordSqliteMemory10Min
),
151 base::TimeDelta::FromMinutes(10));
152 base::MessageLoop::current()->PostDelayedTask(
153 FROM_HERE
, base::Bind(&RecordSqliteMemoryHour
),
154 base::TimeDelta::FromHours(1));
155 base::MessageLoop::current()->PostDelayedTask(
156 FROM_HERE
, base::Bind(&RecordSqliteMemoryDay
),
157 base::TimeDelta::FromDays(1));
164 // Helper to get the sqlite3_file* associated with the "main" database.
165 int GetSqlite3File(sqlite3
* db
, sqlite3_file
** file
) {
167 int rc
= sqlite3_file_control(db
, NULL
, SQLITE_FCNTL_FILE_POINTER
, file
);
171 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
172 // content_unittests, even though it should not be possible.
173 // http://crbug.com/329982
174 if (!*file
|| !(*file
)->pMethods
)
180 // This should match UMA_HISTOGRAM_MEDIUM_TIMES().
181 base::HistogramBase
* GetMediumTimeHistogram(const std::string
& name
) {
182 return base::Histogram::FactoryTimeGet(
184 base::TimeDelta::FromMilliseconds(10),
185 base::TimeDelta::FromMinutes(3),
187 base::HistogramBase::kUmaTargetedHistogramFlag
);
190 std::string
AsUTF8ForSQL(const base::FilePath
& path
) {
192 return base::WideToUTF8(path
.value());
193 #elif defined(OS_POSIX)
203 Connection::ErrorIgnorerCallback
* Connection::current_ignorer_cb_
= NULL
;
206 bool Connection::ShouldIgnoreSqliteError(int error
) {
207 if (!current_ignorer_cb_
)
209 return current_ignorer_cb_
->Run(error
);
213 void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback
* cb
) {
214 CHECK(current_ignorer_cb_
== NULL
);
215 current_ignorer_cb_
= cb
;
219 void Connection::ResetErrorIgnorer() {
220 CHECK(current_ignorer_cb_
);
221 current_ignorer_cb_
= NULL
;
224 bool StatementID::operator<(const StatementID
& other
) const {
225 if (number_
!= other
.number_
)
226 return number_
< other
.number_
;
227 return strcmp(str_
, other
.str_
) < 0;
230 Connection::StatementRef::StatementRef(Connection
* connection
,
233 : connection_(connection
),
235 was_valid_(was_valid
) {
237 connection_
->StatementRefCreated(this);
240 Connection::StatementRef::~StatementRef() {
242 connection_
->StatementRefDeleted(this);
246 void Connection::StatementRef::Close(bool forced
) {
248 // Call to AssertIOAllowed() cannot go at the beginning of the function
249 // because Close() is called unconditionally from destructor to clean
250 // connection_. And if this is inactive statement this won't cause any
251 // disk access and destructor most probably will be called on thread
252 // not allowing disk access.
253 // TODO(paivanof@gmail.com): This should move to the beginning
254 // of the function. http://crbug.com/136655.
256 sqlite3_finalize(stmt_
);
259 connection_
= NULL
; // The connection may be getting deleted.
261 // Forced close is expected to happen from a statement error
262 // handler. In that case maintain the sense of |was_valid_| which
263 // previously held for this ref.
264 was_valid_
= was_valid_
&& forced
;
267 Connection::Connection()
271 exclusive_locking_(false),
272 restrict_to_user_(false),
273 transaction_nesting_(0),
274 needs_rollback_(false),
277 stats_histogram_(NULL
),
278 commit_time_histogram_(NULL
),
279 autocommit_time_histogram_(NULL
),
280 update_time_histogram_(NULL
),
281 query_time_histogram_(NULL
),
282 clock_(new TimeSource()) {
285 Connection::~Connection() {
289 void Connection::RecordEvent(Events event
, size_t count
) {
290 for (size_t i
= 0; i
< count
; ++i
) {
291 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event
, EVENT_MAX_VALUE
);
294 if (stats_histogram_
) {
295 for (size_t i
= 0; i
< count
; ++i
) {
296 stats_histogram_
->Add(event
);
301 void Connection::RecordCommitTime(const base::TimeDelta
& delta
) {
302 RecordUpdateTime(delta
);
303 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta
);
304 if (commit_time_histogram_
)
305 commit_time_histogram_
->AddTime(delta
);
308 void Connection::RecordAutoCommitTime(const base::TimeDelta
& delta
) {
309 RecordUpdateTime(delta
);
310 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta
);
311 if (autocommit_time_histogram_
)
312 autocommit_time_histogram_
->AddTime(delta
);
315 void Connection::RecordUpdateTime(const base::TimeDelta
& delta
) {
316 RecordQueryTime(delta
);
317 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta
);
318 if (update_time_histogram_
)
319 update_time_histogram_
->AddTime(delta
);
322 void Connection::RecordQueryTime(const base::TimeDelta
& delta
) {
323 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta
);
324 if (query_time_histogram_
)
325 query_time_histogram_
->AddTime(delta
);
328 void Connection::RecordTimeAndChanges(
329 const base::TimeDelta
& delta
, bool read_only
) {
331 RecordQueryTime(delta
);
333 const int changes
= sqlite3_changes(db_
);
334 if (sqlite3_get_autocommit(db_
)) {
335 RecordAutoCommitTime(delta
);
336 RecordEvent(EVENT_CHANGES_AUTOCOMMIT
, changes
);
338 RecordUpdateTime(delta
);
339 RecordEvent(EVENT_CHANGES
, changes
);
344 bool Connection::Open(const base::FilePath
& path
) {
345 if (!histogram_tag_
.empty()) {
347 if (base::GetFileSize(path
, &size_64
)) {
348 size_t sample
= static_cast<size_t>(size_64
/ 1024);
349 std::string full_histogram_name
= "Sqlite.SizeKB." + histogram_tag_
;
350 base::HistogramBase
* histogram
=
351 base::Histogram::FactoryGet(
352 full_histogram_name
, 1, 1000000, 50,
353 base::HistogramBase::kUmaTargetedHistogramFlag
);
355 histogram
->Add(sample
);
359 return OpenInternal(AsUTF8ForSQL(path
), RETRY_ON_POISON
);
362 bool Connection::OpenInMemory() {
364 return OpenInternal(":memory:", NO_RETRY
);
367 bool Connection::OpenTemporary() {
368 return OpenInternal("", NO_RETRY
);
371 void Connection::CloseInternal(bool forced
) {
372 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
373 // will delete the -journal file. For ChromiumOS or other more
374 // embedded systems, this is probably not appropriate, whereas on
375 // desktop it might make some sense.
377 // sqlite3_close() needs all prepared statements to be finalized.
379 // Release cached statements.
380 statement_cache_
.clear();
382 // With cached statements released, in-use statements will remain.
383 // Closing the database while statements are in use is an API
384 // violation, except for forced close (which happens from within a
385 // statement's error handler).
386 DCHECK(forced
|| open_statements_
.empty());
388 // Deactivate any outstanding statements so sqlite3_close() works.
389 for (StatementRefSet::iterator i
= open_statements_
.begin();
390 i
!= open_statements_
.end(); ++i
)
392 open_statements_
.clear();
395 // Call to AssertIOAllowed() cannot go at the beginning of the function
396 // because Close() must be called from destructor to clean
397 // statement_cache_, it won't cause any disk access and it most probably
398 // will happen on thread not allowing disk access.
399 // TODO(paivanof@gmail.com): This should move to the beginning
400 // of the function. http://crbug.com/136655.
403 int rc
= sqlite3_close(db_
);
404 if (rc
!= SQLITE_OK
) {
405 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc
);
406 DLOG(FATAL
) << "sqlite3_close failed: " << GetErrorMessage();
412 void Connection::Close() {
413 // If the database was already closed by RazeAndClose(), then no
414 // need to close again. Clear the |poisoned_| bit so that incorrect
415 // API calls are caught.
421 CloseInternal(false);
424 void Connection::Preload() {
428 DLOG_IF(FATAL
, !poisoned_
) << "Cannot preload null db";
432 // Use local settings if provided, otherwise use documented defaults. The
433 // actual results could be fetching via PRAGMA calls.
434 const int page_size
= page_size_
? page_size_
: 1024;
435 sqlite3_int64 preload_size
= page_size
* (cache_size_
? cache_size_
: 2000);
436 if (preload_size
< 1)
439 sqlite3_file
* file
= NULL
;
440 int rc
= GetSqlite3File(db_
, &file
);
444 sqlite3_int64 file_size
= 0;
445 rc
= file
->pMethods
->xFileSize(file
, &file_size
);
449 // Don't preload more than the file contains.
450 if (preload_size
> file_size
)
451 preload_size
= file_size
;
453 scoped_ptr
<char[]> buf(new char[page_size
]);
454 for (sqlite3_int64 pos
= 0; pos
< preload_size
; pos
+= page_size
) {
455 rc
= file
->pMethods
->xRead(file
, buf
.get(), page_size
, pos
);
461 void Connection::TrimMemory(bool aggressively
) {
465 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
466 int original_cache_size
;
468 Statement
sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
469 if (!sql_get_original
.Step()) {
470 DLOG(WARNING
) << "Could not get cache size " << GetErrorMessage();
473 original_cache_size
= sql_get_original
.ColumnInt(0);
475 int shrink_cache_size
= aggressively
? 1 : (original_cache_size
/ 2);
477 // Force sqlite to try to reduce page cache usage.
478 const std::string sql_shrink
=
479 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size
);
480 if (!Execute(sql_shrink
.c_str()))
481 DLOG(WARNING
) << "Could not shrink cache size: " << GetErrorMessage();
483 // Restore cache size.
484 const std::string sql_restore
=
485 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size
);
486 if (!Execute(sql_restore
.c_str()))
487 DLOG(WARNING
) << "Could not restore cache size: " << GetErrorMessage();
490 // Create an in-memory database with the existing database's page
491 // size, then backup that database over the existing database.
492 bool Connection::Raze() {
496 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
500 if (transaction_nesting_
> 0) {
501 DLOG(FATAL
) << "Cannot raze within a transaction";
505 sql::Connection null_db
;
506 if (!null_db
.OpenInMemory()) {
507 DLOG(FATAL
) << "Unable to open in-memory database.";
512 // Enforce SQLite restrictions on |page_size_|.
513 DCHECK(!(page_size_
& (page_size_
- 1)))
514 << " page_size_ " << page_size_
<< " is not a power of two.";
515 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
516 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
517 const std::string sql
=
518 base::StringPrintf("PRAGMA page_size=%d", page_size_
);
519 if (!null_db
.Execute(sql
.c_str()))
523 #if defined(OS_ANDROID)
524 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
525 // in-memory databases do not respect this define.
526 // TODO(shess): Figure out a way to set this without using platform
527 // specific code. AFAICT from sqlite3.c, the only way to do it
528 // would be to create an actual filesystem database, which is
530 if (!null_db
.Execute("PRAGMA auto_vacuum = 1"))
534 // The page size doesn't take effect until a database has pages, and
535 // at this point the null database has none. Changing the schema
536 // version will create the first page. This will not affect the
537 // schema version in the resulting database, as SQLite's backup
538 // implementation propagates the schema version from the original
539 // connection to the new version of the database, incremented by one
540 // so that other readers see the schema change and act accordingly.
541 if (!null_db
.Execute("PRAGMA schema_version = 1"))
544 // SQLite tracks the expected number of database pages in the first
545 // page, and if it does not match the total retrieved from a
546 // filesystem call, treats the database as corrupt. This situation
547 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
548 // used to hint to SQLite to soldier on in that case, specifically
549 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
550 // sqlite3.c lockBtree().]
551 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
552 // page_size" can be used to query such a database.
553 ScopedWritableSchema
writable_schema(db_
);
555 const char* kMain
= "main";
556 int rc
= BackupDatabase(null_db
.db_
, db_
, kMain
);
557 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc
);
559 // The destination database was locked.
560 if (rc
== SQLITE_BUSY
) {
564 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
565 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
566 // isn't even big enough for one page. Either way, reach in and
567 // truncate it before trying again.
568 // TODO(shess): Maybe it would be worthwhile to just truncate from
570 if (rc
== SQLITE_NOTADB
|| rc
== SQLITE_IOERR_SHORT_READ
) {
571 sqlite3_file
* file
= NULL
;
572 rc
= GetSqlite3File(db_
, &file
);
573 if (rc
!= SQLITE_OK
) {
574 DLOG(FATAL
) << "Failure getting file handle.";
578 rc
= file
->pMethods
->xTruncate(file
, 0);
579 if (rc
!= SQLITE_OK
) {
580 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc
);
581 DLOG(FATAL
) << "Failed to truncate file.";
585 rc
= BackupDatabase(null_db
.db_
, db_
, kMain
);
586 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc
);
588 if (rc
!= SQLITE_DONE
) {
589 DLOG(FATAL
) << "Failed retrying Raze().";
593 // The entire database should have been backed up.
594 if (rc
!= SQLITE_DONE
) {
595 // TODO(shess): Figure out which other cases can happen.
596 DLOG(FATAL
) << "Unable to copy entire null database.";
603 bool Connection::RazeWithTimout(base::TimeDelta timeout
) {
605 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
609 ScopedBusyTimeout
busy_timeout(db_
);
610 busy_timeout
.SetTimeout(timeout
);
614 bool Connection::RazeAndClose() {
616 DLOG_IF(FATAL
, !poisoned_
) << "Cannot raze null db";
620 // Raze() cannot run in a transaction.
621 RollbackAllTransactions();
623 bool result
= Raze();
627 // Mark the database so that future API calls fail appropriately,
628 // but don't DCHECK (because after calling this function they are
629 // expected to fail).
635 void Connection::Poison() {
637 DLOG_IF(FATAL
, !poisoned_
) << "Cannot poison null db";
641 RollbackAllTransactions();
644 // Mark the database so that future API calls fail appropriately,
645 // but don't DCHECK (because after calling this function they are
646 // expected to fail).
650 // TODO(shess): To the extent possible, figure out the optimal
651 // ordering for these deletes which will prevent other connections
652 // from seeing odd behavior. For instance, it may be necessary to
653 // manually lock the main database file in a SQLite-compatible fashion
654 // (to prevent other processes from opening it), then delete the
655 // journal files, then delete the main database file. Another option
656 // might be to lock the main database file and poison the header with
657 // junk to prevent other processes from opening it successfully (like
658 // Gears "SQLite poison 3" trick).
661 bool Connection::Delete(const base::FilePath
& path
) {
662 base::ThreadRestrictions::AssertIOAllowed();
664 base::FilePath
journal_path(path
.value() + FILE_PATH_LITERAL("-journal"));
665 base::FilePath
wal_path(path
.value() + FILE_PATH_LITERAL("-wal"));
667 std::string journal_str
= AsUTF8ForSQL(journal_path
);
668 std::string wal_str
= AsUTF8ForSQL(wal_path
);
669 std::string path_str
= AsUTF8ForSQL(path
);
671 sqlite3_vfs
* vfs
= sqlite3_vfs_find(NULL
);
676 // We only work with unix, win32 and mojo filesystems. If you're trying to
677 // use this code with any other VFS, you're not in a good place.
678 CHECK(strncmp(vfs
->zName
, "unix", 4) == 0 ||
679 strncmp(vfs
->zName
, "win32", 5) == 0 ||
680 strcmp(vfs
->zName
, "mojo") == 0);
682 vfs
->xDelete(vfs
, journal_str
.c_str(), 0);
683 vfs
->xDelete(vfs
, wal_str
.c_str(), 0);
684 vfs
->xDelete(vfs
, path_str
.c_str(), 0);
686 int journal_exists
= 0;
687 vfs
->xAccess(vfs
, journal_str
.c_str(), SQLITE_ACCESS_EXISTS
,
691 vfs
->xAccess(vfs
, wal_str
.c_str(), SQLITE_ACCESS_EXISTS
,
695 vfs
->xAccess(vfs
, path_str
.c_str(), SQLITE_ACCESS_EXISTS
,
698 return !journal_exists
&& !wal_exists
&& !path_exists
;
701 bool Connection::BeginTransaction() {
702 if (needs_rollback_
) {
703 DCHECK_GT(transaction_nesting_
, 0);
705 // When we're going to rollback, fail on this begin and don't actually
706 // mark us as entering the nested transaction.
711 if (!transaction_nesting_
) {
712 needs_rollback_
= false;
714 Statement
begin(GetCachedStatement(SQL_FROM_HERE
, "BEGIN TRANSACTION"));
715 RecordOneEvent(EVENT_BEGIN
);
719 transaction_nesting_
++;
723 void Connection::RollbackTransaction() {
724 if (!transaction_nesting_
) {
725 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
729 transaction_nesting_
--;
731 if (transaction_nesting_
> 0) {
732 // Mark the outermost transaction as needing rollback.
733 needs_rollback_
= true;
740 bool Connection::CommitTransaction() {
741 if (!transaction_nesting_
) {
742 DLOG_IF(FATAL
, !poisoned_
) << "Rolling back a nonexistent transaction";
745 transaction_nesting_
--;
747 if (transaction_nesting_
> 0) {
748 // Mark any nested transactions as failing after we've already got one.
749 return !needs_rollback_
;
752 if (needs_rollback_
) {
757 Statement
commit(GetCachedStatement(SQL_FROM_HERE
, "COMMIT"));
759 // Collect the commit time manually, sql::Statement would register it as query
761 const base::TimeTicks before
= Now();
762 bool ret
= commit
.RunWithoutTimers();
763 const base::TimeDelta delta
= Now() - before
;
765 RecordCommitTime(delta
);
766 RecordOneEvent(EVENT_COMMIT
);
771 void Connection::RollbackAllTransactions() {
772 if (transaction_nesting_
> 0) {
773 transaction_nesting_
= 0;
778 bool Connection::AttachDatabase(const base::FilePath
& other_db_path
,
779 const char* attachment_point
) {
780 DCHECK(ValidAttachmentPoint(attachment_point
));
782 Statement
s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
784 s
.BindString16(0, other_db_path
.value());
786 s
.BindString(0, other_db_path
.value());
788 s
.BindString(1, attachment_point
);
792 bool Connection::DetachDatabase(const char* attachment_point
) {
793 DCHECK(ValidAttachmentPoint(attachment_point
));
795 Statement
s(GetUniqueStatement("DETACH DATABASE ?"));
796 s
.BindString(0, attachment_point
);
800 // TODO(shess): Consider changing this to execute exactly one statement. If a
801 // caller wishes to execute multiple statements, that should be explicit, and
802 // perhaps tucked into an explicit transaction with rollback in case of error.
803 int Connection::ExecuteAndReturnErrorCode(const char* sql
) {
806 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
811 RecordOneEvent(EVENT_EXECUTE
);
813 while ((rc
== SQLITE_OK
) && *sql
) {
814 sqlite3_stmt
*stmt
= NULL
;
815 const char *leftover_sql
;
817 const base::TimeTicks before
= Now();
818 rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, &leftover_sql
);
821 // Stop if an error is encountered.
825 // This happens if |sql| originally only contained comments or whitespace.
826 // TODO(shess): Audit to see if this can become a DCHECK(). Having
827 // extraneous comments and whitespace in the SQL statements increases
828 // runtime cost and can easily be shifted out to the C++ layer.
832 // Save for use after statement is finalized.
833 const bool read_only
= !!sqlite3_stmt_readonly(stmt
);
835 RecordOneEvent(Connection::EVENT_STATEMENT_RUN
);
836 while ((rc
= sqlite3_step(stmt
)) == SQLITE_ROW
) {
837 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
838 // is the only legitimate case for this.
839 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS
);
842 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
843 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
844 rc
= sqlite3_finalize(stmt
);
846 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS
);
848 // sqlite3_exec() does this, presumably to avoid spinning the parser for
849 // trailing whitespace.
850 // TODO(shess): Audit to see if this can become a DCHECK.
851 while (base::IsAsciiWhitespace(*sql
)) {
855 const base::TimeDelta delta
= Now() - before
;
856 RecordTimeAndChanges(delta
, read_only
);
861 bool Connection::Execute(const char* sql
) {
863 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
867 int error
= ExecuteAndReturnErrorCode(sql
);
868 if (error
!= SQLITE_OK
)
869 error
= OnSqliteError(error
, NULL
, sql
);
871 // This needs to be a FATAL log because the error case of arriving here is
872 // that there's a malformed SQL statement. This can arise in development if
873 // a change alters the schema but not all queries adjust. This can happen
874 // in production if the schema is corrupted.
875 if (error
== SQLITE_ERROR
)
876 DLOG(FATAL
) << "SQL Error in " << sql
<< ", " << GetErrorMessage();
877 return error
== SQLITE_OK
;
880 bool Connection::ExecuteWithTimeout(const char* sql
, base::TimeDelta timeout
) {
882 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
886 ScopedBusyTimeout
busy_timeout(db_
);
887 busy_timeout
.SetTimeout(timeout
);
891 bool Connection::HasCachedStatement(const StatementID
& id
) const {
892 return statement_cache_
.find(id
) != statement_cache_
.end();
895 scoped_refptr
<Connection::StatementRef
> Connection::GetCachedStatement(
896 const StatementID
& id
,
898 CachedStatementMap::iterator i
= statement_cache_
.find(id
);
899 if (i
!= statement_cache_
.end()) {
900 // Statement is in the cache. It should still be active (we're the only
901 // one invalidating cached statements, and we'll remove it from the cache
902 // if we do that. Make sure we reset it before giving out the cached one in
903 // case it still has some stuff bound.
904 DCHECK(i
->second
->is_valid());
905 sqlite3_reset(i
->second
->stmt());
909 scoped_refptr
<StatementRef
> statement
= GetUniqueStatement(sql
);
910 if (statement
->is_valid())
911 statement_cache_
[id
] = statement
; // Only cache valid statements.
915 scoped_refptr
<Connection::StatementRef
> Connection::GetUniqueStatement(
919 // Return inactive statement.
921 return new StatementRef(NULL
, NULL
, poisoned_
);
923 sqlite3_stmt
* stmt
= NULL
;
924 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
925 if (rc
!= SQLITE_OK
) {
926 // This is evidence of a syntax error in the incoming SQL.
927 if (!ShouldIgnoreSqliteError(rc
))
928 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
930 // It could also be database corruption.
931 OnSqliteError(rc
, NULL
, sql
);
932 return new StatementRef(NULL
, NULL
, false);
934 return new StatementRef(this, stmt
, true);
937 scoped_refptr
<Connection::StatementRef
> Connection::GetUntrackedStatement(
938 const char* sql
) const {
939 // Return inactive statement.
941 return new StatementRef(NULL
, NULL
, poisoned_
);
943 sqlite3_stmt
* stmt
= NULL
;
944 int rc
= sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
);
945 if (rc
!= SQLITE_OK
) {
946 // This is evidence of a syntax error in the incoming SQL.
947 if (!ShouldIgnoreSqliteError(rc
))
948 DLOG(FATAL
) << "SQL compile error " << GetErrorMessage();
949 return new StatementRef(NULL
, NULL
, false);
951 return new StatementRef(NULL
, stmt
, true);
954 std::string
Connection::GetSchema() const {
955 // The ORDER BY should not be necessary, but relying on organic
956 // order for something like this is questionable.
958 "SELECT type, name, tbl_name, sql "
959 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
960 Statement
statement(GetUntrackedStatement(kSql
));
963 while (statement
.Step()) {
964 schema
+= statement
.ColumnString(0);
966 schema
+= statement
.ColumnString(1);
968 schema
+= statement
.ColumnString(2);
970 schema
+= statement
.ColumnString(3);
977 bool Connection::IsSQLValid(const char* sql
) {
980 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
984 sqlite3_stmt
* stmt
= NULL
;
985 if (sqlite3_prepare_v2(db_
, sql
, -1, &stmt
, NULL
) != SQLITE_OK
)
988 sqlite3_finalize(stmt
);
992 bool Connection::DoesTableExist(const char* table_name
) const {
993 return DoesTableOrIndexExist(table_name
, "table");
996 bool Connection::DoesIndexExist(const char* index_name
) const {
997 return DoesTableOrIndexExist(index_name
, "index");
1000 bool Connection::DoesTableOrIndexExist(
1001 const char* name
, const char* type
) const {
1003 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
1004 Statement
statement(GetUntrackedStatement(kSql
));
1006 // This can happen if the database is corrupt and the error is being ignored
1007 // for testing purposes.
1008 if (!statement
.is_valid())
1011 statement
.BindString(0, type
);
1012 statement
.BindString(1, name
);
1014 return statement
.Step(); // Table exists if any row was returned.
1017 bool Connection::DoesColumnExist(const char* table_name
,
1018 const char* column_name
) const {
1019 std::string
sql("PRAGMA TABLE_INFO(");
1020 sql
.append(table_name
);
1023 Statement
statement(GetUntrackedStatement(sql
.c_str()));
1025 // This can happen if the database is corrupt and the error is being ignored
1026 // for testing purposes.
1027 if (!statement
.is_valid())
1030 while (statement
.Step()) {
1031 if (base::EqualsCaseInsensitiveASCII(statement
.ColumnString(1),
1038 int64_t Connection::GetLastInsertRowId() const {
1040 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
1043 return sqlite3_last_insert_rowid(db_
);
1046 int Connection::GetLastChangeCount() const {
1048 DLOG_IF(FATAL
, !poisoned_
) << "Illegal use of connection without a db";
1051 return sqlite3_changes(db_
);
1054 int Connection::GetErrorCode() const {
1056 return SQLITE_ERROR
;
1057 return sqlite3_errcode(db_
);
1060 int Connection::GetLastErrno() const {
1065 if (SQLITE_OK
!= sqlite3_file_control(db_
, NULL
, SQLITE_LAST_ERRNO
, &err
))
1071 const char* Connection::GetErrorMessage() const {
1073 return "sql::Connection has no connection.";
1074 return sqlite3_errmsg(db_
);
1077 bool Connection::OpenInternal(const std::string
& file_name
,
1078 Connection::Retry retry_flag
) {
1082 DLOG(FATAL
) << "sql::Connection is already open.";
1086 // Make sure sqlite3_initialize() is called before anything else.
1089 // Setup the stats histograms immediately rather than allocating lazily.
1090 // Connections which won't exercise all of these probably shouldn't exist.
1091 if (!histogram_tag_
.empty()) {
1093 base::LinearHistogram::FactoryGet(
1094 "Sqlite.Stats." + histogram_tag_
,
1095 1, EVENT_MAX_VALUE
, EVENT_MAX_VALUE
+ 1,
1096 base::HistogramBase::kUmaTargetedHistogramFlag
);
1098 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1099 // unreasonable time for any single operation, so there is not much value to
1100 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1101 // things are entirely busted.
1102 commit_time_histogram_
=
1103 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_
);
1105 autocommit_time_histogram_
=
1106 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_
);
1108 update_time_histogram_
=
1109 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_
);
1111 query_time_histogram_
=
1112 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_
);
1115 // If |poisoned_| is set, it means an error handler called
1116 // RazeAndClose(). Until regular Close() is called, the caller
1117 // should be treating the database as open, but is_open() currently
1118 // only considers the sqlite3 handle's state.
1119 // TODO(shess): Revise is_open() to consider poisoned_, and review
1120 // to see if any non-testing code even depends on it.
1121 DLOG_IF(FATAL
, poisoned_
) << "sql::Connection is already open.";
1124 int err
= sqlite3_open(file_name
.c_str(), &db_
);
1125 if (err
!= SQLITE_OK
) {
1126 // Extended error codes cannot be enabled until a handle is
1127 // available, fetch manually.
1128 err
= sqlite3_extended_errcode(db_
);
1130 // Histogram failures specific to initial open for debugging
1132 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err
);
1134 OnSqliteError(err
, NULL
, "-- sqlite3_open()");
1135 bool was_poisoned
= poisoned_
;
1138 if (was_poisoned
&& retry_flag
== RETRY_ON_POISON
)
1139 return OpenInternal(file_name
, NO_RETRY
);
1143 // TODO(shess): OS_WIN support?
1144 #if defined(OS_POSIX)
1145 if (restrict_to_user_
) {
1146 DCHECK_NE(file_name
, std::string(":memory"));
1147 base::FilePath
file_path(file_name
);
1149 // TODO(shess): Arguably, failure to retrieve and change
1150 // permissions should be fatal if the file exists.
1151 if (base::GetPosixFilePermissions(file_path
, &mode
)) {
1152 mode
&= base::FILE_PERMISSION_USER_MASK
;
1153 base::SetPosixFilePermissions(file_path
, mode
);
1155 // SQLite sets the permissions on these files from the main
1156 // database on create. Set them here in case they already exist
1157 // at this point. Failure to set these permissions should not
1158 // be fatal unless the file doesn't exist.
1159 base::FilePath
journal_path(file_name
+ FILE_PATH_LITERAL("-journal"));
1160 base::FilePath
wal_path(file_name
+ FILE_PATH_LITERAL("-wal"));
1161 base::SetPosixFilePermissions(journal_path
, mode
);
1162 base::SetPosixFilePermissions(wal_path
, mode
);
1165 #endif // defined(OS_POSIX)
1167 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1168 // Chromium already depends on small mallocs being efficient, so we disable
1169 // this to avoid the extra memory overhead.
1170 // This must be called immediatly after opening the database before any SQL
1171 // statements are run.
1172 sqlite3_db_config(db_
, SQLITE_DBCONFIG_LOOKASIDE
, NULL
, 0, 0);
1174 // Enable extended result codes to provide more color on I/O errors.
1175 // Not having extended result codes is not a fatal problem, as
1176 // Chromium code does not attempt to handle I/O errors anyhow. The
1177 // current implementation always returns SQLITE_OK, the DCHECK is to
1178 // quickly notify someone if SQLite changes.
1179 err
= sqlite3_extended_result_codes(db_
, 1);
1180 DCHECK_EQ(err
, SQLITE_OK
) << "Could not enable extended result codes";
1182 // sqlite3_open() does not actually read the database file (unless a
1183 // hot journal is found). Successfully executing this pragma on an
1184 // existing database requires a valid header on page 1.
1185 // TODO(shess): For now, just probing to see what the lay of the
1186 // land is. If it's mostly SQLITE_NOTADB, then the database should
1188 err
= ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1189 if (err
!= SQLITE_OK
)
1190 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err
);
1192 #if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1193 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1194 // REGEXP support. Add it in dynamically.
1195 err
= sqlite3IcuInit(db_
);
1196 DCHECK_EQ(err
, SQLITE_OK
) << "Could not enable ICU support";
1197 #endif // OS_IOS && USE_SYSTEM_SQLITE
1199 // If indicated, lock up the database before doing anything else, so
1200 // that the following code doesn't have to deal with locking.
1201 // TODO(shess): This code is brittle. Find the cases where code
1202 // doesn't request |exclusive_locking_| and audit that it does the
1203 // right thing with SQLITE_BUSY, and that it doesn't make
1204 // assumptions about who might change things in the database.
1205 // http://crbug.com/56559
1206 if (exclusive_locking_
) {
1207 // TODO(shess): This should probably be a failure. Code which
1208 // requests exclusive locking but doesn't get it is almost certain
1209 // to be ill-tested.
1210 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
1213 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1214 // DELETE (default) - delete -journal file to commit.
1215 // TRUNCATE - truncate -journal file to commit.
1216 // PERSIST - zero out header of -journal file to commit.
1217 // TRUNCATE should be faster than DELETE because it won't need directory
1218 // changes for each transaction. PERSIST may break the spirit of using
1220 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
1222 const base::TimeDelta kBusyTimeout
=
1223 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds
);
1225 if (page_size_
!= 0) {
1226 // Enforce SQLite restrictions on |page_size_|.
1227 DCHECK(!(page_size_
& (page_size_
- 1)))
1228 << " page_size_ " << page_size_
<< " is not a power of two.";
1229 const int kSqliteMaxPageSize
= 32768; // from sqliteLimit.h
1230 DCHECK_LE(page_size_
, kSqliteMaxPageSize
);
1231 const std::string sql
=
1232 base::StringPrintf("PRAGMA page_size=%d", page_size_
);
1233 ignore_result(ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
));
1236 if (cache_size_
!= 0) {
1237 const std::string sql
=
1238 base::StringPrintf("PRAGMA cache_size=%d", cache_size_
);
1239 ignore_result(ExecuteWithTimeout(sql
.c_str(), kBusyTimeout
));
1242 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout
)) {
1243 bool was_poisoned
= poisoned_
;
1245 if (was_poisoned
&& retry_flag
== RETRY_ON_POISON
)
1246 return OpenInternal(file_name
, NO_RETRY
);
1253 void Connection::DoRollback() {
1254 Statement
rollback(GetCachedStatement(SQL_FROM_HERE
, "ROLLBACK"));
1256 // Collect the rollback time manually, sql::Statement would register it as
1258 const base::TimeTicks before
= Now();
1259 rollback
.RunWithoutTimers();
1260 const base::TimeDelta delta
= Now() - before
;
1262 RecordUpdateTime(delta
);
1263 RecordOneEvent(EVENT_ROLLBACK
);
1265 needs_rollback_
= false;
1268 void Connection::StatementRefCreated(StatementRef
* ref
) {
1269 DCHECK(open_statements_
.find(ref
) == open_statements_
.end());
1270 open_statements_
.insert(ref
);
1273 void Connection::StatementRefDeleted(StatementRef
* ref
) {
1274 StatementRefSet::iterator i
= open_statements_
.find(ref
);
1275 if (i
== open_statements_
.end())
1276 DLOG(FATAL
) << "Could not find statement";
1278 open_statements_
.erase(i
);
1281 void Connection::set_histogram_tag(const std::string
& tag
) {
1283 histogram_tag_
= tag
;
1286 void Connection::AddTaggedHistogram(const std::string
& name
,
1287 size_t sample
) const {
1288 if (histogram_tag_
.empty())
1291 // TODO(shess): The histogram macros create a bit of static storage
1292 // for caching the histogram object. This code shouldn't execute
1293 // often enough for such caching to be crucial. If it becomes an
1294 // issue, the object could be cached alongside histogram_prefix_.
1295 std::string full_histogram_name
= name
+ "." + histogram_tag_
;
1296 base::HistogramBase
* histogram
=
1297 base::SparseHistogram::FactoryGet(
1298 full_histogram_name
,
1299 base::HistogramBase::kUmaTargetedHistogramFlag
);
1301 histogram
->Add(sample
);
1304 int Connection::OnSqliteError(int err
, sql::Statement
*stmt
, const char* sql
) {
1305 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err
);
1306 AddTaggedHistogram("Sqlite.Error", err
);
1308 // Always log the error.
1310 sql
= stmt
->GetSQLStatement();
1313 LOG(ERROR
) << histogram_tag_
<< " sqlite error " << err
1314 << ", errno " << GetLastErrno()
1315 << ": " << GetErrorMessage()
1316 << ", sql: " << sql
;
1318 if (!error_callback_
.is_null()) {
1319 // Fire from a copy of the callback in case of reentry into
1320 // re/set_error_callback().
1321 // TODO(shess): <http://crbug.com/254584>
1322 ErrorCallback(error_callback_
).Run(err
, stmt
);
1326 // The default handling is to assert on debug and to ignore on release.
1327 if (!ShouldIgnoreSqliteError(err
))
1328 DLOG(FATAL
) << GetErrorMessage();
1332 bool Connection::FullIntegrityCheck(std::vector
<std::string
>* messages
) {
1333 return IntegrityCheckHelper("PRAGMA integrity_check", messages
);
1336 bool Connection::QuickIntegrityCheck() {
1337 std::vector
<std::string
> messages
;
1338 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages
))
1340 return messages
.size() == 1 && messages
[0] == "ok";
1343 // TODO(shess): Allow specifying maximum results (default 100 lines).
1344 bool Connection::IntegrityCheckHelper(
1345 const char* pragma_sql
,
1346 std::vector
<std::string
>* messages
) {
1349 // This has the side effect of setting SQLITE_RecoveryMode, which
1350 // allows SQLite to process through certain cases of corruption.
1351 // Failing to set this pragma probably means that the database is
1353 const char kWritableSchema
[] = "PRAGMA writable_schema = ON";
1354 if (!Execute(kWritableSchema
))
1359 sql::Statement
stmt(GetUniqueStatement(pragma_sql
));
1361 // The pragma appears to return all results (up to 100 by default)
1362 // as a single string. This doesn't appear to be an API contract,
1363 // it could return separate lines, so loop _and_ split.
1364 while (stmt
.Step()) {
1365 std::string
result(stmt
.ColumnString(0));
1366 *messages
= base::SplitString(result
, "\n", base::TRIM_WHITESPACE
,
1367 base::SPLIT_WANT_ALL
);
1369 ret
= stmt
.Succeeded();
1372 // Best effort to put things back as they were before.
1373 const char kNoWritableSchema
[] = "PRAGMA writable_schema = OFF";
1374 ignore_result(Execute(kNoWritableSchema
));
1379 base::TimeTicks
TimeSource::Now() {
1380 return base::TimeTicks::Now();