blob: 05831c9982626c54ab18b1ecedf19dd4ede41773 [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Victor Costancfbfa602018-08-01 23:24:465#include "sql/database.h"
[email protected]e5ffd0e42009-09-11 21:30:566
avi51ba3e692015-12-26 17:30:507#include <limits.h>
avi0b519202015-12-21 07:25:198#include <stddef.h>
9#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:5610#include <string.h>
mostynbd82cd9952016-04-11 20:05:3411
Shubham Aggarwalbe4f97ce2020-06-19 15:58:5712#include "base/feature_list.h"
[email protected]57999812013-02-24 05:40:5213#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4414#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4615#include "base/format_macros.h"
fdoray2dfa76452016-06-07 13:11:2216#include "base/location.h"
[email protected]e5ffd0e42009-09-11 21:30:5617#include "base/logging.h"
Ilya Sherman1c811db2017-12-14 10:36:1818#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0819#include "base/metrics/histogram_macros.h"
[email protected]210ce0af2013-05-15 09:10:3920#include "base/metrics/sparse_histogram.h"
Victor Costan3653df62018-02-08 21:38:1621#include "base/no_destructor.h"
Will Harrisb8693592018-08-28 22:58:4422#include "base/numerics/safe_conversions.h"
fdoray2dfa76452016-06-07 13:11:2223#include "base/single_thread_task_runner.h"
[email protected]80abf152013-05-22 12:42:4224#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1925#include "base/strings/string_util.h"
26#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4527#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1828#include "base/synchronization/lock.h"
Etienne Pierre-Doray0400dfb62018-12-03 19:12:2529#include "base/threading/scoped_blocking_call.h"
ssid9f8022f2015-10-12 17:49:0330#include "base/trace_event/memory_dump_manager.h"
Etienne Bergeron6cb35c72020-02-12 18:09:4831#include "base/trace_event/trace_event.h"
Kevin Marshalla9f05ec2017-07-14 02:10:0532#include "build/build_config.h"
Victor Costancfbfa602018-08-01 23:24:4633#include "sql/database_memory_dump_provider.h"
Victor Costan3653df62018-02-08 21:38:1634#include "sql/initialization.h"
shess9bf2c672015-12-18 01:18:0835#include "sql/meta_table.h"
Victor Costan3ffd9a372019-05-22 00:46:5436#include "sql/sql_features.h"
[email protected]f0a54b22011-07-19 18:40:2137#include "sql/statement.h"
shess5f2c3442017-01-24 02:15:1038#include "sql/vfs_wrapper.h"
[email protected]e33cba42010-08-18 23:37:0339#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5640
[email protected]5b96f3772010-09-28 16:30:5741namespace {
42
43// Spin for up to a second waiting for the lock to clear when setting
44// up the database.
45// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2746const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5747
48class ScopedBusyTimeout {
49 public:
Victor Costancfbfa602018-08-01 23:24:4650 explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
51 ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
[email protected]5b96f3772010-09-28 16:30:5752
53 int SetTimeout(base::TimeDelta timeout) {
54 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
55 return sqlite3_busy_timeout(db_,
56 static_cast<int>(timeout.InMilliseconds()));
57 }
58
59 private:
60 sqlite3* db_;
61};
62
[email protected]6d42f152012-11-10 00:38:2463// Helper to "safely" enable writable_schema. No error checking
64// because it is reasonable to just forge ahead in case of an error.
65// If turning it on fails, then most likely nothing will work, whereas
66// if turning it off fails, it only matters if some code attempts to
67// continue working with the database and tries to modify the
68// sqlite_master table (none of our code does this).
69class ScopedWritableSchema {
70 public:
Victor Costancfbfa602018-08-01 23:24:4671 explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
Victor Costanbd623112018-07-18 04:17:2772 sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2473 }
74 ~ScopedWritableSchema() {
Victor Costanbd623112018-07-18 04:17:2775 sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2476 }
77
78 private:
79 sqlite3* db_;
80};
81
[email protected]7bae5742013-07-10 20:46:1682// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
83// SQLite error code from running the backup step.
84int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
85 DCHECK_NE(src, dst);
86 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
87 if (!backup) {
88 // Since this call only sets things up, this indicates a gross
89 // error in SQLite.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:5290 DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
[email protected]7bae5742013-07-10 20:46:1691 return sqlite3_errcode(dst);
92 }
93
94 // -1 backs up the entire database.
95 int rc = sqlite3_backup_step(backup, -1);
96 int pages = sqlite3_backup_pagecount(backup);
97 sqlite3_backup_finish(backup);
98
99 // If successful, exactly one page should have been backed up. If
100 // this breaks, check this function to make sure assumptions aren't
101 // being broken.
102 if (rc == SQLITE_DONE)
103 DCHECK_EQ(pages, 1);
104
105 return rc;
106}
107
[email protected]8d409412013-07-19 18:25:30108// Be very strict on attachment point. SQLite can handle a much wider
109// character set with appropriate quoting, but Chromium code should
110// just use clean names to start with.
111bool ValidAttachmentPoint(const char* attachment_point) {
112 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20113 if (!(base::IsAsciiDigit(attachment_point[i]) ||
114 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30115 attachment_point[i] == '_')) {
116 return false;
117 }
118 }
119 return true;
120}
121
[email protected]8ada10f2013-12-21 00:42:34122// Helper to get the sqlite3_file* associated with the "main" database.
123int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
Victor Costanbd623112018-07-18 04:17:27124 *file = nullptr;
125 int rc = sqlite3_file_control(db, nullptr, SQLITE_FCNTL_FILE_POINTER, file);
[email protected]8ada10f2013-12-21 00:42:34126 if (rc != SQLITE_OK)
127 return rc;
128
Victor Costanbd623112018-07-18 04:17:27129 // TODO(shess): null in file->pMethods has been observed on android_dbg
[email protected]8ada10f2013-12-21 00:42:34130 // content_unittests, even though it should not be possible.
131 // http://crbug.com/329982
132 if (!*file || !(*file)->pMethods)
133 return SQLITE_ERROR;
134
135 return rc;
136}
137
shess5dac334f2015-11-05 20:47:42138// Convenience to get the sqlite3_file* and the size for the "main" database.
139int GetSqlite3FileAndSize(sqlite3* db,
Victor Costancfbfa602018-08-01 23:24:46140 sqlite3_file** file,
141 sqlite3_int64* db_size) {
shess5dac334f2015-11-05 20:47:42142 int rc = GetSqlite3File(db, file);
143 if (rc != SQLITE_OK)
144 return rc;
145
146 return (*file)->pMethods->xFileSize(*file, db_size);
147}
148
erg102ceb412015-06-20 01:38:13149std::string AsUTF8ForSQL(const base::FilePath& path) {
150#if defined(OS_WIN)
Jan Wilken Dörrie9720dce2020-07-21 17:14:23151 return base::WideToUTF8(path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18152#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
erg102ceb412015-06-20 01:38:13153 return path.value();
154#endif
155}
156
[email protected]5b96f3772010-09-28 16:30:57157} // namespace
158
[email protected]e5ffd0e42009-09-11 21:30:56159namespace sql {
160
[email protected]4350e322013-06-18 22:18:10161// static
Victor Costancfbfa602018-08-01 23:24:46162Database::ErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10163
164// static
Victor Costancfbfa602018-08-01 23:24:46165bool Database::IsExpectedSqliteError(int error) {
shess976814402016-06-21 06:56:25166 if (!current_expecter_cb_)
[email protected]4350e322013-06-18 22:18:10167 return false;
shess976814402016-06-21 06:56:25168 return current_expecter_cb_->Run(error);
[email protected]4350e322013-06-18 22:18:10169}
170
171// static
Victor Costancfbfa602018-08-01 23:24:46172void Database::SetErrorExpecter(Database::ErrorExpecterCallback* cb) {
Victor Costanbd623112018-07-18 04:17:27173 CHECK(!current_expecter_cb_);
shess976814402016-06-21 06:56:25174 current_expecter_cb_ = cb;
[email protected]4350e322013-06-18 22:18:10175}
176
177// static
Victor Costancfbfa602018-08-01 23:24:46178void Database::ResetErrorExpecter() {
shess976814402016-06-21 06:56:25179 CHECK(current_expecter_cb_);
Victor Costanbd623112018-07-18 04:17:27180 current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10181}
182
Victor Costance678e72018-07-24 10:25:00183// static
Victor Costancfbfa602018-08-01 23:24:46184base::FilePath Database::JournalPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00185 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
186}
187
188// static
Victor Costancfbfa602018-08-01 23:24:46189base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00190 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
191}
192
193// static
Victor Costancfbfa602018-08-01 23:24:46194base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00195 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
196}
197
Victor Costancfbfa602018-08-01 23:24:46198Database::StatementRef::StatementRef(Database* database,
199 sqlite3_stmt* stmt,
200 bool was_valid)
201 : database_(database), stmt_(stmt), was_valid_(was_valid) {
202 if (database)
203 database_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56204}
205
Victor Costancfbfa602018-08-01 23:24:46206Database::StatementRef::~StatementRef() {
207 if (database_)
208 database_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38209 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56210}
211
Victor Costancfbfa602018-08-01 23:24:46212void Database::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56213 if (stmt_) {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54214 // Call to InitScopedBlockingCall() cannot go at the beginning of the
215 // function because Close() is called unconditionally from destructor to
216 // clean database_. And if this is inactive statement this won't cause any
217 // disk access and destructor most probably will be called on thread not
218 // allowing disk access.
[email protected]35f7e5392012-07-27 19:54:50219 // TODO([email protected]): This should move to the beginning
220 // of the function. http://crbug.com/136655.
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54221 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:20222 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
[email protected]e5ffd0e42009-09-11 21:30:56223 sqlite3_finalize(stmt_);
Victor Costanbd623112018-07-18 04:17:27224 stmt_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56225 }
Victor Costancfbfa602018-08-01 23:24:46226 database_ = nullptr; // The Database may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38227
228 // Forced close is expected to happen from a statement error
229 // handler. In that case maintain the sense of |was_valid_| which
230 // previously held for this ref.
231 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56232}
233
Victor Costan7f6abbbe2018-07-29 02:57:27234static_assert(
Victor Costancfbfa602018-08-01 23:24:46235 Database::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
236 "Database::kDefaultPageSize must match the value configured into SQLite");
Victor Costan7f6abbbe2018-07-29 02:57:27237
Victor Costancfbfa602018-08-01 23:24:46238constexpr int Database::kDefaultPageSize;
Victor Costan7f6abbbe2018-07-29 02:57:27239
Victor Costancfbfa602018-08-01 23:24:46240Database::Database()
Victor Costanbd623112018-07-18 04:17:27241 : db_(nullptr),
Victor Costan7f6abbbe2018-07-29 02:57:27242 page_size_(kDefaultPageSize),
[email protected]e5ffd0e42009-09-11 21:30:56243 cache_size_(0),
244 exclusive_locking_(false),
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57245 want_wal_mode_(
246 base::FeatureList::IsEnabled(features::kEnableWALModeByDefault)),
[email protected]e5ffd0e42009-09-11 21:30:56247 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50248 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16249 in_memory_(false),
shess58b8df82015-06-03 00:19:32250 poisoned_(false),
shessa62504d2016-11-07 19:26:12251 mmap_alt_status_(false),
kerz42ff2a012016-04-27 04:50:06252 mmap_disabled_(false),
shess7dbd4dee2015-10-06 17:39:16253 mmap_enabled_(false),
254 total_changes_at_last_release_(0),
Victor Costan5e785e32019-02-26 20:39:31255 stats_histogram_(nullptr) {}
[email protected]e5ffd0e42009-09-11 21:30:56256
Victor Costancfbfa602018-08-01 23:24:46257Database::~Database() {
[email protected]e5ffd0e42009-09-11 21:30:56258 Close();
259}
260
Victor Costancfbfa602018-08-01 23:24:46261void Database::RecordEvent(Events event, size_t count) {
shess58b8df82015-06-03 00:19:32262 for (size_t i = 0; i < count; ++i) {
Victor Costanb0e7fc02019-03-01 03:36:27263 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats2", event, EVENT_MAX_VALUE);
shess58b8df82015-06-03 00:19:32264 }
265
266 if (stats_histogram_) {
267 for (size_t i = 0; i < count; ++i) {
268 stats_histogram_->Add(event);
269 }
270 }
271}
272
Victor Costancfbfa602018-08-01 23:24:46273bool Database::Open(const base::FilePath& path) {
Etienne Bergeron6cb35c72020-02-12 18:09:48274 TRACE_EVENT1("sql", "Database::Open", "path", path.MaybeAsASCII());
erg102ceb412015-06-20 01:38:13275 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42276}
[email protected]e5ffd0e42009-09-11 21:30:56277
Victor Costancfbfa602018-08-01 23:24:46278bool Database::OpenInMemory() {
Etienne Bergeron6cb35c72020-02-12 18:09:48279 TRACE_EVENT0("sql", "Database::OpenInMemory");
[email protected]35f7e5392012-07-27 19:54:50280 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13281 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56282}
283
Victor Costancfbfa602018-08-01 23:24:46284bool Database::OpenTemporary() {
Etienne Bergeron6cb35c72020-02-12 18:09:48285 TRACE_EVENT0("sql", "Database::OpenTemporary");
[email protected]8d409412013-07-19 18:25:30286 return OpenInternal("", NO_RETRY);
287}
288
Victor Costancfbfa602018-08-01 23:24:46289void Database::CloseInternal(bool forced) {
Etienne Bergeron6cb35c72020-02-12 18:09:48290 TRACE_EVENT0("sql", "Database::CloseInternal");
[email protected]4e179ba62012-03-17 16:06:47291 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
292 // will delete the -journal file. For ChromiumOS or other more
293 // embedded systems, this is probably not appropriate, whereas on
294 // desktop it might make some sense.
295
[email protected]4b350052012-02-24 20:40:48296 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48297
[email protected]41a97c812013-02-07 02:35:38298 // Release cached statements.
299 statement_cache_.clear();
300
301 // With cached statements released, in-use statements will remain.
302 // Closing the database while statements are in use is an API
303 // violation, except for forced close (which happens from within a
304 // statement's error handler).
305 DCHECK(forced || open_statements_.empty());
306
307 // Deactivate any outstanding statements so sqlite3_close() works.
Victor Costanc7e7f2e2018-07-18 20:07:55308 for (StatementRef* statement_ref : open_statements_)
309 statement_ref->Close(forced);
[email protected]41a97c812013-02-07 02:35:38310 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48311
[email protected]e5ffd0e42009-09-11 21:30:56312 if (db_) {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54313 // Call to InitScopedBlockingCall() cannot go at the beginning of the
314 // function because Close() must be called from destructor to clean
[email protected]35f7e5392012-07-27 19:54:50315 // statement_cache_, it won't cause any disk access and it most probably
316 // will happen on thread not allowing disk access.
317 // TODO([email protected]): This should move to the beginning
318 // of the function. http://crbug.com/136655.
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54319 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:20320 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
[email protected]73fb8d52013-07-24 05:04:28321
Etienne Bergerone7681c72020-01-17 00:51:20322 // Resetting acquires a lock to ensure no dump is happening on the database
ssid3be5b1ec2016-01-13 14:21:57323 // at the same time. Unregister takes ownership of provider and it is safe
324 // since the db is reset. memory_dump_provider_ could be null if db_ was
325 // poisoned.
326 if (memory_dump_provider_) {
327 memory_dump_provider_->ResetDatabase();
328 base::trace_event::MemoryDumpManager::GetInstance()
329 ->UnregisterAndDeleteDumpProviderSoon(
330 std::move(memory_dump_provider_));
331 }
332
[email protected]73fb8d52013-07-24 05:04:28333 int rc = sqlite3_close(db_);
334 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18335 base::UmaHistogramSparse("Sqlite.CloseFailure", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52336 DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage();
[email protected]73fb8d52013-07-24 05:04:28337 }
[email protected]e5ffd0e42009-09-11 21:30:56338 }
Victor Costanbd623112018-07-18 04:17:27339 db_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56340}
341
Victor Costancfbfa602018-08-01 23:24:46342void Database::Close() {
Etienne Bergeron6cb35c72020-02-12 18:09:48343 TRACE_EVENT0("sql", "Database::Close");
[email protected]41a97c812013-02-07 02:35:38344 // If the database was already closed by RazeAndClose(), then no
345 // need to close again. Clear the |poisoned_| bit so that incorrect
346 // API calls are caught.
347 if (poisoned_) {
348 poisoned_ = false;
349 return;
350 }
351
352 CloseInternal(false);
353}
354
Victor Costancfbfa602018-08-01 23:24:46355void Database::Preload() {
Etienne Bergeron6cb35c72020-02-12 18:09:48356 TRACE_EVENT0("sql", "Database::Preload");
Victor Costan3ffd9a372019-05-22 00:46:54357 if (base::FeatureList::IsEnabled(features::kSqlSkipPreload))
358 return;
359
[email protected]e5ffd0e42009-09-11 21:30:56360 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52361 DCHECK(poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56362 return;
363 }
364
Victor Costanb5a0a97002019-09-08 04:55:15365 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:20366 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
Victor Costanb5a0a97002019-09-08 04:55:15367
Victor Costanbcfeb5b2019-10-11 21:38:10368 // Maximum number of bytes that will be prefetched from the database.
369 //
370 // This limit is very aggressive. Here are the trade-offs involved.
371 // 1) Accessing bytes that weren't preread is very expensive on
372 // performance-critical databases, so the limit must exceed the expected
373 // sizes of feature databases.
374 // 2) On some platforms (Windows 7 and, currently, macOS), base::PreReadFile()
375 // falls back to a synchronous read, and blocks until the entire file is
376 // read into memory. So, there's a tangible cost to reading data that would
377 // get evicted before base::PreReadFile() completes. This cost needs to be
378 // balanced with the benefit reading the entire database at once, and
379 // avoiding seeks on spinning disks.
380 constexpr int kPreReadSize = 128 * 1024 * 1024; // 128 MB
381 base::PreReadFile(DbPath(), /*is_executable=*/false, kPreReadSize);
[email protected]e5ffd0e42009-09-11 21:30:56382}
383
Victor Costancfbfa602018-08-01 23:24:46384// SQLite keeps unused pages associated with a database in a cache. It asks
shess7dbd4dee2015-10-06 17:39:16385// the cache for pages by an id, and if the page is present and the database is
386// unchanged, it considers the content of the page valid and doesn't read it
387// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
388// structures created from the memory map data before consulting the cache. On
389// write SQLite creates a new in-memory page structure, copies the data from the
390// memory map, and later writes it, releasing the updated page back to the
391// cache.
392//
393// This means that in memory-mapped mode, the contents of the cached pages are
394// not re-used for reads, but they are re-used for writes if the re-written page
395// is still in the cache. The implementation of sqlite3_db_release_memory() as
396// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
Victor Costancfbfa602018-08-01 23:24:46397// database, so it should free these pages.
shess7dbd4dee2015-10-06 17:39:16398//
399// Unfortunately, the zero page is also freed. That page is never accessed
400// using memory-mapped I/O, and the cached copy can be re-used after verifying
401// the file change counter on disk. Also, fresh pages from cache receive some
402// pager-level initialization before they can be used. Since the information
403// involved will immediately be accessed in various ways, it is unclear if the
404// additional overhead is material, or just moving processor cache effects
405// around.
406//
407// TODO(shess): It would be better to release the pages immediately when they
408// are no longer needed. This would basically happen after SQLite commits a
409// transaction. I had implemented a pcache wrapper to do this, but it involved
410// layering violations, and it had to be setup before any other sqlite call,
411// which was brittle. Also, for large files it would actually make sense to
412// maintain the existing pcache behavior for blocks past the memory-mapped
413// segment. I think drh would accept a reasonable implementation of the overall
414// concept for upstreaming to SQLite core.
415//
416// TODO(shess): Another possibility would be to set the cache size small, which
417// would keep the zero page around, plus some pre-initialized pages, and SQLite
418// can manage things. The downside is that updates larger than the cache would
419// spill to the journal. That could be compensated by setting cache_spill to
420// false. The downside then is that it allows open-ended use of memory for
421// large transactions.
Victor Costancfbfa602018-08-01 23:24:46422void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
Etienne Bergeron6cb35c72020-02-12 18:09:48423 TRACE_EVENT0("sql", "Database::ReleaseCacheMemoryIfNeeded");
shess644fc8a2016-02-26 18:15:58424 // The database could have been closed during a transaction as part of error
425 // recovery.
426 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:46427 DCHECK(poisoned_) << "Illegal use of Database without a db";
shess644fc8a2016-02-26 18:15:58428 return;
429 }
shess7dbd4dee2015-10-06 17:39:16430
431 // If memory-mapping is not enabled, the page cache helps performance.
432 if (!mmap_enabled_)
433 return;
434
435 // On caller request, force the change comparison to fail. Done before the
436 // transaction-nesting test so that the signal can carry to transaction
437 // commit.
438 if (implicit_change_performed)
439 --total_changes_at_last_release_;
440
441 // Cached pages may be re-used within the same transaction.
442 if (transaction_nesting())
443 return;
444
445 // If no changes have been made, skip flushing. This allows the first page of
446 // the database to remain in cache across multiple reads.
447 const int total_changes = sqlite3_total_changes(db_);
448 if (total_changes == total_changes_at_last_release_)
449 return;
450
451 total_changes_at_last_release_ = total_changes;
452 sqlite3_db_release_memory(db_);
453}
454
Victor Costancfbfa602018-08-01 23:24:46455base::FilePath Database::DbPath() const {
shessc8cd2a162015-10-22 20:30:46456 if (!is_open())
457 return base::FilePath();
458
459 const char* path = sqlite3_db_filename(db_, "main");
460 const base::StringPiece db_path(path);
461#if defined(OS_WIN)
Jan Wilken Dörrie9720dce2020-07-21 17:14:23462 return base::FilePath(base::UTF8ToWide(db_path));
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18463#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46464 return base::FilePath(db_path);
465#else
466 NOTREACHED();
467 return base::FilePath();
468#endif
469}
470
Victor Costancfbfa602018-08-01 23:24:46471std::string Database::CollectErrorInfo(int error, Statement* stmt) const {
Etienne Bergeron6cb35c72020-02-12 18:09:48472 TRACE_EVENT0("sql", "Database::CollectErrorInfo");
shessc8cd2a162015-10-22 20:30:46473 // Buffer for accumulating debugging info about the error. Place
474 // more-relevant information earlier, in case things overflow the
475 // fixed-size reporting buffer.
476 std::string debug_info;
477
478 // The error message from the failed operation.
Victor Costancfbfa602018-08-01 23:24:46479 base::StringAppendF(&debug_info, "db error: %d/%s\n", GetErrorCode(),
480 GetErrorMessage());
shessc8cd2a162015-10-22 20:30:46481
482 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
483 // reading code does not entirely convince me. Remove if they turn out to be
484 // the same.
485 if (error != GetErrorCode())
486 base::StringAppendF(&debug_info, "reported error: %d\n", error);
487
Victor Costancfbfa602018-08-01 23:24:46488// System error information. Interpretation of Windows errors is different
489// from posix.
shessc8cd2a162015-10-22 20:30:46490#if defined(OS_WIN)
491 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18492#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46493 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
494#else
495 NOTREACHED(); // Add appropriate log info.
496#endif
497
498 if (stmt) {
499 base::StringAppendF(&debug_info, "statement: %s\n",
500 stmt->GetSQLStatement());
501 } else {
502 base::StringAppendF(&debug_info, "statement: NULL\n");
503 }
504
505 // SQLITE_ERROR often indicates some sort of mismatch between the statement
506 // and the schema, possibly due to a failed schema migration.
507 if (error == SQLITE_ERROR) {
Victor Costanf37f7ae2019-04-11 19:26:12508 static const char kVersionSql[] =
509 "SELECT value FROM meta WHERE key='version'";
510 sqlite3_stmt* sqlite_statement;
511 // When the number of bytes passed to sqlite3_prepare_v3() includes the null
512 // terminator, SQLite avoids a buffer copy.
513 int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql),
514 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
515 /* pzTail= */ nullptr);
shessc8cd2a162015-10-22 20:30:46516 if (rc == SQLITE_OK) {
Victor Costanf37f7ae2019-04-11 19:26:12517 rc = sqlite3_step(sqlite_statement);
shessc8cd2a162015-10-22 20:30:46518 if (rc == SQLITE_ROW) {
519 base::StringAppendF(&debug_info, "version: %d\n",
Victor Costanf37f7ae2019-04-11 19:26:12520 sqlite3_column_int(sqlite_statement, 0));
shessc8cd2a162015-10-22 20:30:46521 } else if (rc == SQLITE_DONE) {
522 debug_info += "version: none\n";
523 } else {
524 base::StringAppendF(&debug_info, "version: error %d\n", rc);
525 }
Victor Costanf37f7ae2019-04-11 19:26:12526 sqlite3_finalize(sqlite_statement);
shessc8cd2a162015-10-22 20:30:46527 } else {
528 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
529 }
530
531 debug_info += "schema:\n";
532
533 // sqlite_master has columns:
534 // type - "index" or "table".
535 // name - name of created element.
536 // tbl_name - name of element, or target table in case of index.
537 // rootpage - root page of the element in database file.
538 // sql - SQL to create the element.
539 // In general, the |sql| column is sufficient to derive the other columns.
540 // |rootpage| is not interesting for debugging, without the contents of the
541 // database. The COALESCE is because certain automatic elements will have a
542 // |name| but no |sql|,
Victor Costanf37f7ae2019-04-11 19:26:12543 static const char kSchemaSql[] =
544 "SELECT COALESCE(sql,name) FROM sqlite_master";
545 rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql),
546 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
547 /* pzTail= */ nullptr);
shessc8cd2a162015-10-22 20:30:46548 if (rc == SQLITE_OK) {
Victor Costanf37f7ae2019-04-11 19:26:12549 while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
550 base::StringAppendF(&debug_info, "%s\n",
551 sqlite3_column_text(sqlite_statement, 0));
shessc8cd2a162015-10-22 20:30:46552 }
553 if (rc != SQLITE_DONE)
554 base::StringAppendF(&debug_info, "error %d\n", rc);
Victor Costanf37f7ae2019-04-11 19:26:12555 sqlite3_finalize(sqlite_statement);
shessc8cd2a162015-10-22 20:30:46556 } else {
557 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
558 }
559 }
560
561 return debug_info;
562}
563
564// TODO(shess): Since this is only called in an error situation, it might be
565// prudent to rewrite in terms of SQLite API calls, and mark the function const.
Victor Costancfbfa602018-08-01 23:24:46566std::string Database::CollectCorruptionInfo() {
Etienne Bergeron6cb35c72020-02-12 18:09:48567 TRACE_EVENT0("sql", "Database::CollectCorruptionInfo");
shessc8cd2a162015-10-22 20:30:46568 // If the file cannot be accessed it is unlikely that an integrity check will
569 // turn up actionable information.
570 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19571 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46572 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
573 return std::string();
574
575 // Buffer for accumulating debugging info about the error. Place
576 // more-relevant information earlier, in case things overflow the
577 // fixed-size reporting buffer.
578 std::string debug_info;
579 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
580 db_size);
581
582 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19583 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46584 if (db_size > kMaxIntegrityCheckSize) {
585 debug_info += "integrity_check skipped due to size\n";
586 } else {
587 std::vector<std::string> messages;
588
589 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
590 // into a string. Probably should be refactored.
591 const base::TimeTicks before = base::TimeTicks::Now();
592 FullIntegrityCheck(&messages);
593 base::StringAppendF(
Victor Costancfbfa602018-08-01 23:24:46594 &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
595 (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
shessc8cd2a162015-10-22 20:30:46596
597 // SQLite returns up to 100 messages by default, trim deeper to
598 // keep close to the 2000-character size limit for dumping.
599 const size_t kMaxMessages = 20;
600 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
601 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
602 }
603 }
604
605 return debug_info;
606}
607
Victor Costancfbfa602018-08-01 23:24:46608bool Database::GetMmapAltStatus(int64_t* status) {
Etienne Bergeron6cb35c72020-02-12 18:09:48609 TRACE_EVENT0("sql", "Database::GetMmapAltStatus");
610
shessa62504d2016-11-07 19:26:12611 // The [meta] version uses a missing table as a signal for a fresh database.
612 // That will not work for the view, which would not exist in either a new or
613 // an existing database. A new database _should_ be only one page long, so
614 // just don't bother optimizing this case (start at offset 0).
615 // TODO(shess): Could the [meta] case also get simpler, then?
616 if (!DoesViewExist("MmapStatus")) {
617 *status = 0;
618 return true;
619 }
620
621 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
622 Statement s(GetUniqueStatement(kMmapStatusSql));
623 if (s.Step())
624 *status = s.ColumnInt64(0);
625 return s.Succeeded();
626}
627
Victor Costancfbfa602018-08-01 23:24:46628bool Database::SetMmapAltStatus(int64_t status) {
shessa62504d2016-11-07 19:26:12629 if (!BeginTransaction())
630 return false;
631
632 // View may not exist on first run.
633 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
634 RollbackTransaction();
635 return false;
636 }
637
638 // Views live in the schema, so they cannot be parameterized. For an integer
639 // value, this construct should be safe from SQL injection, if the value
640 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
641 // value.
Victor Costancfbfa602018-08-01 23:24:46642 const std::string create_view_sql = base::StringPrintf(
643 "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
644 if (!Execute(create_view_sql.c_str())) {
shessa62504d2016-11-07 19:26:12645 RollbackTransaction();
646 return false;
647 }
648
649 return CommitTransaction();
650}
651
Victor Costancfbfa602018-08-01 23:24:46652size_t Database::GetAppropriateMmapSize() {
Etienne Bergeron6cb35c72020-02-12 18:09:48653 TRACE_EVENT0("sql", "Database::GetAppropriateMmapSize");
654
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54655 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:20656 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
shessd90aeea82015-11-13 02:24:31657
shess9bf2c672015-12-18 01:18:08658 // How much to map if no errors are found. 50MB encompasses the 99th
659 // percentile of Chrome databases in the wild, so this should be good.
660 const size_t kMmapEverything = 256 * 1024 * 1024;
661
shessa62504d2016-11-07 19:26:12662 // Progress information is tracked in the [meta] table for databases which use
663 // sql::MetaTable, otherwise it is tracked in a special view.
664 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08665 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12666 if (mmap_alt_status_) {
667 if (!GetMmapAltStatus(&mmap_ofs)) {
668 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
669 return 0;
670 }
671 } else {
672 // If [meta] doesn't exist, yet, it's a new database, assume the best.
673 // sql::MetaTable::Init() will preload kMmapSuccess.
674 if (!MetaTable::DoesTableExist(this)) {
675 RecordOneEvent(EVENT_MMAP_META_MISSING);
676 return kMmapEverything;
677 }
678
679 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
680 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
681 return 0;
682 }
shessd90aeea82015-11-13 02:24:31683 }
684
685 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08686 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31687 RecordOneEvent(EVENT_MMAP_FAILED);
688 return 0;
Victor Costan5e785e32019-02-26 20:39:31689 }
690
691 if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31692 // Continue reading from previous offset.
693 DCHECK_GE(mmap_ofs, 0);
694
695 // TODO(shess): Could this reading code be shared with Preload()? It would
696 // require locking twice (this code wouldn't be able to access |db_size| so
697 // the helper would have to return amount read).
698
699 // Read more of the database looking for errors. The VFS interface is used
700 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
701 // to limit checking to 20MB per run of Chromium.
Victor Costanbd623112018-07-18 04:17:27702 sqlite3_file* file = nullptr;
shessd90aeea82015-11-13 02:24:31703 sqlite3_int64 db_size = 0;
704 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
705 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
706 return 0;
707 }
708
709 // Read the data left, or |g_reads_allowed|, whichever is smaller.
710 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
711 // in a single Chromium run.
712 sqlite3_int64 amount = db_size - mmap_ofs;
713 if (amount < 0)
714 amount = 0;
715 if (amount > 0) {
Victor Costan3653df62018-02-08 21:38:16716 static base::NoDestructor<base::Lock> lock;
717 base::AutoLock auto_lock(*lock);
shessd90aeea82015-11-13 02:24:31718 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
719 if (g_reads_allowed < amount)
720 amount = g_reads_allowed;
721 g_reads_allowed -= amount;
722 }
723
724 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
725 // database was truncated after a previous pass.
726 if (amount <= 0 && mmap_ofs < db_size) {
727 DCHECK_EQ(0, amount);
shessd90aeea82015-11-13 02:24:31728 } else {
729 static const int kPageSize = 4096;
730 char buf[kPageSize];
731 while (amount > 0) {
732 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
733 if (rc == SQLITE_OK) {
734 mmap_ofs += sizeof(buf);
735 amount -= sizeof(buf);
736 } else if (rc == SQLITE_IOERR_SHORT_READ) {
737 // Reached EOF for a database with page size < |kPageSize|.
738 mmap_ofs = db_size;
739 break;
740 } else {
741 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08742 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31743 break;
744 }
745 }
746
747 // Log these events after update to distinguish meta update failure.
shessd90aeea82015-11-13 02:24:31748 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08749 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31750 } else {
Victor Costan5e785e32019-02-26 20:39:31751 DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure);
shessd90aeea82015-11-13 02:24:31752 }
753
shessa62504d2016-11-07 19:26:12754 if (mmap_alt_status_) {
755 if (!SetMmapAltStatus(mmap_ofs)) {
756 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
757 return 0;
758 }
759 } else {
760 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
761 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
762 return 0;
763 }
shessd90aeea82015-11-13 02:24:31764 }
765
Victor Costan5e785e32019-02-26 20:39:31766 if (mmap_ofs == MetaTable::kMmapFailure)
767 RecordOneEvent(EVENT_MMAP_FAILED_NEW);
shessd90aeea82015-11-13 02:24:31768 }
769 }
770
shess9bf2c672015-12-18 01:18:08771 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31772 return 0;
shess9bf2c672015-12-18 01:18:08773 if (mmap_ofs == MetaTable::kMmapSuccess)
774 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31775 return mmap_ofs;
776}
777
Victor Costan52bef812018-12-05 07:41:49778void Database::TrimMemory() {
Etienne Bergeron6cb35c72020-02-12 18:09:48779 TRACE_EVENT0("sql", "Database::TrimMemory");
780
[email protected]be7995f12013-07-18 18:49:14781 if (!db_)
782 return;
783
Victor Costan52bef812018-12-05 07:41:49784 sqlite3_db_release_memory(db_);
[email protected]be7995f12013-07-18 18:49:14785
Victor Costan52bef812018-12-05 07:41:49786 // It is tempting to use sqlite3_release_memory() here as well. However, the
787 // API is documented to be a no-op unless SQLite is built with
788 // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is
789 // incompatible with per-database page cache pools. Behind the scenes,
790 // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache
791 // pool, and sqlite3_release_memory() releases unused pages from this global
792 // pool.
[email protected]be7995f12013-07-18 18:49:14793}
794
[email protected]8e0c01282012-04-06 19:36:49795// Create an in-memory database with the existing database's page
796// size, then backup that database over the existing database.
Victor Costancfbfa602018-08-01 23:24:46797bool Database::Raze() {
Etienne Bergeron6cb35c72020-02-12 18:09:48798 TRACE_EVENT0("sql", "Database::Raze");
799
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54800 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:20801 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
[email protected]35f7e5392012-07-27 19:54:50802
[email protected]8e0c01282012-04-06 19:36:49803 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52804 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49805 return false;
806 }
807
808 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52809 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:49810 return false;
811 }
812
Victor Costancfbfa602018-08-01 23:24:46813 sql::Database null_db;
[email protected]8e0c01282012-04-06 19:36:49814 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52815 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:49816 return false;
817 }
818
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57819 const std::string page_size_sql =
820 base::StringPrintf("PRAGMA page_size=%d", page_size_);
821 if (!null_db.Execute(page_size_sql.c_str()))
Victor Costan7f6abbbe2018-07-29 02:57:27822 return false;
[email protected]69c58452012-08-06 19:22:42823
[email protected]6d42f152012-11-10 00:38:24824#if defined(OS_ANDROID)
825 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
826 // in-memory databases do not respect this define.
827 // TODO(shess): Figure out a way to set this without using platform
828 // specific code. AFAICT from sqlite3.c, the only way to do it
829 // would be to create an actual filesystem database, which is
830 // unfortunate.
831 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
832 return false;
833#endif
[email protected]8e0c01282012-04-06 19:36:49834
835 // The page size doesn't take effect until a database has pages, and
836 // at this point the null database has none. Changing the schema
837 // version will create the first page. This will not affect the
838 // schema version in the resulting database, as SQLite's backup
839 // implementation propagates the schema version from the original
Victor Costancfbfa602018-08-01 23:24:46840 // database to the new version of the database, incremented by one
[email protected]8e0c01282012-04-06 19:36:49841 // so that other readers see the schema change and act accordingly.
842 if (!null_db.Execute("PRAGMA schema_version = 1"))
843 return false;
844
[email protected]6d42f152012-11-10 00:38:24845 // SQLite tracks the expected number of database pages in the first
846 // page, and if it does not match the total retrieved from a
847 // filesystem call, treats the database as corrupt. This situation
848 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
849 // used to hint to SQLite to soldier on in that case, specifically
850 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
851 // sqlite3.c lockBtree().]
852 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
853 // page_size" can be used to query such a database.
854 ScopedWritableSchema writable_schema(db_);
855
shess92a6fb22017-04-23 04:33:30856#if defined(OS_WIN)
857 // On Windows, truncate silently fails when applied to memory-mapped files.
858 // Disable memory-mapping so that the truncate succeeds. Note that other
Victor Costancfbfa602018-08-01 23:24:46859 // Database connections may have memory-mapped the file, so this may not
860 // entirely prevent the problem.
shess92a6fb22017-04-23 04:33:30861 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
862 ignore_result(Execute("PRAGMA mmap_size = 0"));
863#endif
864
[email protected]7bae5742013-07-10 20:46:16865 const char* kMain = "main";
866 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:18867 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:49868
869 // The destination database was locked.
870 if (rc == SQLITE_BUSY) {
871 return false;
872 }
873
[email protected]7bae5742013-07-10 20:46:16874 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
875 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
876 // isn't even big enough for one page. Either way, reach in and
877 // truncate it before trying again.
878 // TODO(shess): Maybe it would be worthwhile to just truncate from
879 // the get-go?
880 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
Victor Costanbd623112018-07-18 04:17:27881 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:34882 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:16883 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52884 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:16885 return false;
[email protected]7bae5742013-07-10 20:46:16886 }
887
888 rc = file->pMethods->xTruncate(file, 0);
889 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18890 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52891 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:16892 return false;
893 }
894
895 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:18896 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:16897
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52898 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:16899 }
900
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57901 // Page size of |db_| and |null_db| differ.
902 if (rc == SQLITE_READONLY) {
903 // Enter TRUNCATE mode to change page size.
904 // TODO([email protected]): Need a guarantee here that there is no other
905 // database connection open.
906 ignore_result(Execute("PRAGMA journal_mode=TRUNCATE;"));
907 if (!Execute(page_size_sql.c_str())) {
908 return false;
909 }
910 // Page size isn't changed until the database is vacuumed.
911 ignore_result(Execute("VACUUM"));
912 // Re-enter WAL mode.
913 if (UseWALMode()) {
914 ignore_result(Execute("PRAGMA journal_mode=WAL;"));
915 }
916
917 rc = BackupDatabase(null_db.db_, db_, kMain);
918 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
919
920 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
921 }
922
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52923 // TODO(shess): Figure out which other cases can happen.
924 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
925
Shubham Aggarwalbe4f97ce2020-06-19 15:58:57926 // Checkpoint to propagate transactions to the database file and empty the WAL
927 // file.
928 // The database can still contain old data if the Checkpoint fails so fail the
929 // Raze.
930 if (!CheckpointDatabase()) {
931 return false;
932 }
933
[email protected]8e0c01282012-04-06 19:36:49934 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52935 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:49936}
937
Victor Costancfbfa602018-08-01 23:24:46938bool Database::RazeAndClose() {
Etienne Bergeron6cb35c72020-02-12 18:09:48939 TRACE_EVENT0("sql", "Database::RazeAndClose");
940
[email protected]41a97c812013-02-07 02:35:38941 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52942 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:38943 return false;
944 }
945
946 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:30947 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:38948
949 bool result = Raze();
950
951 CloseInternal(true);
952
953 // Mark the database so that future API calls fail appropriately,
954 // but don't DCHECK (because after calling this function they are
955 // expected to fail).
956 poisoned_ = true;
957
958 return result;
959}
960
Victor Costancfbfa602018-08-01 23:24:46961void Database::Poison() {
Etienne Bergeron6cb35c72020-02-12 18:09:48962 TRACE_EVENT0("sql", "Database::Poison");
963
[email protected]8d409412013-07-19 18:25:30964 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52965 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:30966 return;
967 }
968
969 RollbackAllTransactions();
970 CloseInternal(true);
971
972 // Mark the database so that future API calls fail appropriately,
973 // but don't DCHECK (because after calling this function they are
974 // expected to fail).
975 poisoned_ = true;
976}
977
[email protected]8d2e39e2013-06-24 05:55:08978// TODO(shess): To the extent possible, figure out the optimal
Victor Costancfbfa602018-08-01 23:24:46979// ordering for these deletes which will prevent other Database connections
[email protected]8d2e39e2013-06-24 05:55:08980// from seeing odd behavior. For instance, it may be necessary to
981// manually lock the main database file in a SQLite-compatible fashion
982// (to prevent other processes from opening it), then delete the
983// journal files, then delete the main database file. Another option
984// might be to lock the main database file and poison the header with
985// junk to prevent other processes from opening it successfully (like
986// Gears "SQLite poison 3" trick).
987//
988// static
Victor Costancfbfa602018-08-01 23:24:46989bool Database::Delete(const base::FilePath& path) {
Etienne Bergeron6cb35c72020-02-12 18:09:48990 TRACE_EVENT1("sql", "Database::Delete", "path", path.MaybeAsASCII());
991
Etienne Bergeron436d42212019-02-26 17:15:12992 base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
993 base::BlockingType::MAY_BLOCK);
[email protected]8d2e39e2013-06-24 05:55:08994
Victor Costancfbfa602018-08-01 23:24:46995 base::FilePath journal_path = Database::JournalPath(path);
996 base::FilePath wal_path = Database::WriteAheadLogPath(path);
[email protected]8d2e39e2013-06-24 05:55:08997
erg102ceb412015-06-20 01:38:13998 std::string journal_str = AsUTF8ForSQL(journal_path);
999 std::string wal_str = AsUTF8ForSQL(wal_path);
1000 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081001
Victor Costan3653df62018-02-08 21:38:161002 EnsureSqliteInitialized();
shess702467622015-09-16 19:04:551003
Victor Costanbd623112018-07-18 04:17:271004 sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
erg102ceb412015-06-20 01:38:131005 CHECK(vfs);
1006 CHECK(vfs->xDelete);
1007 CHECK(vfs->xAccess);
1008
1009 // We only work with unix, win32 and mojo filesystems. If you're trying to
1010 // use this code with any other VFS, you're not in a good place.
1011 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1012 strncmp(vfs->zName, "win32", 5) == 0 ||
1013 strcmp(vfs->zName, "mojo") == 0);
1014
1015 vfs->xDelete(vfs, journal_str.c_str(), 0);
1016 vfs->xDelete(vfs, wal_str.c_str(), 0);
1017 vfs->xDelete(vfs, path_str.c_str(), 0);
1018
1019 int journal_exists = 0;
Victor Costance678e72018-07-24 10:25:001020 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
erg102ceb412015-06-20 01:38:131021
1022 int wal_exists = 0;
Victor Costance678e72018-07-24 10:25:001023 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
erg102ceb412015-06-20 01:38:131024
1025 int path_exists = 0;
Victor Costance678e72018-07-24 10:25:001026 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
erg102ceb412015-06-20 01:38:131027
1028 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081029}
1030
Victor Costancfbfa602018-08-01 23:24:461031bool Database::BeginTransaction() {
Etienne Bergeron6cb35c72020-02-12 18:09:481032 TRACE_EVENT0("sql", "Database::BeginTransaction");
1033
[email protected]e5ffd0e42009-09-11 21:30:561034 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331035 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561036
1037 // When we're going to rollback, fail on this begin and don't actually
1038 // mark us as entering the nested transaction.
1039 return false;
1040 }
1041
1042 bool success = true;
1043 if (!transaction_nesting_) {
1044 needs_rollback_ = false;
1045
1046 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:591047 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561048 return false;
1049 }
1050 transaction_nesting_++;
1051 return success;
1052}
1053
Victor Costancfbfa602018-08-01 23:24:461054void Database::RollbackTransaction() {
Etienne Bergeron6cb35c72020-02-12 18:09:481055 TRACE_EVENT0("sql", "Database::RollbackTransaction");
1056
[email protected]e5ffd0e42009-09-11 21:30:561057 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521058 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561059 return;
1060 }
1061
1062 transaction_nesting_--;
1063
1064 if (transaction_nesting_ > 0) {
1065 // Mark the outermost transaction as needing rollback.
1066 needs_rollback_ = true;
1067 return;
1068 }
1069
1070 DoRollback();
1071}
1072
Victor Costancfbfa602018-08-01 23:24:461073bool Database::CommitTransaction() {
Etienne Bergeron6cb35c72020-02-12 18:09:481074 TRACE_EVENT0("sql", "Database::CommitTransaction");
1075
[email protected]e5ffd0e42009-09-11 21:30:561076 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521077 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561078 return false;
1079 }
1080 transaction_nesting_--;
1081
1082 if (transaction_nesting_ > 0) {
1083 // Mark any nested transactions as failing after we've already got one.
1084 return !needs_rollback_;
1085 }
1086
1087 if (needs_rollback_) {
1088 DoRollback();
1089 return false;
1090 }
1091
1092 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321093
Victor Costan5e785e32019-02-26 20:39:311094 bool succeeded = commit.Run();
shess58b8df82015-06-03 00:19:321095
shess7dbd4dee2015-10-06 17:39:161096 // Release dirty cache pages after the transaction closes.
1097 ReleaseCacheMemoryIfNeeded(false);
1098
Victor Costan5e785e32019-02-26 20:39:311099 return succeeded;
[email protected]e5ffd0e42009-09-11 21:30:561100}
1101
Victor Costancfbfa602018-08-01 23:24:461102void Database::RollbackAllTransactions() {
Etienne Bergeron6cb35c72020-02-12 18:09:481103 TRACE_EVENT0("sql", "Database::RollbackAllTransactions");
1104
[email protected]8d409412013-07-19 18:25:301105 if (transaction_nesting_ > 0) {
1106 transaction_nesting_ = 0;
1107 DoRollback();
1108 }
1109}
1110
Victor Costancfbfa602018-08-01 23:24:461111bool Database::AttachDatabase(const base::FilePath& other_db_path,
1112 const char* attachment_point,
1113 InternalApiToken) {
Etienne Bergeron6cb35c72020-02-12 18:09:481114 TRACE_EVENT0("sql", "Database::AttachDatabase");
1115
[email protected]8d409412013-07-19 18:25:301116 DCHECK(ValidAttachmentPoint(attachment_point));
1117
1118 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1119#if OS_WIN
Jan Wilken Dörrie9720dce2020-07-21 17:14:231120 s.BindString16(0, base::AsStringPiece16(other_db_path.value()));
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181121#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberibd1301f2018-05-18 21:00:091122 s.BindString(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181123#else
1124#error Unsupported platform
[email protected]8d409412013-07-19 18:25:301125#endif
1126 s.BindString(1, attachment_point);
1127 return s.Run();
1128}
1129
Victor Costancfbfa602018-08-01 23:24:461130bool Database::DetachDatabase(const char* attachment_point, InternalApiToken) {
Etienne Bergeron6cb35c72020-02-12 18:09:481131 TRACE_EVENT0("sql", "Database::DetachDatabase");
1132
[email protected]8d409412013-07-19 18:25:301133 DCHECK(ValidAttachmentPoint(attachment_point));
1134
1135 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1136 s.BindString(0, attachment_point);
1137 return s.Run();
1138}
1139
shess58b8df82015-06-03 00:19:321140// TODO(shess): Consider changing this to execute exactly one statement. If a
1141// caller wishes to execute multiple statements, that should be explicit, and
1142// perhaps tucked into an explicit transaction with rollback in case of error.
Victor Costancfbfa602018-08-01 23:24:461143int Database::ExecuteAndReturnErrorCode(const char* sql) {
Etienne Bergeron6cb35c72020-02-12 18:09:481144 TRACE_EVENT0("sql", "Database::ExecuteAndReturnErrorCode");
1145
Victor Costan5e785e32019-02-26 20:39:311146 DCHECK(sql);
Etienne Pierre-Doraya71d7af2019-02-07 02:07:541147
[email protected]41a97c812013-02-07 02:35:381148 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461149 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381150 return SQLITE_ERROR;
1151 }
shess58b8df82015-06-03 00:19:321152
Victor Costan5e785e32019-02-26 20:39:311153 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:201154 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
Victor Costan5e785e32019-02-26 20:39:311155
shess58b8df82015-06-03 00:19:321156 int rc = SQLITE_OK;
1157 while ((rc == SQLITE_OK) && *sql) {
Victor Costanf37f7ae2019-04-11 19:26:121158 sqlite3_stmt* sqlite_statement;
Victor Costancfbfa602018-08-01 23:24:461159 const char* leftover_sql;
Victor Costanf37f7ae2019-04-11 19:26:121160 rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0,
1161 &sqlite_statement, &leftover_sql);
shess58b8df82015-06-03 00:19:321162 // Stop if an error is encountered.
1163 if (rc != SQLITE_OK)
1164 break;
1165
Victor Costanf37f7ae2019-04-11 19:26:121166 sql = leftover_sql;
1167
shess58b8df82015-06-03 00:19:321168 // This happens if |sql| originally only contained comments or whitespace.
1169 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1170 // extraneous comments and whitespace in the SQL statements increases
1171 // runtime cost and can easily be shifted out to the C++ layer.
Victor Costanf37f7ae2019-04-11 19:26:121172 if (!sqlite_statement)
shess58b8df82015-06-03 00:19:321173 continue;
1174
Victor Costanf37f7ae2019-04-11 19:26:121175 while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
shess58b8df82015-06-03 00:19:321176 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
Victor Costan5e785e32019-02-26 20:39:311177 // is the only legitimate case for this. Previously recorded histograms
1178 // show significant use of this code path.
shess58b8df82015-06-03 00:19:321179 }
1180
1181 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1182 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
Victor Costanf37f7ae2019-04-11 19:26:121183 rc = sqlite3_finalize(sqlite_statement);
shess58b8df82015-06-03 00:19:321184
1185 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1186 // trailing whitespace.
1187 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021188 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321189 sql++;
1190 }
shess58b8df82015-06-03 00:19:321191 }
shess7dbd4dee2015-10-06 17:39:161192
1193 // Most calls to Execute() modify the database. The main exceptions would be
1194 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1195 // but sometimes don't.
1196 ReleaseCacheMemoryIfNeeded(true);
1197
shess58b8df82015-06-03 00:19:321198 return rc;
[email protected]eff1fa522011-12-12 23:50:591199}
1200
Victor Costancfbfa602018-08-01 23:24:461201bool Database::Execute(const char* sql) {
Etienne Bergeron6cb35c72020-02-12 18:09:481202 TRACE_EVENT1("sql", "Database::Execute", "query", TRACE_STR_COPY(sql));
1203
[email protected]41a97c812013-02-07 02:35:381204 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461205 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381206 return false;
1207 }
1208
[email protected]eff1fa522011-12-12 23:50:591209 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001210 if (error != SQLITE_OK)
Victor Costanbd623112018-07-18 04:17:271211 error = OnSqliteError(error, nullptr, sql);
[email protected]473ad792012-11-10 00:55:001212
[email protected]28fe0ff2012-02-25 00:40:331213 // This needs to be a FATAL log because the error case of arriving here is
1214 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101215 // a change alters the schema but not all queries adjust. This can happen
1216 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521217 DCHECK_NE(error, SQLITE_ERROR)
1218 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591219 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561220}
1221
Victor Costancfbfa602018-08-01 23:24:461222bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
Etienne Bergeron6cb35c72020-02-12 18:09:481223 TRACE_EVENT0("sql", "Database::ExecuteWithTimeout");
1224
[email protected]41a97c812013-02-07 02:35:381225 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461226 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]5b96f3772010-09-28 16:30:571227 return false;
[email protected]41a97c812013-02-07 02:35:381228 }
[email protected]5b96f3772010-09-28 16:30:571229
1230 ScopedBusyTimeout busy_timeout(db_);
1231 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591232 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571233}
1234
Victor Costancfbfa602018-08-01 23:24:461235scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
Victor Costan12daa3ac92018-07-19 01:05:581236 StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:561237 const char* sql) {
Victor Costanc7e7f2e2018-07-18 20:07:551238 auto it = statement_cache_.find(id);
1239 if (it != statement_cache_.end()) {
Victor Costan613b4302018-11-20 05:32:431240 // Statement is in the cache. It should still be valid. We're the only
1241 // entity invalidating cached statements, and we remove them from the cache
Victor Costan87cf8c72018-07-19 19:36:041242 // when we do that.
Victor Costanc7e7f2e2018-07-18 20:07:551243 DCHECK(it->second->is_valid());
Victor Costan613b4302018-11-20 05:32:431244 DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
Victor Costan87cf8c72018-07-19 19:36:041245 << "GetCachedStatement used with same ID but different SQL";
1246
1247 // Reset the statement so it can be reused.
Victor Costanc7e7f2e2018-07-18 20:07:551248 sqlite3_reset(it->second->stmt());
1249 return it->second;
[email protected]e5ffd0e42009-09-11 21:30:561250 }
1251
1252 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
Victor Costan613b4302018-11-20 05:32:431253 if (statement->is_valid()) {
[email protected]e5ffd0e42009-09-11 21:30:561254 statement_cache_[id] = statement; // Only cache valid statements.
Victor Costan613b4302018-11-20 05:32:431255 DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
1256 << "Input SQL does not match SQLite's normalized version";
1257 }
[email protected]e5ffd0e42009-09-11 21:30:561258 return statement;
1259}
1260
Victor Costancfbfa602018-08-01 23:24:461261scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
[email protected]e5ffd0e42009-09-11 21:30:561262 const char* sql) {
shess9e77283d2016-06-13 23:53:201263 return GetStatementImpl(this, sql);
1264}
1265
Victor Costancfbfa602018-08-01 23:24:461266scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1267 sql::Database* tracking_db,
1268 const char* sql) const {
shess9e77283d2016-06-13 23:53:201269 DCHECK(sql);
Victor Costan87cf8c72018-07-19 19:36:041270 DCHECK(!tracking_db || tracking_db == this);
[email protected]35f7e5392012-07-27 19:54:501271
[email protected]41a97c812013-02-07 02:35:381272 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561273 if (!db_)
Victor Costan3b02cdf2018-07-18 00:39:561274 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561275
Victor Costan5e785e32019-02-26 20:39:311276 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:201277 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
Victor Costan5e785e32019-02-26 20:39:311278
Victor Costanf37f7ae2019-04-11 19:26:121279 // TODO(pwnall): Cached statements (but not unique statements) should be
1280 // prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT.
1281 sqlite3_stmt* sqlite_statement;
1282 int rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0,
1283 &sqlite_statement, /* pzTail= */ nullptr);
[email protected]473ad792012-11-10 00:55:001284 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591285 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521286 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001287
1288 // It could also be database corruption.
Victor Costanbd623112018-07-18 04:17:271289 OnSqliteError(rc, nullptr, sql);
Victor Costan3b02cdf2018-07-18 00:39:561290 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
[email protected]e5ffd0e42009-09-11 21:30:561291 }
Victor Costanf37f7ae2019-04-11 19:26:121292 return base::MakeRefCounted<StatementRef>(tracking_db, sqlite_statement,
1293 true);
[email protected]e5ffd0e42009-09-11 21:30:561294}
1295
Victor Costancfbfa602018-08-01 23:24:461296scoped_refptr<Database::StatementRef> Database::GetUntrackedStatement(
[email protected]2eec0a22012-07-24 01:59:581297 const char* sql) const {
Victor Costanbd623112018-07-18 04:17:271298 return GetStatementImpl(nullptr, sql);
[email protected]2eec0a22012-07-24 01:59:581299}
1300
Victor Costancfbfa602018-08-01 23:24:461301std::string Database::GetSchema() const {
[email protected]92cd00a2013-08-16 11:09:581302 // The ORDER BY should not be necessary, but relying on organic
1303 // order for something like this is questionable.
Victor Costan87cf8c72018-07-19 19:36:041304 static const char kSql[] =
[email protected]92cd00a2013-08-16 11:09:581305 "SELECT type, name, tbl_name, sql "
1306 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1307 Statement statement(GetUntrackedStatement(kSql));
1308
1309 std::string schema;
1310 while (statement.Step()) {
1311 schema += statement.ColumnString(0);
1312 schema += '|';
1313 schema += statement.ColumnString(1);
1314 schema += '|';
1315 schema += statement.ColumnString(2);
1316 schema += '|';
1317 schema += statement.ColumnString(3);
1318 schema += '\n';
1319 }
1320
1321 return schema;
1322}
1323
Victor Costancfbfa602018-08-01 23:24:461324bool Database::IsSQLValid(const char* sql) {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:541325 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:201326 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
[email protected]41a97c812013-02-07 02:35:381327 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461328 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381329 return false;
1330 }
1331
Victor Costanf37f7ae2019-04-11 19:26:121332 sqlite3_stmt* sqlite_statement = nullptr;
1333 if (sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0,
1334 &sqlite_statement,
1335 /* pzTail= */ nullptr) != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591336 return false;
Victor Costanf37f7ae2019-04-11 19:26:121337 }
[email protected]eff1fa522011-12-12 23:50:591338
Victor Costanf37f7ae2019-04-11 19:26:121339 sqlite3_finalize(sqlite_statement);
[email protected]eff1fa522011-12-12 23:50:591340 return true;
1341}
1342
Victor Costancfbfa602018-08-01 23:24:461343bool Database::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121344 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531345}
1346
Victor Costancfbfa602018-08-01 23:24:461347bool Database::DoesTableExist(const char* table_name) const {
shessa62504d2016-11-07 19:26:121348 return DoesSchemaItemExist(table_name, "table");
1349}
1350
Victor Costancfbfa602018-08-01 23:24:461351bool Database::DoesViewExist(const char* view_name) const {
shessa62504d2016-11-07 19:26:121352 return DoesSchemaItemExist(view_name, "view");
1353}
1354
Victor Costancfbfa602018-08-01 23:24:461355bool Database::DoesSchemaItemExist(const char* name, const char* type) const {
Victor Costanf85512e52019-04-10 20:51:361356 static const char kSql[] =
1357 "SELECT 1 FROM sqlite_master WHERE type=? AND name=?";
[email protected]2eec0a22012-07-24 01:59:581358 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471359
Victor Costanf85512e52019-04-10 20:51:361360 if (!statement.is_valid()) {
1361 // The database is corrupt.
shess92a2ab12015-04-09 01:59:471362 return false;
Victor Costanf85512e52019-04-10 20:51:361363 }
shess92a2ab12015-04-09 01:59:471364
[email protected]e2cadec82011-12-13 02:00:531365 statement.BindString(0, type);
1366 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331367
[email protected]e5ffd0e42009-09-11 21:30:561368 return statement.Step(); // Table exists if any row was returned.
1369}
1370
Victor Costancfbfa602018-08-01 23:24:461371bool Database::DoesColumnExist(const char* table_name,
1372 const char* column_name) const {
Victor Costan1ff47e92018-12-07 11:10:431373 // sqlite3_table_column_metadata uses out-params to return column definition
1374 // details, such as the column type and whether it allows NULL values. These
1375 // aren't needed to compute the current method's result, so we pass in nullptr
1376 // for all the out-params.
1377 int error = sqlite3_table_column_metadata(
1378 db_, "main", table_name, column_name, /* pzDataType= */ nullptr,
1379 /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr,
1380 /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr);
1381 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561382}
1383
Victor Costancfbfa602018-08-01 23:24:461384int64_t Database::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561385 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461386 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]e5ffd0e42009-09-11 21:30:561387 return 0;
1388 }
1389 return sqlite3_last_insert_rowid(db_);
1390}
1391
Victor Costancfbfa602018-08-01 23:24:461392int Database::GetLastChangeCount() const {
[email protected]1ed78a32009-09-15 20:24:171393 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461394 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]1ed78a32009-09-15 20:24:171395 return 0;
1396 }
1397 return sqlite3_changes(db_);
1398}
1399
Victor Costancfbfa602018-08-01 23:24:461400int Database::GetErrorCode() const {
[email protected]e5ffd0e42009-09-11 21:30:561401 if (!db_)
1402 return SQLITE_ERROR;
1403 return sqlite3_errcode(db_);
1404}
1405
Victor Costancfbfa602018-08-01 23:24:461406int Database::GetLastErrno() const {
[email protected]767718e52010-09-21 23:18:491407 if (!db_)
1408 return -1;
1409
1410 int err = 0;
Victor Costanbd623112018-07-18 04:17:271411 if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
[email protected]767718e52010-09-21 23:18:491412 return -2;
1413
1414 return err;
1415}
1416
Victor Costancfbfa602018-08-01 23:24:461417const char* Database::GetErrorMessage() const {
[email protected]e5ffd0e42009-09-11 21:30:561418 if (!db_)
Victor Costancfbfa602018-08-01 23:24:461419 return "sql::Database is not opened.";
[email protected]e5ffd0e42009-09-11 21:30:561420 return sqlite3_errmsg(db_);
1421}
1422
Victor Costancfbfa602018-08-01 23:24:461423bool Database::OpenInternal(const std::string& file_name,
1424 Database::Retry retry_flag) {
Etienne Bergeron6cb35c72020-02-12 18:09:481425 TRACE_EVENT1("sql", "Database::OpenInternal", "path", file_name);
1426
[email protected]9cfbc922009-11-17 20:13:171427 if (db_) {
Victor Costancfbfa602018-08-01 23:24:461428 DLOG(DCHECK) << "sql::Database is already open.";
[email protected]9cfbc922009-11-17 20:13:171429 return false;
1430 }
1431
Victor Costan5e785e32019-02-26 20:39:311432 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
Etienne Bergerone7681c72020-01-17 00:51:201433 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
Victor Costan5e785e32019-02-26 20:39:311434
Victor Costan3653df62018-02-08 21:38:161435 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181436
shess58b8df82015-06-03 00:19:321437 // Setup the stats histograms immediately rather than allocating lazily.
Victor Costancfbfa602018-08-01 23:24:461438 // Databases which won't exercise all of these probably shouldn't exist.
shess58b8df82015-06-03 00:19:321439 if (!histogram_tag_.empty()) {
Victor Costancfbfa602018-08-01 23:24:461440 stats_histogram_ = base::LinearHistogram::FactoryGet(
Victor Costanb0e7fc02019-03-01 03:36:271441 "Sqlite.Stats2." + histogram_tag_, 1, EVENT_MAX_VALUE,
Victor Costancfbfa602018-08-01 23:24:461442 EVENT_MAX_VALUE + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
shess58b8df82015-06-03 00:19:321443 }
1444
[email protected]41a97c812013-02-07 02:35:381445 // If |poisoned_| is set, it means an error handler called
1446 // RazeAndClose(). Until regular Close() is called, the caller
1447 // should be treating the database as open, but is_open() currently
1448 // only considers the sqlite3 handle's state.
1449 // TODO(shess): Revise is_open() to consider poisoned_, and review
1450 // to see if any non-testing code even depends on it.
Victor Costancfbfa602018-08-01 23:24:461451 DCHECK(!poisoned_) << "sql::Database is already open.";
[email protected]7bae5742013-07-10 20:46:161452 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381453
shess5f2c3442017-01-24 02:15:101454 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1455 sqlite3_vfs* vfs = VFSWrapper();
1456 const char* vfs_name = (vfs ? vfs->zName : nullptr);
Victor Costanc6d3a862018-11-20 18:41:231457
1458 // The flags are documented at https://www.sqlite.org/c3ref/open.html.
1459 //
1460 // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
1461 // disparate features with their own databases, and having separate page
1462 // caches makes it easier to reason about each feature's performance in
1463 // isolation.
1464 int err = sqlite3_open_v2(
1465 file_name.c_str(), &db_,
1466 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_PRIVATECACHE,
1467 vfs_name);
[email protected]765b44502009-10-02 05:01:421468 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281469 // Extended error codes cannot be enabled until a handle is
1470 // available, fetch manually.
1471 err = sqlite3_extended_errcode(db_);
1472
[email protected]bd2ccdb4a2012-12-07 22:14:501473 // Histogram failures specific to initial open for debugging
1474 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181475 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501476
Victor Costanbd623112018-07-18 04:17:271477 OnSqliteError(err, nullptr, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131478 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291479 Close();
[email protected]fed734a2013-07-17 04:45:131480
1481 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1482 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421483 return false;
1484 }
1485
Shubham Aggarwalbe4f97ce2020-06-19 15:58:571486 // If indicated, lock up the database before doing anything else, so
1487 // that the following code doesn't have to deal with locking.
1488 //
1489 // Needs to happen before any other operation is performed in WAL mode so that
1490 // no operation relies on shared memory if exclusive locking is turned on.
1491 //
1492 // TODO(shess): This code is brittle. Find the cases where code
1493 // doesn't request |exclusive_locking_| and audit that it does the
1494 // right thing with SQLITE_BUSY, and that it doesn't make
1495 // assumptions about who might change things in the database.
1496 // http://crbug.com/56559
1497 if (exclusive_locking_) {
1498 // TODO(shess): This should probably be a failure. Code which
1499 // requests exclusive locking but doesn't get it is almost certain
1500 // to be ill-tested.
1501 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
1502 }
1503
[email protected]73fb8d52013-07-24 05:04:281504 // Enable extended result codes to provide more color on I/O errors.
1505 // Not having extended result codes is not a fatal problem, as
1506 // Chromium code does not attempt to handle I/O errors anyhow. The
1507 // current implementation always returns SQLITE_OK, the DCHECK is to
1508 // quickly notify someone if SQLite changes.
1509 err = sqlite3_extended_result_codes(db_, 1);
1510 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1511
shessbccd300e2016-08-20 00:06:561512 // sqlite3_open() does not actually read the database file (unless a hot
1513 // journal is found). Successfully executing this pragma on an existing
1514 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1515 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501516 // TODO(shess): For now, just probing to see what the lay of the
1517 // land is. If it's mostly SQLITE_NOTADB, then the database should
1518 // be razed.
1519 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561520 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181521 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561522 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1523
1524 // Retry or bail out if the error handler poisoned the handle.
Victor Costanf1e9443b2018-12-05 04:35:531525 // TODO(shess): Move this handling to one place (see also sqlite3_open).
1526 // Possibly a wrapper function?
shessbccd300e2016-08-20 00:06:561527 if (poisoned_) {
1528 Close();
1529 if (retry_flag == RETRY_ON_POISON)
1530 return OpenInternal(file_name, NO_RETRY);
1531 return false;
1532 }
1533 }
[email protected]658f8332010-09-18 04:40:431534
Shubham Aggarwalbe4f97ce2020-06-19 15:58:571535 const base::TimeDelta kBusyTimeout =
1536 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1537
1538 // Needs to happen before entering WAL mode. Will only work if this the first
1539 // time the database is being opened in WAL mode.
1540 const std::string page_size_sql =
1541 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1542 ignore_result(ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout));
[email protected]5b96f3772010-09-28 16:30:571543
[email protected]4e179ba62012-03-17 16:06:471544 // http://www.sqlite.org/pragma.html#pragma_journal_mode
Shubham Aggarwalbe4f97ce2020-06-19 15:58:571545 // WAL - Use a write-ahead log instead of a journal file.
[email protected]4e179ba62012-03-17 16:06:471546 // DELETE (default) - delete -journal file to commit.
1547 // TRUNCATE - truncate -journal file to commit.
1548 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091549 // TRUNCATE should be faster than DELETE because it won't need directory
1550 // changes for each transaction. PERSIST may break the spirit of using
1551 // secure_delete.
Shubham Aggarwalbe4f97ce2020-06-19 15:58:571552 //
1553 // Needs to be performed after setting exclusive locking mode. Otherwise can
1554 // fail if underlying VFS doesn't support shared memory.
1555 if (UseWALMode()) {
1556 // Set the synchronous flag to NORMAL. This means that writers don't flush
1557 // the WAL file after every write. The WAL file is only flushed on a
1558 // checkpoint. In this case, transcations might lose durability on a power
1559 // loss (but still durable after an application crash).
1560 // TODO([email protected]): Evaluate if this loss of durability is a
1561 // concern.
1562 ignore_result(Execute("PRAGMA synchronous=NORMAL"));
[email protected]4e179ba62012-03-17 16:06:471563
Shubham Aggarwalbe4f97ce2020-06-19 15:58:571564 // Opening the db in WAL mode can fail (eg if the underlying VFS doesn't
1565 // support shared memory and we are not in exclusive locking mode).
1566 //
1567 // TODO([email protected]): We should probably catch a failure here.
1568 ignore_result(Execute("PRAGMA journal_mode=WAL"));
1569 } else {
1570 ignore_result(Execute("PRAGMA journal_mode=TRUNCATE"));
1571 }
[email protected]765b44502009-10-02 05:01:421572
1573 if (cache_size_ != 0) {
Victor Costancfbfa602018-08-01 23:24:461574 const std::string cache_size_sql =
[email protected]7d3cbc92013-03-18 22:33:041575 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
Victor Costancfbfa602018-08-01 23:24:461576 ignore_result(ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421577 }
1578
Victor Costanf1e9443b2018-12-05 04:35:531579 static_assert(SQLITE_SECURE_DELETE == 1,
1580 "Chrome assumes secure_delete is on by default.");
[email protected]6e0b1442011-08-09 23:23:581581
shess5dac334f2015-11-05 20:47:421582 // Set a reasonable chunk size for larger files. This reduces churn from
1583 // remapping memory on size changes. It also reduces filesystem
1584 // fragmentation.
1585 // TODO(shess): It may make sense to have this be hinted by the client.
1586 // Database sizes seem to be bimodal, some clients have consistently small
1587 // databases (<20k) while other clients have a broad distribution of sizes
1588 // (hundreds of kilobytes to many megabytes).
Victor Costanbd623112018-07-18 04:17:271589 sqlite3_file* file = nullptr;
shess5dac334f2015-11-05 20:47:421590 sqlite3_int64 db_size = 0;
1591 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1592 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1593 int chunk_size = 4 * 1024;
1594 if (db_size > 128 * 1024)
1595 chunk_size = 32 * 1024;
Victor Costanbd623112018-07-18 04:17:271596 sqlite3_file_control(db_, nullptr, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
shess5dac334f2015-11-05 20:47:421597 }
1598
shess2f3a814b2015-11-05 18:11:101599 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311600 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1601 // safe range to memory-map based on past regular I/O. This value will be
1602 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1603 // 64-bit platforms.
1604 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1605 std::string mmap_sql =
Victor Costan4c2f3e922018-08-21 04:47:591606 base::StringPrintf("PRAGMA mmap_size=%" PRIuS, mmap_size);
shessd90aeea82015-11-13 02:24:311607 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101608
1609 // Determine if memory-mapping has actually been enabled. The Execute() above
1610 // can succeed without changing the amount mapped.
1611 mmap_enabled_ = false;
1612 {
1613 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1614 if (s.Step() && s.ColumnInt64(0) > 0)
1615 mmap_enabled_ = true;
1616 }
1617
ssid3be5b1ec2016-01-13 14:21:571618 DCHECK(!memory_dump_provider_);
1619 memory_dump_provider_.reset(
Victor Costancfbfa602018-08-01 23:24:461620 new DatabaseMemoryDumpProvider(db_, histogram_tag_));
ssid3be5b1ec2016-01-13 14:21:571621 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
Victor Costancfbfa602018-08-01 23:24:461622 memory_dump_provider_.get(), "sql::Database", nullptr);
ssid3be5b1ec2016-01-13 14:21:571623
[email protected]765b44502009-10-02 05:01:421624 return true;
1625}
1626
Victor Costancfbfa602018-08-01 23:24:461627void Database::DoRollback() {
Etienne Bergeron6cb35c72020-02-12 18:09:481628 TRACE_EVENT0("sql", "Database::DoRollback");
1629
[email protected]e5ffd0e42009-09-11 21:30:561630 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321631
Victor Costan5e785e32019-02-26 20:39:311632 rollback.Run();
shess58b8df82015-06-03 00:19:321633
shess7dbd4dee2015-10-06 17:39:161634 // The cache may have been accumulating dirty pages for commit. Note that in
1635 // some cases sql::Transaction can fire rollback after a database is closed.
1636 if (is_open())
1637 ReleaseCacheMemoryIfNeeded(false);
1638
[email protected]44ad7d902012-03-23 00:09:051639 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561640}
1641
Victor Costancfbfa602018-08-01 23:24:461642void Database::StatementRefCreated(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551643 DCHECK(!open_statements_.count(ref))
1644 << __func__ << " already called with this statement";
[email protected]e5ffd0e42009-09-11 21:30:561645 open_statements_.insert(ref);
1646}
1647
Victor Costancfbfa602018-08-01 23:24:461648void Database::StatementRefDeleted(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551649 DCHECK(open_statements_.count(ref))
1650 << __func__ << " called with non-existing statement";
1651 open_statements_.erase(ref);
[email protected]e5ffd0e42009-09-11 21:30:561652}
1653
Victor Costancfbfa602018-08-01 23:24:461654void Database::set_histogram_tag(const std::string& tag) {
shess58b8df82015-06-03 00:19:321655 DCHECK(!is_open());
Victor Costan87cf8c72018-07-19 19:36:041656
shess58b8df82015-06-03 00:19:321657 histogram_tag_ = tag;
1658}
1659
Will Harrisb8693592018-08-28 22:58:441660void Database::AddTaggedHistogram(const std::string& name, int sample) const {
[email protected]210ce0af2013-05-15 09:10:391661 if (histogram_tag_.empty())
1662 return;
1663
1664 // TODO(shess): The histogram macros create a bit of static storage
1665 // for caching the histogram object. This code shouldn't execute
1666 // often enough for such caching to be crucial. If it becomes an
1667 // issue, the object could be cached alongside histogram_prefix_.
1668 std::string full_histogram_name = name + "." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:461669 base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
1670 full_histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]210ce0af2013-05-15 09:10:391671 if (histogram)
1672 histogram->Add(sample);
1673}
1674
Victor Costancfbfa602018-08-01 23:24:461675int Database::OnSqliteError(int err,
1676 sql::Statement* stmt,
1677 const char* sql) const {
Etienne Bergeron6cb35c72020-02-12 18:09:481678 TRACE_EVENT0("sql", "Database::OnSqliteError");
1679
Ilya Sherman1c811db2017-12-14 10:36:181680 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391681 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141682
1683 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581684 if (!sql && stmt)
1685 sql = stmt->GetSQLStatement();
1686 if (!sql)
1687 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061688
1689 std::string id = histogram_tag_;
1690 if (id.empty())
1691 id = DbPath().BaseName().AsUTF8Unsafe();
Victor Costancfbfa602018-08-01 23:24:461692 LOG(ERROR) << id << " sqlite error " << err << ", errno " << GetLastErrno()
1693 << ": " << GetErrorMessage() << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141694
[email protected]c3881b372013-05-17 08:39:461695 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561696 // Fire from a copy of the callback in case of reentry into
1697 // re/set_error_callback().
1698 // TODO(shess): <http://crbug.com/254584>
1699 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461700 return err;
1701 }
1702
[email protected]faa604e2009-09-25 22:38:591703 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251704 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521705 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591706 return err;
1707}
1708
Victor Costancfbfa602018-08-01 23:24:461709bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
[email protected]579446c2013-12-16 18:36:521710 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1711}
1712
Victor Costancfbfa602018-08-01 23:24:461713bool Database::QuickIntegrityCheck() {
[email protected]579446c2013-12-16 18:36:521714 std::vector<std::string> messages;
1715 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1716 return false;
1717 return messages.size() == 1 && messages[0] == "ok";
1718}
1719
Victor Costancfbfa602018-08-01 23:24:461720std::string Database::GetDiagnosticInfo(int extended_error,
1721 Statement* statement) {
afakhry7c9abe72016-08-05 17:33:191722 // Prevent reentrant calls to the error callback.
1723 ErrorCallback original_callback = std::move(error_callback_);
1724 reset_error_callback();
1725
1726 // Trim extended error codes.
1727 const int error = (extended_error & 0xFF);
Victor Costancfbfa602018-08-01 23:24:461728 // CollectCorruptionInfo() is implemented in terms of sql::Database,
afakhry7c9abe72016-08-05 17:33:191729 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1730 std::string result = (error == SQLITE_CORRUPT)
1731 ? CollectCorruptionInfo()
1732 : CollectErrorInfo(extended_error, statement);
1733
1734 // The following queries must be executed after CollectErrorInfo() above, so
1735 // if they result in their own errors, they don't interfere with
1736 // CollectErrorInfo().
1737 const bool has_valid_header =
1738 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1739 const bool select_sqlite_master_result =
1740 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1741 SQLITE_OK);
1742
1743 // Restore the original error callback.
1744 error_callback_ = std::move(original_callback);
1745
1746 base::StringAppendF(&result, "Has valid header: %s\n",
1747 (has_valid_header ? "Yes" : "No"));
1748 base::StringAppendF(&result, "Has valid schema: %s\n",
1749 (select_sqlite_master_result ? "Yes" : "No"));
1750
1751 return result;
1752}
1753
[email protected]80abf152013-05-22 12:42:421754// TODO(shess): Allow specifying maximum results (default 100 lines).
Victor Costancfbfa602018-08-01 23:24:461755bool Database::IntegrityCheckHelper(const char* pragma_sql,
1756 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421757 messages->clear();
1758
[email protected]4658e2a02013-06-06 23:05:001759 // This has the side effect of setting SQLITE_RecoveryMode, which
1760 // allows SQLite to process through certain cases of corruption.
1761 // Failing to set this pragma probably means that the database is
1762 // beyond recovery.
Victor Costan4c2f3e922018-08-21 04:47:591763 static const char kWritableSchemaSql[] = "PRAGMA writable_schema=ON";
Victor Costan1d868352018-06-26 19:06:481764 if (!Execute(kWritableSchemaSql))
[email protected]4658e2a02013-06-06 23:05:001765 return false;
1766
1767 bool ret = false;
1768 {
[email protected]579446c2013-12-16 18:36:521769 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001770
1771 // The pragma appears to return all results (up to 100 by default)
1772 // as a single string. This doesn't appear to be an API contract,
1773 // it could return separate lines, so loop _and_ split.
1774 while (stmt.Step()) {
1775 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181776 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1777 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001778 }
1779 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421780 }
[email protected]4658e2a02013-06-06 23:05:001781
1782 // Best effort to put things back as they were before.
Victor Costan4c2f3e922018-08-21 04:47:591783 static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema=OFF";
Victor Costan1d868352018-06-26 19:06:481784 ignore_result(Execute(kNoWritableSchemaSql));
[email protected]4658e2a02013-06-06 23:05:001785
1786 return ret;
[email protected]80abf152013-05-22 12:42:421787}
1788
Victor Costancfbfa602018-08-01 23:24:461789bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1790 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131791 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381792 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131793}
1794
Shubham Aggarwalbe4f97ce2020-06-19 15:58:571795bool Database::UseWALMode() const {
1796#if defined(OS_FUCHSIA)
1797 // WAL mode is only enabled on Fuchsia for databases with exclusive
1798 // locking, because this case does not require shared memory support.
1799 // At the time this was implemented (May 2020), Fuchsia's shared
1800 // memory support was insufficient for SQLite's needs.
1801 return want_wal_mode_ && exclusive_locking_;
1802#else
1803 return want_wal_mode_;
1804#endif // defined(OS_FUCHSIA)
1805}
1806
1807bool Database::CheckpointDatabase() {
1808 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
1809 InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
1810
1811 static const char* kMainDb = "main";
1812 int rc = sqlite3_wal_checkpoint_v2(db_, kMainDb, SQLITE_CHECKPOINT_PASSIVE,
1813 /*pnLog=*/nullptr,
1814 /*pnCkpt=*/nullptr);
1815
1816 return rc == SQLITE_OK;
1817}
1818
[email protected]e5ffd0e42009-09-11 21:30:561819} // namespace sql