blob: 964fd61e87eb4c0939a69e1f599783be3767accc [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
[email protected]57999812013-02-24 05:40:5212#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4413#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4614#include "base/format_macros.h"
fdoray2dfa76452016-06-07 13:11:2215#include "base/location.h"
[email protected]e5ffd0e42009-09-11 21:30:5616#include "base/logging.h"
Ilya Sherman1c811db2017-12-14 10:36:1817#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0818#include "base/metrics/histogram_macros.h"
[email protected]210ce0af2013-05-15 09:10:3919#include "base/metrics/sparse_histogram.h"
Victor Costan3653df62018-02-08 21:38:1620#include "base/no_destructor.h"
Will Harrisb8693592018-08-28 22:58:4421#include "base/numerics/safe_conversions.h"
fdoray2dfa76452016-06-07 13:11:2222#include "base/single_thread_task_runner.h"
[email protected]80abf152013-05-22 12:42:4223#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1924#include "base/strings/string_util.h"
25#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4526#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1827#include "base/synchronization/lock.h"
Etienne Pierre-Doray0400dfb62018-12-03 19:12:2528#include "base/threading/scoped_blocking_call.h"
ssid9f8022f2015-10-12 17:49:0329#include "base/trace_event/memory_dump_manager.h"
Kevin Marshalla9f05ec2017-07-14 02:10:0530#include "build/build_config.h"
Victor Costancfbfa602018-08-01 23:24:4631#include "sql/database_memory_dump_provider.h"
Victor Costan3653df62018-02-08 21:38:1632#include "sql/initialization.h"
shess9bf2c672015-12-18 01:18:0833#include "sql/meta_table.h"
Victor Costan3ffd9a372019-05-22 00:46:5434#include "sql/sql_features.h"
[email protected]f0a54b22011-07-19 18:40:2135#include "sql/statement.h"
shess5f2c3442017-01-24 02:15:1036#include "sql/vfs_wrapper.h"
[email protected]e33cba42010-08-18 23:37:0337#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5638
[email protected]5b96f3772010-09-28 16:30:5739namespace {
40
41// Spin for up to a second waiting for the lock to clear when setting
42// up the database.
43// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2744const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5745
46class ScopedBusyTimeout {
47 public:
Victor Costancfbfa602018-08-01 23:24:4648 explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
49 ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
[email protected]5b96f3772010-09-28 16:30:5750
51 int SetTimeout(base::TimeDelta timeout) {
52 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
53 return sqlite3_busy_timeout(db_,
54 static_cast<int>(timeout.InMilliseconds()));
55 }
56
57 private:
58 sqlite3* db_;
59};
60
[email protected]6d42f152012-11-10 00:38:2461// Helper to "safely" enable writable_schema. No error checking
62// because it is reasonable to just forge ahead in case of an error.
63// If turning it on fails, then most likely nothing will work, whereas
64// if turning it off fails, it only matters if some code attempts to
65// continue working with the database and tries to modify the
66// sqlite_master table (none of our code does this).
67class ScopedWritableSchema {
68 public:
Victor Costancfbfa602018-08-01 23:24:4669 explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
Victor Costanbd623112018-07-18 04:17:2770 sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2471 }
72 ~ScopedWritableSchema() {
Victor Costanbd623112018-07-18 04:17:2773 sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2474 }
75
76 private:
77 sqlite3* db_;
78};
79
[email protected]7bae5742013-07-10 20:46:1680// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
81// SQLite error code from running the backup step.
82int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
83 DCHECK_NE(src, dst);
84 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
85 if (!backup) {
86 // Since this call only sets things up, this indicates a gross
87 // error in SQLite.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:5288 DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
[email protected]7bae5742013-07-10 20:46:1689 return sqlite3_errcode(dst);
90 }
91
92 // -1 backs up the entire database.
93 int rc = sqlite3_backup_step(backup, -1);
94 int pages = sqlite3_backup_pagecount(backup);
95 sqlite3_backup_finish(backup);
96
97 // If successful, exactly one page should have been backed up. If
98 // this breaks, check this function to make sure assumptions aren't
99 // being broken.
100 if (rc == SQLITE_DONE)
101 DCHECK_EQ(pages, 1);
102
103 return rc;
104}
105
[email protected]8d409412013-07-19 18:25:30106// Be very strict on attachment point. SQLite can handle a much wider
107// character set with appropriate quoting, but Chromium code should
108// just use clean names to start with.
109bool ValidAttachmentPoint(const char* attachment_point) {
110 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20111 if (!(base::IsAsciiDigit(attachment_point[i]) ||
112 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30113 attachment_point[i] == '_')) {
114 return false;
115 }
116 }
117 return true;
118}
119
[email protected]8ada10f2013-12-21 00:42:34120// Helper to get the sqlite3_file* associated with the "main" database.
121int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
Victor Costanbd623112018-07-18 04:17:27122 *file = nullptr;
123 int rc = sqlite3_file_control(db, nullptr, SQLITE_FCNTL_FILE_POINTER, file);
[email protected]8ada10f2013-12-21 00:42:34124 if (rc != SQLITE_OK)
125 return rc;
126
Victor Costanbd623112018-07-18 04:17:27127 // TODO(shess): null in file->pMethods has been observed on android_dbg
[email protected]8ada10f2013-12-21 00:42:34128 // content_unittests, even though it should not be possible.
129 // http://crbug.com/329982
130 if (!*file || !(*file)->pMethods)
131 return SQLITE_ERROR;
132
133 return rc;
134}
135
shess5dac334f2015-11-05 20:47:42136// Convenience to get the sqlite3_file* and the size for the "main" database.
137int GetSqlite3FileAndSize(sqlite3* db,
Victor Costancfbfa602018-08-01 23:24:46138 sqlite3_file** file,
139 sqlite3_int64* db_size) {
shess5dac334f2015-11-05 20:47:42140 int rc = GetSqlite3File(db, file);
141 if (rc != SQLITE_OK)
142 return rc;
143
144 return (*file)->pMethods->xFileSize(*file, db_size);
145}
146
erg102ceb412015-06-20 01:38:13147std::string AsUTF8ForSQL(const base::FilePath& path) {
148#if defined(OS_WIN)
jdoerrie6312bf62019-02-01 22:03:42149 return base::UTF16ToUTF8(path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18150#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
erg102ceb412015-06-20 01:38:13151 return path.value();
152#endif
153}
154
[email protected]5b96f3772010-09-28 16:30:57155} // namespace
156
[email protected]e5ffd0e42009-09-11 21:30:56157namespace sql {
158
[email protected]4350e322013-06-18 22:18:10159// static
Victor Costancfbfa602018-08-01 23:24:46160Database::ErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10161
162// static
Victor Costancfbfa602018-08-01 23:24:46163bool Database::IsExpectedSqliteError(int error) {
shess976814402016-06-21 06:56:25164 if (!current_expecter_cb_)
[email protected]4350e322013-06-18 22:18:10165 return false;
shess976814402016-06-21 06:56:25166 return current_expecter_cb_->Run(error);
[email protected]4350e322013-06-18 22:18:10167}
168
169// static
Victor Costancfbfa602018-08-01 23:24:46170void Database::SetErrorExpecter(Database::ErrorExpecterCallback* cb) {
Victor Costanbd623112018-07-18 04:17:27171 CHECK(!current_expecter_cb_);
shess976814402016-06-21 06:56:25172 current_expecter_cb_ = cb;
[email protected]4350e322013-06-18 22:18:10173}
174
175// static
Victor Costancfbfa602018-08-01 23:24:46176void Database::ResetErrorExpecter() {
shess976814402016-06-21 06:56:25177 CHECK(current_expecter_cb_);
Victor Costanbd623112018-07-18 04:17:27178 current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10179}
180
Victor Costance678e72018-07-24 10:25:00181// static
Victor Costancfbfa602018-08-01 23:24:46182base::FilePath Database::JournalPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00183 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
184}
185
186// static
Victor Costancfbfa602018-08-01 23:24:46187base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00188 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
189}
190
191// static
Victor Costancfbfa602018-08-01 23:24:46192base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00193 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
194}
195
Victor Costancfbfa602018-08-01 23:24:46196Database::StatementRef::StatementRef(Database* database,
197 sqlite3_stmt* stmt,
198 bool was_valid)
199 : database_(database), stmt_(stmt), was_valid_(was_valid) {
200 if (database)
201 database_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56202}
203
Victor Costancfbfa602018-08-01 23:24:46204Database::StatementRef::~StatementRef() {
205 if (database_)
206 database_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38207 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56208}
209
Victor Costancfbfa602018-08-01 23:24:46210void Database::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56211 if (stmt_) {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54212 // Call to InitScopedBlockingCall() cannot go at the beginning of the
213 // function because Close() is called unconditionally from destructor to
214 // clean database_. And if this is inactive statement this won't cause any
215 // disk access and destructor most probably will be called on thread not
216 // allowing disk access.
[email protected]35f7e5392012-07-27 19:54:50217 // TODO([email protected]): This should move to the beginning
218 // of the function. http://crbug.com/136655.
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54219 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
220 InitScopedBlockingCall(&scoped_blocking_call);
[email protected]e5ffd0e42009-09-11 21:30:56221 sqlite3_finalize(stmt_);
Victor Costanbd623112018-07-18 04:17:27222 stmt_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56223 }
Victor Costancfbfa602018-08-01 23:24:46224 database_ = nullptr; // The Database may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38225
226 // Forced close is expected to happen from a statement error
227 // handler. In that case maintain the sense of |was_valid_| which
228 // previously held for this ref.
229 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56230}
231
Victor Costan7f6abbbe2018-07-29 02:57:27232static_assert(
Victor Costancfbfa602018-08-01 23:24:46233 Database::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
234 "Database::kDefaultPageSize must match the value configured into SQLite");
Victor Costan7f6abbbe2018-07-29 02:57:27235
Victor Costancfbfa602018-08-01 23:24:46236constexpr int Database::kDefaultPageSize;
Victor Costan7f6abbbe2018-07-29 02:57:27237
Victor Costancfbfa602018-08-01 23:24:46238Database::Database()
Victor Costanbd623112018-07-18 04:17:27239 : db_(nullptr),
Victor Costan7f6abbbe2018-07-29 02:57:27240 page_size_(kDefaultPageSize),
[email protected]e5ffd0e42009-09-11 21:30:56241 cache_size_(0),
242 exclusive_locking_(false),
243 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50244 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16245 in_memory_(false),
shess58b8df82015-06-03 00:19:32246 poisoned_(false),
shessa62504d2016-11-07 19:26:12247 mmap_alt_status_(false),
kerz42ff2a012016-04-27 04:50:06248 mmap_disabled_(false),
shess7dbd4dee2015-10-06 17:39:16249 mmap_enabled_(false),
250 total_changes_at_last_release_(0),
Victor Costan5e785e32019-02-26 20:39:31251 stats_histogram_(nullptr) {}
[email protected]e5ffd0e42009-09-11 21:30:56252
Victor Costancfbfa602018-08-01 23:24:46253Database::~Database() {
[email protected]e5ffd0e42009-09-11 21:30:56254 Close();
255}
256
Victor Costancfbfa602018-08-01 23:24:46257void Database::RecordEvent(Events event, size_t count) {
shess58b8df82015-06-03 00:19:32258 for (size_t i = 0; i < count; ++i) {
Victor Costanb0e7fc02019-03-01 03:36:27259 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats2", event, EVENT_MAX_VALUE);
shess58b8df82015-06-03 00:19:32260 }
261
262 if (stats_histogram_) {
263 for (size_t i = 0; i < count; ++i) {
264 stats_histogram_->Add(event);
265 }
266 }
267}
268
Victor Costancfbfa602018-08-01 23:24:46269bool Database::Open(const base::FilePath& path) {
erg102ceb412015-06-20 01:38:13270 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42271}
[email protected]e5ffd0e42009-09-11 21:30:56272
Victor Costancfbfa602018-08-01 23:24:46273bool Database::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50274 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13275 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56276}
277
Victor Costancfbfa602018-08-01 23:24:46278bool Database::OpenTemporary() {
[email protected]8d409412013-07-19 18:25:30279 return OpenInternal("", NO_RETRY);
280}
281
Victor Costancfbfa602018-08-01 23:24:46282void Database::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47283 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
284 // will delete the -journal file. For ChromiumOS or other more
285 // embedded systems, this is probably not appropriate, whereas on
286 // desktop it might make some sense.
287
[email protected]4b350052012-02-24 20:40:48288 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48289
[email protected]41a97c812013-02-07 02:35:38290 // Release cached statements.
291 statement_cache_.clear();
292
293 // With cached statements released, in-use statements will remain.
294 // Closing the database while statements are in use is an API
295 // violation, except for forced close (which happens from within a
296 // statement's error handler).
297 DCHECK(forced || open_statements_.empty());
298
299 // Deactivate any outstanding statements so sqlite3_close() works.
Victor Costanc7e7f2e2018-07-18 20:07:55300 for (StatementRef* statement_ref : open_statements_)
301 statement_ref->Close(forced);
[email protected]41a97c812013-02-07 02:35:38302 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48303
[email protected]e5ffd0e42009-09-11 21:30:56304 if (db_) {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54305 // Call to InitScopedBlockingCall() cannot go at the beginning of the
306 // function because Close() must be called from destructor to clean
[email protected]35f7e5392012-07-27 19:54:50307 // statement_cache_, it won't cause any disk access and it most probably
308 // will happen on thread not allowing disk access.
309 // TODO([email protected]): This should move to the beginning
310 // of the function. http://crbug.com/136655.
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54311 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
312 InitScopedBlockingCall(&scoped_blocking_call);
[email protected]73fb8d52013-07-24 05:04:28313
ssid3be5b1ec2016-01-13 14:21:57314 // Reseting acquires a lock to ensure no dump is happening on the database
315 // at the same time. Unregister takes ownership of provider and it is safe
316 // since the db is reset. memory_dump_provider_ could be null if db_ was
317 // poisoned.
318 if (memory_dump_provider_) {
319 memory_dump_provider_->ResetDatabase();
320 base::trace_event::MemoryDumpManager::GetInstance()
321 ->UnregisterAndDeleteDumpProviderSoon(
322 std::move(memory_dump_provider_));
323 }
324
[email protected]73fb8d52013-07-24 05:04:28325 int rc = sqlite3_close(db_);
326 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18327 base::UmaHistogramSparse("Sqlite.CloseFailure", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52328 DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage();
[email protected]73fb8d52013-07-24 05:04:28329 }
[email protected]e5ffd0e42009-09-11 21:30:56330 }
Victor Costanbd623112018-07-18 04:17:27331 db_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56332}
333
Victor Costancfbfa602018-08-01 23:24:46334void Database::Close() {
[email protected]41a97c812013-02-07 02:35:38335 // If the database was already closed by RazeAndClose(), then no
336 // need to close again. Clear the |poisoned_| bit so that incorrect
337 // API calls are caught.
338 if (poisoned_) {
339 poisoned_ = false;
340 return;
341 }
342
343 CloseInternal(false);
344}
345
Victor Costancfbfa602018-08-01 23:24:46346void Database::Preload() {
Victor Costan3ffd9a372019-05-22 00:46:54347 if (base::FeatureList::IsEnabled(features::kSqlSkipPreload))
348 return;
349
[email protected]e5ffd0e42009-09-11 21:30:56350 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52351 DCHECK(poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56352 return;
353 }
354
Victor Costanb5a0a97002019-09-08 04:55:15355 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
356 InitScopedBlockingCall(&scoped_blocking_call);
357
Victor Costan7f6abbbe2018-07-29 02:57:27358 // The constructor and set_page_size() ensure that page_size_ is never zero.
359 const int page_size = page_size_;
360 DCHECK(page_size);
361
[email protected]8ada10f2013-12-21 00:42:34362 // Use local settings if provided, otherwise use documented defaults. The
363 // actual results could be fetching via PRAGMA calls.
[email protected]8ada10f2013-12-21 00:42:34364 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
365 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56366 return;
367
Victor Costanb5a0a97002019-09-08 04:55:15368 base::PreReadFile(DbPath(), /*is_executable=*/false, preload_size);
[email protected]e5ffd0e42009-09-11 21:30:56369}
370
Victor Costancfbfa602018-08-01 23:24:46371// SQLite keeps unused pages associated with a database in a cache. It asks
shess7dbd4dee2015-10-06 17:39:16372// the cache for pages by an id, and if the page is present and the database is
373// unchanged, it considers the content of the page valid and doesn't read it
374// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
375// structures created from the memory map data before consulting the cache. On
376// write SQLite creates a new in-memory page structure, copies the data from the
377// memory map, and later writes it, releasing the updated page back to the
378// cache.
379//
380// This means that in memory-mapped mode, the contents of the cached pages are
381// not re-used for reads, but they are re-used for writes if the re-written page
382// is still in the cache. The implementation of sqlite3_db_release_memory() as
383// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
Victor Costancfbfa602018-08-01 23:24:46384// database, so it should free these pages.
shess7dbd4dee2015-10-06 17:39:16385//
386// Unfortunately, the zero page is also freed. That page is never accessed
387// using memory-mapped I/O, and the cached copy can be re-used after verifying
388// the file change counter on disk. Also, fresh pages from cache receive some
389// pager-level initialization before they can be used. Since the information
390// involved will immediately be accessed in various ways, it is unclear if the
391// additional overhead is material, or just moving processor cache effects
392// around.
393//
394// TODO(shess): It would be better to release the pages immediately when they
395// are no longer needed. This would basically happen after SQLite commits a
396// transaction. I had implemented a pcache wrapper to do this, but it involved
397// layering violations, and it had to be setup before any other sqlite call,
398// which was brittle. Also, for large files it would actually make sense to
399// maintain the existing pcache behavior for blocks past the memory-mapped
400// segment. I think drh would accept a reasonable implementation of the overall
401// concept for upstreaming to SQLite core.
402//
403// TODO(shess): Another possibility would be to set the cache size small, which
404// would keep the zero page around, plus some pre-initialized pages, and SQLite
405// can manage things. The downside is that updates larger than the cache would
406// spill to the journal. That could be compensated by setting cache_spill to
407// false. The downside then is that it allows open-ended use of memory for
408// large transactions.
Victor Costancfbfa602018-08-01 23:24:46409void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
shess644fc8a2016-02-26 18:15:58410 // The database could have been closed during a transaction as part of error
411 // recovery.
412 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:46413 DCHECK(poisoned_) << "Illegal use of Database without a db";
shess644fc8a2016-02-26 18:15:58414 return;
415 }
shess7dbd4dee2015-10-06 17:39:16416
417 // If memory-mapping is not enabled, the page cache helps performance.
418 if (!mmap_enabled_)
419 return;
420
421 // On caller request, force the change comparison to fail. Done before the
422 // transaction-nesting test so that the signal can carry to transaction
423 // commit.
424 if (implicit_change_performed)
425 --total_changes_at_last_release_;
426
427 // Cached pages may be re-used within the same transaction.
428 if (transaction_nesting())
429 return;
430
431 // If no changes have been made, skip flushing. This allows the first page of
432 // the database to remain in cache across multiple reads.
433 const int total_changes = sqlite3_total_changes(db_);
434 if (total_changes == total_changes_at_last_release_)
435 return;
436
437 total_changes_at_last_release_ = total_changes;
438 sqlite3_db_release_memory(db_);
439}
440
Victor Costancfbfa602018-08-01 23:24:46441base::FilePath Database::DbPath() const {
shessc8cd2a162015-10-22 20:30:46442 if (!is_open())
443 return base::FilePath();
444
445 const char* path = sqlite3_db_filename(db_, "main");
446 const base::StringPiece db_path(path);
447#if defined(OS_WIN)
jdoerrie6312bf62019-02-01 22:03:42448 return base::FilePath(base::UTF8ToUTF16(db_path));
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18449#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46450 return base::FilePath(db_path);
451#else
452 NOTREACHED();
453 return base::FilePath();
454#endif
455}
456
Victor Costancfbfa602018-08-01 23:24:46457std::string Database::CollectErrorInfo(int error, Statement* stmt) const {
shessc8cd2a162015-10-22 20:30:46458 // Buffer for accumulating debugging info about the error. Place
459 // more-relevant information earlier, in case things overflow the
460 // fixed-size reporting buffer.
461 std::string debug_info;
462
463 // The error message from the failed operation.
Victor Costancfbfa602018-08-01 23:24:46464 base::StringAppendF(&debug_info, "db error: %d/%s\n", GetErrorCode(),
465 GetErrorMessage());
shessc8cd2a162015-10-22 20:30:46466
467 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
468 // reading code does not entirely convince me. Remove if they turn out to be
469 // the same.
470 if (error != GetErrorCode())
471 base::StringAppendF(&debug_info, "reported error: %d\n", error);
472
Victor Costancfbfa602018-08-01 23:24:46473// System error information. Interpretation of Windows errors is different
474// from posix.
shessc8cd2a162015-10-22 20:30:46475#if defined(OS_WIN)
476 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18477#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46478 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
479#else
480 NOTREACHED(); // Add appropriate log info.
481#endif
482
483 if (stmt) {
484 base::StringAppendF(&debug_info, "statement: %s\n",
485 stmt->GetSQLStatement());
486 } else {
487 base::StringAppendF(&debug_info, "statement: NULL\n");
488 }
489
490 // SQLITE_ERROR often indicates some sort of mismatch between the statement
491 // and the schema, possibly due to a failed schema migration.
492 if (error == SQLITE_ERROR) {
Victor Costanf37f7ae2019-04-11 19:26:12493 static const char kVersionSql[] =
494 "SELECT value FROM meta WHERE key='version'";
495 sqlite3_stmt* sqlite_statement;
496 // When the number of bytes passed to sqlite3_prepare_v3() includes the null
497 // terminator, SQLite avoids a buffer copy.
498 int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql),
499 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
500 /* pzTail= */ nullptr);
shessc8cd2a162015-10-22 20:30:46501 if (rc == SQLITE_OK) {
Victor Costanf37f7ae2019-04-11 19:26:12502 rc = sqlite3_step(sqlite_statement);
shessc8cd2a162015-10-22 20:30:46503 if (rc == SQLITE_ROW) {
504 base::StringAppendF(&debug_info, "version: %d\n",
Victor Costanf37f7ae2019-04-11 19:26:12505 sqlite3_column_int(sqlite_statement, 0));
shessc8cd2a162015-10-22 20:30:46506 } else if (rc == SQLITE_DONE) {
507 debug_info += "version: none\n";
508 } else {
509 base::StringAppendF(&debug_info, "version: error %d\n", rc);
510 }
Victor Costanf37f7ae2019-04-11 19:26:12511 sqlite3_finalize(sqlite_statement);
shessc8cd2a162015-10-22 20:30:46512 } else {
513 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
514 }
515
516 debug_info += "schema:\n";
517
518 // sqlite_master has columns:
519 // type - "index" or "table".
520 // name - name of created element.
521 // tbl_name - name of element, or target table in case of index.
522 // rootpage - root page of the element in database file.
523 // sql - SQL to create the element.
524 // In general, the |sql| column is sufficient to derive the other columns.
525 // |rootpage| is not interesting for debugging, without the contents of the
526 // database. The COALESCE is because certain automatic elements will have a
527 // |name| but no |sql|,
Victor Costanf37f7ae2019-04-11 19:26:12528 static const char kSchemaSql[] =
529 "SELECT COALESCE(sql,name) FROM sqlite_master";
530 rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql),
531 SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
532 /* pzTail= */ nullptr);
shessc8cd2a162015-10-22 20:30:46533 if (rc == SQLITE_OK) {
Victor Costanf37f7ae2019-04-11 19:26:12534 while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
535 base::StringAppendF(&debug_info, "%s\n",
536 sqlite3_column_text(sqlite_statement, 0));
shessc8cd2a162015-10-22 20:30:46537 }
538 if (rc != SQLITE_DONE)
539 base::StringAppendF(&debug_info, "error %d\n", rc);
Victor Costanf37f7ae2019-04-11 19:26:12540 sqlite3_finalize(sqlite_statement);
shessc8cd2a162015-10-22 20:30:46541 } else {
542 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
543 }
544 }
545
546 return debug_info;
547}
548
549// TODO(shess): Since this is only called in an error situation, it might be
550// prudent to rewrite in terms of SQLite API calls, and mark the function const.
Victor Costancfbfa602018-08-01 23:24:46551std::string Database::CollectCorruptionInfo() {
shessc8cd2a162015-10-22 20:30:46552 // If the file cannot be accessed it is unlikely that an integrity check will
553 // turn up actionable information.
554 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19555 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46556 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
557 return std::string();
558
559 // Buffer for accumulating debugging info about the error. Place
560 // more-relevant information earlier, in case things overflow the
561 // fixed-size reporting buffer.
562 std::string debug_info;
563 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
564 db_size);
565
566 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19567 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46568 if (db_size > kMaxIntegrityCheckSize) {
569 debug_info += "integrity_check skipped due to size\n";
570 } else {
571 std::vector<std::string> messages;
572
573 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
574 // into a string. Probably should be refactored.
575 const base::TimeTicks before = base::TimeTicks::Now();
576 FullIntegrityCheck(&messages);
577 base::StringAppendF(
Victor Costancfbfa602018-08-01 23:24:46578 &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
579 (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
shessc8cd2a162015-10-22 20:30:46580
581 // SQLite returns up to 100 messages by default, trim deeper to
582 // keep close to the 2000-character size limit for dumping.
583 const size_t kMaxMessages = 20;
584 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
585 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
586 }
587 }
588
589 return debug_info;
590}
591
Victor Costancfbfa602018-08-01 23:24:46592bool Database::GetMmapAltStatus(int64_t* status) {
shessa62504d2016-11-07 19:26:12593 // The [meta] version uses a missing table as a signal for a fresh database.
594 // That will not work for the view, which would not exist in either a new or
595 // an existing database. A new database _should_ be only one page long, so
596 // just don't bother optimizing this case (start at offset 0).
597 // TODO(shess): Could the [meta] case also get simpler, then?
598 if (!DoesViewExist("MmapStatus")) {
599 *status = 0;
600 return true;
601 }
602
603 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
604 Statement s(GetUniqueStatement(kMmapStatusSql));
605 if (s.Step())
606 *status = s.ColumnInt64(0);
607 return s.Succeeded();
608}
609
Victor Costancfbfa602018-08-01 23:24:46610bool Database::SetMmapAltStatus(int64_t status) {
shessa62504d2016-11-07 19:26:12611 if (!BeginTransaction())
612 return false;
613
614 // View may not exist on first run.
615 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
616 RollbackTransaction();
617 return false;
618 }
619
620 // Views live in the schema, so they cannot be parameterized. For an integer
621 // value, this construct should be safe from SQL injection, if the value
622 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
623 // value.
Victor Costancfbfa602018-08-01 23:24:46624 const std::string create_view_sql = base::StringPrintf(
625 "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
626 if (!Execute(create_view_sql.c_str())) {
shessa62504d2016-11-07 19:26:12627 RollbackTransaction();
628 return false;
629 }
630
631 return CommitTransaction();
632}
633
Victor Costancfbfa602018-08-01 23:24:46634size_t Database::GetAppropriateMmapSize() {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54635 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
636 InitScopedBlockingCall(&scoped_blocking_call);
shessd90aeea82015-11-13 02:24:31637
shess9bf2c672015-12-18 01:18:08638 // How much to map if no errors are found. 50MB encompasses the 99th
639 // percentile of Chrome databases in the wild, so this should be good.
640 const size_t kMmapEverything = 256 * 1024 * 1024;
641
shessa62504d2016-11-07 19:26:12642 // Progress information is tracked in the [meta] table for databases which use
643 // sql::MetaTable, otherwise it is tracked in a special view.
644 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08645 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12646 if (mmap_alt_status_) {
647 if (!GetMmapAltStatus(&mmap_ofs)) {
648 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
649 return 0;
650 }
651 } else {
652 // If [meta] doesn't exist, yet, it's a new database, assume the best.
653 // sql::MetaTable::Init() will preload kMmapSuccess.
654 if (!MetaTable::DoesTableExist(this)) {
655 RecordOneEvent(EVENT_MMAP_META_MISSING);
656 return kMmapEverything;
657 }
658
659 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
660 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
661 return 0;
662 }
shessd90aeea82015-11-13 02:24:31663 }
664
665 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08666 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31667 RecordOneEvent(EVENT_MMAP_FAILED);
668 return 0;
Victor Costan5e785e32019-02-26 20:39:31669 }
670
671 if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31672 // Continue reading from previous offset.
673 DCHECK_GE(mmap_ofs, 0);
674
675 // TODO(shess): Could this reading code be shared with Preload()? It would
676 // require locking twice (this code wouldn't be able to access |db_size| so
677 // the helper would have to return amount read).
678
679 // Read more of the database looking for errors. The VFS interface is used
680 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
681 // to limit checking to 20MB per run of Chromium.
Victor Costanbd623112018-07-18 04:17:27682 sqlite3_file* file = nullptr;
shessd90aeea82015-11-13 02:24:31683 sqlite3_int64 db_size = 0;
684 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
685 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
686 return 0;
687 }
688
689 // Read the data left, or |g_reads_allowed|, whichever is smaller.
690 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
691 // in a single Chromium run.
692 sqlite3_int64 amount = db_size - mmap_ofs;
693 if (amount < 0)
694 amount = 0;
695 if (amount > 0) {
Victor Costan3653df62018-02-08 21:38:16696 static base::NoDestructor<base::Lock> lock;
697 base::AutoLock auto_lock(*lock);
shessd90aeea82015-11-13 02:24:31698 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
699 if (g_reads_allowed < amount)
700 amount = g_reads_allowed;
701 g_reads_allowed -= amount;
702 }
703
704 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
705 // database was truncated after a previous pass.
706 if (amount <= 0 && mmap_ofs < db_size) {
707 DCHECK_EQ(0, amount);
shessd90aeea82015-11-13 02:24:31708 } else {
709 static const int kPageSize = 4096;
710 char buf[kPageSize];
711 while (amount > 0) {
712 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
713 if (rc == SQLITE_OK) {
714 mmap_ofs += sizeof(buf);
715 amount -= sizeof(buf);
716 } else if (rc == SQLITE_IOERR_SHORT_READ) {
717 // Reached EOF for a database with page size < |kPageSize|.
718 mmap_ofs = db_size;
719 break;
720 } else {
721 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08722 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31723 break;
724 }
725 }
726
727 // Log these events after update to distinguish meta update failure.
shessd90aeea82015-11-13 02:24:31728 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08729 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31730 } else {
Victor Costan5e785e32019-02-26 20:39:31731 DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure);
shessd90aeea82015-11-13 02:24:31732 }
733
shessa62504d2016-11-07 19:26:12734 if (mmap_alt_status_) {
735 if (!SetMmapAltStatus(mmap_ofs)) {
736 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
737 return 0;
738 }
739 } else {
740 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
741 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
742 return 0;
743 }
shessd90aeea82015-11-13 02:24:31744 }
745
Victor Costan5e785e32019-02-26 20:39:31746 if (mmap_ofs == MetaTable::kMmapFailure)
747 RecordOneEvent(EVENT_MMAP_FAILED_NEW);
shessd90aeea82015-11-13 02:24:31748 }
749 }
750
shess9bf2c672015-12-18 01:18:08751 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31752 return 0;
shess9bf2c672015-12-18 01:18:08753 if (mmap_ofs == MetaTable::kMmapSuccess)
754 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31755 return mmap_ofs;
756}
757
Victor Costan52bef812018-12-05 07:41:49758void Database::TrimMemory() {
[email protected]be7995f12013-07-18 18:49:14759 if (!db_)
760 return;
761
Victor Costan52bef812018-12-05 07:41:49762 sqlite3_db_release_memory(db_);
[email protected]be7995f12013-07-18 18:49:14763
Victor Costan52bef812018-12-05 07:41:49764 // It is tempting to use sqlite3_release_memory() here as well. However, the
765 // API is documented to be a no-op unless SQLite is built with
766 // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is
767 // incompatible with per-database page cache pools. Behind the scenes,
768 // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache
769 // pool, and sqlite3_release_memory() releases unused pages from this global
770 // pool.
[email protected]be7995f12013-07-18 18:49:14771}
772
[email protected]8e0c01282012-04-06 19:36:49773// Create an in-memory database with the existing database's page
774// size, then backup that database over the existing database.
Victor Costancfbfa602018-08-01 23:24:46775bool Database::Raze() {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:54776 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
777 InitScopedBlockingCall(&scoped_blocking_call);
[email protected]35f7e5392012-07-27 19:54:50778
[email protected]8e0c01282012-04-06 19:36:49779 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52780 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49781 return false;
782 }
783
784 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52785 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:49786 return false;
787 }
788
Victor Costancfbfa602018-08-01 23:24:46789 sql::Database null_db;
[email protected]8e0c01282012-04-06 19:36:49790 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52791 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:49792 return false;
793 }
794
Victor Costan7f6abbbe2018-07-29 02:57:27795 const std::string sql = base::StringPrintf("PRAGMA page_size=%d", page_size_);
796 if (!null_db.Execute(sql.c_str()))
797 return false;
[email protected]69c58452012-08-06 19:22:42798
[email protected]6d42f152012-11-10 00:38:24799#if defined(OS_ANDROID)
800 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
801 // in-memory databases do not respect this define.
802 // TODO(shess): Figure out a way to set this without using platform
803 // specific code. AFAICT from sqlite3.c, the only way to do it
804 // would be to create an actual filesystem database, which is
805 // unfortunate.
806 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
807 return false;
808#endif
[email protected]8e0c01282012-04-06 19:36:49809
810 // The page size doesn't take effect until a database has pages, and
811 // at this point the null database has none. Changing the schema
812 // version will create the first page. This will not affect the
813 // schema version in the resulting database, as SQLite's backup
814 // implementation propagates the schema version from the original
Victor Costancfbfa602018-08-01 23:24:46815 // database to the new version of the database, incremented by one
[email protected]8e0c01282012-04-06 19:36:49816 // so that other readers see the schema change and act accordingly.
817 if (!null_db.Execute("PRAGMA schema_version = 1"))
818 return false;
819
[email protected]6d42f152012-11-10 00:38:24820 // SQLite tracks the expected number of database pages in the first
821 // page, and if it does not match the total retrieved from a
822 // filesystem call, treats the database as corrupt. This situation
823 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
824 // used to hint to SQLite to soldier on in that case, specifically
825 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
826 // sqlite3.c lockBtree().]
827 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
828 // page_size" can be used to query such a database.
829 ScopedWritableSchema writable_schema(db_);
830
shess92a6fb22017-04-23 04:33:30831#if defined(OS_WIN)
832 // On Windows, truncate silently fails when applied to memory-mapped files.
833 // Disable memory-mapping so that the truncate succeeds. Note that other
Victor Costancfbfa602018-08-01 23:24:46834 // Database connections may have memory-mapped the file, so this may not
835 // entirely prevent the problem.
shess92a6fb22017-04-23 04:33:30836 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
837 ignore_result(Execute("PRAGMA mmap_size = 0"));
838#endif
839
[email protected]7bae5742013-07-10 20:46:16840 const char* kMain = "main";
841 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:18842 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:49843
844 // The destination database was locked.
845 if (rc == SQLITE_BUSY) {
846 return false;
847 }
848
[email protected]7bae5742013-07-10 20:46:16849 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
850 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
851 // isn't even big enough for one page. Either way, reach in and
852 // truncate it before trying again.
853 // TODO(shess): Maybe it would be worthwhile to just truncate from
854 // the get-go?
855 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
Victor Costanbd623112018-07-18 04:17:27856 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:34857 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:16858 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52859 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:16860 return false;
[email protected]7bae5742013-07-10 20:46:16861 }
862
863 rc = file->pMethods->xTruncate(file, 0);
864 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18865 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52866 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:16867 return false;
868 }
869
870 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:18871 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:16872
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52873 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:16874 }
875
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52876 // TODO(shess): Figure out which other cases can happen.
877 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
878
[email protected]8e0c01282012-04-06 19:36:49879 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52880 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:49881}
882
Victor Costancfbfa602018-08-01 23:24:46883bool Database::RazeAndClose() {
[email protected]41a97c812013-02-07 02:35:38884 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52885 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:38886 return false;
887 }
888
889 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:30890 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:38891
892 bool result = Raze();
893
894 CloseInternal(true);
895
896 // Mark the database so that future API calls fail appropriately,
897 // but don't DCHECK (because after calling this function they are
898 // expected to fail).
899 poisoned_ = true;
900
901 return result;
902}
903
Victor Costancfbfa602018-08-01 23:24:46904void Database::Poison() {
[email protected]8d409412013-07-19 18:25:30905 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52906 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:30907 return;
908 }
909
910 RollbackAllTransactions();
911 CloseInternal(true);
912
913 // Mark the database so that future API calls fail appropriately,
914 // but don't DCHECK (because after calling this function they are
915 // expected to fail).
916 poisoned_ = true;
917}
918
[email protected]8d2e39e2013-06-24 05:55:08919// TODO(shess): To the extent possible, figure out the optimal
Victor Costancfbfa602018-08-01 23:24:46920// ordering for these deletes which will prevent other Database connections
[email protected]8d2e39e2013-06-24 05:55:08921// from seeing odd behavior. For instance, it may be necessary to
922// manually lock the main database file in a SQLite-compatible fashion
923// (to prevent other processes from opening it), then delete the
924// journal files, then delete the main database file. Another option
925// might be to lock the main database file and poison the header with
926// junk to prevent other processes from opening it successfully (like
927// Gears "SQLite poison 3" trick).
928//
929// static
Victor Costancfbfa602018-08-01 23:24:46930bool Database::Delete(const base::FilePath& path) {
Etienne Bergeron436d42212019-02-26 17:15:12931 base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
932 base::BlockingType::MAY_BLOCK);
[email protected]8d2e39e2013-06-24 05:55:08933
Victor Costancfbfa602018-08-01 23:24:46934 base::FilePath journal_path = Database::JournalPath(path);
935 base::FilePath wal_path = Database::WriteAheadLogPath(path);
[email protected]8d2e39e2013-06-24 05:55:08936
erg102ceb412015-06-20 01:38:13937 std::string journal_str = AsUTF8ForSQL(journal_path);
938 std::string wal_str = AsUTF8ForSQL(wal_path);
939 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:08940
Victor Costan3653df62018-02-08 21:38:16941 EnsureSqliteInitialized();
shess702467622015-09-16 19:04:55942
Victor Costanbd623112018-07-18 04:17:27943 sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
erg102ceb412015-06-20 01:38:13944 CHECK(vfs);
945 CHECK(vfs->xDelete);
946 CHECK(vfs->xAccess);
947
948 // We only work with unix, win32 and mojo filesystems. If you're trying to
949 // use this code with any other VFS, you're not in a good place.
950 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
951 strncmp(vfs->zName, "win32", 5) == 0 ||
952 strcmp(vfs->zName, "mojo") == 0);
953
954 vfs->xDelete(vfs, journal_str.c_str(), 0);
955 vfs->xDelete(vfs, wal_str.c_str(), 0);
956 vfs->xDelete(vfs, path_str.c_str(), 0);
957
958 int journal_exists = 0;
Victor Costance678e72018-07-24 10:25:00959 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
erg102ceb412015-06-20 01:38:13960
961 int wal_exists = 0;
Victor Costance678e72018-07-24 10:25:00962 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
erg102ceb412015-06-20 01:38:13963
964 int path_exists = 0;
Victor Costance678e72018-07-24 10:25:00965 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
erg102ceb412015-06-20 01:38:13966
967 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:08968}
969
Victor Costancfbfa602018-08-01 23:24:46970bool Database::BeginTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:56971 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33972 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56973
974 // When we're going to rollback, fail on this begin and don't actually
975 // mark us as entering the nested transaction.
976 return false;
977 }
978
979 bool success = true;
980 if (!transaction_nesting_) {
981 needs_rollback_ = false;
982
983 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59984 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56985 return false;
986 }
987 transaction_nesting_++;
988 return success;
989}
990
Victor Costancfbfa602018-08-01 23:24:46991void Database::RollbackTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:56992 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52993 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56994 return;
995 }
996
997 transaction_nesting_--;
998
999 if (transaction_nesting_ > 0) {
1000 // Mark the outermost transaction as needing rollback.
1001 needs_rollback_ = true;
1002 return;
1003 }
1004
1005 DoRollback();
1006}
1007
Victor Costancfbfa602018-08-01 23:24:461008bool Database::CommitTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561009 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521010 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561011 return false;
1012 }
1013 transaction_nesting_--;
1014
1015 if (transaction_nesting_ > 0) {
1016 // Mark any nested transactions as failing after we've already got one.
1017 return !needs_rollback_;
1018 }
1019
1020 if (needs_rollback_) {
1021 DoRollback();
1022 return false;
1023 }
1024
1025 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321026
Victor Costan5e785e32019-02-26 20:39:311027 bool succeeded = commit.Run();
shess58b8df82015-06-03 00:19:321028
shess7dbd4dee2015-10-06 17:39:161029 // Release dirty cache pages after the transaction closes.
1030 ReleaseCacheMemoryIfNeeded(false);
1031
Victor Costan5e785e32019-02-26 20:39:311032 return succeeded;
[email protected]e5ffd0e42009-09-11 21:30:561033}
1034
Victor Costancfbfa602018-08-01 23:24:461035void Database::RollbackAllTransactions() {
[email protected]8d409412013-07-19 18:25:301036 if (transaction_nesting_ > 0) {
1037 transaction_nesting_ = 0;
1038 DoRollback();
1039 }
1040}
1041
Victor Costancfbfa602018-08-01 23:24:461042bool Database::AttachDatabase(const base::FilePath& other_db_path,
1043 const char* attachment_point,
1044 InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301045 DCHECK(ValidAttachmentPoint(attachment_point));
1046
1047 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1048#if OS_WIN
1049 s.BindString16(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181050#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberibd1301f2018-05-18 21:00:091051 s.BindString(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181052#else
1053#error Unsupported platform
[email protected]8d409412013-07-19 18:25:301054#endif
1055 s.BindString(1, attachment_point);
1056 return s.Run();
1057}
1058
Victor Costancfbfa602018-08-01 23:24:461059bool Database::DetachDatabase(const char* attachment_point, InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301060 DCHECK(ValidAttachmentPoint(attachment_point));
1061
1062 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1063 s.BindString(0, attachment_point);
1064 return s.Run();
1065}
1066
shess58b8df82015-06-03 00:19:321067// TODO(shess): Consider changing this to execute exactly one statement. If a
1068// caller wishes to execute multiple statements, that should be explicit, and
1069// perhaps tucked into an explicit transaction with rollback in case of error.
Victor Costancfbfa602018-08-01 23:24:461070int Database::ExecuteAndReturnErrorCode(const char* sql) {
Victor Costan5e785e32019-02-26 20:39:311071 DCHECK(sql);
Etienne Pierre-Doraya71d7af2019-02-07 02:07:541072
[email protected]41a97c812013-02-07 02:35:381073 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461074 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381075 return SQLITE_ERROR;
1076 }
shess58b8df82015-06-03 00:19:321077
Victor Costan5e785e32019-02-26 20:39:311078 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
1079 InitScopedBlockingCall(&scoped_blocking_call);
1080
shess58b8df82015-06-03 00:19:321081 int rc = SQLITE_OK;
1082 while ((rc == SQLITE_OK) && *sql) {
Victor Costanf37f7ae2019-04-11 19:26:121083 sqlite3_stmt* sqlite_statement;
Victor Costancfbfa602018-08-01 23:24:461084 const char* leftover_sql;
Victor Costanf37f7ae2019-04-11 19:26:121085 rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0,
1086 &sqlite_statement, &leftover_sql);
shess58b8df82015-06-03 00:19:321087 // Stop if an error is encountered.
1088 if (rc != SQLITE_OK)
1089 break;
1090
Victor Costanf37f7ae2019-04-11 19:26:121091 sql = leftover_sql;
1092
shess58b8df82015-06-03 00:19:321093 // This happens if |sql| originally only contained comments or whitespace.
1094 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1095 // extraneous comments and whitespace in the SQL statements increases
1096 // runtime cost and can easily be shifted out to the C++ layer.
Victor Costanf37f7ae2019-04-11 19:26:121097 if (!sqlite_statement)
shess58b8df82015-06-03 00:19:321098 continue;
1099
Victor Costanf37f7ae2019-04-11 19:26:121100 while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
shess58b8df82015-06-03 00:19:321101 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
Victor Costan5e785e32019-02-26 20:39:311102 // is the only legitimate case for this. Previously recorded histograms
1103 // show significant use of this code path.
shess58b8df82015-06-03 00:19:321104 }
1105
1106 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1107 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
Victor Costanf37f7ae2019-04-11 19:26:121108 rc = sqlite3_finalize(sqlite_statement);
shess58b8df82015-06-03 00:19:321109
1110 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1111 // trailing whitespace.
1112 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021113 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321114 sql++;
1115 }
shess58b8df82015-06-03 00:19:321116 }
shess7dbd4dee2015-10-06 17:39:161117
1118 // Most calls to Execute() modify the database. The main exceptions would be
1119 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1120 // but sometimes don't.
1121 ReleaseCacheMemoryIfNeeded(true);
1122
shess58b8df82015-06-03 00:19:321123 return rc;
[email protected]eff1fa522011-12-12 23:50:591124}
1125
Victor Costancfbfa602018-08-01 23:24:461126bool Database::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381127 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461128 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381129 return false;
1130 }
1131
[email protected]eff1fa522011-12-12 23:50:591132 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001133 if (error != SQLITE_OK)
Victor Costanbd623112018-07-18 04:17:271134 error = OnSqliteError(error, nullptr, sql);
[email protected]473ad792012-11-10 00:55:001135
[email protected]28fe0ff2012-02-25 00:40:331136 // This needs to be a FATAL log because the error case of arriving here is
1137 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101138 // a change alters the schema but not all queries adjust. This can happen
1139 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521140 DCHECK_NE(error, SQLITE_ERROR)
1141 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591142 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561143}
1144
Victor Costancfbfa602018-08-01 23:24:461145bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381146 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461147 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]5b96f3772010-09-28 16:30:571148 return false;
[email protected]41a97c812013-02-07 02:35:381149 }
[email protected]5b96f3772010-09-28 16:30:571150
1151 ScopedBusyTimeout busy_timeout(db_);
1152 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591153 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571154}
1155
Victor Costancfbfa602018-08-01 23:24:461156scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
Victor Costan12daa3ac92018-07-19 01:05:581157 StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:561158 const char* sql) {
Victor Costanc7e7f2e2018-07-18 20:07:551159 auto it = statement_cache_.find(id);
1160 if (it != statement_cache_.end()) {
Victor Costan613b4302018-11-20 05:32:431161 // Statement is in the cache. It should still be valid. We're the only
1162 // entity invalidating cached statements, and we remove them from the cache
Victor Costan87cf8c72018-07-19 19:36:041163 // when we do that.
Victor Costanc7e7f2e2018-07-18 20:07:551164 DCHECK(it->second->is_valid());
Victor Costan613b4302018-11-20 05:32:431165 DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
Victor Costan87cf8c72018-07-19 19:36:041166 << "GetCachedStatement used with same ID but different SQL";
1167
1168 // Reset the statement so it can be reused.
Victor Costanc7e7f2e2018-07-18 20:07:551169 sqlite3_reset(it->second->stmt());
1170 return it->second;
[email protected]e5ffd0e42009-09-11 21:30:561171 }
1172
1173 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
Victor Costan613b4302018-11-20 05:32:431174 if (statement->is_valid()) {
[email protected]e5ffd0e42009-09-11 21:30:561175 statement_cache_[id] = statement; // Only cache valid statements.
Victor Costan613b4302018-11-20 05:32:431176 DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
1177 << "Input SQL does not match SQLite's normalized version";
1178 }
[email protected]e5ffd0e42009-09-11 21:30:561179 return statement;
1180}
1181
Victor Costancfbfa602018-08-01 23:24:461182scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
[email protected]e5ffd0e42009-09-11 21:30:561183 const char* sql) {
shess9e77283d2016-06-13 23:53:201184 return GetStatementImpl(this, sql);
1185}
1186
Victor Costancfbfa602018-08-01 23:24:461187scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1188 sql::Database* tracking_db,
1189 const char* sql) const {
shess9e77283d2016-06-13 23:53:201190 DCHECK(sql);
Victor Costan87cf8c72018-07-19 19:36:041191 DCHECK(!tracking_db || tracking_db == this);
[email protected]35f7e5392012-07-27 19:54:501192
[email protected]41a97c812013-02-07 02:35:381193 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561194 if (!db_)
Victor Costan3b02cdf2018-07-18 00:39:561195 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561196
Victor Costan5e785e32019-02-26 20:39:311197 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
1198 InitScopedBlockingCall(&scoped_blocking_call);
1199
Victor Costanf37f7ae2019-04-11 19:26:121200 // TODO(pwnall): Cached statements (but not unique statements) should be
1201 // prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT.
1202 sqlite3_stmt* sqlite_statement;
1203 int rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0,
1204 &sqlite_statement, /* pzTail= */ nullptr);
[email protected]473ad792012-11-10 00:55:001205 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591206 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521207 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001208
1209 // It could also be database corruption.
Victor Costanbd623112018-07-18 04:17:271210 OnSqliteError(rc, nullptr, sql);
Victor Costan3b02cdf2018-07-18 00:39:561211 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
[email protected]e5ffd0e42009-09-11 21:30:561212 }
Victor Costanf37f7ae2019-04-11 19:26:121213 return base::MakeRefCounted<StatementRef>(tracking_db, sqlite_statement,
1214 true);
[email protected]e5ffd0e42009-09-11 21:30:561215}
1216
Victor Costancfbfa602018-08-01 23:24:461217scoped_refptr<Database::StatementRef> Database::GetUntrackedStatement(
[email protected]2eec0a22012-07-24 01:59:581218 const char* sql) const {
Victor Costanbd623112018-07-18 04:17:271219 return GetStatementImpl(nullptr, sql);
[email protected]2eec0a22012-07-24 01:59:581220}
1221
Victor Costancfbfa602018-08-01 23:24:461222std::string Database::GetSchema() const {
[email protected]92cd00a2013-08-16 11:09:581223 // The ORDER BY should not be necessary, but relying on organic
1224 // order for something like this is questionable.
Victor Costan87cf8c72018-07-19 19:36:041225 static const char kSql[] =
[email protected]92cd00a2013-08-16 11:09:581226 "SELECT type, name, tbl_name, sql "
1227 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1228 Statement statement(GetUntrackedStatement(kSql));
1229
1230 std::string schema;
1231 while (statement.Step()) {
1232 schema += statement.ColumnString(0);
1233 schema += '|';
1234 schema += statement.ColumnString(1);
1235 schema += '|';
1236 schema += statement.ColumnString(2);
1237 schema += '|';
1238 schema += statement.ColumnString(3);
1239 schema += '\n';
1240 }
1241
1242 return schema;
1243}
1244
Victor Costancfbfa602018-08-01 23:24:461245bool Database::IsSQLValid(const char* sql) {
Etienne Pierre-Doraya71d7af2019-02-07 02:07:541246 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
1247 InitScopedBlockingCall(&scoped_blocking_call);
[email protected]41a97c812013-02-07 02:35:381248 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461249 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381250 return false;
1251 }
1252
Victor Costanf37f7ae2019-04-11 19:26:121253 sqlite3_stmt* sqlite_statement = nullptr;
1254 if (sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, /* prepFlags= */ 0,
1255 &sqlite_statement,
1256 /* pzTail= */ nullptr) != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591257 return false;
Victor Costanf37f7ae2019-04-11 19:26:121258 }
[email protected]eff1fa522011-12-12 23:50:591259
Victor Costanf37f7ae2019-04-11 19:26:121260 sqlite3_finalize(sqlite_statement);
[email protected]eff1fa522011-12-12 23:50:591261 return true;
1262}
1263
Victor Costancfbfa602018-08-01 23:24:461264bool Database::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121265 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531266}
1267
Victor Costancfbfa602018-08-01 23:24:461268bool Database::DoesTableExist(const char* table_name) const {
shessa62504d2016-11-07 19:26:121269 return DoesSchemaItemExist(table_name, "table");
1270}
1271
Victor Costancfbfa602018-08-01 23:24:461272bool Database::DoesViewExist(const char* view_name) const {
shessa62504d2016-11-07 19:26:121273 return DoesSchemaItemExist(view_name, "view");
1274}
1275
Victor Costancfbfa602018-08-01 23:24:461276bool Database::DoesSchemaItemExist(const char* name, const char* type) const {
Victor Costanf85512e52019-04-10 20:51:361277 static const char kSql[] =
1278 "SELECT 1 FROM sqlite_master WHERE type=? AND name=?";
[email protected]2eec0a22012-07-24 01:59:581279 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471280
Victor Costanf85512e52019-04-10 20:51:361281 if (!statement.is_valid()) {
1282 // The database is corrupt.
shess92a2ab12015-04-09 01:59:471283 return false;
Victor Costanf85512e52019-04-10 20:51:361284 }
shess92a2ab12015-04-09 01:59:471285
[email protected]e2cadec82011-12-13 02:00:531286 statement.BindString(0, type);
1287 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331288
[email protected]e5ffd0e42009-09-11 21:30:561289 return statement.Step(); // Table exists if any row was returned.
1290}
1291
Victor Costancfbfa602018-08-01 23:24:461292bool Database::DoesColumnExist(const char* table_name,
1293 const char* column_name) const {
Victor Costan1ff47e92018-12-07 11:10:431294 // sqlite3_table_column_metadata uses out-params to return column definition
1295 // details, such as the column type and whether it allows NULL values. These
1296 // aren't needed to compute the current method's result, so we pass in nullptr
1297 // for all the out-params.
1298 int error = sqlite3_table_column_metadata(
1299 db_, "main", table_name, column_name, /* pzDataType= */ nullptr,
1300 /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr,
1301 /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr);
1302 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561303}
1304
Victor Costancfbfa602018-08-01 23:24:461305int64_t Database::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561306 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461307 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]e5ffd0e42009-09-11 21:30:561308 return 0;
1309 }
1310 return sqlite3_last_insert_rowid(db_);
1311}
1312
Victor Costancfbfa602018-08-01 23:24:461313int Database::GetLastChangeCount() const {
[email protected]1ed78a32009-09-15 20:24:171314 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461315 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]1ed78a32009-09-15 20:24:171316 return 0;
1317 }
1318 return sqlite3_changes(db_);
1319}
1320
Victor Costancfbfa602018-08-01 23:24:461321int Database::GetErrorCode() const {
[email protected]e5ffd0e42009-09-11 21:30:561322 if (!db_)
1323 return SQLITE_ERROR;
1324 return sqlite3_errcode(db_);
1325}
1326
Victor Costancfbfa602018-08-01 23:24:461327int Database::GetLastErrno() const {
[email protected]767718e52010-09-21 23:18:491328 if (!db_)
1329 return -1;
1330
1331 int err = 0;
Victor Costanbd623112018-07-18 04:17:271332 if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
[email protected]767718e52010-09-21 23:18:491333 return -2;
1334
1335 return err;
1336}
1337
Victor Costancfbfa602018-08-01 23:24:461338const char* Database::GetErrorMessage() const {
[email protected]e5ffd0e42009-09-11 21:30:561339 if (!db_)
Victor Costancfbfa602018-08-01 23:24:461340 return "sql::Database is not opened.";
[email protected]e5ffd0e42009-09-11 21:30:561341 return sqlite3_errmsg(db_);
1342}
1343
Victor Costancfbfa602018-08-01 23:24:461344bool Database::OpenInternal(const std::string& file_name,
1345 Database::Retry retry_flag) {
[email protected]9cfbc922009-11-17 20:13:171346 if (db_) {
Victor Costancfbfa602018-08-01 23:24:461347 DLOG(DCHECK) << "sql::Database is already open.";
[email protected]9cfbc922009-11-17 20:13:171348 return false;
1349 }
1350
Victor Costan5e785e32019-02-26 20:39:311351 base::Optional<base::ScopedBlockingCall> scoped_blocking_call;
1352 InitScopedBlockingCall(&scoped_blocking_call);
1353
Victor Costan3653df62018-02-08 21:38:161354 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181355
shess58b8df82015-06-03 00:19:321356 // Setup the stats histograms immediately rather than allocating lazily.
Victor Costancfbfa602018-08-01 23:24:461357 // Databases which won't exercise all of these probably shouldn't exist.
shess58b8df82015-06-03 00:19:321358 if (!histogram_tag_.empty()) {
Victor Costancfbfa602018-08-01 23:24:461359 stats_histogram_ = base::LinearHistogram::FactoryGet(
Victor Costanb0e7fc02019-03-01 03:36:271360 "Sqlite.Stats2." + histogram_tag_, 1, EVENT_MAX_VALUE,
Victor Costancfbfa602018-08-01 23:24:461361 EVENT_MAX_VALUE + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
shess58b8df82015-06-03 00:19:321362 }
1363
[email protected]41a97c812013-02-07 02:35:381364 // If |poisoned_| is set, it means an error handler called
1365 // RazeAndClose(). Until regular Close() is called, the caller
1366 // should be treating the database as open, but is_open() currently
1367 // only considers the sqlite3 handle's state.
1368 // TODO(shess): Revise is_open() to consider poisoned_, and review
1369 // to see if any non-testing code even depends on it.
Victor Costancfbfa602018-08-01 23:24:461370 DCHECK(!poisoned_) << "sql::Database is already open.";
[email protected]7bae5742013-07-10 20:46:161371 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381372
shess5f2c3442017-01-24 02:15:101373 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1374 sqlite3_vfs* vfs = VFSWrapper();
1375 const char* vfs_name = (vfs ? vfs->zName : nullptr);
Victor Costanc6d3a862018-11-20 18:41:231376
1377 // The flags are documented at https://www.sqlite.org/c3ref/open.html.
1378 //
1379 // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
1380 // disparate features with their own databases, and having separate page
1381 // caches makes it easier to reason about each feature's performance in
1382 // isolation.
1383 int err = sqlite3_open_v2(
1384 file_name.c_str(), &db_,
1385 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_PRIVATECACHE,
1386 vfs_name);
[email protected]765b44502009-10-02 05:01:421387 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281388 // Extended error codes cannot be enabled until a handle is
1389 // available, fetch manually.
1390 err = sqlite3_extended_errcode(db_);
1391
[email protected]bd2ccdb4a2012-12-07 22:14:501392 // Histogram failures specific to initial open for debugging
1393 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181394 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501395
Victor Costanbd623112018-07-18 04:17:271396 OnSqliteError(err, nullptr, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131397 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291398 Close();
[email protected]fed734a2013-07-17 04:45:131399
1400 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1401 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421402 return false;
1403 }
1404
[email protected]73fb8d52013-07-24 05:04:281405 // Enable extended result codes to provide more color on I/O errors.
1406 // Not having extended result codes is not a fatal problem, as
1407 // Chromium code does not attempt to handle I/O errors anyhow. The
1408 // current implementation always returns SQLITE_OK, the DCHECK is to
1409 // quickly notify someone if SQLite changes.
1410 err = sqlite3_extended_result_codes(db_, 1);
1411 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1412
shessbccd300e2016-08-20 00:06:561413 // sqlite3_open() does not actually read the database file (unless a hot
1414 // journal is found). Successfully executing this pragma on an existing
1415 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1416 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501417 // TODO(shess): For now, just probing to see what the lay of the
1418 // land is. If it's mostly SQLITE_NOTADB, then the database should
1419 // be razed.
1420 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561421 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181422 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561423 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1424
1425 // Retry or bail out if the error handler poisoned the handle.
Victor Costanf1e9443b2018-12-05 04:35:531426 // TODO(shess): Move this handling to one place (see also sqlite3_open).
1427 // Possibly a wrapper function?
shessbccd300e2016-08-20 00:06:561428 if (poisoned_) {
1429 Close();
1430 if (retry_flag == RETRY_ON_POISON)
1431 return OpenInternal(file_name, NO_RETRY);
1432 return false;
1433 }
1434 }
[email protected]658f8332010-09-18 04:40:431435
[email protected]5b96f3772010-09-28 16:30:571436 // If indicated, lock up the database before doing anything else, so
1437 // that the following code doesn't have to deal with locking.
1438 // TODO(shess): This code is brittle. Find the cases where code
1439 // doesn't request |exclusive_locking_| and audit that it does the
1440 // right thing with SQLITE_BUSY, and that it doesn't make
1441 // assumptions about who might change things in the database.
1442 // http://crbug.com/56559
1443 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101444 // TODO(shess): This should probably be a failure. Code which
1445 // requests exclusive locking but doesn't get it is almost certain
1446 // to be ill-tested.
1447 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571448 }
1449
[email protected]4e179ba2012-03-17 16:06:471450 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1451 // DELETE (default) - delete -journal file to commit.
1452 // TRUNCATE - truncate -journal file to commit.
1453 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091454 // TRUNCATE should be faster than DELETE because it won't need directory
1455 // changes for each transaction. PERSIST may break the spirit of using
1456 // secure_delete.
Victor Costan4c2f3e922018-08-21 04:47:591457 ignore_result(Execute("PRAGMA journal_mode=TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471458
[email protected]c68ce172011-11-24 22:30:271459 const base::TimeDelta kBusyTimeout =
Victor Costancfbfa602018-08-01 23:24:461460 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
[email protected]c68ce172011-11-24 22:30:271461
Victor Costancfbfa602018-08-01 23:24:461462 const std::string page_size_sql =
1463 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1464 ignore_result(ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421465
1466 if (cache_size_ != 0) {
Victor Costancfbfa602018-08-01 23:24:461467 const std::string cache_size_sql =
[email protected]7d3cbc92013-03-18 22:33:041468 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
Victor Costancfbfa602018-08-01 23:24:461469 ignore_result(ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421470 }
1471
Victor Costanf1e9443b2018-12-05 04:35:531472 static_assert(SQLITE_SECURE_DELETE == 1,
1473 "Chrome assumes secure_delete is on by default.");
[email protected]6e0b1442011-08-09 23:23:581474
shess5dac334f2015-11-05 20:47:421475 // Set a reasonable chunk size for larger files. This reduces churn from
1476 // remapping memory on size changes. It also reduces filesystem
1477 // fragmentation.
1478 // TODO(shess): It may make sense to have this be hinted by the client.
1479 // Database sizes seem to be bimodal, some clients have consistently small
1480 // databases (<20k) while other clients have a broad distribution of sizes
1481 // (hundreds of kilobytes to many megabytes).
Victor Costanbd623112018-07-18 04:17:271482 sqlite3_file* file = nullptr;
shess5dac334f2015-11-05 20:47:421483 sqlite3_int64 db_size = 0;
1484 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1485 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1486 int chunk_size = 4 * 1024;
1487 if (db_size > 128 * 1024)
1488 chunk_size = 32 * 1024;
Victor Costanbd623112018-07-18 04:17:271489 sqlite3_file_control(db_, nullptr, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
shess5dac334f2015-11-05 20:47:421490 }
1491
shess2f3a814b2015-11-05 18:11:101492 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311493 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1494 // safe range to memory-map based on past regular I/O. This value will be
1495 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1496 // 64-bit platforms.
1497 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1498 std::string mmap_sql =
Victor Costan4c2f3e922018-08-21 04:47:591499 base::StringPrintf("PRAGMA mmap_size=%" PRIuS, mmap_size);
shessd90aeea82015-11-13 02:24:311500 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101501
1502 // Determine if memory-mapping has actually been enabled. The Execute() above
1503 // can succeed without changing the amount mapped.
1504 mmap_enabled_ = false;
1505 {
1506 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1507 if (s.Step() && s.ColumnInt64(0) > 0)
1508 mmap_enabled_ = true;
1509 }
1510
ssid3be5b1ec2016-01-13 14:21:571511 DCHECK(!memory_dump_provider_);
1512 memory_dump_provider_.reset(
Victor Costancfbfa602018-08-01 23:24:461513 new DatabaseMemoryDumpProvider(db_, histogram_tag_));
ssid3be5b1ec2016-01-13 14:21:571514 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
Victor Costancfbfa602018-08-01 23:24:461515 memory_dump_provider_.get(), "sql::Database", nullptr);
ssid3be5b1ec2016-01-13 14:21:571516
[email protected]765b44502009-10-02 05:01:421517 return true;
1518}
1519
Victor Costancfbfa602018-08-01 23:24:461520void Database::DoRollback() {
[email protected]e5ffd0e42009-09-11 21:30:561521 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321522
Victor Costan5e785e32019-02-26 20:39:311523 rollback.Run();
shess58b8df82015-06-03 00:19:321524
shess7dbd4dee2015-10-06 17:39:161525 // The cache may have been accumulating dirty pages for commit. Note that in
1526 // some cases sql::Transaction can fire rollback after a database is closed.
1527 if (is_open())
1528 ReleaseCacheMemoryIfNeeded(false);
1529
[email protected]44ad7d902012-03-23 00:09:051530 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561531}
1532
Victor Costancfbfa602018-08-01 23:24:461533void Database::StatementRefCreated(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551534 DCHECK(!open_statements_.count(ref))
1535 << __func__ << " already called with this statement";
[email protected]e5ffd0e42009-09-11 21:30:561536 open_statements_.insert(ref);
1537}
1538
Victor Costancfbfa602018-08-01 23:24:461539void Database::StatementRefDeleted(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551540 DCHECK(open_statements_.count(ref))
1541 << __func__ << " called with non-existing statement";
1542 open_statements_.erase(ref);
[email protected]e5ffd0e42009-09-11 21:30:561543}
1544
Victor Costancfbfa602018-08-01 23:24:461545void Database::set_histogram_tag(const std::string& tag) {
shess58b8df82015-06-03 00:19:321546 DCHECK(!is_open());
Victor Costan87cf8c72018-07-19 19:36:041547
shess58b8df82015-06-03 00:19:321548 histogram_tag_ = tag;
1549}
1550
Will Harrisb8693592018-08-28 22:58:441551void Database::AddTaggedHistogram(const std::string& name, int sample) const {
[email protected]210ce0af2013-05-15 09:10:391552 if (histogram_tag_.empty())
1553 return;
1554
1555 // TODO(shess): The histogram macros create a bit of static storage
1556 // for caching the histogram object. This code shouldn't execute
1557 // often enough for such caching to be crucial. If it becomes an
1558 // issue, the object could be cached alongside histogram_prefix_.
1559 std::string full_histogram_name = name + "." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:461560 base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
1561 full_histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]210ce0af2013-05-15 09:10:391562 if (histogram)
1563 histogram->Add(sample);
1564}
1565
Victor Costancfbfa602018-08-01 23:24:461566int Database::OnSqliteError(int err,
1567 sql::Statement* stmt,
1568 const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181569 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391570 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141571
1572 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581573 if (!sql && stmt)
1574 sql = stmt->GetSQLStatement();
1575 if (!sql)
1576 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061577
1578 std::string id = histogram_tag_;
1579 if (id.empty())
1580 id = DbPath().BaseName().AsUTF8Unsafe();
Victor Costancfbfa602018-08-01 23:24:461581 LOG(ERROR) << id << " sqlite error " << err << ", errno " << GetLastErrno()
1582 << ": " << GetErrorMessage() << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141583
[email protected]c3881b372013-05-17 08:39:461584 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561585 // Fire from a copy of the callback in case of reentry into
1586 // re/set_error_callback().
1587 // TODO(shess): <http://crbug.com/254584>
1588 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461589 return err;
1590 }
1591
[email protected]faa604e2009-09-25 22:38:591592 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251593 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521594 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591595 return err;
1596}
1597
Victor Costancfbfa602018-08-01 23:24:461598bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
[email protected]579446c2013-12-16 18:36:521599 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1600}
1601
Victor Costancfbfa602018-08-01 23:24:461602bool Database::QuickIntegrityCheck() {
[email protected]579446c2013-12-16 18:36:521603 std::vector<std::string> messages;
1604 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1605 return false;
1606 return messages.size() == 1 && messages[0] == "ok";
1607}
1608
Victor Costancfbfa602018-08-01 23:24:461609std::string Database::GetDiagnosticInfo(int extended_error,
1610 Statement* statement) {
afakhry7c9abe72016-08-05 17:33:191611 // Prevent reentrant calls to the error callback.
1612 ErrorCallback original_callback = std::move(error_callback_);
1613 reset_error_callback();
1614
1615 // Trim extended error codes.
1616 const int error = (extended_error & 0xFF);
Victor Costancfbfa602018-08-01 23:24:461617 // CollectCorruptionInfo() is implemented in terms of sql::Database,
afakhry7c9abe72016-08-05 17:33:191618 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1619 std::string result = (error == SQLITE_CORRUPT)
1620 ? CollectCorruptionInfo()
1621 : CollectErrorInfo(extended_error, statement);
1622
1623 // The following queries must be executed after CollectErrorInfo() above, so
1624 // if they result in their own errors, they don't interfere with
1625 // CollectErrorInfo().
1626 const bool has_valid_header =
1627 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1628 const bool select_sqlite_master_result =
1629 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1630 SQLITE_OK);
1631
1632 // Restore the original error callback.
1633 error_callback_ = std::move(original_callback);
1634
1635 base::StringAppendF(&result, "Has valid header: %s\n",
1636 (has_valid_header ? "Yes" : "No"));
1637 base::StringAppendF(&result, "Has valid schema: %s\n",
1638 (select_sqlite_master_result ? "Yes" : "No"));
1639
1640 return result;
1641}
1642
[email protected]80abf152013-05-22 12:42:421643// TODO(shess): Allow specifying maximum results (default 100 lines).
Victor Costancfbfa602018-08-01 23:24:461644bool Database::IntegrityCheckHelper(const char* pragma_sql,
1645 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421646 messages->clear();
1647
[email protected]4658e2a02013-06-06 23:05:001648 // This has the side effect of setting SQLITE_RecoveryMode, which
1649 // allows SQLite to process through certain cases of corruption.
1650 // Failing to set this pragma probably means that the database is
1651 // beyond recovery.
Victor Costan4c2f3e922018-08-21 04:47:591652 static const char kWritableSchemaSql[] = "PRAGMA writable_schema=ON";
Victor Costan1d868352018-06-26 19:06:481653 if (!Execute(kWritableSchemaSql))
[email protected]4658e2a02013-06-06 23:05:001654 return false;
1655
1656 bool ret = false;
1657 {
[email protected]579446c2013-12-16 18:36:521658 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001659
1660 // The pragma appears to return all results (up to 100 by default)
1661 // as a single string. This doesn't appear to be an API contract,
1662 // it could return separate lines, so loop _and_ split.
1663 while (stmt.Step()) {
1664 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181665 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1666 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001667 }
1668 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421669 }
[email protected]4658e2a02013-06-06 23:05:001670
1671 // Best effort to put things back as they were before.
Victor Costan4c2f3e922018-08-21 04:47:591672 static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema=OFF";
Victor Costan1d868352018-06-26 19:06:481673 ignore_result(Execute(kNoWritableSchemaSql));
[email protected]4658e2a02013-06-06 23:05:001674
1675 return ret;
[email protected]80abf152013-05-22 12:42:421676}
1677
Victor Costancfbfa602018-08-01 23:24:461678bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1679 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131680 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381681 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131682}
1683
[email protected]e5ffd0e42009-09-11 21:30:561684} // namespace sql