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