Use upstream clang 14 for desktop
[platform/framework/web/chromium-efl.git] / sql / database.cc
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.
4
5 #include "sql/database.h"
6
7 #include <limits.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <string.h>
11
12 #include <algorithm>
13 #include <memory>
14 #include <tuple>
15
16 #include "base/check.h"
17 #include "base/dcheck_is_on.h"
18 #include "base/feature_list.h"
19 #include "base/files/file_path.h"
20 #include "base/files/file_util.h"
21 #include "base/format_macros.h"
22 #include "base/location.h"
23 #include "base/logging.h"
24 #include "base/memory/raw_ptr.h"
25 #include "base/no_destructor.h"
26 #include "base/notreached.h"
27 #include "base/numerics/safe_conversions.h"
28 #include "base/ranges/algorithm.h"
29 #include "base/sequence_checker.h"
30 #include "base/strings/strcat.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_piece.h"
33 #include "base/strings/string_split.h"
34 #include "base/strings/string_util.h"
35 #include "base/strings/stringprintf.h"
36 #include "base/strings/utf_string_conversions.h"
37 #include "base/synchronization/lock.h"
38 #include "base/task/single_thread_task_runner.h"
39 #include "base/threading/scoped_blocking_call.h"
40 #include "base/trace_event/memory_dump_manager.h"
41 #include "base/trace_event/trace_event.h"
42 #include "base/tracing/protos/chrome_track_event.pbzero.h"
43 #include "base/types/pass_key.h"
44 #include "build/build_config.h"
45 #include "sql/database_memory_dump_provider.h"
46 #include "sql/initialization.h"
47 #include "sql/meta_table.h"
48 #include "sql/sql_features.h"
49 #include "sql/sqlite_result_code.h"
50 #include "sql/sqlite_result_code_values.h"
51 #include "sql/statement.h"
52 #include "sql/vfs_wrapper.h"
53 #include "third_party/sqlite/sqlite3.h"
54
55 namespace sql {
56
57 namespace {
58
59 bool enable_mmap_by_default_ = true;
60
61 // The name of the main database associated with a sqlite3* connection.
62 //
63 // SQLite has the ability to ATTACH multiple databases to the same connection.
64 // As a consequence, some SQLite APIs require the connection-specific database
65 // name. This is the right name to be passed to such APIs.
66 static constexpr char kSqliteMainDatabaseName[] = "main";
67
68 // Magic path value telling sqlite3_open_v2() to open an in-memory database.
69 static constexpr char kSqliteOpenInMemoryPath[] = ":memory:";
70
71 // Spin for up to a second waiting for the lock to clear when setting
72 // up the database.
73 // TODO(shess): Better story on this.  http://crbug.com/56559
74 const int kBusyTimeoutSeconds = 1;
75
76 class ScopedBusyTimeout {
77  public:
78   explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
79   ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
80
81   int SetTimeout(base::TimeDelta timeout) {
82     DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
83     return sqlite3_busy_timeout(db_,
84                                 static_cast<int>(timeout.InMilliseconds()));
85   }
86
87  private:
88   raw_ptr<sqlite3> db_;
89 };
90
91 // Helper to "safely" enable writable_schema.  No error checking
92 // because it is reasonable to just forge ahead in case of an error.
93 // If turning it on fails, then most likely nothing will work, whereas
94 // if turning it off fails, it only matters if some code attempts to
95 // continue working with the database and tries to modify the
96 // sqlite_schema table (none of our code does this).
97 class ScopedWritableSchema {
98  public:
99   explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
100     sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
101   }
102   ~ScopedWritableSchema() {
103     sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
104   }
105
106  private:
107   raw_ptr<sqlite3> db_;
108 };
109
110 // Raze() helper that uses SQLite's online backup API.
111 //
112 // Returns the SQLite error code produced by sqlite3_backup_step(). SQLITE_DONE
113 // signals success. SQLITE_OK will never be returned.
114 //
115 // The implementation is tailored for the Raze() use case. In particular, the
116 // SQLite API use and and error handling is optimized for 1-page databases.
117 SqliteResultCode BackupDatabaseForRaze(sqlite3* source_db,
118                                        sqlite3* destination_db) {
119   DCHECK(source_db);
120   DCHECK(destination_db);
121   DCHECK_NE(source_db, destination_db);
122
123   // https://www.sqlite.org/backup.html has a high-level overview of SQLite's
124   // backup support. https://www.sqlite.org/c3ref/backup_finish.html describes
125   // the API.
126   static constexpr char kMainDatabaseName[] = "main";
127   sqlite3_backup* backup = sqlite3_backup_init(
128       destination_db, kMainDatabaseName, source_db, kMainDatabaseName);
129   if (!backup) {
130     // sqlite3_backup_init() fails if a transaction is ongoing. In particular,
131     // SQL statements that return multiple rows keep a read transaction open
132     // until all the Step() calls are executed.
133     return ToSqliteResultCode(chrome_sqlite3_extended_errcode(destination_db));
134   }
135
136   constexpr int kUnlimitedPageCount = -1;  // Back up entire database.
137   auto sqlite_result_code =
138       ToSqliteResultCode(sqlite3_backup_step(backup, kUnlimitedPageCount));
139   DCHECK_NE(sqlite_result_code, SqliteResultCode::kOk)
140       << "sqlite3_backup_step() returned SQLITE_OK (instead of SQLITE_DONE) "
141       << "when asked to back up the entire database";
142
143 #if DCHECK_IS_ON()
144   if (sqlite_result_code == SqliteResultCode::kDone) {
145     // If successful, exactly one page should have been backed up.
146     DCHECK_EQ(sqlite3_backup_pagecount(backup), 1)
147         << __func__ << " was intended to be used with 1-page databases";
148   }
149 #endif  // DCHECK_IS_ON()
150
151   // sqlite3_backup_finish() releases the sqlite3_backup object.
152   //
153   // It returns an error code only if the backup encountered a permanent error.
154   // We use the the sqlite3_backup_step() result instead, because it also tells
155   // us about temporary errors, like SQLITE_BUSY.
156   //
157   // We pass the sqlite3_backup_finish() result code through
158   // ToSqliteResultCode() to catch codes that should never occur, like
159   // SQLITE_MISUSE.
160   std::ignore = ToSqliteResultCode(sqlite3_backup_finish(backup));
161
162   return sqlite_result_code;
163 }
164
165 bool ValidAttachmentPoint(base::StringPiece attachment_point) {
166   // SQLite could handle a much wider character set, with appropriate quoting.
167   //
168   // Chrome's constraint is easy to remember, and sufficient for the few
169   // existing use cases. ATTACH is a discouraged feature, so no new use cases
170   // are expected.
171   return base::ranges::all_of(attachment_point,
172                               [](char ch) { return base::IsAsciiLower(ch); });
173 }
174
175 std::string AsUTF8ForSQL(const base::FilePath& path) {
176 #if BUILDFLAG(IS_WIN)
177   return base::WideToUTF8(path.value());
178 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
179   return path.value();
180 #endif
181 }
182
183 }  // namespace
184
185 // static
186 Database::ScopedErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
187
188 // static
189 bool Database::IsExpectedSqliteError(int sqlite_error_code) {
190   DCHECK_NE(sqlite_error_code, SQLITE_OK)
191       << __func__ << " received non-error result code";
192   DCHECK_NE(sqlite_error_code, SQLITE_DONE)
193       << __func__ << " received non-error result code";
194   DCHECK_NE(sqlite_error_code, SQLITE_ROW)
195       << __func__ << " received non-error result code";
196
197   if (!current_expecter_cb_)
198     return false;
199   return current_expecter_cb_->Run(sqlite_error_code);
200 }
201
202 // static
203 void Database::SetScopedErrorExpecter(
204     Database::ScopedErrorExpecterCallback* cb,
205     base::PassKey<test::ScopedErrorExpecter>) {
206   CHECK(!current_expecter_cb_);
207   current_expecter_cb_ = cb;
208 }
209
210 // static
211 void Database::ResetScopedErrorExpecter(
212     base::PassKey<test::ScopedErrorExpecter>) {
213   CHECK(current_expecter_cb_);
214   current_expecter_cb_ = nullptr;
215 }
216
217 // static
218 base::FilePath Database::JournalPath(const base::FilePath& db_path) {
219   return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
220 }
221
222 // static
223 base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
224   return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
225 }
226
227 // static
228 base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
229   return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
230 }
231
232 Database::StatementRef::StatementRef(Database* database,
233                                      sqlite3_stmt* stmt,
234                                      bool was_valid)
235     : database_(database), stmt_(stmt), was_valid_(was_valid) {
236   DCHECK_EQ(database == nullptr, stmt == nullptr);
237   if (database)
238     database_->StatementRefCreated(this);
239 }
240
241 Database::StatementRef::~StatementRef() {
242   if (database_)
243     database_->StatementRefDeleted(this);
244   Close(false);
245 }
246
247 void Database::StatementRef::Close(bool forced) {
248   if (stmt_) {
249     // Call to InitScopedBlockingCall() cannot go at the beginning of the
250     // function because Close() is called unconditionally from destructor to
251     // clean database_. And if this is inactive statement this won't cause any
252     // disk access and destructor most probably will be called on thread not
253     // allowing disk access.
254     // TODO(paivanof@gmail.com): This should move to the beginning
255     // of the function. http://crbug.com/136655.
256     absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
257     InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
258
259     // `stmt_` references memory loaned from the sqlite3 library. Stop
260     // referencing it from the raw_ptr<> before returning it. This avoids the
261     // raw_ptr<> becoming dangling.
262     sqlite3_stmt* statement = stmt_;
263     stmt_ = nullptr;
264
265     // sqlite3_finalize()'s result code is ignored because it reports the same
266     // error as the most recent sqlite3_step(). The result code is passed
267     // through ToSqliteResultCode() to catch issues like SQLITE_MISUSE.
268     std::ignore = ToSqliteResultCode(sqlite3_finalize(statement));
269   }
270   database_ = nullptr;  // The Database may be getting deleted.
271
272   // Forced close is expected to happen from a statement error
273   // handler.  In that case maintain the sense of |was_valid_| which
274   // previously held for this ref.
275   was_valid_ = was_valid_ && forced;
276 }
277
278 static_assert(DatabaseOptions::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
279               "DatabaseOptions::kDefaultPageSize must match the value "
280               "configured into SQLite");
281
282 DatabaseDiagnostics::DatabaseDiagnostics() = default;
283 DatabaseDiagnostics::~DatabaseDiagnostics() = default;
284
285 void DatabaseDiagnostics::WriteIntoTrace(
286     perfetto::TracedProto<TraceProto> context) const {
287   context->set_reported_sqlite_error_code(reported_sqlite_error_code);
288   context->set_error_code(error_code);
289   context->set_last_errno(last_errno);
290   context->set_sql_statement(sql_statement);
291   context->set_version(version);
292   for (const auto& sql : schema_sql_rows) {
293     context->add_schema_sql_rows(sql);
294   }
295   for (const auto& name : schema_other_row_names) {
296     context->add_schema_other_row_names(name);
297   }
298   context->set_has_valid_header(has_valid_header);
299   context->set_has_valid_schema(has_valid_schema);
300   context->set_error_message(error_message);
301 }
302
303 // DatabaseOptions::explicit_locking needs to be set to false for historical
304 // reasons.
305 Database::Database() : Database({.exclusive_locking = false}) {}
306
307 Database::Database(DatabaseOptions options)
308     : options_(options), mmap_disabled_(!enable_mmap_by_default_) {
309   DCHECK_GE(options.page_size, 512);
310   DCHECK_LE(options.page_size, 65536);
311   DCHECK(!(options.page_size & (options.page_size - 1)))
312       << "page_size must be a power of two";
313   DCHECK(!options_.mmap_alt_status_discouraged ||
314          options_.enable_views_discouraged)
315       << "mmap_alt_status requires views";
316
317   // It's valid to construct a database on a sequence and then pass it to a
318   // different sequence before usage.
319   DETACH_FROM_SEQUENCE(sequence_checker_);
320 }
321
322 Database::~Database() {
323   Close();
324 }
325
326 // static
327 void Database::DisableMmapByDefault() {
328   enable_mmap_by_default_ = false;
329 }
330
331 bool Database::Open(const base::FilePath& path) {
332   std::string path_string = AsUTF8ForSQL(path);
333   TRACE_EVENT1("sql", "Database::Open", "path", path_string);
334
335   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
336   DCHECK(!path.empty());
337   DCHECK_NE(path_string, kSqliteOpenInMemoryPath)
338       << "Path conflicts with SQLite magic identifier";
339
340   return OpenInternal(path_string, OpenMode::kRetryOnPoision);
341 }
342
343 bool Database::OpenInMemory() {
344   TRACE_EVENT0("sql", "Database::OpenInMemory");
345
346   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
347
348   in_memory_ = true;
349   return OpenInternal(kSqliteOpenInMemoryPath, OpenMode::kInMemory);
350 }
351
352 bool Database::OpenTemporary(base::PassKey<Recovery>) {
353   TRACE_EVENT0("sql", "Database::OpenTemporary");
354
355   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
356   return OpenInternal(std::string(), OpenMode::kTemporary);
357 }
358
359 void Database::CloseInternal(bool forced) {
360   TRACE_EVENT0("sql", "Database::CloseInternal");
361   // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
362   // will delete the -journal file.  For ChromiumOS or other more
363   // embedded systems, this is probably not appropriate, whereas on
364   // desktop it might make some sense.
365
366   // sqlite3_close() needs all prepared statements to be finalized.
367
368   // Release cached statements.
369   statement_cache_.clear();
370
371   // With cached statements released, in-use statements will remain.
372   // Closing the database while statements are in use is an API
373   // violation, except for forced close (which happens from within a
374   // statement's error handler).
375   DCHECK(forced || open_statements_.empty());
376
377   // Deactivate any outstanding statements so sqlite3_close() works.
378   for (StatementRef* statement_ref : open_statements_)
379     statement_ref->Close(forced);
380   open_statements_.clear();
381
382   if (db_) {
383     // Call to InitScopedBlockingCall() cannot go at the beginning of the
384     // function because Close() must be called from destructor to clean
385     // statement_cache_, it won't cause any disk access and it most probably
386     // will happen on thread not allowing disk access.
387     // TODO(paivanof@gmail.com): This should move to the beginning
388     // of the function. http://crbug.com/136655.
389     absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
390     InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
391
392     // Resetting acquires a lock to ensure no dump is happening on the database
393     // at the same time. Unregister takes ownership of provider and it is safe
394     // since the db is reset. memory_dump_provider_ could be null if db_ was
395     // poisoned.
396     if (memory_dump_provider_) {
397       memory_dump_provider_->ResetDatabase();
398       base::trace_event::MemoryDumpManager::GetInstance()
399           ->UnregisterAndDeleteDumpProviderSoon(
400               std::move(memory_dump_provider_));
401     }
402
403     auto sqlite_result_code = ToSqliteResultCode(sqlite3_close(db_));
404
405     DCHECK_NE(sqlite_result_code, SqliteResultCode::kBusy)
406         << "sqlite3_close() called while prepared statements are still alive";
407     DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
408         << "sqlite3_close() failed in an unexpected way: " << GetErrorMessage();
409
410     // The reset must happen after the DCHECKs above. GetErrorMessage() needs a
411     // valid `db_` value.
412     db_ = nullptr;
413   }
414 }
415
416 void Database::Close() {
417   TRACE_EVENT0("sql", "Database::Close");
418   // If the database was already closed by RazeAndClose(), then no
419   // need to close again.  Clear the |poisoned_| bit so that incorrect
420   // API calls are caught.
421   if (poisoned_) {
422     poisoned_ = false;
423     return;
424   }
425
426   CloseInternal(false);
427 }
428
429 void Database::Preload() {
430   TRACE_EVENT0("sql", "Database::Preload");
431
432   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
433   if (!db_) {
434     DCHECK(poisoned_) << "Cannot preload null db";
435     return;
436   }
437
438   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
439   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
440
441   // Maximum number of bytes that will be prefetched from the database.
442   //
443   // This limit is very aggressive. The main trade-off involved is that having
444   // SQLite block on reading from disk has a high impact on Chrome startup cost
445   // for the databases that are on the critical path to startup. So, the limit
446   // must exceed the expected sizes of databases on the critical path.
447   //
448   // On Windows 7, base::PreReadFile() falls back to a synchronous read, and
449   // blocks until the entire file is read into memory. This is a minor factor at
450   // this point, because Chrome has very limited support for Windows 7.
451   constexpr int kPreReadSize = 128 * 1024 * 1024;  // 128 MB
452   base::PreReadFile(DbPath(), /*is_executable=*/false, kPreReadSize);
453 }
454
455 // SQLite keeps unused pages associated with a database in a cache.  It asks
456 // the cache for pages by an id, and if the page is present and the database is
457 // unchanged, it considers the content of the page valid and doesn't read it
458 // from disk.  When memory-mapped I/O is enabled, on read SQLite uses page
459 // structures created from the memory map data before consulting the cache.  On
460 // write SQLite creates a new in-memory page structure, copies the data from the
461 // memory map, and later writes it, releasing the updated page back to the
462 // cache.
463 //
464 // This means that in memory-mapped mode, the contents of the cached pages are
465 // not re-used for reads, but they are re-used for writes if the re-written page
466 // is still in the cache. The implementation of sqlite3_db_release_memory() as
467 // of SQLite 3.8.7.4 frees all pages from pcaches associated with the
468 // database, so it should free these pages.
469 //
470 // Unfortunately, the zero page is also freed.  That page is never accessed
471 // using memory-mapped I/O, and the cached copy can be re-used after verifying
472 // the file change counter on disk.  Also, fresh pages from cache receive some
473 // pager-level initialization before they can be used.  Since the information
474 // involved will immediately be accessed in various ways, it is unclear if the
475 // additional overhead is material, or just moving processor cache effects
476 // around.
477 //
478 // TODO(shess): It would be better to release the pages immediately when they
479 // are no longer needed.  This would basically happen after SQLite commits a
480 // transaction.  I had implemented a pcache wrapper to do this, but it involved
481 // layering violations, and it had to be setup before any other sqlite call,
482 // which was brittle.  Also, for large files it would actually make sense to
483 // maintain the existing pcache behavior for blocks past the memory-mapped
484 // segment.  I think drh would accept a reasonable implementation of the overall
485 // concept for upstreaming to SQLite core.
486 //
487 // TODO(shess): Another possibility would be to set the cache size small, which
488 // would keep the zero page around, plus some pre-initialized pages, and SQLite
489 // can manage things.  The downside is that updates larger than the cache would
490 // spill to the journal.  That could be compensated by setting cache_spill to
491 // false.  The downside then is that it allows open-ended use of memory for
492 // large transactions.
493 void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
494   TRACE_EVENT0("sql", "Database::ReleaseCacheMemoryIfNeeded");
495   // The database could have been closed during a transaction as part of error
496   // recovery.
497   if (!db_) {
498     DCHECK(poisoned_) << "Illegal use of Database without a db";
499     return;
500   }
501
502   // If memory-mapping is not enabled, the page cache helps performance.
503   if (!mmap_enabled_)
504     return;
505
506   // On caller request, force the change comparison to fail.  Done before the
507   // transaction-nesting test so that the signal can carry to transaction
508   // commit.
509   if (implicit_change_performed)
510     --total_changes_at_last_release_;
511
512   // Cached pages may be re-used within the same transaction.
513   DCHECK_GE(transaction_nesting_, 0);
514   if (transaction_nesting_)
515     return;
516
517   // If no changes have been made, skip flushing.  This allows the first page of
518   // the database to remain in cache across multiple reads.
519   const int64_t total_changes = sqlite3_total_changes64(db_);
520   if (total_changes == total_changes_at_last_release_)
521     return;
522
523   total_changes_at_last_release_ = total_changes;
524
525   // Passing the result code through ToSqliteResultCode() to catch issues such
526   // as SQLITE_MISUSE.
527   std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
528 }
529
530 base::FilePath Database::DbPath() const {
531   if (!is_open())
532     return base::FilePath();
533
534   const char* path = sqlite3_db_filename(db_, "main");
535   if (!path)
536     return base::FilePath();
537   const base::StringPiece db_path(path);
538 #if BUILDFLAG(IS_WIN)
539   return base::FilePath(base::UTF8ToWide(db_path));
540 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
541   return base::FilePath(db_path);
542 #else
543   NOTREACHED();
544   return base::FilePath();
545 #endif
546 }
547
548 std::string Database::CollectErrorInfo(int sqlite_error_code,
549                                        Statement* stmt,
550                                        DatabaseDiagnostics* diagnostics) const {
551   TRACE_EVENT0("sql", "Database::CollectErrorInfo");
552
553   DCHECK_NE(sqlite_error_code, SQLITE_OK)
554       << __func__ << " received non-error result code";
555   DCHECK_NE(sqlite_error_code, SQLITE_DONE)
556       << __func__ << " received non-error result code";
557   DCHECK_NE(sqlite_error_code, SQLITE_ROW)
558       << __func__ << " received non-error result code";
559
560   // Buffer for accumulating debugging info about the error.  Place
561   // more-relevant information earlier, in case things overflow the
562   // fixed-size reporting buffer.
563   std::string debug_info;
564
565   // The error message from the failed operation.
566   int error_code = GetErrorCode();
567   base::StringAppendF(&debug_info, "db error: %d/%s\n", error_code,
568                       GetErrorMessage());
569   if (diagnostics) {
570     diagnostics->error_code = error_code;
571     diagnostics->error_message = GetErrorMessage();
572   }
573
574   // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
575   // reading code does not entirely convince me.  Remove if they turn out to be
576   // the same.
577   if (sqlite_error_code != GetErrorCode())
578     base::StringAppendF(&debug_info, "reported error: %d\n", sqlite_error_code);
579
580 // System error information.  Interpretation of Windows errors is different
581 // from posix.
582 #if BUILDFLAG(IS_WIN)
583   int last_errno = GetLastErrno();
584   base::StringAppendF(&debug_info, "LastError: %d\n", last_errno);
585   if (diagnostics) {
586     diagnostics->last_errno = last_errno;
587   }
588 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
589   int last_errno = GetLastErrno();
590   base::StringAppendF(&debug_info, "errno: %d\n", last_errno);
591   if (diagnostics) {
592     diagnostics->last_errno = last_errno;
593   }
594 #else
595   NOTREACHED();  // Add appropriate log info.
596 #endif
597
598   if (stmt) {
599     std::string sql_string = stmt->GetSQLStatement();
600     base::StringAppendF(&debug_info, "statement: %s\n", sql_string.c_str());
601     if (diagnostics) {
602       diagnostics->sql_statement = sql_string;
603     }
604   } else {
605     base::StringAppendF(&debug_info, "statement: NULL\n");
606   }
607
608   // SQLITE_ERROR often indicates some sort of mismatch between the statement
609   // and the schema, possibly due to a failed schema migration.
610   if (sqlite_error_code == SQLITE_ERROR) {
611     static constexpr char kVersionSql[] =
612         "SELECT value FROM meta WHERE key='version'";
613     sqlite3_stmt* sqlite_statement;
614     // When the number of bytes passed to sqlite3_prepare_v3() includes the null
615     // terminator, SQLite avoids a buffer copy.
616     int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql),
617                                 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
618                                 /* pzTail= */ nullptr);
619     if (rc == SQLITE_OK) {
620       rc = sqlite3_step(sqlite_statement);
621       if (rc == SQLITE_ROW) {
622         int version = sqlite3_column_int(sqlite_statement, 0);
623         base::StringAppendF(&debug_info, "version: %d\n", version);
624         if (diagnostics) {
625           diagnostics->version = version;
626         }
627       } else if (rc == SQLITE_DONE) {
628         debug_info += "version: none\n";
629       } else {
630         base::StringAppendF(&debug_info, "version: error %d\n", rc);
631       }
632       sqlite3_finalize(sqlite_statement);
633     } else {
634       base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
635     }
636
637     // Get all the SQL from sqlite_schema.
638     debug_info += "schema:\n";
639     static constexpr char kSchemaSql[] =
640         "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY ROWID";
641     rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql),
642                             SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
643                             /* pzTail= */ nullptr);
644     if (rc == SQLITE_OK) {
645       while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
646         std::string text;
647         base::StringAppendF(&text, "%s",
648                             sqlite3_column_text(sqlite_statement, 0));
649         debug_info += text + "\n";
650         if (diagnostics) {
651           diagnostics->schema_sql_rows.push_back(text);
652         }
653       }
654
655       if (rc != SQLITE_DONE)
656         base::StringAppendF(&debug_info, "error %d\n", rc);
657       sqlite3_finalize(sqlite_statement);
658     } else {
659       base::StringAppendF(&debug_info, "prepare error %d\n", rc);
660     }
661
662     // Automatically generated indices have a NULL 'sql' column. For those rows,
663     // we log the name column instead.
664     debug_info += "schema rows with only name:\n";
665     static constexpr char kSchemaOtherRowNamesSql[] =
666         "SELECT name FROM sqlite_schema WHERE sql IS NULL ORDER BY ROWID";
667     rc = sqlite3_prepare_v3(db_, kSchemaOtherRowNamesSql,
668                             sizeof(kSchemaOtherRowNamesSql),
669                             SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
670                             /* pzTail= */ nullptr);
671     if (rc == SQLITE_OK) {
672       while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
673         std::string text;
674         base::StringAppendF(&text, "%s",
675                             sqlite3_column_text(sqlite_statement, 0));
676         debug_info += text + "\n";
677         if (diagnostics) {
678           diagnostics->schema_other_row_names.push_back(text);
679         }
680       }
681
682       if (rc != SQLITE_DONE)
683         base::StringAppendF(&debug_info, "error %d\n", rc);
684       sqlite3_finalize(sqlite_statement);
685     } else {
686       base::StringAppendF(&debug_info, "prepare error %d\n", rc);
687     }
688   }
689
690   return debug_info;
691 }
692
693 // TODO(shess): Since this is only called in an error situation, it might be
694 // prudent to rewrite in terms of SQLite API calls, and mark the function const.
695 std::string Database::CollectCorruptionInfo() {
696   TRACE_EVENT0("sql", "Database::CollectCorruptionInfo");
697   // If the file cannot be accessed it is unlikely that an integrity check will
698   // turn up actionable information.
699   const base::FilePath db_path = DbPath();
700   int64_t db_size = -1;
701   if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
702     return std::string();
703
704   // Buffer for accumulating debugging info about the error.  Place
705   // more-relevant information earlier, in case things overflow the
706   // fixed-size reporting buffer.
707   std::string debug_info;
708   base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
709                       db_size);
710
711   // Only check files up to 8M to keep things from blocking too long.
712   const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
713   if (db_size > kMaxIntegrityCheckSize) {
714     debug_info += "integrity_check skipped due to size\n";
715   } else {
716     std::vector<std::string> messages;
717
718     // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
719     // into a string.  Probably should be refactored.
720     const base::TimeTicks before = base::TimeTicks::Now();
721     FullIntegrityCheck(&messages);
722     base::StringAppendF(
723         &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
724         (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
725
726     // SQLite returns up to 100 messages by default, trim deeper to
727     // keep close to the 2000-character size limit for dumping.
728     const size_t kMaxMessages = 20;
729     for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
730       base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
731     }
732   }
733
734   return debug_info;
735 }
736
737 bool Database::GetMmapAltStatus(int64_t* status) {
738   TRACE_EVENT0("sql", "Database::GetMmapAltStatus");
739
740   // The [meta] version uses a missing table as a signal for a fresh database.
741   // That will not work for the view, which would not exist in either a new or
742   // an existing database.  A new database _should_ be only one page long, so
743   // just don't bother optimizing this case (start at offset 0).
744   // TODO(shess): Could the [meta] case also get simpler, then?
745   if (!DoesViewExist("MmapStatus")) {
746     *status = 0;
747     return true;
748   }
749
750   const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
751   Statement s(GetUniqueStatement(kMmapStatusSql));
752   if (s.Step())
753     *status = s.ColumnInt64(0);
754   return s.Succeeded();
755 }
756
757 bool Database::SetMmapAltStatus(int64_t status) {
758   if (!BeginTransaction())
759     return false;
760
761   // View may not exist on first run.
762   if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
763     RollbackTransaction();
764     return false;
765   }
766
767   // Views live in the schema, so they cannot be parameterized.  For an integer
768   // value, this construct should be safe from SQL injection, if the value
769   // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
770   // value.
771   const std::string create_view_sql = base::StringPrintf(
772       "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
773   if (!Execute(create_view_sql.c_str())) {
774     RollbackTransaction();
775     return false;
776   }
777
778   return CommitTransaction();
779 }
780
781 size_t Database::ComputeMmapSizeForOpen() {
782   TRACE_EVENT0("sql", "Database::ComputeMmapSizeForOpen");
783
784   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
785   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
786
787   // How much to map if no errors are found.  50MB encompasses the 99th
788   // percentile of Chrome databases in the wild, so this should be good.
789   const size_t kMmapEverything = 256 * 1024 * 1024;
790
791   // Progress information is tracked in the [meta] table for databases which use
792   // sql::MetaTable, otherwise it is tracked in a special view.
793   // TODO(pwnall): Migrate all databases to using a meta table.
794   int64_t mmap_ofs = 0;
795   if (options_.mmap_alt_status_discouraged) {
796     if (!GetMmapAltStatus(&mmap_ofs))
797       return 0;
798   } else {
799     // If [meta] doesn't exist, yet, it's a new database, assume the best.
800     // sql::MetaTable::Init() will preload kMmapSuccess.
801     if (!MetaTable::DoesTableExist(this))
802       return kMmapEverything;
803
804     if (!MetaTable::GetMmapStatus(this, &mmap_ofs))
805       return 0;
806   }
807
808   // Database read failed in the past, don't memory map.
809   if (mmap_ofs == MetaTable::kMmapFailure)
810     return 0;
811
812   if (mmap_ofs != MetaTable::kMmapSuccess) {
813     // Continue reading from previous offset.
814     DCHECK_GE(mmap_ofs, 0);
815
816     // GetSqliteVfsFile() returns null for in-memory and temporary databases.
817     // This is fine, we don't want to enable memory-mapping in those cases
818     // anyway.
819     //
820     // First, memory-mapping is a no-op for in-memory databases.
821     //
822     // Second, temporary databases are only used for corruption recovery, which
823     // occurs in response to I/O errors. An environment with heightened I/O
824     // errors translates into a higher risk of mmap-induced Chrome crashes.
825     sqlite3_int64 db_size = 0;
826     sqlite3_file* file = GetSqliteVfsFile();
827     if (!file || file->pMethods->xFileSize(file, &db_size) != SQLITE_OK)
828       return 0;
829
830     // Read more of the database looking for errors.  The VFS interface is used
831     // to assure that the reads are valid for SQLite.  |g_reads_allowed| is used
832     // to limit checking to 20MB per run of Chromium.
833     //
834     // Read the data left, or |g_reads_allowed|, whichever is smaller.
835     // |g_reads_allowed| limits the total amount of I/O to spend verifying data
836     // in a single Chromium run.
837     sqlite3_int64 amount = db_size - mmap_ofs;
838     if (amount < 0)
839       amount = 0;
840     if (amount > 0) {
841       static base::NoDestructor<base::Lock> lock;
842       base::AutoLock auto_lock(*lock);
843       static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
844       if (g_reads_allowed < amount)
845         amount = g_reads_allowed;
846       g_reads_allowed -= amount;
847     }
848
849     // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
850     // database was truncated after a previous pass.
851     if (amount <= 0 && mmap_ofs < db_size) {
852       DCHECK_EQ(0, amount);
853     } else {
854       static const int kPageSize = 4096;
855       char buf[kPageSize];
856       while (amount > 0) {
857         int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
858         if (rc == SQLITE_OK) {
859           mmap_ofs += sizeof(buf);
860           amount -= sizeof(buf);
861         } else if (rc == SQLITE_IOERR_SHORT_READ) {
862           // Reached EOF for a database with page size < |kPageSize|.
863           mmap_ofs = db_size;
864           break;
865         } else {
866           // TODO(shess): Consider calling OnSqliteError().
867           mmap_ofs = MetaTable::kMmapFailure;
868           break;
869         }
870       }
871
872       // Log these events after update to distinguish meta update failure.
873       if (mmap_ofs >= db_size) {
874         mmap_ofs = MetaTable::kMmapSuccess;
875       } else {
876         DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure);
877       }
878
879       if (options_.mmap_alt_status_discouraged) {
880         if (!SetMmapAltStatus(mmap_ofs))
881           return 0;
882       } else {
883         if (!MetaTable::SetMmapStatus(this, mmap_ofs))
884           return 0;
885       }
886     }
887   }
888
889   if (mmap_ofs == MetaTable::kMmapFailure)
890     return 0;
891   if (mmap_ofs == MetaTable::kMmapSuccess)
892     return kMmapEverything;
893   return mmap_ofs;
894 }
895
896 int Database::SqlitePrepareFlags() const {
897   return options_.enable_virtual_tables_discouraged ? 0
898                                                     : SQLITE_PREPARE_NO_VTAB;
899 }
900
901 sqlite3_file* Database::GetSqliteVfsFile() {
902   DCHECK(db_) << "Database not opened";
903
904   // sqlite3_file_control() accepts a null pointer to mean the "main" database
905   // attached to a connection. https://www.sqlite.org/c3ref/file_control.html
906   constexpr const char* kMainDatabaseName = nullptr;
907
908   sqlite3_file* result = nullptr;
909   auto sqlite_result_code = ToSqliteResultCode(sqlite3_file_control(
910       db_, kMainDatabaseName, SQLITE_FCNTL_FILE_POINTER, &result));
911
912   // SQLITE_FCNTL_FILE_POINTER is handled directly by SQLite, not by the VFS. It
913   // is only supposed to fail with SQLITE_ERROR if the database name is not
914   // recognized. However, "main" should always be recognized.
915   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
916       << "sqlite3_file_control(SQLITE_FCNTL_FILE_POINTER) failed";
917
918   // SQLite does not return null when called on an in-memory or temporary
919   // database. Instead, it returns returns a VFS file object with a null
920   // pMethods member.
921   DCHECK(result)
922       << "sqlite3_file_control() succeded but returned a null sqlite3_file*";
923   if (!result->pMethods) {
924     // If this assumption fails, sql::Database will still function correctly,
925     // but will miss some configuration optimizations. The DCHECK is here to
926     // alert us (via test failures and ASAN canary builds) of such cases.
927     DCHECK_EQ(DbPath().AsUTF8Unsafe(), "")
928         << "sqlite3_file_control() returned a sqlite3_file* with null pMethods "
929         << "in a case when it shouldn't have.";
930
931     return nullptr;
932   }
933
934   return result;
935 }
936
937 void Database::TrimMemory() {
938   TRACE_EVENT0("sql", "Database::TrimMemory");
939
940   if (!db_)
941     return;
942
943   // Passing the result code through ToSqliteResultCode() to catch issues such
944   // as SQLITE_MISUSE.
945   std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
946
947   // It is tempting to use sqlite3_release_memory() here as well. However, the
948   // API is documented to be a no-op unless SQLite is built with
949   // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is
950   // incompatible with per-database page cache pools. Behind the scenes,
951   // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache
952   // pool, and sqlite3_release_memory() releases unused pages from this global
953   // pool.
954 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
955 #error "This method assumes SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined"
956 #endif  // defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
957 }
958
959 // Create an in-memory database with the existing database's page
960 // size, then backup that database over the existing database.
961 bool Database::Raze() {
962   TRACE_EVENT0("sql", "Database::Raze");
963
964   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
965   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
966
967   if (!db_) {
968     DCHECK(poisoned_) << "Cannot raze null db";
969     return false;
970   }
971
972   DCHECK_GE(transaction_nesting_, 0);
973   if (transaction_nesting_ > 0) {
974     DLOG(DCHECK) << "Cannot raze within a transaction";
975     return false;
976   }
977
978   sql::Database null_db(sql::DatabaseOptions{
979       .exclusive_locking = true,
980       .page_size = options_.page_size,
981       .cache_size = 0,
982       .enable_foreign_keys_discouraged =
983           options_.enable_foreign_keys_discouraged,
984       .enable_views_discouraged = options_.enable_views_discouraged,
985       .enable_virtual_tables_discouraged =
986           options_.enable_virtual_tables_discouraged,
987   });
988   if (!null_db.OpenInMemory()) {
989     DLOG(DCHECK) << "Unable to open in-memory database.";
990     return false;
991   }
992
993 #if BUILDFLAG(IS_ANDROID)
994   // Android compiles with SQLITE_DEFAULT_AUTOVACUUM.  Unfortunately,
995   // in-memory databases do not respect this define.
996   // TODO(shess): Figure out a way to set this without using platform
997   // specific code.  AFAICT from sqlite3.c, the only way to do it
998   // would be to create an actual filesystem database, which is
999   // unfortunate.
1000   if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1001     return false;
1002 #endif
1003
1004   // The page size doesn't take effect until a database has pages, and
1005   // at this point the null database has none.  Changing the schema
1006   // version will create the first page.  This will not affect the
1007   // schema version in the resulting database, as SQLite's backup
1008   // implementation propagates the schema version from the original
1009   // database to the new version of the database, incremented by one
1010   // so that other readers see the schema change and act accordingly.
1011   if (!null_db.Execute("PRAGMA schema_version = 1"))
1012     return false;
1013
1014   // SQLite tracks the expected number of database pages in the first
1015   // page, and if it does not match the total retrieved from a
1016   // filesystem call, treats the database as corrupt.  This situation
1017   // breaks almost all SQLite calls.  "PRAGMA writable_schema" can be
1018   // used to hint to SQLite to soldier on in that case, specifically
1019   // for purposes of recovery.  [See SQLITE_CORRUPT_BKPT case in
1020   // sqlite3.c lockBtree().]
1021   // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1022   // page_size" can be used to query such a database.
1023   ScopedWritableSchema writable_schema(db_);
1024
1025 #if BUILDFLAG(IS_WIN)
1026   // On Windows, truncate silently fails when applied to memory-mapped files.
1027   // Disable memory-mapping so that the truncate succeeds.  Note that other
1028   // Database connections may have memory-mapped the file, so this may not
1029   // entirely prevent the problem.
1030   // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1031   std::ignore = Execute("PRAGMA mmap_size = 0");
1032 #endif
1033
1034   SqliteResultCode sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
1035
1036   // The destination database was locked.
1037   if (sqlite_result_code == SqliteResultCode::kBusy)
1038     return false;
1039
1040   // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1041   // formatted correctly.  SQLITE_IOERR_SHORT_READ can happen if db_
1042   // isn't even big enough for one page.  Either way, reach in and
1043   // truncate it before trying again.
1044   // TODO(shess): Maybe it would be worthwhile to just truncate from
1045   // the get-go?
1046   if (sqlite_result_code == SqliteResultCode::kNotADatabase ||
1047       sqlite_result_code == SqliteResultCode::kIoShortRead) {
1048     sqlite3_file* file = GetSqliteVfsFile();
1049     if (!file || file->pMethods->xTruncate(file, 0) != SQLITE_OK) {
1050       DLOG(DCHECK) << "Failed to truncate file.";
1051       return false;
1052     }
1053
1054     sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
1055     if (sqlite_result_code != SqliteResultCode::kDone)
1056       return false;
1057   }
1058
1059   // Page size of |db_| and |null_db| differ.
1060   if (sqlite_result_code == SqliteResultCode::kReadOnly) {
1061     // Enter TRUNCATE mode to change page size.
1062     // TODO(shuagga@microsoft.com): Need a guarantee here that there is no other
1063     // database connection open.
1064     std::ignore = Execute("PRAGMA journal_mode=TRUNCATE;");
1065     const std::string page_size_sql = base::StrCat(
1066         {"PRAGMA page_size=", base::NumberToString(options_.page_size)});
1067     if (!Execute(page_size_sql.c_str())) {
1068       return false;
1069     }
1070     // Page size isn't changed until the database is vacuumed.
1071     std::ignore = Execute("VACUUM");
1072     // Re-enter WAL mode.
1073     if (UseWALMode()) {
1074       std::ignore = Execute("PRAGMA journal_mode=WAL;");
1075     }
1076
1077     sqlite_result_code = BackupDatabaseForRaze(null_db.db_, db_);
1078     if (sqlite_result_code != SqliteResultCode::kDone)
1079       return false;
1080   }
1081
1082   if (sqlite_result_code != SqliteResultCode::kDone) {
1083     NOTIMPLEMENTED() << "Unhandled sqlite3_backup_step() error: "
1084                      << sqlite_result_code;
1085     return false;
1086   }
1087
1088   // Checkpoint to propagate transactions to the database file and empty the WAL
1089   // file.
1090   // The database can still contain old data if the Checkpoint fails so fail the
1091   // Raze.
1092   return CheckpointDatabase();
1093 }
1094
1095 bool Database::RazeAndClose() {
1096   TRACE_EVENT0("sql", "Database::RazeAndClose");
1097
1098   if (!db_) {
1099     DCHECK(poisoned_) << "Cannot raze null db";
1100     return false;
1101   }
1102
1103   // Raze() cannot run in a transaction.
1104   RollbackAllTransactions();
1105
1106   bool result = Raze();
1107
1108   CloseInternal(true);
1109
1110   // Mark the database so that future API calls fail appropriately,
1111   // but don't DCHECK (because after calling this function they are
1112   // expected to fail).
1113   poisoned_ = true;
1114
1115   return result;
1116 }
1117
1118 void Database::Poison() {
1119   TRACE_EVENT0("sql", "Database::Poison");
1120
1121   if (!db_) {
1122     DCHECK(poisoned_) << "Cannot poison null db";
1123     return;
1124   }
1125
1126   RollbackAllTransactions();
1127   CloseInternal(true);
1128
1129   // Mark the database so that future API calls fail appropriately,
1130   // but don't DCHECK (because after calling this function they are
1131   // expected to fail).
1132   poisoned_ = true;
1133 }
1134
1135 // TODO(shess): To the extent possible, figure out the optimal
1136 // ordering for these deletes which will prevent other Database connections
1137 // from seeing odd behavior.  For instance, it may be necessary to
1138 // manually lock the main database file in a SQLite-compatible fashion
1139 // (to prevent other processes from opening it), then delete the
1140 // journal files, then delete the main database file.  Another option
1141 // might be to lock the main database file and poison the header with
1142 // junk to prevent other processes from opening it successfully (like
1143 // Gears "SQLite poison 3" trick).
1144 //
1145 // static
1146 bool Database::Delete(const base::FilePath& path) {
1147   TRACE_EVENT1("sql", "Database::Delete", "path", path.MaybeAsASCII());
1148
1149   base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
1150                                                 base::BlockingType::MAY_BLOCK);
1151
1152   base::FilePath journal_path = Database::JournalPath(path);
1153   base::FilePath wal_path = Database::WriteAheadLogPath(path);
1154
1155   std::string journal_str = AsUTF8ForSQL(journal_path);
1156   std::string wal_str = AsUTF8ForSQL(wal_path);
1157   std::string path_str = AsUTF8ForSQL(path);
1158
1159   EnsureSqliteInitialized();
1160
1161   sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
1162   CHECK(vfs);
1163   CHECK(vfs->xDelete);
1164   CHECK(vfs->xAccess);
1165
1166   // We only work with the VFS implementations listed below. If you're trying to
1167   // use this code with any other VFS, you're not in a good place.
1168   CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1169         strncmp(vfs->zName, "win32", 5) == 0 ||
1170         strcmp(vfs->zName, "storage_service") == 0);
1171
1172   vfs->xDelete(vfs, journal_str.c_str(), 0);
1173   vfs->xDelete(vfs, wal_str.c_str(), 0);
1174   vfs->xDelete(vfs, path_str.c_str(), 0);
1175
1176   int journal_exists = 0;
1177   vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
1178
1179   int wal_exists = 0;
1180   vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
1181
1182   int path_exists = 0;
1183   vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
1184
1185   return !journal_exists && !wal_exists && !path_exists;
1186 }
1187
1188 bool Database::BeginTransaction() {
1189   TRACE_EVENT0("sql", "Database::BeginTransaction");
1190
1191   if (needs_rollback_) {
1192     DCHECK_GT(transaction_nesting_, 0);
1193
1194     // When we're going to rollback, fail on this begin and don't actually
1195     // mark us as entering the nested transaction.
1196     return false;
1197   }
1198
1199   bool success = true;
1200   DCHECK_GE(transaction_nesting_, 0);
1201   if (!transaction_nesting_) {
1202     needs_rollback_ = false;
1203
1204     Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
1205     if (!begin.Run())
1206       return false;
1207   }
1208   ++transaction_nesting_;
1209   return success;
1210 }
1211
1212 void Database::RollbackTransaction() {
1213   TRACE_EVENT0("sql", "Database::RollbackTransaction");
1214
1215   DCHECK_GE(transaction_nesting_, 0);
1216   if (!transaction_nesting_) {
1217     DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
1218     return;
1219   }
1220
1221   DCHECK_GT(transaction_nesting_, 0);
1222   --transaction_nesting_;
1223
1224   if (transaction_nesting_ > 0) {
1225     // Mark the outermost transaction as needing rollback.
1226     needs_rollback_ = true;
1227     return;
1228   }
1229
1230   DoRollback();
1231 }
1232
1233 bool Database::CommitTransaction() {
1234   TRACE_EVENT0("sql", "Database::CommitTransaction");
1235
1236   DCHECK_GE(transaction_nesting_, 0);
1237   if (!transaction_nesting_) {
1238     DCHECK(poisoned_) << "Committing a nonexistent transaction";
1239     return false;
1240   }
1241
1242   DCHECK_GT(transaction_nesting_, 0);
1243   --transaction_nesting_;
1244
1245   if (transaction_nesting_ > 0) {
1246     // Mark any nested transactions as failing after we've already got one.
1247     return !needs_rollback_;
1248   }
1249
1250   if (needs_rollback_) {
1251     DoRollback();
1252     return false;
1253   }
1254
1255   Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
1256
1257   bool succeeded = commit.Run();
1258
1259   // Release dirty cache pages after the transaction closes.
1260   ReleaseCacheMemoryIfNeeded(false);
1261
1262   return succeeded;
1263 }
1264
1265 void Database::RollbackAllTransactions() {
1266   TRACE_EVENT0("sql", "Database::RollbackAllTransactions");
1267
1268   DCHECK_GE(transaction_nesting_, 0);
1269   if (transaction_nesting_ > 0) {
1270     transaction_nesting_ = 0;
1271     DoRollback();
1272   }
1273 }
1274
1275 bool Database::AttachDatabase(const base::FilePath& other_db_path,
1276                               base::StringPiece attachment_point,
1277                               InternalApiToken) {
1278   TRACE_EVENT0("sql", "Database::AttachDatabase");
1279
1280   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1281   DCHECK(ValidAttachmentPoint(attachment_point));
1282
1283   Statement statement(GetUniqueStatement("ATTACH ? AS ?"));
1284 #if OS_WIN
1285   statement.BindString16(0, base::AsStringPiece16(other_db_path.value()));
1286 #else
1287   statement.BindString(0, other_db_path.value());
1288 #endif
1289   statement.BindString(1, attachment_point);
1290   return statement.Run();
1291 }
1292
1293 bool Database::DetachDatabase(base::StringPiece attachment_point,
1294                               InternalApiToken) {
1295   TRACE_EVENT0("sql", "Database::DetachDatabase");
1296
1297   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1298   DCHECK(ValidAttachmentPoint(attachment_point));
1299
1300   Statement statement(GetUniqueStatement("DETACH ?"));
1301   statement.BindString(0, attachment_point);
1302   return statement.Run();
1303 }
1304
1305 // TODO(crbug.com/1230443): Change this to execute exactly one statement.
1306 SqliteResultCode Database::ExecuteAndReturnResultCode(const char* sql) {
1307   TRACE_EVENT0("sql", "Database::ExecuteAndReturnErrorCode");
1308
1309   DCHECK(sql);
1310
1311   if (!db_) {
1312     DCHECK(poisoned_) << "Illegal use of Database without a db";
1313     return SqliteResultCode::kError;
1314   }
1315
1316   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1317   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1318
1319   SqliteResultCode sqlite_result_code = SqliteResultCode::kOk;
1320   while ((sqlite_result_code == SqliteResultCode::kOk) && *sql) {
1321     sqlite3_stmt* sqlite_statement;
1322     const char* leftover_sql;
1323     sqlite_result_code = ToSqliteResultCode(
1324         sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
1325                            &sqlite_statement, &leftover_sql));
1326
1327 #if DCHECK_IS_ON()
1328     // Report SQL compilation errors. On developer machines, the errors are most
1329     // likely caused by invalid SQL in an under-development feature. In
1330     // production, SQL compilation errors are caused by database schema
1331     // corruption.
1332     //
1333     // DCHECK would not be appropriate here, because on-disk data is always
1334     // subject to corruption, so Chrome cannot assume that the database schema
1335     // will remain intact.
1336     if (sqlite_result_code == SqliteResultCode::kError) {
1337       DLOG(ERROR) << "SQL compilation error: " << GetErrorMessage()
1338                   << ". Statement: " << sql;
1339     }
1340 #endif  // DCHECK_IS_ON()
1341
1342     // Stop if compiling the SQL statement fails.
1343     if (sqlite_result_code != SqliteResultCode::kOk) {
1344       DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1345           << "sqlite3_prepare_v3() returned unexpected non-error result code";
1346       DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1347           << "sqlite3_prepare_v3() returned unexpected non-error result code";
1348       break;
1349     }
1350
1351     sql = leftover_sql;
1352
1353     // This happens if |sql| originally only contained comments or whitespace.
1354     // TODO(shess): Audit to see if this can become a DCHECK().  Having
1355     // extraneous comments and whitespace in the SQL statements increases
1356     // runtime cost and can easily be shifted out to the C++ layer.
1357     if (!sqlite_statement)
1358       continue;
1359
1360     while (true) {
1361       sqlite_result_code = ToSqliteResultCode(sqlite3_step(sqlite_statement));
1362       if (sqlite_result_code != SqliteResultCode::kRow)
1363         break;
1364
1365       // TODO(shess): Audit to see if this can become a DCHECK.  I think PRAGMA
1366       // is the only legitimate case for this. Previously recorded histograms
1367       // show significant use of this code path.
1368     }
1369
1370     // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1371     // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1372     sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
1373     DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1374         << "sqlite3_finalize() returned unexpected non-error result code";
1375     DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1376         << "sqlite3_finalize() returned unexpected non-error result code";
1377
1378     // sqlite3_exec() does this, presumably to avoid spinning the parser for
1379     // trailing whitespace.
1380     // TODO(shess): Audit to see if this can become a DCHECK.
1381     while (base::IsAsciiWhitespace(*sql)) {
1382       sql++;
1383     }
1384   }
1385
1386   // Most calls to Execute() modify the database.  The main exceptions would be
1387   // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1388   // but sometimes don't.
1389   ReleaseCacheMemoryIfNeeded(true);
1390
1391   DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1392       << __func__ << " about to return unexpected non-error result code";
1393   DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1394       << __func__ << " about to return unexpected non-error result code";
1395   return sqlite_result_code;
1396 }
1397
1398 bool Database::Execute(const char* sql) {
1399   TRACE_EVENT1("sql", "Database::Execute", "query", TRACE_STR_COPY(sql));
1400
1401   if (!db_) {
1402     DCHECK(poisoned_) << "Illegal use of Database without a db";
1403     return false;
1404   }
1405
1406   SqliteResultCode sqlite_result_code = ExecuteAndReturnResultCode(sql);
1407   if (sqlite_result_code != SqliteResultCode::kOk)
1408     OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr, sql);
1409
1410   return sqlite_result_code == SqliteResultCode::kOk;
1411 }
1412
1413 bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
1414   TRACE_EVENT0("sql", "Database::ExecuteWithTimeout");
1415
1416   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1417   if (!db_) {
1418     DCHECK(poisoned_) << "Illegal use of Database without a db";
1419     return false;
1420   }
1421
1422   ScopedBusyTimeout busy_timeout(db_);
1423   busy_timeout.SetTimeout(timeout);
1424   return Execute(sql);
1425 }
1426
1427 bool Database::ExecuteScriptForTesting(const char* sql_script) {
1428   DCHECK(sql_script);
1429   if (!db_) {
1430     DCHECK(poisoned_) << "Illegal use of Database without a db";
1431     return false;
1432   }
1433
1434   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1435   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1436
1437   while (*sql_script) {
1438     sqlite3_stmt* sqlite_statement;
1439     auto sqlite_result_code = ToSqliteResultCode(
1440         sqlite3_prepare_v3(db_, sql_script, /*nByte=*/-1, SqlitePrepareFlags(),
1441                            &sqlite_statement, &sql_script));
1442     if (sqlite_result_code != SqliteResultCode::kOk)
1443       return false;
1444
1445     if (!sqlite_statement) {
1446       // Trailing comment or whitespace after the last semicolon.
1447       return true;
1448     }
1449
1450     // TODO(pwnall): Investigate restricting ExecuteScriptForTesting() to
1451     //               statements that don't produce any result rows.
1452     do {
1453       sqlite_result_code = ToSqliteResultCode(sqlite3_step(sqlite_statement));
1454     } while (sqlite_result_code == SqliteResultCode::kRow);
1455
1456     // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1457     // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1458     sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
1459     if (sqlite_result_code != SqliteResultCode::kOk)
1460       return false;
1461   }
1462
1463   return true;
1464 }
1465
1466 scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
1467     StatementID id,
1468     const char* sql) {
1469   auto it = statement_cache_.find(id);
1470   if (it != statement_cache_.end()) {
1471     // Statement is in the cache. It should still be valid. We're the only
1472     // entity invalidating cached statements, and we remove them from the cache
1473     // when we do that.
1474     DCHECK(it->second->is_valid());
1475     DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
1476         << "GetCachedStatement used with same ID but different SQL";
1477
1478     // Reset the statement so it can be reused.
1479     //
1480     // ToSqliteResultCode() is called to ensure that sqlite3_reset() doesn't
1481     // return a concerning code, such as SQLITE_MISUSE. The processed error code
1482     // is ignored because sqlite3_reset() returns an error code if the last
1483     // sqlite3_step() failed, and that error was already reported when we ran
1484     // sqlite3_step(), via Statement::Run() or Statement::Step().
1485     std::ignore = ToSqliteResultCode(sqlite3_reset(it->second->stmt()));
1486     return it->second;
1487   }
1488
1489   scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1490   if (statement->is_valid()) {
1491     statement_cache_[id] = statement;  // Only cache valid statements.
1492     DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
1493         << "Input SQL does not match SQLite's normalized version";
1494   }
1495   return statement;
1496 }
1497
1498 scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
1499     const char* sql) {
1500   return GetStatementImpl(sql, /*is_readonly=*/false);
1501 }
1502
1503 scoped_refptr<Database::StatementRef> Database::GetReadonlyStatement(
1504     const char* sql) {
1505   return GetStatementImpl(sql, /*is_readonly=*/true);
1506 }
1507
1508 scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1509     const char* sql,
1510     bool is_readonly) {
1511   DCHECK(sql);
1512
1513   // Return inactive statement.
1514   if (!db_)
1515     return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
1516
1517   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1518   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1519
1520 #if DCHECK_IS_ON()
1521   const char* unused_sql = nullptr;
1522   const char** unused_sql_ptr = &unused_sql;
1523 #else
1524   constexpr const char** unused_sql_ptr = nullptr;
1525 #endif  // DCHECK_IS_ON()
1526   // TODO(pwnall): Cached statements (but not unique statements) should be
1527   //               prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT.
1528   sqlite3_stmt* sqlite_statement;
1529   auto sqlite_result_code = ToSqliteResultCode(
1530       sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
1531                          &sqlite_statement, unused_sql_ptr));
1532
1533 #if DCHECK_IS_ON()
1534   // Report SQL compilation errors. On developer machines, the errors are most
1535   // likely caused by invalid SQL in an under-development feature. In
1536   // production, SQL compilation errors are caused by database schema
1537   // corruption.
1538   //
1539   // DCHECK would not be appropriate here, because on-disk data is always
1540   // subject to corruption, so Chrome cannot assume that the database schema
1541   // will remain intact.
1542   if (sqlite_result_code == SqliteResultCode::kError) {
1543     DLOG(ERROR) << "SQL compilation error: " << GetErrorMessage()
1544                 << ". Statement: " << sql;
1545   }
1546 #endif  // DCHECK_IS_ON()
1547
1548   if (sqlite_result_code != SqliteResultCode::kOk) {
1549     DCHECK_NE(sqlite_result_code, SqliteResultCode::kDone)
1550         << "sqlite3_prepare_v3() returned unexpected non-error result code";
1551     DCHECK_NE(sqlite_result_code, SqliteResultCode::kRow)
1552         << "sqlite3_prepare_v3() returned unexpected non-error result code";
1553     OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr, sql);
1554     return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
1555   }
1556
1557   // If readonly statement is expected and the statement is not readonly, return
1558   // an invalid statement and close the created statement.
1559   if (is_readonly && sqlite3_stmt_readonly(sqlite_statement) == 0) {
1560     DLOG(ERROR) << "Readonly SQL statement failed readonly test " << sql;
1561     // Make a `StatementRef` that will close the created statement.
1562     base::MakeRefCounted<StatementRef>(this, sqlite_statement, true);
1563
1564     return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
1565   }
1566
1567 #if DCHECK_IS_ON()
1568   DCHECK_EQ(unused_sql, sql + strlen(sql))
1569       << "Unused text: " << std::string(unused_sql) << "\n"
1570       << "in prepared SQL statement: " << std::string(sql);
1571 #endif  // DCHECK_IS_ON()
1572
1573   DCHECK(sqlite_statement) << "No SQL statement in string: " << sql;
1574
1575   return base::MakeRefCounted<StatementRef>(this, sqlite_statement, true);
1576 }
1577
1578 std::string Database::GetSchema() {
1579   // The ORDER BY should not be necessary, but relying on organic
1580   // order for something like this is questionable.
1581   static const char kSql[] =
1582       "SELECT type, name, tbl_name, sql "
1583       "FROM sqlite_schema ORDER BY 1, 2, 3, 4";
1584   Statement statement(GetUniqueStatement(kSql));
1585
1586   std::string schema;
1587   while (statement.Step()) {
1588     schema += statement.ColumnString(0);
1589     schema += '|';
1590     schema += statement.ColumnString(1);
1591     schema += '|';
1592     schema += statement.ColumnString(2);
1593     schema += '|';
1594     schema += statement.ColumnString(3);
1595     schema += '\n';
1596   }
1597
1598   return schema;
1599 }
1600
1601 bool Database::IsSQLValid(const char* sql) {
1602   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1603
1604   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1605   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1606   if (!db_) {
1607     DCHECK(poisoned_) << "Illegal use of Database without a db";
1608     return false;
1609   }
1610
1611 #if DCHECK_IS_ON()
1612   const char* unused_sql = nullptr;
1613   const char** unused_sql_ptr = &unused_sql;
1614 #else
1615   constexpr const char** unused_sql_ptr = nullptr;
1616 #endif  // DCHECK_IS_ON()
1617
1618   sqlite3_stmt* sqlite_statement = nullptr;
1619   auto sqlite_result_code = ToSqliteResultCode(
1620       sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(),
1621                          &sqlite_statement, unused_sql_ptr));
1622   if (sqlite_result_code != SqliteResultCode::kOk)
1623     return false;
1624
1625 #if DCHECK_IS_ON()
1626   DCHECK_EQ(unused_sql, sql + strlen(sql))
1627       << "Unused text: " << std::string(unused_sql) << "\n"
1628       << "in SQL statement: " << std::string(sql);
1629 #endif  // DCHECK_IS_ON()
1630
1631   DCHECK(sqlite_statement) << "No SQL statement in string: " << sql;
1632
1633   sqlite_result_code = ToSqliteResultCode(sqlite3_finalize(sqlite_statement));
1634   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1635       << "sqlite3_finalize() failed for valid statement";
1636   return true;
1637 }
1638
1639 bool Database::DoesIndexExist(base::StringPiece index_name) {
1640   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1641   return DoesSchemaItemExist(index_name, "index");
1642 }
1643
1644 bool Database::DoesTableExist(base::StringPiece table_name) {
1645   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1646   return DoesSchemaItemExist(table_name, "table");
1647 }
1648
1649 bool Database::DoesViewExist(base::StringPiece view_name) {
1650   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1651   return DoesSchemaItemExist(view_name, "view");
1652 }
1653
1654 bool Database::DoesSchemaItemExist(base::StringPiece name,
1655                                    base::StringPiece type) {
1656   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1657
1658   static const char kSql[] =
1659       "SELECT 1 FROM sqlite_schema WHERE type=? AND name=?";
1660   Statement statement(GetUniqueStatement(kSql));
1661
1662   if (!statement.is_valid()) {
1663     // The database is corrupt.
1664     return false;
1665   }
1666
1667   statement.BindString(0, type);
1668   statement.BindString(1, name);
1669
1670   return statement.Step();  // Table exists if any row was returned.
1671 }
1672
1673 bool Database::DoesColumnExist(const char* table_name,
1674                                const char* column_name) {
1675   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1676
1677   // sqlite3_table_column_metadata uses out-params to return column definition
1678   // details, such as the column type and whether it allows NULL values. These
1679   // aren't needed to compute the current method's result, so we pass in nullptr
1680   // for all the out-params.
1681   auto sqlite_result_code = ToSqliteResultCode(sqlite3_table_column_metadata(
1682       db_, "main", table_name, column_name, /* pzDataType= */ nullptr,
1683       /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr,
1684       /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr));
1685   return sqlite_result_code == SqliteResultCode::kOk;
1686 }
1687
1688 int64_t Database::GetLastInsertRowId() const {
1689   if (!db_) {
1690     DCHECK(poisoned_) << "Illegal use of Database without a db";
1691     return 0;
1692   }
1693   int64_t last_rowid = sqlite3_last_insert_rowid(db_);
1694   DCHECK(last_rowid != 0) << "No successful INSERT in a table with ROWID";
1695   return last_rowid;
1696 }
1697
1698 int64_t Database::GetLastChangeCount() {
1699   if (!db_) {
1700     DCHECK(poisoned_) << "Illegal use of Database without a db";
1701     return 0;
1702   }
1703   return sqlite3_changes64(db_);
1704 }
1705
1706 int Database::GetMemoryUsage() {
1707   if (!db_) {
1708     DCHECK(poisoned_) << "Illegal use of Database without a db";
1709     return 0;
1710   }
1711
1712   // The following calls all set the high watermark to zero.
1713   // See https://www.sqlite.org/c3ref/c_dbstatus_options.html
1714   int high_watermark = 0;
1715
1716   int cache_memory = 0, schema_memory = 0, statement_memory = 0;
1717
1718   auto sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
1719       db_, SQLITE_DBSTATUS_CACHE_USED, &cache_memory, &high_watermark,
1720       /*resetFlg=*/0));
1721   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1722       << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED) failed";
1723
1724 #if DCHECK_IS_ON()
1725   int shared_cache_memory = 0;
1726   sqlite_result_code = ToSqliteResultCode(
1727       sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED_SHARED,
1728                         &shared_cache_memory, &high_watermark, /*resetFlg=*/0));
1729   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1730       << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED_SHARED) failed";
1731   DCHECK_EQ(shared_cache_memory, cache_memory)
1732       << "Memory counting assumes that each database uses a private page cache";
1733 #endif  // DCHECK_IS_ON()
1734
1735   sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
1736       db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_memory, &high_watermark,
1737       /*resetFlg=*/0));
1738   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1739       << "sqlite3_db_status(SQLITE_DBSTATUS_SCHEMA_USED) failed";
1740
1741   sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
1742       db_, SQLITE_DBSTATUS_STMT_USED, &statement_memory, &high_watermark,
1743       /*resetFlg=*/0));
1744   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
1745       << "sqlite3_db_status(SQLITE_DBSTATUS_STMT_USED) failed";
1746
1747   return cache_memory + schema_memory + statement_memory;
1748 }
1749
1750 int Database::GetErrorCode() const {
1751   if (!db_)
1752     return SQLITE_ERROR;
1753   return sqlite3_extended_errcode(db_);
1754 }
1755
1756 int Database::GetLastErrno() const {
1757   if (!db_)
1758     return -1;
1759
1760   int err = 0;
1761   if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
1762     return -2;
1763
1764   return err;
1765 }
1766
1767 const char* Database::GetErrorMessage() const {
1768   if (!db_)
1769     return "sql::Database is not opened.";
1770   return sqlite3_errmsg(db_);
1771 }
1772
1773 bool Database::OpenInternal(const std::string& db_file_path,
1774                             Database::OpenMode mode) {
1775   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
1776   TRACE_EVENT1("sql", "Database::OpenInternal", "path", db_file_path);
1777
1778   DCHECK(mode != OpenMode::kTemporary || db_file_path.empty())
1779       << "Temporary databases should be open with an empty file path";
1780
1781   if (mode == OpenMode::kInMemory) {
1782     DCHECK_EQ(db_file_path, kSqliteOpenInMemoryPath)
1783         << "In-memory databases should be open with the magic :memory: path";
1784   } else {
1785     DCHECK_NE(db_file_path, kSqliteOpenInMemoryPath)
1786         << "Database file path conflicts with SQLite magic identifier";
1787   }
1788
1789   if (db_) {
1790     DLOG(DCHECK) << "sql::Database is already open.";
1791     return false;
1792   }
1793
1794   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
1795   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1796
1797   EnsureSqliteInitialized();
1798
1799   // If |poisoned_| is set, it means an error handler called
1800   // RazeAndClose().  Until regular Close() is called, the caller
1801   // should be treating the database as open, but is_open() currently
1802   // only considers the sqlite3 handle's state.
1803   // TODO(shess): Revise is_open() to consider poisoned_, and review
1804   // to see if any non-testing code even depends on it.
1805   DCHECK(!poisoned_) << "sql::Database is already open.";
1806   poisoned_ = false;
1807
1808   // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1809   sqlite3_vfs* vfs = VFSWrapper();
1810   const char* vfs_name = (vfs ? vfs->zName : nullptr);
1811
1812   // The flags are documented at https://www.sqlite.org/c3ref/open.html.
1813   //
1814   // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
1815   // disparate features with their own databases, and having separate page
1816   // caches makes it easier to reason about each feature's performance in
1817   // isolation.
1818   //
1819   // SQLITE_OPEN_EXRESCODE enables the full range of SQLite error codes. See
1820   // https://www.sqlite.org/rescode.html for details.
1821   int open_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
1822                    SQLITE_OPEN_EXRESCODE | SQLITE_OPEN_PRIVATECACHE;
1823   auto sqlite_result_code = ToSqliteResultCode(
1824       sqlite3_open_v2(db_file_path.c_str(), &db_, open_flags, vfs_name));
1825   if (sqlite_result_code != SqliteResultCode::kOk) {
1826     OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr,
1827                   "-- sqlite3_open_v2()");
1828     bool was_poisoned = poisoned_;
1829     Close();
1830
1831     if (was_poisoned && mode == OpenMode::kRetryOnPoision)
1832       return OpenInternal(db_file_path, OpenMode::kNone);
1833     return false;
1834   }
1835
1836   ConfigureSqliteDatabaseObject();
1837
1838   // If indicated, enable shared mode ("NORMAL") on the database, so it can be
1839   // opened by multiple processes. This needs to happen before WAL mode is
1840   // enabled.
1841   //
1842   // TODO(crbug.com/1120969): Remove support for non-exclusive mode.
1843   static_assert(
1844       SQLITE_DEFAULT_LOCKING_MODE == 1,
1845       "Chrome assumes SQLite is configured to default to EXCLUSIVE locking");
1846   if (!options_.exclusive_locking) {
1847     if (!Execute("PRAGMA locking_mode=NORMAL"))
1848       return false;
1849   }
1850
1851   // The sqlite3_open*() methods only perform I/O on the database file if a hot
1852   // journal is found. Force SQLite to parse the header and database schema, so
1853   // we can signal irrecoverable corruption early.
1854   //
1855   // sqlite3_table_column_metadata() causes SQLite to parse the database schema.
1856   // Since the schema is stored inside a table B-tree, parsing the schema
1857   // implies parsing the database header.
1858   //
1859   // sqlite3_table_column_metadata() can be used with a null database name, but
1860   // that will cause it to search for the table in all databases that are
1861   // ATTACHed to the connection. While Chrome features (almost) never use
1862   // ATTACHed databases, we prefer to be explicit here.
1863   //
1864   // sqlite3_table_column_metadata() can be used with a null column name, and
1865   // will report on the existence of the table with the given name. This is
1866   // sufficient for the purpose of getting SQLite to parse the database schema.
1867   // See https://www.sqlite.org/c3ref/table_column_metadata.html for details.
1868   static constexpr char kSqliteSchemaTable[] = "sqlite_schema";
1869   sqlite_result_code = ToSqliteResultCode(sqlite3_table_column_metadata(
1870       db_, kSqliteMainDatabaseName, kSqliteSchemaTable, /*zColumnName=*/nullptr,
1871       /*pzDataType=*/nullptr, /*pzCollSeq=*/nullptr, /*pNotNull=*/nullptr,
1872       /*pPrimaryKey=*/nullptr, /*pAutoinc=*/nullptr));
1873   if (sqlite_result_code != SqliteResultCode::kOk) {
1874     OnSqliteError(ToSqliteErrorCode(sqlite_result_code), nullptr,
1875                   "-- sqlite3_table_column_metadata()");
1876
1877     // Retry or bail out if the error handler poisoned the handle.
1878     // TODO(shess): Move this handling to one place (see also sqlite3_open).
1879     //              Possibly a wrapper function?
1880     if (poisoned_) {
1881       Close();
1882       if (mode == OpenMode::kRetryOnPoision)
1883         return OpenInternal(db_file_path, OpenMode::kNone);
1884       return false;
1885     }
1886   }
1887
1888   const base::TimeDelta kBusyTimeout = base::Seconds(kBusyTimeoutSeconds);
1889
1890   // Needs to happen before entering WAL mode. Will only work if this the first
1891   // time the database is being opened in WAL mode.
1892   const std::string page_size_sql =
1893       base::StringPrintf("PRAGMA page_size=%d", options_.page_size);
1894   std::ignore = ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout);
1895
1896   // http://www.sqlite.org/pragma.html#pragma_journal_mode
1897   // WAL - Use a write-ahead log instead of a journal file.
1898   // DELETE (default) - delete -journal file to commit.
1899   // TRUNCATE - truncate -journal file to commit.
1900   // PERSIST - zero out header of -journal file to commit.
1901   // TRUNCATE should be faster than DELETE because it won't need directory
1902   // changes for each transaction.  PERSIST may break the spirit of using
1903   // secure_delete.
1904   //
1905   // Needs to be performed after setting exclusive locking mode. Otherwise can
1906   // fail if underlying VFS doesn't support shared memory.
1907   if (UseWALMode()) {
1908     // Set the synchronous flag to NORMAL. This means that writers don't flush
1909     // the WAL file after every write. The WAL file is only flushed on a
1910     // checkpoint. In this case, transcations might lose durability on a power
1911     // loss (but still durable after an application crash).
1912     // TODO(shuagga@microsoft.com): Evaluate if this loss of durability is a
1913     // concern.
1914     std::ignore = Execute("PRAGMA synchronous=NORMAL");
1915
1916     // Opening the db in WAL mode can fail (eg if the underlying VFS doesn't
1917     // support shared memory and we are not in exclusive locking mode).
1918     //
1919     // TODO(shuagga@microsoft.com): We should probably catch a failure here.
1920     std::ignore = Execute("PRAGMA journal_mode=WAL");
1921   } else {
1922     std::ignore = Execute("PRAGMA journal_mode=TRUNCATE");
1923   }
1924
1925   if (options_.flush_to_media)
1926     std::ignore = Execute("PRAGMA fullfsync=1");
1927
1928   if (options_.cache_size != 0) {
1929     const std::string cache_size_sql = base::StrCat(
1930         {"PRAGMA cache_size=", base::NumberToString(options_.cache_size)});
1931     std::ignore = ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout);
1932   }
1933
1934   static_assert(SQLITE_SECURE_DELETE == 1,
1935                 "Chrome assumes secure_delete is on by default.");
1936
1937   // When SQLite needs to grow a database file, it uses a configurable
1938   // increment. Larger values reduce filesystem fragmentation and mmap()
1939   // churn, as the database file is grown less often. Smaller values waste
1940   // less disk space.
1941   //
1942   // We currently set different values for small vs large files.
1943   //
1944   // TODO(crbug.com/1305778): Replace file size-based heuristic with a
1945   // DatabaseOptions member. Use the DatabaseOptions value for temporary
1946   // databases as well.
1947   sqlite3_file* file = GetSqliteVfsFile();
1948
1949   // GetSqliteVfsFile() returns null for in-memory and temporary databases. This
1950   // is fine, because these databases start out empty, so the heuristic below
1951   // would never set a chunk size on them anyway.
1952   if (file) {
1953     sqlite3_int64 db_size = 0;
1954     sqlite_result_code =
1955         ToSqliteResultCode(file->pMethods->xFileSize(file, &db_size));
1956     if (sqlite_result_code == SqliteResultCode::kOk && db_size > 16 * 1024) {
1957       int chunk_size = 4 * 1024;
1958       if (db_size > 128 * 1024)
1959         chunk_size = 32 * 1024;
1960
1961       sqlite3_file_control(db_, /*zDbName=*/nullptr, SQLITE_FCNTL_CHUNK_SIZE,
1962                            &chunk_size);
1963     }
1964   }
1965
1966   size_t mmap_size = mmap_disabled_ ? 0 : ComputeMmapSizeForOpen();
1967
1968   // We explicitly issue a "PRGAMA mmap_size=0" to disable memory-mapping. We
1969   // could skip executing the PRAGMA in that case, and use a static_assert to
1970   // ensure that SQLITE_DEFAULT_MMAP_SIZE > 0. We didn't choose this alternative
1971   // because would cost us a bit more logic, and the optimization would apply to
1972   // edge cases, such as in-memory databases.  More details at
1973   // https://www.sqlite.org/pragma.html#pragma_mmap_size.
1974   std::string pragma_mmap_size_sql =
1975       base::StrCat({"PRAGMA mmap_size=", base::NumberToString(mmap_size)});
1976   std::ignore = Execute(pragma_mmap_size_sql.c_str());
1977
1978   // Determine if memory-mapping has actually been enabled.  The Execute() above
1979   // can succeed without changing the amount mapped.
1980   mmap_enabled_ = false;
1981   {
1982     Statement pragma_mmap_size(GetUniqueStatement("PRAGMA mmap_size"));
1983     if (pragma_mmap_size.Step() && pragma_mmap_size.ColumnInt64(0) > 0)
1984       mmap_enabled_ = true;
1985   }
1986
1987   DCHECK(!memory_dump_provider_);
1988   memory_dump_provider_ =
1989       std::make_unique<DatabaseMemoryDumpProvider>(db_, histogram_tag_);
1990   base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1991       memory_dump_provider_.get(), "sql::Database", /*task_runner=*/nullptr);
1992
1993   return true;
1994 }
1995
1996 void Database::ConfigureSqliteDatabaseObject() {
1997   // The use of SQLite's non-standard string quoting is not allowed in Chrome.
1998   //
1999   // Allowing double-quoted string literals is now considered a misfeature by
2000   // SQLite authors. See https://www.sqlite.org/quirks.html#dblquote
2001   auto sqlite_result_code = ToSqliteResultCode(
2002       sqlite3_db_config(db_, SQLITE_DBCONFIG_DQS_DDL, 0, nullptr));
2003   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2004       << "sqlite3_db_config(SQLITE_DBCONFIG_DQS_DDL) should not fail";
2005   sqlite_result_code = ToSqliteResultCode(
2006       sqlite3_db_config(db_, SQLITE_DBCONFIG_DQS_DML, 0, nullptr));
2007   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2008       << "sqlite3_db_config(SQLITE_DBCONFIG_DQS_DML) should not fail";
2009
2010   sqlite_result_code = ToSqliteResultCode(sqlite3_db_config(
2011       db_, SQLITE_DBCONFIG_ENABLE_FKEY,
2012       options_.enable_foreign_keys_discouraged ? 1 : 0, nullptr));
2013   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2014       << "sqlite3_db_config(SQLITE_DBCONFIG_ENABLE_FKEY) should not fail";
2015
2016   // The use of triggers is discouraged for Chrome code. Thanks to this
2017   // configuration change, triggers are not executed. CREATE TRIGGER and DROP
2018   // TRIGGER still succeed.
2019   sqlite_result_code = ToSqliteResultCode(
2020       sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_TRIGGER, 0, nullptr));
2021   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2022       << "sqlite3_db_config() should not fail";
2023
2024   sqlite_result_code = ToSqliteResultCode(
2025       sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_VIEW,
2026                         options_.enable_views_discouraged ? 1 : 0, nullptr));
2027   DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
2028       << "sqlite3_db_config() should not fail";
2029 }
2030
2031 void Database::DoRollback() {
2032   TRACE_EVENT0("sql", "Database::DoRollback");
2033
2034   Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
2035
2036   rollback.Run();
2037
2038   // The cache may have been accumulating dirty pages for commit.  Note that in
2039   // some cases sql::Transaction can fire rollback after a database is closed.
2040   if (is_open())
2041     ReleaseCacheMemoryIfNeeded(false);
2042
2043   needs_rollback_ = false;
2044 }
2045
2046 void Database::StatementRefCreated(StatementRef* ref) {
2047   DCHECK(!open_statements_.count(ref))
2048       << __func__ << " already called with this statement";
2049   open_statements_.insert(ref);
2050 }
2051
2052 void Database::StatementRefDeleted(StatementRef* ref) {
2053   DCHECK(open_statements_.count(ref))
2054       << __func__ << " called with non-existing statement";
2055   open_statements_.erase(ref);
2056 }
2057
2058 void Database::set_histogram_tag(const std::string& tag) {
2059   DCHECK(!is_open());
2060
2061   histogram_tag_ = tag;
2062 }
2063
2064 void Database::OnSqliteError(SqliteErrorCode sqlite_error_code,
2065                              sql::Statement* statement,
2066                              const char* sql_statement) {
2067   TRACE_EVENT0("sql", "Database::OnSqliteError");
2068
2069   DCHECK_NE(statement != nullptr, sql_statement != nullptr)
2070       << __func__ << " should either get a Statement or a raw SQL string";
2071
2072   // Log errors for developers.
2073   //
2074   // This block is wrapped around a DCHECK_IS_ON() check so we don't waste CPU
2075   // cycles computing the strings that make up the log message in production.
2076 #if DCHECK_IS_ON()
2077   std::string logged_statement;
2078   if (statement) {
2079     logged_statement = statement->GetSQLStatement();
2080   } else {
2081     logged_statement = sql_statement;
2082   }
2083
2084   std::string database_id = histogram_tag_;
2085   if (database_id.empty())
2086     database_id = DbPath().BaseName().AsUTF8Unsafe();
2087
2088   // This logging block cannot be a DCHECK, because valid usage of sql::Database
2089   // can still encounter SQLite errors in production. For example, valid SQL
2090   // statements can fail when a database is corrupted.
2091   //
2092   // This logging block should not use LOG(ERROR) because many features built on
2093   // top of sql::Database can recover from most errors.
2094   DVLOG(1) << "SQLite error! This may indicate a programming error!\n"
2095            << "Database: " << database_id
2096            << " sqlite_error_code: " << sqlite_error_code
2097            << " errno: " << GetLastErrno()
2098            << "\nSQLite error description: " << GetErrorMessage()
2099            << "\nSQL statement: " << logged_statement;
2100 #endif  // DCHECK_IS_ON()
2101
2102   // Inform the error expecter that we've encountered the error.
2103   std::ignore = IsExpectedSqliteError(static_cast<int>(sqlite_error_code));
2104
2105   if (!error_callback_.is_null()) {
2106     // Create an additional reference to the state in `error_callback_`, so the
2107     // state doesn't go away if the callback changes `error_callback_` by
2108     // calling set_error_callback() or reset_error_callback(). This avoids a
2109     // subtle source of use-after-frees. See https://crbug.com/254584.
2110     ErrorCallback error_callback_copy = error_callback_;
2111     error_callback_copy.Run(static_cast<int>(sqlite_error_code), statement);
2112     return;
2113   }
2114 }
2115
2116 std::string Database::GetDiagnosticInfo(int sqlite_error_code,
2117                                         Statement* statement,
2118                                         DatabaseDiagnostics* diagnostics) {
2119   DCHECK_NE(sqlite_error_code, SQLITE_OK)
2120       << __func__ << " received non-error result code";
2121   DCHECK_NE(sqlite_error_code, SQLITE_DONE)
2122       << __func__ << " received non-error result code";
2123   DCHECK_NE(sqlite_error_code, SQLITE_ROW)
2124       << __func__ << " received non-error result code";
2125
2126   // Prevent reentrant calls to the error callback.
2127   ErrorCallback original_callback = std::move(error_callback_);
2128   error_callback_.Reset();
2129
2130   if (diagnostics) {
2131     diagnostics->reported_sqlite_error_code = sqlite_error_code;
2132   }
2133
2134   // Trim extended error codes.
2135   const int primary_error_code = sqlite_error_code & 0xff;
2136
2137   // CollectCorruptionInfo() is implemented in terms of sql::Database,
2138   // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
2139   std::string result =
2140       (primary_error_code == SQLITE_CORRUPT)
2141           ? CollectCorruptionInfo()
2142           : CollectErrorInfo(sqlite_error_code, statement, diagnostics);
2143
2144   // The following queries must be executed after CollectErrorInfo() above, so
2145   // if they result in their own errors, they don't interfere with
2146   // CollectErrorInfo().
2147   const bool has_valid_header = Execute("PRAGMA auto_vacuum");
2148   const bool has_valid_schema = Execute("SELECT COUNT(*) FROM sqlite_schema");
2149
2150   // Restore the original error callback.
2151   error_callback_ = std::move(original_callback);
2152
2153   base::StringAppendF(&result, "Has valid header: %s\n",
2154                       (has_valid_header ? "Yes" : "No"));
2155   base::StringAppendF(&result, "Has valid schema: %s\n",
2156                       (has_valid_schema ? "Yes" : "No"));
2157   if (diagnostics) {
2158     diagnostics->has_valid_header = has_valid_header;
2159     diagnostics->has_valid_schema = has_valid_schema;
2160   }
2161
2162   return result;
2163 }
2164
2165 bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
2166   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
2167   messages->clear();
2168
2169   // The PRAGMA below has the side effect of setting SQLITE_RecoveryMode, which
2170   // allows SQLite to process through certain cases of corruption.
2171   if (!Execute("PRAGMA writable_schema=ON")) {
2172     // The "PRAGMA integrity_check" statement executed below may return less
2173     // useful information. However, incomplete information is still better than
2174     // nothing, so we press on.
2175     messages->push_back("PRAGMA writable_schema=ON failed");
2176   }
2177
2178   // We need to bypass sql::Statement and use raw SQLite C API calls here.
2179   //
2180   // "PRAGMA integrity_check" reports SQLITE_CORRUPT when the database is
2181   // corrupt. Reporting SQLITE_CORRUPT is undesirable in this case, because it
2182   // causes our sql::Statement infrastructure to call the database error
2183   // handler, which triggers feature-level error handling. However,
2184   // FullIntegrityCheck() callers presumably already know that the database is
2185   // corrupted, and are trying to collect diagnostic information for reporting.
2186   sqlite3_stmt* statement = nullptr;
2187
2188   // https://www.sqlite.org/c3ref/prepare.html states that SQLite will perform
2189   // slightly better if sqlite_prepare_v3() receives a zero-terminated statement
2190   // string, and a statement size that includes the zero byte. Fortunately,
2191   // C++'s string literal and sizeof() operator do exactly that.
2192   constexpr char kIntegrityCheckSql[] = "PRAGMA integrity_check";
2193   const auto prepare_result_code = ToSqliteResultCode(
2194       sqlite3_prepare_v3(db_, kIntegrityCheckSql, sizeof(kIntegrityCheckSql),
2195                          SqlitePrepareFlags(), &statement, /*pzTail=*/nullptr));
2196   if (prepare_result_code != SqliteResultCode::kOk)
2197     return false;
2198
2199   // "PRAGMA integrity_check" currently returns multiple lines as a single row.
2200   //
2201   // However, since https://www.sqlite.org/pragma.html#pragma_integrity_check
2202   // states that multiple records may be returned, the code below can handle
2203   // multiple records, each of which has multiple lines.
2204   std::vector<std::string> result_lines;
2205
2206   while (ToSqliteResultCode(sqlite3_step(statement)) ==
2207          SqliteResultCode::kRow) {
2208     const uint8_t* row = chrome_sqlite3_column_text(statement, /*iCol=*/0);
2209     DCHECK(row) << "PRAGMA integrity_check should never return NULL rows";
2210
2211     const int row_size = sqlite3_column_bytes(statement, /*iCol=*/0);
2212     base::StringPiece row_string(reinterpret_cast<const char*>(row), row_size);
2213
2214     const std::vector<base::StringPiece> row_lines = base::SplitStringPiece(
2215         row_string, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
2216     for (base::StringPiece row_line : row_lines)
2217       result_lines.emplace_back(row_line);
2218   }
2219
2220   const auto finalize_result_code =
2221       ToSqliteResultCode(sqlite3_finalize(statement));
2222   // sqlite3_finalize() may return SQLITE_CORRUPT when the integrity check
2223   // discovers any problems. We still consider this case a success, as long as
2224   // the statement produced at least one diagnostic message.
2225   const bool success = (result_lines.size() > 0) ||
2226                        (finalize_result_code == SqliteResultCode::kOk);
2227   *messages = std::move(result_lines);
2228
2229   // Best-effort attempt to undo the "PRAGMA writable_schema=ON" executed above.
2230   std::ignore = Execute("PRAGMA writable_schema=OFF");
2231
2232   return success;
2233 }
2234
2235 bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
2236                                  const std::string& dump_name) {
2237   return memory_dump_provider_ &&
2238          memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
2239 }
2240
2241 bool Database::UseWALMode() const {
2242 #if BUILDFLAG(IS_FUCHSIA)
2243   // WAL mode is only enabled on Fuchsia for databases with exclusive
2244   // locking, because this case does not require shared memory support.
2245   // At the time this was implemented (May 2020), Fuchsia's shared
2246   // memory support was insufficient for SQLite's needs.
2247   return options_.wal_mode && options_.exclusive_locking;
2248 #else
2249   return options_.wal_mode;
2250 #endif  // BUILDFLAG(IS_FUCHSIA)
2251 }
2252
2253 bool Database::CheckpointDatabase() {
2254   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
2255   absl::optional<base::ScopedBlockingCall> scoped_blocking_call;
2256   InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
2257
2258   auto sqlite_result_code = ToSqliteResultCode(sqlite3_wal_checkpoint_v2(
2259       db_, kSqliteMainDatabaseName, SQLITE_CHECKPOINT_PASSIVE,
2260       /*pnLog=*/nullptr, /*pnCkpt=*/nullptr));
2261
2262   return sqlite_result_code == SqliteResultCode::kOk;
2263 }
2264
2265 }  // namespace sql