1 // Copyright 2012 The Chromium Authors
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/database.h"
16 #include "base/check.h"
17 #include "base/containers/contains.h"
18 #include "base/dcheck_is_on.h"
19 #include "base/feature_list.h"
20 #include "base/files/file_path.h"
21 #include "base/files/file_util.h"
22 #include "base/format_macros.h"
23 #include "base/location.h"
24 #include "base/logging.h"
25 #include "base/memory/raw_ptr.h"
26 #include "base/no_destructor.h"
27 #include "base/notreached.h"
28 #include "base/numerics/safe_conversions.h"
29 #include "base/ranges/algorithm.h"
30 #include "base/sequence_checker.h"
31 #include "base/strings/strcat.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/string_split.h"
35 #include "base/strings/string_util.h"
36 #include "base/strings/stringprintf.h"
37 #include "base/strings/utf_string_conversions.h"
38 #include "base/synchronization/lock.h"
39 #include "base/task/single_thread_task_runner.h"
40 #include "base/threading/scoped_blocking_call.h"
41 #include "base/trace_event/memory_dump_manager.h"
42 #include "base/trace_event/trace_event.h"
43 #include "base/tracing/protos/chrome_track_event.pbzero.h"
44 #include "base/types/pass_key.h"
45 #include "build/build_config.h"
46 #include "sql/database_memory_dump_provider.h"
47 #include "sql/initialization.h"
48 #include "sql/meta_table.h"
49 #include "sql/sql_features.h"
50 #include "sql/sqlite_result_code.h"
51 #include "sql/sqlite_result_code_values.h"
52 #include "sql/statement.h"
53 #include "sql/vfs_wrapper.h"
54 #include "third_party/sqlite/sqlite3.h"
60 bool enable_mmap_by_default_ = true;
62 // The name of the main database associated with a sqlite3* connection.
64 // SQLite has the ability to ATTACH multiple databases to the same connection.
65 // As a consequence, some SQLite APIs require the connection-specific database
66 // name. This is the right name to be passed to such APIs.
67 static constexpr char kSqliteMainDatabaseName[] = "main";
69 // Magic path value telling sqlite3_open_v2() to open an in-memory database.
70 static constexpr char kSqliteOpenInMemoryPath[] = ":memory:";
72 // Spin for up to a second waiting for the lock to clear when setting
74 // TODO(shess): Better story on this. http://crbug.com/56559
75 const int kBusyTimeoutSeconds = 1;
77 class ScopedBusyTimeout {
79 explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
80 ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
82 int SetTimeout(base::TimeDelta timeout) {
83 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
84 return sqlite3_busy_timeout(db_,
85 static_cast<int>(timeout.InMilliseconds()));
92 // Helper to "safely" enable writable_schema. No error checking
93 // because it is reasonable to just forge ahead in case of an error.
94 // If turning it on fails, then most likely nothing will work, whereas
95 // if turning it off fails, it only matters if some code attempts to
96 // continue working with the database and tries to modify the
97 // sqlite_schema table (none of our code does this).
98 class ScopedWritableSchema {
100 explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
101 sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
103 ~ScopedWritableSchema() {
104 sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
108 raw_ptr<sqlite3> db_;
111 // Raze() helper that uses SQLite's online backup API.
113 // Returns the SQLite error code produced by sqlite3_backup_step(). SQLITE_DONE
114 // signals success. SQLITE_OK will never be returned.
116 // The implementation is tailored for the Raze() use case. In particular, the
117 // SQLite API use and and error handling is optimized for 1-page databases.
118 SqliteResultCode BackupDatabaseForRaze(sqlite3* source_db,
119 sqlite3* destination_db) {
121 DCHECK(destination_db);
122 DCHECK_NE(source_db, destination_db);
124 // https://www.sqlite.org/backup.html has a high-level overview of SQLite's
125 // backup support. https://www.sqlite.org/c3ref/backup_finish.html describes
127 static constexpr char kMainDatabaseName[] = "main";
128 sqlite3_backup* backup = sqlite3_backup_init(
129 destination_db, kMainDatabaseName, source_db, kMainDatabaseName);
131 // sqlite3_backup_init() fails if a transaction is ongoing. In particular,
132 // SQL statements that return multiple rows keep a read transaction open
133 // until all the Step() calls are executed.
134 return ToSqliteResultCode(chrome_sqlite3_extended_errcode(destination_db));
137 constexpr int kUnlimitedPageCount = -1; // Back up entire database.
138 auto sqlite_result_code =
139 ToSqliteResultCode(sqlite3_backup_step(backup, kUnlimitedPageCount));
140 DCHECK_NE(sqlite_result_code, SqliteResultCode::kOk)
141 << "sqlite3_backup_step() returned SQLITE_OK (instead of SQLITE_DONE) "
142 << "when asked to back up the entire database";
145 if (sqlite_result_code == SqliteResultCode::kDone) {
146 // If successful, exactly one page should have been backed up.
147 DCHECK_EQ(sqlite3_backup_pagecount(backup), 1)
148 << __func__ << " was intended to be used with 1-page databases";
150 #endif // DCHECK_IS_ON()
152 // sqlite3_backup_finish() releases the sqlite3_backup object.
154 // It returns an error code only if the backup encountered a permanent error.
155 // We use the the sqlite3_backup_step() result instead, because it also tells
156 // us about temporary errors, like SQLITE_BUSY.
158 // We pass the sqlite3_backup_finish() result code through
159 // ToSqliteResultCode() to catch codes that should never occur, like
161 std::ignore = ToSqliteResultCode(sqlite3_backup_finish(backup));
163 return sqlite_result_code;
166 bool ValidAttachmentPoint(base::StringPiece attachment_point) {
167 // SQLite could handle a much wider character set, with appropriate quoting.
169 // Chrome's constraint is easy to remember, and sufficient for the few
170 // existing use cases. ATTACH is a discouraged feature, so no new use cases
172 return base::ranges::all_of(attachment_point,
173 [](char ch) { return base::IsAsciiLower(ch); });
176 std::string AsUTF8ForSQL(const base::FilePath& path) {
177 #if BUILDFLAG(IS_WIN)
178 return base::WideToUTF8(path.value());
179 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
187 Database::ScopedErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
190 bool Database::IsExpectedSqliteError(int sqlite_error_code) {
191 DCHECK_NE(sqlite_error_code, SQLITE_OK)
192 << __func__ << " received non-error result code";
193 DCHECK_NE(sqlite_error_code, SQLITE_DONE)
194 << __func__ << " received non-error result code";
195 DCHECK_NE(sqlite_error_code, SQLITE_ROW)
196 << __func__ << " received non-error result code";
198 if (!current_expecter_cb_)
200 return current_expecter_cb_->Run(sqlite_error_code);
204 void Database::SetScopedErrorExpecter(
205 Database::ScopedErrorExpecterCallback* cb,
206 base::PassKey<test::ScopedErrorExpecter>) {
207 CHECK(!current_expecter_cb_);
208 current_expecter_cb_ = cb;
212 void Database::ResetScopedErrorExpecter(
213 base::PassKey<test::ScopedErrorExpecter>) {
214 CHECK(current_expecter_cb_);
215 current_expecter_cb_ = nullptr;
219 base::FilePath Database::JournalPath(const base::FilePath& db_path) {
220 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
224 base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
225 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
229 base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
230 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
233 Database::StatementRef::StatementRef(Database* database,
236 : database_(database), stmt_(stmt), was_valid_(was_valid) {
237 DCHECK_EQ(database == nullptr, stmt == nullptr);
239 database_->StatementRefCreated(this);
242 Database::StatementRef::~StatementRef() {
244 database_->StatementRefDeleted(this);
248 void Database::StatementRef::Close(bool forced) {
250 // Call to InitScopedBlockingCall() cannot go at the beginning of the
251 // function because Close() is called unconditionally from destructor to
252 // clean database_. And if this is inactive statement this won't cause any
253 // disk access and destructor most probably will be called on thread not
254 // allowing disk access.
255 // TODO(paivanof@gmail.com): This should move to the beginning
256 // of the function. http://crbug.com/136655.
257 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
258 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
260 // `stmt_` references memory loaned from the sqlite3 library. Stop
261 // referencing it from the raw_ptr<> before returning it. This avoids the
262 // raw_ptr<> becoming dangling.
263 sqlite3_stmt* statement = stmt_;
266 // sqlite3_finalize()'s result code is ignored because it reports the same
267 // error as the most recent sqlite3_step(). The result code is passed
268 // through ToSqliteResultCode() to catch issues like SQLITE_MISUSE.
269 std::ignore = ToSqliteResultCode(sqlite3_finalize(statement));
271 database_ = nullptr; // The Database may be getting deleted.
273 // Forced close is expected to happen from a statement error
274 // handler. In that case maintain the sense of |was_valid_| which
275 // previously held for this ref.
276 was_valid_ = was_valid_ && forced;
279 static_assert(DatabaseOptions::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
280 "DatabaseOptions::kDefaultPageSize must match the value "
281 "configured into SQLite");
283 DatabaseDiagnostics::DatabaseDiagnostics() = default;
284 DatabaseDiagnostics::~DatabaseDiagnostics() = default;
286 void DatabaseDiagnostics::WriteIntoTrace(
287 perfetto::TracedProto<TraceProto> context) const {
288 context->set_reported_sqlite_error_code(reported_sqlite_error_code);
289 context->set_error_code(error_code);
290 context->set_last_errno(last_errno);
291 context->set_sql_statement(sql_statement);
292 context->set_version(version);
293 for (const auto& sql : schema_sql_rows) {
294 context->add_schema_sql_rows(sql);
296 for (const auto& name : schema_other_row_names) {
297 context->add_schema_other_row_names(name);
299 context->set_has_valid_header(has_valid_header);
300 context->set_has_valid_schema(has_valid_schema);
301 context->set_error_message(error_message);
304 // DatabaseOptions::explicit_locking needs to be set to false for historical
306 Database::Database() : Database({.exclusive_locking = false}) {}
308 Database::Database(DatabaseOptions options)
309 : options_(options), mmap_disabled_(!enable_mmap_by_default_) {
310 DCHECK_GE(options.page_size, 512);
311 DCHECK_LE(options.page_size, 65536);
312 DCHECK(!(options.page_size & (options.page_size - 1)))
313 << "page_size must be a power of two";
314 DCHECK(!options_.mmap_alt_status_discouraged ||
315 options_.enable_views_discouraged)
316 << "mmap_alt_status requires views";
318 // It's valid to construct a database on a sequence and then pass it to a
319 // different sequence before usage.
320 DETACH_FROM_SEQUENCE(sequence_checker_);
323 Database::~Database() {
328 void Database::DisableMmapByDefault() {
329 enable_mmap_by_default_ = false;
332 bool Database::Open(const base::FilePath& path) {
333 std::string path_string = AsUTF8ForSQL(path);
334 TRACE_EVENT1("sql", "Database::Open", "path", path_string);
336 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
337 DCHECK(!path.empty());
338 DCHECK_NE(path_string, kSqliteOpenInMemoryPath)
339 << "Path conflicts with SQLite magic identifier";
341 return OpenInternal(path_string, OpenMode::kRetryOnPoision);
344 bool Database::OpenInMemory() {
345 TRACE_EVENT0("sql", "Database::OpenInMemory");
347 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
350 return OpenInternal(kSqliteOpenInMemoryPath, OpenMode::kInMemory);
353 bool Database::OpenTemporary(base::PassKey<Recovery>) {
354 TRACE_EVENT0("sql", "Database::OpenTemporary");
356 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
357 return OpenInternal(std::string(), OpenMode::kTemporary);
360 void Database::CloseInternal(bool forced) {
361 TRACE_EVENT0("sql", "Database::CloseInternal");
362 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
363 // will delete the -journal file. For ChromiumOS or other more
364 // embedded systems, this is probably not appropriate, whereas on
365 // desktop it might make some sense.
367 // sqlite3_close() needs all prepared statements to be finalized.
369 // Release cached statements.
370 statement_cache_.clear();
372 // With cached statements released, in-use statements will remain.
373 // Closing the database while statements are in use is an API
374 // violation, except for forced close (which happens from within a
375 // statement's error handler).
376 DCHECK(forced || open_statements_.empty());
378 // Deactivate any outstanding statements so sqlite3_close() works.
379 for (StatementRef* statement_ref : open_statements_)
380 statement_ref->Close(forced);
381 open_statements_.clear();
384 // Call to InitScopedBlockingCall() cannot go at the beginning of the
385 // function because Close() must be called from destructor to clean
386 // statement_cache_, it won't cause any disk access and it most probably
387 // will happen on thread not allowing disk access.
388 // TODO(paivanof@gmail.com): This should move to the beginning
389 // of the function. http://crbug.com/136655.
390 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
391 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
393 // Resetting acquires a lock to ensure no dump is happening on the database
394 // at the same time. Unregister takes ownership of provider and it is safe
395 // since the db is reset. memory_dump_provider_ could be null if db_ was
397 if (memory_dump_provider_) {
398 memory_dump_provider_->ResetDatabase();
399 base::trace_event::MemoryDumpManager::GetInstance()
400 ->UnregisterAndDeleteDumpProviderSoon(
401 std::move(memory_dump_provider_));
404 auto sqlite_result_code = ToSqliteResultCode(sqlite3_close(db_));
406 DCHECK_NE(sqlite_result_code, SqliteResultCode::kBusy)
407 << "sqlite3_close() called while prepared statements are still alive";
408 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
409 << "sqlite3_close() failed in an unexpected way: " << GetErrorMessage();
411 // The reset must happen after the DCHECKs above. GetErrorMessage() needs a
412 // valid `db_` value.
417 bool Database::is_open() const {
418 bool is_closed_due_to_poisoning =
419 poisoned_ && base::FeatureList::IsEnabled(
420 sql::features::kConsiderPoisonedDatabasesClosed);
421 return static_cast<bool>(db_) && !is_closed_due_to_poisoning;
424 void Database::Close() {
425 TRACE_EVENT0("sql", "Database::Close");
426 // If the database was already closed by RazeAndPoison(), then no
427 // need to close again. Clear the |poisoned_| bit so that incorrect
428 // API calls are caught.
434 CloseInternal(false);
437 void Database::Preload() {
438 TRACE_EVENT0("sql", "Database::Preload");
440 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
442 DCHECK(poisoned_) << "Cannot preload null db";
446 CHECK(!options_.exclusive_database_file_lock)
447 << "Cannot preload an exclusively locked database.";
449 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
450 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
452 // Maximum number of bytes that will be prefetched from the database.
454 // This limit is very aggressive. The main trade-off involved is that having
455 // SQLite block on reading from disk has a high impact on Chrome startup cost
456 // for the databases that are on the critical path to startup. So, the limit
457 // must exceed the expected sizes of databases on the critical path.
459 // On Windows 7, base::PreReadFile() falls back to a synchronous read, and
460 // blocks until the entire file is read into memory. This is a minor factor at
461 // this point, because Chrome has very limited support for Windows 7.
462 constexpr int kPreReadSize = 128 * 1024 * 1024; // 128 MB
463 base::PreReadFile(DbPath(), /*is_executable=*/false, kPreReadSize);
466 // SQLite keeps unused pages associated with a database in a cache. It asks
467 // the cache for pages by an id, and if the page is present and the database is
468 // unchanged, it considers the content of the page valid and doesn't read it
469 // from disk. When memory-mapped I/O is enabled, on read SQLite uses page
470 // structures created from the memory map data before consulting the cache. On
471 // write SQLite creates a new in-memory page structure, copies the data from the
472 // memory map, and later writes it, releasing the updated page back to the
475 // This means that in memory-mapped mode, the contents of the cached pages are
476 // not re-used for reads, but they are re-used for writes if the re-written page
477 // is still in the cache. The implementation of sqlite3_db_release_memory() as
478 // of SQLite 3.8.7.4 frees all pages from pcaches associated with the
479 // database, so it should free these pages.
481 // Unfortunately, the zero page is also freed. That page is never accessed
482 // using memory-mapped I/O, and the cached copy can be re-used after verifying
483 // the file change counter on disk. Also, fresh pages from cache receive some
484 // pager-level initialization before they can be used. Since the information
485 // involved will immediately be accessed in various ways, it is unclear if the
486 // additional overhead is material, or just moving processor cache effects
489 // TODO(shess): It would be better to release the pages immediately when they
490 // are no longer needed. This would basically happen after SQLite commits a
491 // transaction. I had implemented a pcache wrapper to do this, but it involved
492 // layering violations, and it had to be setup before any other sqlite call,
493 // which was brittle. Also, for large files it would actually make sense to
494 // maintain the existing pcache behavior for blocks past the memory-mapped
495 // segment. I think drh would accept a reasonable implementation of the overall
496 // concept for upstreaming to SQLite core.
498 // TODO(shess): Another possibility would be to set the cache size small, which
499 // would keep the zero page around, plus some pre-initialized pages, and SQLite
500 // can manage things. The downside is that updates larger than the cache would
501 // spill to the journal. That could be compensated by setting cache_spill to
502 // false. The downside then is that it allows open-ended use of memory for
503 // large transactions.
504 void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
505 TRACE_EVENT0("sql", "Database::ReleaseCacheMemoryIfNeeded");
506 // The database could have been closed during a transaction as part of error
509 DCHECK(poisoned_) << "Illegal use of Database without a db";
513 // If memory-mapping is not enabled, the page cache helps performance.
517 // On caller request, force the change comparison to fail. Done before the
518 // transaction-nesting test so that the signal can carry to transaction
520 if (implicit_change_performed)
521 --total_changes_at_last_release_;
523 // Cached pages may be re-used within the same transaction.
524 DCHECK_GE(transaction_nesting_, 0);
525 if (transaction_nesting_)
528 // If no changes have been made, skip flushing. This allows the first page of
529 // the database to remain in cache across multiple reads.
530 const int64_t total_changes = sqlite3_total_changes64(db_);
531 if (total_changes == total_changes_at_last_release_)
534 total_changes_at_last_release_ = total_changes;
536 // Passing the result code through ToSqliteResultCode() to catch issues such
538 std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
541 base::FilePath Database::DbPath() const {
543 return base::FilePath();
545 const char* path = sqlite3_db_filename(db_, "main");
547 return base::FilePath();
548 const base::StringPiece db_path(path);
549 #if BUILDFLAG(IS_WIN)
550 return base::FilePath(base::UTF8ToWide(db_path));
551 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
552 return base::FilePath(db_path);
555 return base::FilePath();
559 std::string Database::CollectErrorInfo(int sqlite_error_code,
561 DatabaseDiagnostics* diagnostics) const {
562 TRACE_EVENT0("sql", "Database::CollectErrorInfo");
564 DCHECK_NE(sqlite_error_code, SQLITE_OK)
565 << __func__ << " received non-error result code";
566 DCHECK_NE(sqlite_error_code, SQLITE_DONE)
567 << __func__ << " received non-error result code";
568 DCHECK_NE(sqlite_error_code, SQLITE_ROW)
569 << __func__ << " received non-error result code";
571 // Buffer for accumulating debugging info about the error. Place
572 // more-relevant information earlier, in case things overflow the
573 // fixed-size reporting buffer.
574 std::string debug_info;
576 // The error message from the failed operation.
577 int error_code = GetErrorCode();
578 base::StringAppendF(&debug_info, "db error: %d/%s\n", error_code,
581 diagnostics->error_code = error_code;
582 diagnostics->error_message = GetErrorMessage();
585 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
586 // reading code does not entirely convince me. Remove if they turn out to be
588 if (sqlite_error_code != GetErrorCode())
589 base::StringAppendF(&debug_info, "reported error: %d\n", sqlite_error_code);
591 // System error information. Interpretation of Windows errors is different
593 #if BUILDFLAG(IS_WIN)
594 int last_errno = GetLastErrno();
595 base::StringAppendF(&debug_info, "LastError: %d\n", last_errno);
597 diagnostics->last_errno = last_errno;
599 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
600 int last_errno = GetLastErrno();
601 base::StringAppendF(&debug_info, "errno: %d\n", last_errno);
603 diagnostics->last_errno = last_errno;
606 NOTREACHED(); // Add appropriate log info.
610 std::string sql_string = stmt->GetSQLStatement();
611 base::StringAppendF(&debug_info, "statement: %s\n", sql_string.c_str());
613 diagnostics->sql_statement = sql_string;
616 base::StringAppendF(&debug_info, "statement: NULL\n");
619 // SQLITE_ERROR often indicates some sort of mismatch between the statement
620 // and the schema, possibly due to a failed schema migration.
621 if (sqlite_error_code == SQLITE_ERROR) {
622 static constexpr char kVersionSql[] =
623 "SELECT value FROM meta WHERE key='version'";
624 sqlite3_stmt* sqlite_statement;
625 // When the number of bytes passed to sqlite3_prepare_v3() includes the null
626 // terminator, SQLite avoids a buffer copy.
627 int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql),
628 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
629 /* pzTail= */ nullptr);
630 if (rc == SQLITE_OK) {
631 rc = sqlite3_step(sqlite_statement);
632 if (rc == SQLITE_ROW) {
633 int version = sqlite3_column_int(sqlite_statement, 0);
634 base::StringAppendF(&debug_info, "version: %d\n", version);
636 diagnostics->version = version;
638 } else if (rc == SQLITE_DONE) {
639 debug_info += "version: none\n";
641 base::StringAppendF(&debug_info, "version: error %d\n", rc);
643 sqlite3_finalize(sqlite_statement);
645 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
648 // Get all the SQL from sqlite_schema.
649 debug_info += "schema:\n";
650 static constexpr char kSchemaSql[] =
651 "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY ROWID";
652 rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql),
653 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
654 /* pzTail= */ nullptr);
655 if (rc == SQLITE_OK) {
656 while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
658 base::StringAppendF(&text, "%s",
659 reinterpret_cast<const char*>(
660 sqlite3_column_text(sqlite_statement, 0)));
661 debug_info += text + "\n";
663 diagnostics->schema_sql_rows.push_back(text);
667 if (rc != SQLITE_DONE)
668 base::StringAppendF(&debug_info, "error %d\n", rc);
669 sqlite3_finalize(sqlite_statement);
671 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
674 // Automatically generated indices have a NULL 'sql' column. For those rows,
675 // we log the name column instead.
676 debug_info += "schema rows with only name:\n";
677 static constexpr char kSchemaOtherRowNamesSql[] =
678 "SELECT name FROM sqlite_schema WHERE sql IS NULL ORDER BY ROWID";
679 rc = sqlite3_prepare_v3(db_, kSchemaOtherRowNamesSql,
680 sizeof(kSchemaOtherRowNamesSql),
681 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
682 /* pzTail= */ nullptr);
683 if (rc == SQLITE_OK) {
684 while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
686 base::StringAppendF(&text, "%s",
687 reinterpret_cast<const char*>(
688 sqlite3_column_text(sqlite_statement, 0)));
689 debug_info += text + "\n";
691 diagnostics->schema_other_row_names.push_back(text);
695 if (rc != SQLITE_DONE)
696 base::StringAppendF(&debug_info, "error %d\n", rc);
697 sqlite3_finalize(sqlite_statement);
699 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
706 // TODO(shess): Since this is only called in an error situation, it might be
707 // prudent to rewrite in terms of SQLite API calls, and mark the function const.
708 std::string Database::CollectCorruptionInfo() {
709 TRACE_EVENT0("sql", "Database::CollectCorruptionInfo");
710 // If the file cannot be accessed it is unlikely that an integrity check will
711 // turn up actionable information.
712 const base::FilePath db_path = DbPath();
713 int64_t db_size = -1;
714 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
715 return std::string();
717 // Buffer for accumulating debugging info about the error. Place
718 // more-relevant information earlier, in case things overflow the
719 // fixed-size reporting buffer.
720 std::string debug_info;
721 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
724 // Only check files up to 8M to keep things from blocking too long.
725 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
726 if (db_size > kMaxIntegrityCheckSize) {
727 debug_info += "integrity_check skipped due to size\n";
729 std::vector<std::string> messages;
731 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
732 // into a string. Probably should be refactored.
733 const base::TimeTicks before = base::TimeTicks::Now();
734 FullIntegrityCheck(&messages);
736 &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
737 (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
739 // SQLite returns up to 100 messages by default, trim deeper to
740 // keep close to the 2000-character size limit for dumping.
741 const size_t kMaxMessages = 20;
742 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
743 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
750 bool Database::GetMmapAltStatus(int64_t* status) {
751 TRACE_EVENT0("sql", "Database::GetMmapAltStatus");
753 // The [meta] version uses a missing table as a signal for a fresh database.
754 // That will not work for the view, which would not exist in either a new or
755 // an existing database. A new database _should_ be only one page long, so
756 // just don't bother optimizing this case (start at offset 0).
757 // TODO(shess): Could the [meta] case also get simpler, then?
758 if (!DoesViewExist("MmapStatus")) {
763 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
764 Statement s(GetUniqueStatement(kMmapStatusSql));
766 *status = s.ColumnInt64(0);
767 return s.Succeeded();
770 bool Database::SetMmapAltStatus(int64_t status) {
771 if (!BeginTransaction())
774 // View may not exist on first run.
775 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
776 RollbackTransaction();
780 // Views live in the schema, so they cannot be parameterized. For an integer
781 // value, this construct should be safe from SQL injection, if the value
782 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
784 const std::string create_view_sql = base::StringPrintf(
785 "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
786 if (!Execute(create_view_sql.c_str())) {
787 RollbackTransaction();
791 return CommitTransaction();
794 size_t Database::ComputeMmapSizeForOpen() {
795 TRACE_EVENT0("sql", "Database::ComputeMmapSizeForOpen");
797 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
798 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
800 // How much to map if no errors are found. 50MB encompasses the 99th
801 // percentile of Chrome databases in the wild, so this should be good.
802 const size_t kMmapEverything = 256 * 1024 * 1024;
804 // Progress information is tracked in the [meta] table for databases which use
805 // sql::MetaTable, otherwise it is tracked in a special view.
806 // TODO(pwnall): Migrate all databases to using a meta table.
807 int64_t mmap_ofs = 0;
808 if (options_.mmap_alt_status_discouraged) {
809 if (!GetMmapAltStatus(&mmap_ofs))
812 // If [meta] doesn't exist, yet, it's a new database, assume the best.
813 // sql::MetaTable::Init() will preload kMmapSuccess.
814 if (!MetaTable::DoesTableExist(this))
815 return kMmapEverything;
817 if (!MetaTable::GetMmapStatus(this, &mmap_ofs))
821 // Database read failed in the past, don't memory map.
822 if (mmap_ofs == MetaTable::kMmapFailure)
825 if (mmap_ofs != MetaTable::kMmapSuccess) {
826 // Continue reading from previous offset.
827 DCHECK_GE(mmap_ofs, 0);
829 // GetSqliteVfsFile() returns null for in-memory and temporary databases.
830 // This is fine, we don't want to enable memory-mapping in those cases
833 // First, memory-mapping is a no-op for in-memory databases.
835 // Second, temporary databases are only used for corruption recovery, which
836 // occurs in response to I/O errors. An environment with heightened I/O
837 // errors translates into a higher risk of mmap-induced Chrome crashes.
838 sqlite3_int64 db_size = 0;
839 sqlite3_file* file = GetSqliteVfsFile();
840 if (!file || file->pMethods->xFileSize(file, &db_size) != SQLITE_OK)
843 // Read more of the database looking for errors. The VFS interface is used
844 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
845 // to limit checking to 20MB per run of Chromium.
847 // Read the data left, or |g_reads_allowed|, whichever is smaller.
848 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
849 // in a single Chromium run.
850 sqlite3_int64 amount = db_size - mmap_ofs;
854 static base::NoDestructor<base::Lock> lock;
855 base::AutoLock auto_lock(*lock);
856 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
857 if (g_reads_allowed < amount)
858 amount = g_reads_allowed;
859 g_reads_allowed -= amount;
862 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
863 // database was truncated after a previous pass.
864 if (amount <= 0 && mmap_ofs < db_size) {
865 DCHECK_EQ(0, amount);
867 static const int kPageSize = 4096;
870 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
871 if (rc == SQLITE_OK) {
872 mmap_ofs += sizeof(buf);
873 amount -= sizeof(buf);
874 } else if (rc == SQLITE_IOERR_SHORT_READ) {
875 // Reached EOF for a database with page size < |kPageSize|.
879 // TODO(shess): Consider calling OnSqliteError().
880 mmap_ofs = MetaTable::kMmapFailure;
885 // Log these events after update to distinguish meta update failure.
886 if (mmap_ofs >= db_size) {
887 mmap_ofs = MetaTable::kMmapSuccess;
889 DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure);
892 if (options_.mmap_alt_status_discouraged) {
893 if (!SetMmapAltStatus(mmap_ofs))
896 if (!MetaTable::SetMmapStatus(this, mmap_ofs))
902 if (mmap_ofs == MetaTable::kMmapFailure)
904 if (mmap_ofs == MetaTable::kMmapSuccess)
905 return kMmapEverything;
909 int Database::SqlitePrepareFlags() const {
910 return options_.enable_virtual_tables_discouraged ? 0
911 : SQLITE_PREPARE_NO_VTAB;
914 sqlite3_file* Database::GetSqliteVfsFile() {
915 DCHECK(db_) << "Database not opened";
917 // sqlite3_file_control() accepts a null pointer to mean the "main" database
918 // attached to a connection. https://www.sqlite.org/c3ref/file_control.html
919 constexpr const char* kMainDatabaseName = nullptr;
921 sqlite3_file* result = nullptr;
922 auto sqlite_result_code = ToSqliteResultCode(sqlite3_file_control(
923 db_, kMainDatabaseName, SQLITE_FCNTL_FILE_POINTER, &result));
925 // SQLITE_FCNTL_FILE_POINTER is handled directly by SQLite, not by the VFS. It
926 // is only supposed to fail with SQLITE_ERROR if the database name is not
927 // recognized. However, "main" should always be recognized.
928 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
929 << "sqlite3_file_control(SQLITE_FCNTL_FILE_POINTER) failed";
931 // SQLite does not return null when called on an in-memory or temporary
932 // database. Instead, it returns returns a VFS file object with a null
935 << "sqlite3_file_control() succeded but returned a null sqlite3_file*";
936 if (!result->pMethods) {
937 // If this assumption fails, sql::Database will still function correctly,
938 // but will miss some configuration optimizations. The DCHECK is here to
939 // alert us (via test failures and ASAN canary builds) of such cases.
940 DCHECK_EQ(DbPath().AsUTF8Unsafe(), "")
941 << "sqlite3_file_control() returned a sqlite3_file* with null pMethods "
942 << "in a case when it shouldn't have.";
950 void Database::TrimMemory() {
951 TRACE_EVENT0("sql", "Database::TrimMemory");
956 // Passing the result code through ToSqliteResultCode() to catch issues such
958 std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
960 // It is tempting to use sqlite3_release_memory() here as well. However, the
961 // API is documented to be a no-op unless SQLite is built with
962 // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is
963 // incompatible with per-database page cache pools. Behind the scenes,
964 // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache
965 // pool, and sqlite3_release_memory() releases unused pages from this global
967 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
968 #error "This method assumes SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined"
969 #endif // defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
972 // Create an in-memory database with the existing database's page
973 // size, then backup that database over the existing database.
974 bool Database::Raze() {
975 TRACE_EVENT0("sql", "Database::Raze");
977 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
978 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
981 DCHECK(poisoned_) << "Cannot raze null db";
985 DCHECK_GE(transaction_nesting_, 0);
986 if (transaction_nesting_ > 0) {
987 DLOG(DCHECK) << "Cannot raze within a transaction";
991 sql::Database null_db(sql::DatabaseOptions{
992 .exclusive_locking = true,
993 .page_size = options_.page_size,
995 .enable_views_discouraged = options_.enable_views_discouraged,
996 .enable_virtual_tables_discouraged =
997 options_.enable_virtual_tables_discouraged,
999 if (!null_db.OpenInMemory()) {
1000 DLOG(DCHECK) << "Unable to open in-memory database.";
1004 #if BUILDFLAG(IS_ANDROID)
1005 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1006 // in-memory databases do not respect this define.
1007 // TODO(shess): Figure out a way to set this without using platform
1008 // specific code. AFAICT from sqlite3.c, the only way to do it
1009 // would be to create an actual filesystem database, which is
1011 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1015 // The page size doesn't take effect until a database has pages, and
1016 // at this point the null database has none. Changing the schema
1017 // version will create the first page. This will not affect the
1018 // schema version in the resulting database, as SQLite's backup
1019 // implementation propagates the schema version from the original
1020 // database to the new version of the database, incremented by one
1021 // so that other readers see the schema change and act accordingly.
1022 if (!null_db.Execute("PRAGMA schema_version = 1"))
1025 // SQLite tracks the expected number of database pages in the first
1026 // page, and if it does not match the total retrieved from a
1027 // filesystem call, treats the database as corrupt. This situation
1028 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1029 // used to hint to SQLite to soldier on in that case, specifically
1030 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1031 // sqlite3.c lockBtree().]
1032 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1033 // page_size" can be used to query such a database.
1034 ScopedWritableSchema writable_schema(db_);
1036 #if BUILDFLAG(IS_WIN)
1037 // On Windows, truncate silently fails when applied to memory-mapped files.
1038 // Disable memory-mapping so that the truncate succeeds. Note that other
1039 // Database connections may have memory-mapped the file, so this may not
1040 // entirely prevent the problem.
1041 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1042 std::ignore = Execute("PRAGMA mmap_size = 0");
1045 SqliteResultCode sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
1047 // The destination database was locked.
1048 if (sqlite_result_code == SqliteResultCode::kBusy)
1051 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1052 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1053 // isn't even big enough for one page. Either way, reach in and
1054 // truncate it before trying again.
1055 // TODO(shess): Maybe it would be worthwhile to just truncate from
1057 if (sqlite_result_code == SqliteResultCode::kNotADatabase ||
1058 sqlite_result_code == SqliteResultCode::kIoShortRead) {
1059 sqlite3_file* file = GetSqliteVfsFile();
1060 if (!file || file->pMethods->xTruncate(file, 0) != SQLITE_OK) {
1061 DLOG(DCHECK) << "Failed to truncate file.";
1065 sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
1066 if (sqlite_result_code != SqliteResultCode::kDone)
1070 // Page size of |db_| and |null_db| differ.
1071 if (sqlite_result_code == SqliteResultCode::kReadOnly) {
1072 // Enter TRUNCATE mode to change page size.
1073 // TODO(shuagga@microsoft.com): Need a guarantee here that there is no other
1074 // database connection open.
1075 std::ignore = Execute("PRAGMA journal_mode=TRUNCATE;");
1076 const std::string page_size_sql = base::StrCat(
1077 {"PRAGMA page_size=", base::NumberToString(options_.page_size)});
1078 if (!Execute(page_size_sql.c_str())) {
1081 // Page size isn't changed until the database is vacuumed.
1082 std::ignore = Execute("VACUUM");
1083 // Re-enter WAL mode.
1085 std::ignore = Execute("PRAGMA journal_mode=WAL;");
1088 sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
1089 if (sqlite_result_code != SqliteResultCode::kDone)
1093 if (sqlite_result_code != SqliteResultCode::kDone) {
1094 NOTIMPLEMENTED() << "Unhandled sqlite3_backup_step() error: "
1095 << sqlite_result_code;
1099 // Checkpoint to propagate transactions to the database file and empty the WAL
1101 // The database can still contain old data if the Checkpoint fails so fail the
1103 return CheckpointDatabase();
1106 bool Database::RazeAndPoison() {
1107 TRACE_EVENT0("sql", "Database::RazeAndPoison");
1110 DCHECK(poisoned_) << "Cannot raze null db";
1114 // Raze() cannot run in a transaction.
1115 RollbackAllTransactions();
1117 bool result = Raze();
1119 CloseInternal(true);
1121 // Mark the database so that future API calls fail appropriately,
1122 // but don't DCHECK (because after calling this function they are
1123 // expected to fail).
1129 void Database::Poison() {
1130 TRACE_EVENT0("sql", "Database::Poison");
1133 DCHECK(poisoned_) << "Cannot poison null db";
1137 RollbackAllTransactions();
1138 CloseInternal(true);
1140 // Mark the database so that future API calls fail appropriately,
1141 // but don't DCHECK (because after calling this function they are
1142 // expected to fail).
1146 // TODO(shess): To the extent possible, figure out the optimal
1147 // ordering for these deletes which will prevent other Database connections
1148 // from seeing odd behavior. For instance, it may be necessary to
1149 // manually lock the main database file in a SQLite-compatible fashion
1150 // (to prevent other processes from opening it), then delete the
1151 // journal files, then delete the main database file. Another option
1152 // might be to lock the main database file and poison the header with
1153 // junk to prevent other processes from opening it successfully (like
1154 // Gears "SQLite poison 3" trick).
1157 bool Database::Delete(const base::FilePath& path) {
1158 TRACE_EVENT1("sql", "Database::Delete", "path", path.MaybeAsASCII());
1160 base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
1161 base::BlockingType::MAY_BLOCK);
1163 base::FilePath journal_path = Database::JournalPath(path);
1164 base::FilePath wal_path = Database::WriteAheadLogPath(path);
1166 std::string journal_str = AsUTF8ForSQL(journal_path);
1167 std::string wal_str = AsUTF8ForSQL(wal_path);
1168 std::string path_str = AsUTF8ForSQL(path);
1170 EnsureSqliteInitialized();
1172 sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
1174 CHECK(vfs->xDelete);
1175 CHECK(vfs->xAccess);
1177 // We only work with the VFS implementations listed below. If you're trying to
1178 // use this code with any other VFS, you're not in a good place.
1179 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1180 strncmp(vfs->zName, "win32", 5) == 0 ||
1181 strcmp(vfs->zName, "storage_service") == 0);
1183 vfs->xDelete(vfs, journal_str.c_str(), 0);
1184 vfs->xDelete(vfs, wal_str.c_str(), 0);
1185 vfs->xDelete(vfs, path_str.c_str(), 0);
1187 int journal_exists = 0;
1188 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
1191 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
1193 int path_exists = 0;
1194 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
1196 return !journal_exists && !wal_exists && !path_exists;
1199 bool Database::BeginTransaction() {
1200 TRACE_EVENT0("sql", "Database::BeginTransaction");
1202 if (needs_rollback_) {
1203 DCHECK_GT(transaction_nesting_, 0);
1205 // When we're going to rollback, fail on this begin and don't actually
1206 // mark us as entering the nested transaction.
1210 bool success = true;
1211 DCHECK_GE(transaction_nesting_, 0);
1212 if (!transaction_nesting_) {
1213 needs_rollback_ = false;
1215 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
1219 ++transaction_nesting_;
1223 void Database::RollbackTransaction() {
1224 TRACE_EVENT0("sql", "Database::RollbackTransaction");
1226 DCHECK_GE(transaction_nesting_, 0);
1227 if (!transaction_nesting_) {
1228 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
1232 DCHECK_GT(transaction_nesting_, 0);
1233 --transaction_nesting_;
1235 if (transaction_nesting_ > 0) {
1236 // Mark the outermost transaction as needing rollback.
1237 needs_rollback_ = true;
1244 bool Database::CommitTransaction() {
1245 TRACE_EVENT0("sql", "Database::CommitTransaction");
1247 DCHECK_GE(transaction_nesting_, 0);
1248 if (!transaction_nesting_) {
1249 DCHECK(poisoned_) << "Committing a nonexistent transaction";
1253 DCHECK_GT(transaction_nesting_, 0);
1254 --transaction_nesting_;
1256 if (transaction_nesting_ > 0) {
1257 // Mark any nested transactions as failing after we've already got one.
1258 return !needs_rollback_;
1261 if (needs_rollback_) {
1266 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
1268 bool succeeded = commit.Run();
1270 // Release dirty cache pages after the transaction closes.
1271 ReleaseCacheMemoryIfNeeded(false);
1276 void Database::RollbackAllTransactions() {
1277 TRACE_EVENT0("sql", "Database::RollbackAllTransactions");
1279 DCHECK_GE(transaction_nesting_, 0);
1280 if (transaction_nesting_ > 0) {
1281 transaction_nesting_ = 0;
1286 bool Database::AttachDatabase(const base::FilePath& other_db_path,
1287 base::StringPiece attachment_point,
1289 TRACE_EVENT0("sql", "Database::AttachDatabase");
1291 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1292 DCHECK(ValidAttachmentPoint(attachment_point));
1294 Statement statement(GetUniqueStatement("ATTACH ? AS ?"));
1295 #if BUILDFLAG(IS_WIN)
1296 statement.BindString16(0, base::AsStringPiece16(other_db_path.value()));
1298 statement.BindString(0, other_db_path.value());
1300 statement.BindString(1, attachment_point);
1301 return statement.Run();
1304 bool Database::DetachDatabase(base::StringPiece attachment_point,
1306 TRACE_EVENT0("sql", "Database::DetachDatabase");
1308 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1309 DCHECK(ValidAttachmentPoint(attachment_point));
1311 Statement statement(GetUniqueStatement("DETACH ?"));
1312 statement.BindString(0, attachment_point);
1313 return statement.Run();
1316 // TODO(crbug.com/1230443): Change this to execute exactly one statement.
1317 SqliteResultCode Database::ExecuteAndReturnResultCode(const char* sql) {
1318 TRACE_EVENT0("sql", "Database::ExecuteAndReturnErrorCode");
1323 DCHECK(poisoned_) << "Illegal use of Database without a db";
1324 return SqliteResultCode::kError;
1327 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1328 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1330 SqliteResultCode sqlite_result_code = SqliteResultCode::kOk;
1331 while ((sqlite_result_code == SqliteResultCode::kOk) && *sql) {
1332 sqlite3_stmt* sqlite_statement;
1333 const char* leftover_sql;
1334 sqlite_result_code = ToSqliteResultCode(
1335 sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
1336 &sqlite_statement, &leftover_sql));
1339 // Report SQL compilation errors. On developer machines, the errors are most
1340 // likely caused by invalid SQL in an under-development feature. In
1341 // production, SQL compilation errors are caused by database schema
1344 // DCHECK would not be appropriate here, because on-disk data is always
1345 // subject to corruption, so Chrome cannot assume that the database schema
1346 // will remain intact.
1347 if (sqlite_result_code == SqliteResultCode::kError) {
1348 DLOG(ERROR) << "SQL compilation error: " << GetErrorMessage()
1349 << ". Statement: " << sql;
1351 #endif // DCHECK_IS_ON()
1353 // Stop if compiling the SQL statement fails.
1354 if (sqlite_result_code != SqliteResultCode::kOk) {
1355 DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1356 << "sqlite3_prepare_v3() returned unexpected non-error result code";
1357 DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1358 << "sqlite3_prepare_v3() returned unexpected non-error result code";
1364 // This happens if |sql| originally only contained comments or whitespace.
1365 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1366 // extraneous comments and whitespace in the SQL statements increases
1367 // runtime cost and can easily be shifted out to the C++ layer.
1368 if (!sqlite_statement)
1372 sqlite_result_code = ToSqliteResultCode(sqlite3_step(sqlite_statement));
1373 if (sqlite_result_code != SqliteResultCode::kRow)
1376 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1377 // is the only legitimate case for this. Previously recorded histograms
1378 // show significant use of this code path.
1381 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1382 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1383 sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
1384 DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1385 << "sqlite3_finalize() returned unexpected non-error result code";
1386 DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1387 << "sqlite3_finalize() returned unexpected non-error result code";
1389 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1390 // trailing whitespace.
1391 // TODO(shess): Audit to see if this can become a DCHECK.
1392 while (base::IsAsciiWhitespace(*sql)) {
1397 // Most calls to Execute() modify the database. The main exceptions would be
1398 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1399 // but sometimes don't.
1400 ReleaseCacheMemoryIfNeeded(true);
1402 DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1403 << __func__ << " about to return unexpected non-error result code";
1404 DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1405 << __func__ << " about to return unexpected non-error result code";
1406 return sqlite_result_code;
1409 bool Database::Execute(const char* sql) {
1410 TRACE_EVENT1("sql", "Database::Execute", "query", TRACE_STR_COPY(sql));
1413 DCHECK(poisoned_) << "Illegal use of Database without a db";
1417 SqliteResultCode sqlite_result_code = ExecuteAndReturnResultCode(sql);
1418 if (sqlite_result_code != SqliteResultCode::kOk)
1419 OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr, sql);
1421 return sqlite_result_code == SqliteResultCode::kOk;
1424 bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
1425 TRACE_EVENT0("sql", "Database::ExecuteWithTimeout");
1427 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1429 DCHECK(poisoned_) << "Illegal use of Database without a db";
1433 ScopedBusyTimeout busy_timeout(db_);
1434 busy_timeout.SetTimeout(timeout);
1435 return Execute(sql);
1438 bool Database::ExecuteScriptForTesting(const char* sql_script) {
1441 DCHECK(poisoned_) << "Illegal use of Database without a db";
1445 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1446 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1448 while (*sql_script) {
1449 sqlite3_stmt* sqlite_statement;
1450 auto sqlite_result_code = ToSqliteResultCode(
1451 sqlite3_prepare_v3(db_, sql_script, /*nByte=*/-1, SqlitePrepareFlags(),
1452 &sqlite_statement, &sql_script));
1453 if (sqlite_result_code != SqliteResultCode::kOk)
1456 if (!sqlite_statement) {
1457 // Trailing comment or whitespace after the last semicolon.
1461 // TODO(pwnall): Investigate restricting ExecuteScriptForTesting() to
1462 // statements that don't produce any result rows.
1464 sqlite_result_code = ToSqliteResultCode(sqlite3_step(sqlite_statement));
1465 } while (sqlite_result_code == SqliteResultCode::kRow);
1467 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1468 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1469 sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
1470 if (sqlite_result_code != SqliteResultCode::kOk)
1477 scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
1480 auto it = statement_cache_.find(id);
1481 if (it != statement_cache_.end()) {
1482 // Statement is in the cache. It should still be valid. We're the only
1483 // entity invalidating cached statements, and we remove them from the cache
1485 DCHECK(it->second->is_valid());
1486 DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
1487 << "GetCachedStatement used with same ID but different SQL";
1489 // Reset the statement so it can be reused.
1491 // ToSqliteResultCode() is called to ensure that sqlite3_reset() doesn't
1492 // return a concerning code, such as SQLITE_MISUSE. The processed error code
1493 // is ignored because sqlite3_reset() returns an error code if the last
1494 // sqlite3_step() failed, and that error was already reported when we ran
1495 // sqlite3_step(), via Statement::Run() or Statement::Step().
1496 std::ignore = ToSqliteResultCode(sqlite3_reset(it->second->stmt()));
1500 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1501 if (statement->is_valid()) {
1502 statement_cache_[id] = statement; // Only cache valid statements.
1503 DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
1504 << "Input SQL does not match SQLite's normalized version";
1509 scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
1511 return GetStatementImpl(sql, /*is_readonly=*/false);
1514 scoped_refptr<Database::StatementRef> Database::GetReadonlyStatement(
1516 return GetStatementImpl(sql, /*is_readonly=*/true);
1519 scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1524 // Return inactive statement.
1526 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
1528 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1529 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1532 const char* unused_sql = nullptr;
1533 const char** unused_sql_ptr = &unused_sql;
1535 constexpr const char** unused_sql_ptr = nullptr;
1536 #endif // DCHECK_IS_ON()
1537 // TODO(pwnall): Cached statements (but not unique statements) should be
1538 // prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT.
1539 sqlite3_stmt* sqlite_statement;
1540 auto sqlite_result_code = ToSqliteResultCode(
1541 sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
1542 &sqlite_statement, unused_sql_ptr));
1545 // Report SQL compilation errors. On developer machines, the errors are most
1546 // likely caused by invalid SQL in an under-development feature. In
1547 // production, SQL compilation errors are caused by database schema
1550 // DCHECK would not be appropriate here, because on-disk data is always
1551 // subject to corruption, so Chrome cannot assume that the database schema
1552 // will remain intact.
1553 if (sqlite_result_code == SqliteResultCode::kError) {
1554 DLOG(ERROR) << "SQL compilation error: " << GetErrorMessage()
1555 << ". Statement: " << sql;
1557 #endif // DCHECK_IS_ON()
1559 if (sqlite_result_code != SqliteResultCode::kOk) {
1560 DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1561 << "sqlite3_prepare_v3() returned unexpected non-error result code";
1562 DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1563 << "sqlite3_prepare_v3() returned unexpected non-error result code";
1564 OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr, sql);
1565 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
1568 // If readonly statement is expected and the statement is not readonly, return
1569 // an invalid statement and close the created statement.
1570 if (is_readonly && sqlite3_stmt_readonly(sqlite_statement) == 0) {
1571 DLOG(ERROR) << "Readonly SQL statement failed readonly test " << sql;
1572 // Make a `StatementRef` that will close the created statement.
1573 base::MakeRefCounted<StatementRef>(this, sqlite_statement, true);
1575 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
1579 DCHECK_EQ(unused_sql, sql + strlen(sql))
1580 << "Unused text: " << std::string(unused_sql) << "\n"
1581 << "in prepared SQL statement: " << std::string(sql);
1582 #endif // DCHECK_IS_ON()
1584 DCHECK(sqlite_statement) << "No SQL statement in string: " << sql;
1586 return base::MakeRefCounted<StatementRef>(this, sqlite_statement, true);
1589 std::string Database::GetSchema() {
1590 // The ORDER BY should not be necessary, but relying on organic
1591 // order for something like this is questionable.
1592 static const char kSql[] =
1593 "SELECT type, name, tbl_name, sql "
1594 "FROM sqlite_schema ORDER BY 1, 2, 3, 4";
1595 Statement statement(GetUniqueStatement(kSql));
1598 while (statement.Step()) {
1599 schema += statement.ColumnString(0);
1601 schema += statement.ColumnString(1);
1603 schema += statement.ColumnString(2);
1605 schema += statement.ColumnString(3);
1612 bool Database::IsSQLValid(const char* sql) {
1613 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1615 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1616 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1618 DCHECK(poisoned_) << "Illegal use of Database without a db";
1623 const char* unused_sql = nullptr;
1624 const char** unused_sql_ptr = &unused_sql;
1626 constexpr const char** unused_sql_ptr = nullptr;
1627 #endif // DCHECK_IS_ON()
1629 sqlite3_stmt* sqlite_statement = nullptr;
1630 auto sqlite_result_code = ToSqliteResultCode(
1631 sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
1632 &sqlite_statement, unused_sql_ptr));
1633 if (sqlite_result_code != SqliteResultCode::kOk)
1637 DCHECK_EQ(unused_sql, sql + strlen(sql))
1638 << "Unused text: " << std::string(unused_sql) << "\n"
1639 << "in SQL statement: " << std::string(sql);
1640 #endif // DCHECK_IS_ON()
1642 DCHECK(sqlite_statement) << "No SQL statement in string: " << sql;
1644 sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
1645 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1646 << "sqlite3_finalize() failed for valid statement";
1650 bool Database::DoesIndexExist(base::StringPiece index_name) {
1651 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1652 return DoesSchemaItemExist(index_name, "index");
1655 bool Database::DoesTableExist(base::StringPiece table_name) {
1656 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1657 return DoesSchemaItemExist(table_name, "table");
1660 bool Database::DoesViewExist(base::StringPiece view_name) {
1661 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1662 return DoesSchemaItemExist(view_name, "view");
1665 bool Database::DoesSchemaItemExist(base::StringPiece name,
1666 base::StringPiece type) {
1667 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1669 static const char kSql[] =
1670 "SELECT 1 FROM sqlite_schema WHERE type=? AND name=?";
1671 Statement statement(GetUniqueStatement(kSql));
1673 if (!statement.is_valid()) {
1674 // The database is corrupt.
1678 statement.BindString(0, type);
1679 statement.BindString(1, name);
1681 return statement.Step(); // Table exists if any row was returned.
1684 bool Database::DoesColumnExist(const char* table_name,
1685 const char* column_name) {
1686 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1689 DCHECK(poisoned_) << "Illegal use of Database without a db";
1693 // sqlite3_table_column_metadata uses out-params to return column definition
1694 // details, such as the column type and whether it allows NULL values. These
1695 // aren't needed to compute the current method's result, so we pass in nullptr
1696 // for all the out-params.
1697 auto sqlite_result_code = ToSqliteResultCode(sqlite3_table_column_metadata(
1698 db_, "main", table_name, column_name, /* pzDataType= */ nullptr,
1699 /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr,
1700 /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr));
1701 return sqlite_result_code == SqliteResultCode::kOk;
1704 int64_t Database::GetLastInsertRowId() const {
1706 DCHECK(poisoned_) << "Illegal use of Database without a db";
1709 int64_t last_rowid = sqlite3_last_insert_rowid(db_);
1710 DCHECK(last_rowid != 0) << "No successful INSERT in a table with ROWID";
1714 int64_t Database::GetLastChangeCount() {
1716 DCHECK(poisoned_) << "Illegal use of Database without a db";
1719 return sqlite3_changes64(db_);
1722 int Database::GetMemoryUsage() {
1724 DCHECK(poisoned_) << "Illegal use of Database without a db";
1728 // The following calls all set the high watermark to zero.
1729 // See https://www.sqlite.org/c3ref/c_dbstatus_options.html
1730 int high_watermark = 0;
1732 int cache_memory = 0, schema_memory = 0, statement_memory = 0;
1734 auto sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
1735 db_, SQLITE_DBSTATUS_CACHE_USED, &cache_memory, &high_watermark,
1737 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1738 << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED) failed";
1741 int shared_cache_memory = 0;
1742 sqlite_result_code = ToSqliteResultCode(
1743 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED_SHARED,
1744 &shared_cache_memory, &high_watermark, /*resetFlg=*/0));
1745 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1746 << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED_SHARED) failed";
1747 DCHECK_EQ(shared_cache_memory, cache_memory)
1748 << "Memory counting assumes that each database uses a private page cache";
1749 #endif // DCHECK_IS_ON()
1751 sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
1752 db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_memory, &high_watermark,
1754 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1755 << "sqlite3_db_status(SQLITE_DBSTATUS_SCHEMA_USED) failed";
1757 sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
1758 db_, SQLITE_DBSTATUS_STMT_USED, &statement_memory, &high_watermark,
1760 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1761 << "sqlite3_db_status(SQLITE_DBSTATUS_STMT_USED) failed";
1763 return cache_memory + schema_memory + statement_memory;
1766 int Database::GetErrorCode() const {
1768 return SQLITE_ERROR;
1769 return sqlite3_extended_errcode(db_);
1772 int Database::GetLastErrno() const {
1777 if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
1783 const char* Database::GetErrorMessage() const {
1785 return "sql::Database is not opened.";
1786 return sqlite3_errmsg(db_);
1789 bool Database::OpenInternal(const std::string& db_file_path,
1790 Database::OpenMode mode) {
1791 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1792 TRACE_EVENT1("sql", "Database::OpenInternal", "path", db_file_path);
1794 DCHECK(mode != OpenMode::kTemporary || db_file_path.empty())
1795 << "Temporary databases should be open with an empty file path";
1797 if (mode == OpenMode::kInMemory) {
1798 DCHECK_EQ(db_file_path, kSqliteOpenInMemoryPath)
1799 << "In-memory databases should be open with the magic :memory: path";
1801 DCHECK_NE(db_file_path, kSqliteOpenInMemoryPath)
1802 << "Database file path conflicts with SQLite magic identifier";
1806 DLOG(DCHECK) << "sql::Database is already open.";
1810 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1811 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1813 EnsureSqliteInitialized();
1815 // If |poisoned_| is set, it means an error handler called
1816 // RazeAndPoison(). Until regular Close() is called, the caller
1817 // should be treating the database as open, but is_open() currently
1818 // only considers the sqlite3 handle's state.
1819 DCHECK(!poisoned_) << "sql::Database is already open.";
1822 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1823 sqlite3_vfs* vfs = VFSWrapper();
1824 const char* vfs_name = (vfs ? vfs->zName : nullptr);
1826 // The flags are documented at https://www.sqlite.org/c3ref/open.html.
1828 // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
1829 // disparate features with their own databases, and having separate page
1830 // caches makes it easier to reason about each feature's performance in
1833 // SQLITE_OPEN_EXRESCODE enables the full range of SQLite error codes. See
1834 // https://www.sqlite.org/rescode.html for details.
1835 int open_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
1836 SQLITE_OPEN_EXRESCODE | SQLITE_OPEN_PRIVATECACHE;
1837 std::string uri_file_path = db_file_path;
1838 if (options_.exclusive_database_file_lock) {
1839 #if BUILDFLAG(IS_WIN)
1840 if (mode == OpenMode::kNone || mode == OpenMode::kRetryOnPoision) {
1841 // Do not allow query injection.
1842 if (base::Contains(db_file_path, '?')) {
1845 open_flags |= SQLITE_OPEN_URI;
1846 uri_file_path = base::StrCat({"file:", db_file_path, "?exclusive=true"});
1849 NOTREACHED_NORETURN()
1850 << "exclusive_database_file_lock is only supported on Windows.";
1851 #endif // BUILDFLAG(IS_WIN)
1854 auto sqlite_result_code = ToSqliteResultCode(
1855 sqlite3_open_v2(uri_file_path.c_str(), &db_, open_flags, vfs_name));
1856 if (sqlite_result_code != SqliteResultCode::kOk) {
1857 // sqlite3_open_v2() will usually create a database connection handle, even
1858 // if an error occurs (see https://www.sqlite.org/c3ref/open.html).
1859 // Therefore, we'll clear `db_` immediately - particularly before triggering
1860 // an error callback which may check whether a database connection exists.
1862 // Deallocate resources allocated during the failed open.
1863 // See https://www.sqlite.org/c3ref/close.html.
1868 OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr,
1869 "-- sqlite3_open_v2()");
1870 bool was_poisoned = poisoned_;
1873 if (was_poisoned && mode == OpenMode::kRetryOnPoision)
1874 return OpenInternal(db_file_path, OpenMode::kNone);
1878 ConfigureSqliteDatabaseObject();
1880 // If indicated, enable shared mode ("NORMAL") on the database, so it can be
1881 // opened by multiple processes. This needs to happen before WAL mode is
1884 // TODO(crbug.com/1120969): Remove support for non-exclusive mode.
1886 SQLITE_DEFAULT_LOCKING_MODE == 1,
1887 "Chrome assumes SQLite is configured to default to EXCLUSIVE locking");
1888 if (!options_.exclusive_locking) {
1889 if (!Execute("PRAGMA locking_mode=NORMAL"))
1893 // The sqlite3_open*() methods only perform I/O on the database file if a hot
1894 // journal is found. Force SQLite to parse the header and database schema, so
1895 // we can signal irrecoverable corruption early.
1897 // sqlite3_table_column_metadata() causes SQLite to parse the database schema.
1898 // Since the schema is stored inside a table B-tree, parsing the schema
1899 // implies parsing the database header.
1901 // sqlite3_table_column_metadata() can be used with a null database name, but
1902 // that will cause it to search for the table in all databases that are
1903 // ATTACHed to the connection. While Chrome features (almost) never use
1904 // ATTACHed databases, we prefer to be explicit here.
1906 // sqlite3_table_column_metadata() can be used with a null column name, and
1907 // will report on the existence of the table with the given name. This is
1908 // sufficient for the purpose of getting SQLite to parse the database schema.
1909 // See https://www.sqlite.org/c3ref/table_column_metadata.html for details.
1910 static constexpr char kSqliteSchemaTable[] = "sqlite_schema";
1911 sqlite_result_code = ToSqliteResultCode(sqlite3_table_column_metadata(
1912 db_, kSqliteMainDatabaseName, kSqliteSchemaTable, /*zColumnName=*/nullptr,
1913 /*pzDataType=*/nullptr, /*pzCollSeq=*/nullptr, /*pNotNull=*/nullptr,
1914 /*pPrimaryKey=*/nullptr, /*pAutoinc=*/nullptr));
1915 if (sqlite_result_code != SqliteResultCode::kOk) {
1916 OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr,
1917 "-- sqlite3_table_column_metadata()");
1919 // Retry or bail out if the error handler poisoned the handle.
1920 // TODO(shess): Move this handling to one place (see also sqlite3_open).
1921 // Possibly a wrapper function?
1924 if (mode == OpenMode::kRetryOnPoision)
1925 return OpenInternal(db_file_path, OpenMode::kNone);
1930 const base::TimeDelta kBusyTimeout = base::Seconds(kBusyTimeoutSeconds);
1932 // Needs to happen before entering WAL mode. Will only work if this the first
1933 // time the database is being opened in WAL mode.
1934 const std::string page_size_sql =
1935 base::StringPrintf("PRAGMA page_size=%d", options_.page_size);
1936 std::ignore = ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout);
1938 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1939 // WAL - Use a write-ahead log instead of a journal file.
1940 // DELETE (default) - delete -journal file to commit.
1941 // TRUNCATE - truncate -journal file to commit.
1942 // PERSIST - zero out header of -journal file to commit.
1943 // TRUNCATE should be faster than DELETE because it won't need directory
1944 // changes for each transaction. PERSIST may break the spirit of using
1947 // Needs to be performed after setting exclusive locking mode. Otherwise can
1948 // fail if underlying VFS doesn't support shared memory.
1950 // Set the synchronous flag to NORMAL. This means that writers don't flush
1951 // the WAL file after every write. The WAL file is only flushed on a
1952 // checkpoint. In this case, transcations might lose durability on a power
1953 // loss (but still durable after an application crash).
1954 // TODO(shuagga@microsoft.com): Evaluate if this loss of durability is a
1956 std::ignore = Execute("PRAGMA synchronous=NORMAL");
1958 // Opening the db in WAL mode can fail (eg if the underlying VFS doesn't
1959 // support shared memory and we are not in exclusive locking mode).
1961 // TODO(shuagga@microsoft.com): We should probably catch a failure here.
1962 std::ignore = Execute("PRAGMA journal_mode=WAL");
1964 std::ignore = Execute("PRAGMA journal_mode=TRUNCATE");
1967 if (options_.flush_to_media)
1968 std::ignore = Execute("PRAGMA fullfsync=1");
1970 if (options_.cache_size != 0) {
1971 const std::string cache_size_sql = base::StrCat(
1972 {"PRAGMA cache_size=", base::NumberToString(options_.cache_size)});
1973 std::ignore = ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout);
1976 static_assert(SQLITE_SECURE_DELETE == 1,
1977 "Chrome assumes secure_delete is on by default.");
1979 // When SQLite needs to grow a database file, it uses a configurable
1980 // increment. Larger values reduce filesystem fragmentation and mmap()
1981 // churn, as the database file is grown less often. Smaller values waste
1984 // We currently set different values for small vs large files.
1986 // TODO(crbug.com/1305778): Replace file size-based heuristic with a
1987 // DatabaseOptions member. Use the DatabaseOptions value for temporary
1988 // databases as well.
1989 sqlite3_file* file = GetSqliteVfsFile();
1991 // GetSqliteVfsFile() returns null for in-memory and temporary databases. This
1992 // is fine, because these databases start out empty, so the heuristic below
1993 // would never set a chunk size on them anyway.
1995 sqlite3_int64 db_size = 0;
1996 sqlite_result_code =
1997 ToSqliteResultCode(file->pMethods->xFileSize(file, &db_size));
1998 if (sqlite_result_code == SqliteResultCode::kOk && db_size > 16 * 1024) {
1999 int chunk_size = 4 * 1024;
2000 if (db_size > 128 * 1024)
2001 chunk_size = 32 * 1024;
2003 sqlite3_file_control(db_, /*zDbName=*/nullptr, SQLITE_FCNTL_CHUNK_SIZE,
2008 size_t mmap_size = mmap_disabled_ ? 0 : ComputeMmapSizeForOpen();
2010 // We explicitly issue a "PRGAMA mmap_size=0" to disable memory-mapping. We
2011 // could skip executing the PRAGMA in that case, and use a static_assert to
2012 // ensure that SQLITE_DEFAULT_MMAP_SIZE > 0. We didn't choose this alternative
2013 // because would cost us a bit more logic, and the optimization would apply to
2014 // edge cases, such as in-memory databases. More details at
2015 // https://www.sqlite.org/pragma.html#pragma_mmap_size.
2016 std::string pragma_mmap_size_sql =
2017 base::StrCat({"PRAGMA mmap_size=", base::NumberToString(mmap_size)});
2018 std::ignore = Execute(pragma_mmap_size_sql.c_str());
2020 // Determine if memory-mapping has actually been enabled. The Execute() above
2021 // can succeed without changing the amount mapped.
2022 mmap_enabled_ = false;
2024 Statement pragma_mmap_size(GetUniqueStatement("PRAGMA mmap_size"));
2025 if (pragma_mmap_size.Step() && pragma_mmap_size.ColumnInt64(0) > 0)
2026 mmap_enabled_ = true;
2029 DCHECK(!memory_dump_provider_);
2030 memory_dump_provider_ =
2031 std::make_unique<DatabaseMemoryDumpProvider>(db_, histogram_tag_);
2032 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
2033 memory_dump_provider_.get(), "sql::Database", /*task_runner=*/nullptr);
2038 void Database::ConfigureSqliteDatabaseObject() {
2039 // The use of SQLite's non-standard string quoting is not allowed in Chrome.
2041 // Allowing double-quoted string literals is now considered a misfeature by
2042 // SQLite authors. See https://www.sqlite.org/quirks.html#dblquote
2043 auto sqlite_result_code = ToSqliteResultCode(
2044 sqlite3_db_config(db_, SQLITE_DBCONFIG_DQS_DDL, 0, nullptr));
2045 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2046 << "sqlite3_db_config(SQLITE_DBCONFIG_DQS_DDL) should not fail";
2047 sqlite_result_code = ToSqliteResultCode(
2048 sqlite3_db_config(db_, SQLITE_DBCONFIG_DQS_DML, 0, nullptr));
2049 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2050 << "sqlite3_db_config(SQLITE_DBCONFIG_DQS_DML) should not fail";
2052 sqlite_result_code = ToSqliteResultCode(
2053 sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_FKEY, 0, nullptr));
2054 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2055 << "sqlite3_db_config(SQLITE_DBCONFIG_ENABLE_FKEY) should not fail";
2057 // The use of triggers is discouraged for Chrome code. Thanks to this
2058 // configuration change, triggers are not executed. CREATE TRIGGER and DROP
2059 // TRIGGER still succeed.
2060 sqlite_result_code = ToSqliteResultCode(
2061 sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_TRIGGER, 0, nullptr));
2062 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2063 << "sqlite3_db_config() should not fail";
2065 sqlite_result_code = ToSqliteResultCode(
2066 sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_VIEW,
2067 options_.enable_views_discouraged ? 1 : 0, nullptr));
2068 DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2069 << "sqlite3_db_config() should not fail";
2072 void Database::DoRollback() {
2073 TRACE_EVENT0("sql", "Database::DoRollback");
2075 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
2079 // The cache may have been accumulating dirty pages for commit. Note that in
2080 // some cases sql::Transaction can fire rollback after a database is closed.
2082 ReleaseCacheMemoryIfNeeded(false);
2084 needs_rollback_ = false;
2087 void Database::StatementRefCreated(StatementRef* ref) {
2088 DCHECK(!open_statements_.count(ref))
2089 << __func__ << " already called with this statement";
2090 open_statements_.insert(ref);
2093 void Database::StatementRefDeleted(StatementRef* ref) {
2094 DCHECK(open_statements_.count(ref))
2095 << __func__ << " called with non-existing statement";
2096 open_statements_.erase(ref);
2099 void Database::set_histogram_tag(const std::string& tag) {
2102 histogram_tag_ = tag;
2105 void Database::OnSqliteError(SqliteErrorCode sqlite_error_code,
2106 sql::Statement* statement,
2107 const char* sql_statement) {
2108 TRACE_EVENT0("sql", "Database::OnSqliteError");
2110 DCHECK_NE(statement != nullptr, sql_statement != nullptr)
2111 << __func__ << " should either get a Statement or a raw SQL string";
2113 // Log errors for developers.
2115 // This block is wrapped around a DCHECK_IS_ON() check so we don't waste CPU
2116 // cycles computing the strings that make up the log message in production.
2118 std::string logged_statement;
2120 logged_statement = statement->GetSQLStatement();
2122 logged_statement = sql_statement;
2125 std::string database_id = histogram_tag_;
2126 if (database_id.empty())
2127 database_id = DbPath().BaseName().AsUTF8Unsafe();
2129 // This logging block cannot be a DCHECK, because valid usage of sql::Database
2130 // can still encounter SQLite errors in production. For example, valid SQL
2131 // statements can fail when a database is corrupted.
2133 // This logging block should not use LOG(ERROR) because many features built on
2134 // top of sql::Database can recover from most errors.
2135 DVLOG(1) << "SQLite error! This may indicate a programming error!\n"
2136 << "Database: " << database_id
2137 << " sqlite_error_code: " << sqlite_error_code
2138 << " errno: " << GetLastErrno()
2139 << "\nSQLite error description: " << GetErrorMessage()
2140 << "\nSQL statement: " << logged_statement;
2141 #endif // DCHECK_IS_ON()
2143 // Inform the error expecter that we've encountered the error.
2144 std::ignore = IsExpectedSqliteError(static_cast<int>(sqlite_error_code));
2146 if (!error_callback_.is_null()) {
2147 // Create an additional reference to the state in `error_callback_`, so the
2148 // state doesn't go away if the callback changes `error_callback_` by
2149 // calling set_error_callback() or reset_error_callback(). This avoids a
2150 // subtle source of use-after-frees. See https://crbug.com/254584.
2151 ErrorCallback error_callback_copy = error_callback_;
2152 error_callback_copy.Run(static_cast<int>(sqlite_error_code), statement);
2157 std::string Database::GetDiagnosticInfo(int sqlite_error_code,
2158 Statement* statement,
2159 DatabaseDiagnostics* diagnostics) {
2160 DCHECK_NE(sqlite_error_code, SQLITE_OK)
2161 << __func__ << " received non-error result code";
2162 DCHECK_NE(sqlite_error_code, SQLITE_DONE)
2163 << __func__ << " received non-error result code";
2164 DCHECK_NE(sqlite_error_code, SQLITE_ROW)
2165 << __func__ << " received non-error result code";
2167 // Prevent reentrant calls to the error callback.
2168 ErrorCallback original_callback = std::move(error_callback_);
2169 error_callback_.Reset();
2172 diagnostics->reported_sqlite_error_code = sqlite_error_code;
2175 // Trim extended error codes.
2176 const int primary_error_code = sqlite_error_code & 0xff;
2178 // CollectCorruptionInfo() is implemented in terms of sql::Database,
2179 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
2180 std::string result =
2181 (primary_error_code == SQLITE_CORRUPT)
2182 ? CollectCorruptionInfo()
2183 : CollectErrorInfo(sqlite_error_code, statement, diagnostics);
2185 // The following queries must be executed after CollectErrorInfo() above, so
2186 // if they result in their own errors, they don't interfere with
2187 // CollectErrorInfo().
2188 const bool has_valid_header = Execute("PRAGMA auto_vacuum");
2189 const bool has_valid_schema = Execute("SELECT COUNT(*) FROM sqlite_schema");
2191 // Restore the original error callback.
2192 error_callback_ = std::move(original_callback);
2194 base::StringAppendF(&result, "Has valid header: %s\n",
2195 (has_valid_header ? "Yes" : "No"));
2196 base::StringAppendF(&result, "Has valid schema: %s\n",
2197 (has_valid_schema ? "Yes" : "No"));
2199 diagnostics->has_valid_header = has_valid_header;
2200 diagnostics->has_valid_schema = has_valid_schema;
2206 bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
2207 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
2210 // The PRAGMA below has the side effect of setting SQLITE_RecoveryMode, which
2211 // allows SQLite to process through certain cases of corruption.
2212 if (!Execute("PRAGMA writable_schema=ON")) {
2213 // The "PRAGMA integrity_check" statement executed below may return less
2214 // useful information. However, incomplete information is still better than
2215 // nothing, so we press on.
2216 messages->push_back("PRAGMA writable_schema=ON failed");
2219 // We need to bypass sql::Statement and use raw SQLite C API calls here.
2221 // "PRAGMA integrity_check" reports SQLITE_CORRUPT when the database is
2222 // corrupt. Reporting SQLITE_CORRUPT is undesirable in this case, because it
2223 // causes our sql::Statement infrastructure to call the database error
2224 // handler, which triggers feature-level error handling. However,
2225 // FullIntegrityCheck() callers presumably already know that the database is
2226 // corrupted, and are trying to collect diagnostic information for reporting.
2227 sqlite3_stmt* statement = nullptr;
2229 // https://www.sqlite.org/c3ref/prepare.html states that SQLite will perform
2230 // slightly better if sqlite_prepare_v3() receives a zero-terminated statement
2231 // string, and a statement size that includes the zero byte. Fortunately,
2232 // C++'s string literal and sizeof() operator do exactly that.
2233 constexpr char kIntegrityCheckSql[] = "PRAGMA integrity_check";
2234 const auto prepare_result_code = ToSqliteResultCode(
2235 sqlite3_prepare_v3(db_, kIntegrityCheckSql, sizeof(kIntegrityCheckSql),
2236 SqlitePrepareFlags(), &statement, /*pzTail=*/nullptr));
2237 if (prepare_result_code != SqliteResultCode::kOk)
2240 // "PRAGMA integrity_check" currently returns multiple lines as a single row.
2242 // However, since https://www.sqlite.org/pragma.html#pragma_integrity_check
2243 // states that multiple records may be returned, the code below can handle
2244 // multiple records, each of which has multiple lines.
2245 std::vector<std::string> result_lines;
2247 while (ToSqliteResultCode(sqlite3_step(statement)) ==
2248 SqliteResultCode::kRow) {
2249 const uint8_t* row = chrome_sqlite3_column_text(statement, /*iCol=*/0);
2250 DCHECK(row) << "PRAGMA integrity_check should never return NULL rows";
2252 const int row_size = sqlite3_column_bytes(statement, /*iCol=*/0);
2253 base::StringPiece row_string(reinterpret_cast<const char*>(row), row_size);
2255 const std::vector<base::StringPiece> row_lines = base::SplitStringPiece(
2256 row_string, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
2257 for (base::StringPiece row_line : row_lines)
2258 result_lines.emplace_back(row_line);
2261 const auto finalize_result_code =
2262 ToSqliteResultCode(sqlite3_finalize(statement));
2263 // sqlite3_finalize() may return SQLITE_CORRUPT when the integrity check
2264 // discovers any problems. We still consider this case a success, as long as
2265 // the statement produced at least one diagnostic message.
2266 const bool success = (result_lines.size() > 0) ||
2267 (finalize_result_code == SqliteResultCode::kOk);
2268 *messages = std::move(result_lines);
2270 // Best-effort attempt to undo the "PRAGMA writable_schema=ON" executed above.
2271 std::ignore = Execute("PRAGMA writable_schema=OFF");
2276 bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
2277 const std::string& dump_name) {
2278 return memory_dump_provider_ &&
2279 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
2282 bool Database::UseWALMode() const {
2283 #if BUILDFLAG(IS_FUCHSIA)
2284 // WAL mode is only enabled on Fuchsia for databases with exclusive
2285 // locking, because this case does not require shared memory support.
2286 // At the time this was implemented (May 2020), Fuchsia's shared
2287 // memory support was insufficient for SQLite's needs.
2288 return options_.wal_mode && options_.exclusive_locking;
2290 return options_.wal_mode;
2291 #endif // BUILDFLAG(IS_FUCHSIA)
2294 bool Database::CheckpointDatabase() {
2295 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
2296 absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
2297 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
2299 auto sqlite_result_code = ToSqliteResultCode(sqlite3_wal_checkpoint_v2(
2300 db_, kSqliteMainDatabaseName, SQLITE_CHECKPOINT_PASSIVE,
2301 /*pnLog=*/nullptr, /*pnCkpt=*/nullptr));
2303 return sqlite_result_code == SqliteResultCode::kOk;