blob: e820382ea3422c6be102d970ee13bc61cbadf0c4 [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
tzikb9dae932017-02-10 03:57:3012#include "base/debug/alias.h"
shessc8cd2a162015-10-22 20:30:4613#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5214#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4415#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4616#include "base/format_macros.h"
17#include "base/json/json_file_value_serializer.h"
fdoray2dfa76452016-06-07 13:11:2218#include "base/location.h"
[email protected]e5ffd0e42009-09-11 21:30:5619#include "base/logging.h"
Ilya Sherman1c811db2017-12-14 10:36:1820#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0821#include "base/metrics/histogram_macros.h"
[email protected]210ce0af2013-05-15 09:10:3922#include "base/metrics/sparse_histogram.h"
Victor Costan3653df62018-02-08 21:38:1623#include "base/no_destructor.h"
Will Harrisb8693592018-08-28 22:58:4424#include "base/numerics/safe_conversions.h"
fdoray2dfa76452016-06-07 13:11:2225#include "base/single_thread_task_runner.h"
[email protected]80abf152013-05-22 12:42:4226#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1927#include "base/strings/string_util.h"
28#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4529#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1830#include "base/synchronization/lock.h"
Etienne Pierre-Doray0400dfb62018-12-03 19:12:2531#include "base/threading/scoped_blocking_call.h"
Victor Costan87cf8c72018-07-19 19:36:0432#include "base/time/default_tick_clock.h"
ssid9f8022f2015-10-12 17:49:0333#include "base/trace_event/memory_dump_manager.h"
Kevin Marshalla9f05ec2017-07-14 02:10:0534#include "build/build_config.h"
Victor Costancfbfa602018-08-01 23:24:4635#include "sql/database_memory_dump_provider.h"
Victor Costan3653df62018-02-08 21:38:1636#include "sql/initialization.h"
shess9bf2c672015-12-18 01:18:0837#include "sql/meta_table.h"
Victor Costan4c2f3e922018-08-21 04:47:5938#include "sql/sql_features.h"
[email protected]f0a54b22011-07-19 18:40:2139#include "sql/statement.h"
shess5f2c3442017-01-24 02:15:1040#include "sql/vfs_wrapper.h"
[email protected]e33cba42010-08-18 23:37:0341#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5642
[email protected]5b96f3772010-09-28 16:30:5743namespace {
44
45// Spin for up to a second waiting for the lock to clear when setting
46// up the database.
47// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2748const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5749
50class ScopedBusyTimeout {
51 public:
Victor Costancfbfa602018-08-01 23:24:4652 explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
53 ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
[email protected]5b96f3772010-09-28 16:30:5754
55 int SetTimeout(base::TimeDelta timeout) {
56 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
57 return sqlite3_busy_timeout(db_,
58 static_cast<int>(timeout.InMilliseconds()));
59 }
60
61 private:
62 sqlite3* db_;
63};
64
[email protected]6d42f152012-11-10 00:38:2465// Helper to "safely" enable writable_schema. No error checking
66// because it is reasonable to just forge ahead in case of an error.
67// If turning it on fails, then most likely nothing will work, whereas
68// if turning it off fails, it only matters if some code attempts to
69// continue working with the database and tries to modify the
70// sqlite_master table (none of our code does this).
71class ScopedWritableSchema {
72 public:
Victor Costancfbfa602018-08-01 23:24:4673 explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
Victor Costanbd623112018-07-18 04:17:2774 sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2475 }
76 ~ScopedWritableSchema() {
Victor Costanbd623112018-07-18 04:17:2777 sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2478 }
79
80 private:
81 sqlite3* db_;
82};
83
[email protected]7bae5742013-07-10 20:46:1684// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
85// SQLite error code from running the backup step.
86int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
87 DCHECK_NE(src, dst);
88 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
89 if (!backup) {
90 // Since this call only sets things up, this indicates a gross
91 // error in SQLite.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:5292 DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
[email protected]7bae5742013-07-10 20:46:1693 return sqlite3_errcode(dst);
94 }
95
96 // -1 backs up the entire database.
97 int rc = sqlite3_backup_step(backup, -1);
98 int pages = sqlite3_backup_pagecount(backup);
99 sqlite3_backup_finish(backup);
100
101 // If successful, exactly one page should have been backed up. If
102 // this breaks, check this function to make sure assumptions aren't
103 // being broken.
104 if (rc == SQLITE_DONE)
105 DCHECK_EQ(pages, 1);
106
107 return rc;
108}
109
[email protected]8d409412013-07-19 18:25:30110// Be very strict on attachment point. SQLite can handle a much wider
111// character set with appropriate quoting, but Chromium code should
112// just use clean names to start with.
113bool ValidAttachmentPoint(const char* attachment_point) {
114 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20115 if (!(base::IsAsciiDigit(attachment_point[i]) ||
116 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30117 attachment_point[i] == '_')) {
118 return false;
119 }
120 }
121 return true;
122}
123
[email protected]8ada10f2013-12-21 00:42:34124// Helper to get the sqlite3_file* associated with the "main" database.
125int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
Victor Costanbd623112018-07-18 04:17:27126 *file = nullptr;
127 int rc = sqlite3_file_control(db, nullptr, SQLITE_FCNTL_FILE_POINTER, file);
[email protected]8ada10f2013-12-21 00:42:34128 if (rc != SQLITE_OK)
129 return rc;
130
Victor Costanbd623112018-07-18 04:17:27131 // TODO(shess): null in file->pMethods has been observed on android_dbg
[email protected]8ada10f2013-12-21 00:42:34132 // content_unittests, even though it should not be possible.
133 // http://crbug.com/329982
134 if (!*file || !(*file)->pMethods)
135 return SQLITE_ERROR;
136
137 return rc;
138}
139
shess5dac334f2015-11-05 20:47:42140// Convenience to get the sqlite3_file* and the size for the "main" database.
141int GetSqlite3FileAndSize(sqlite3* db,
Victor Costancfbfa602018-08-01 23:24:46142 sqlite3_file** file,
143 sqlite3_int64* db_size) {
shess5dac334f2015-11-05 20:47:42144 int rc = GetSqlite3File(db, file);
145 if (rc != SQLITE_OK)
146 return rc;
147
148 return (*file)->pMethods->xFileSize(*file, db_size);
149}
150
shess58b8df82015-06-03 00:19:32151// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
152base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
153 return base::Histogram::FactoryTimeGet(
Victor Costancfbfa602018-08-01 23:24:46154 name, base::TimeDelta::FromMilliseconds(10),
155 base::TimeDelta::FromMinutes(3), 50,
shess58b8df82015-06-03 00:19:32156 base::HistogramBase::kUmaTargetedHistogramFlag);
157}
158
erg102ceb412015-06-20 01:38:13159std::string AsUTF8ForSQL(const base::FilePath& path) {
160#if defined(OS_WIN)
jdoerrie6312bf62019-02-01 22:03:42161 return base::UTF16ToUTF8(path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18162#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
erg102ceb412015-06-20 01:38:13163 return path.value();
164#endif
165}
166
[email protected]5b96f3772010-09-28 16:30:57167} // namespace
168
[email protected]e5ffd0e42009-09-11 21:30:56169namespace sql {
170
[email protected]4350e322013-06-18 22:18:10171// static
Victor Costancfbfa602018-08-01 23:24:46172Database::ErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10173
174// static
Victor Costancfbfa602018-08-01 23:24:46175bool Database::IsExpectedSqliteError(int error) {
shess976814402016-06-21 06:56:25176 if (!current_expecter_cb_)
[email protected]4350e322013-06-18 22:18:10177 return false;
shess976814402016-06-21 06:56:25178 return current_expecter_cb_->Run(error);
[email protected]4350e322013-06-18 22:18:10179}
180
Victor Costancfbfa602018-08-01 23:24:46181void Database::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
shessc8cd2a162015-10-22 20:30:46182 AssertIOAllowed();
183
afakhry7c9abe72016-08-05 17:33:19184 std::string debug_info = GetDiagnosticInfo(extended_error, stmt);
shessc8cd2a162015-10-22 20:30:46185 if (!debug_info.empty() && RegisterIntentToUpload()) {
Lukasz Anforowicz68c21772018-01-13 03:42:44186 DEBUG_ALIAS_FOR_CSTR(debug_buf, debug_info.c_str(), 2000);
shessc8cd2a162015-10-22 20:30:46187 base::debug::DumpWithoutCrashing();
188 }
189}
190
[email protected]4350e322013-06-18 22:18:10191// static
Victor Costancfbfa602018-08-01 23:24:46192void Database::SetErrorExpecter(Database::ErrorExpecterCallback* cb) {
Victor Costanbd623112018-07-18 04:17:27193 CHECK(!current_expecter_cb_);
shess976814402016-06-21 06:56:25194 current_expecter_cb_ = cb;
[email protected]4350e322013-06-18 22:18:10195}
196
197// static
Victor Costancfbfa602018-08-01 23:24:46198void Database::ResetErrorExpecter() {
shess976814402016-06-21 06:56:25199 CHECK(current_expecter_cb_);
Victor Costanbd623112018-07-18 04:17:27200 current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10201}
202
Victor Costance678e72018-07-24 10:25:00203// static
Victor Costancfbfa602018-08-01 23:24:46204base::FilePath Database::JournalPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00205 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
206}
207
208// static
Victor Costancfbfa602018-08-01 23:24:46209base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00210 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
211}
212
213// static
Victor Costancfbfa602018-08-01 23:24:46214base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00215 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
216}
217
Victor Costancfbfa602018-08-01 23:24:46218Database::StatementRef::StatementRef(Database* database,
219 sqlite3_stmt* stmt,
220 bool was_valid)
221 : database_(database), stmt_(stmt), was_valid_(was_valid) {
222 if (database)
223 database_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56224}
225
Victor Costancfbfa602018-08-01 23:24:46226Database::StatementRef::~StatementRef() {
227 if (database_)
228 database_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38229 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56230}
231
Victor Costancfbfa602018-08-01 23:24:46232void Database::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56233 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50234 // Call to AssertIOAllowed() cannot go at the beginning of the function
235 // because Close() is called unconditionally from destructor to clean
Victor Costancfbfa602018-08-01 23:24:46236 // database_. And if this is inactive statement this won't cause any
[email protected]35f7e5392012-07-27 19:54:50237 // disk access and destructor most probably will be called on thread
238 // not allowing disk access.
239 // TODO([email protected]): This should move to the beginning
240 // of the function. http://crbug.com/136655.
241 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56242 sqlite3_finalize(stmt_);
Victor Costanbd623112018-07-18 04:17:27243 stmt_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56244 }
Victor Costancfbfa602018-08-01 23:24:46245 database_ = nullptr; // The Database may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38246
247 // Forced close is expected to happen from a statement error
248 // handler. In that case maintain the sense of |was_valid_| which
249 // previously held for this ref.
250 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56251}
252
Victor Costan7f6abbbe2018-07-29 02:57:27253static_assert(
Victor Costancfbfa602018-08-01 23:24:46254 Database::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
255 "Database::kDefaultPageSize must match the value configured into SQLite");
Victor Costan7f6abbbe2018-07-29 02:57:27256
Victor Costancfbfa602018-08-01 23:24:46257constexpr int Database::kDefaultPageSize;
Victor Costan7f6abbbe2018-07-29 02:57:27258
Victor Costancfbfa602018-08-01 23:24:46259Database::Database()
Victor Costanbd623112018-07-18 04:17:27260 : db_(nullptr),
Victor Costan7f6abbbe2018-07-29 02:57:27261 page_size_(kDefaultPageSize),
[email protected]e5ffd0e42009-09-11 21:30:56262 cache_size_(0),
263 exclusive_locking_(false),
264 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50265 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16266 in_memory_(false),
shess58b8df82015-06-03 00:19:32267 poisoned_(false),
shessa62504d2016-11-07 19:26:12268 mmap_alt_status_(false),
kerz42ff2a012016-04-27 04:50:06269 mmap_disabled_(false),
shess7dbd4dee2015-10-06 17:39:16270 mmap_enabled_(false),
271 total_changes_at_last_release_(0),
Victor Costanbd623112018-07-18 04:17:27272 stats_histogram_(nullptr),
273 commit_time_histogram_(nullptr),
274 autocommit_time_histogram_(nullptr),
275 update_time_histogram_(nullptr),
276 query_time_histogram_(nullptr),
Victor Costan87cf8c72018-07-19 19:36:04277 clock_(std::make_unique<base::DefaultTickClock>()) {}
[email protected]e5ffd0e42009-09-11 21:30:56278
Victor Costancfbfa602018-08-01 23:24:46279Database::~Database() {
[email protected]e5ffd0e42009-09-11 21:30:56280 Close();
281}
282
Victor Costancfbfa602018-08-01 23:24:46283void Database::RecordEvent(Events event, size_t count) {
shess58b8df82015-06-03 00:19:32284 for (size_t i = 0; i < count; ++i) {
285 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
286 }
287
288 if (stats_histogram_) {
289 for (size_t i = 0; i < count; ++i) {
290 stats_histogram_->Add(event);
291 }
292 }
293}
294
Victor Costancfbfa602018-08-01 23:24:46295void Database::RecordCommitTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32296 RecordUpdateTime(delta);
297 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
298 if (commit_time_histogram_)
299 commit_time_histogram_->AddTime(delta);
300}
301
Victor Costancfbfa602018-08-01 23:24:46302void Database::RecordAutoCommitTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32303 RecordUpdateTime(delta);
304 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
305 if (autocommit_time_histogram_)
306 autocommit_time_histogram_->AddTime(delta);
307}
308
Victor Costancfbfa602018-08-01 23:24:46309void Database::RecordUpdateTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32310 RecordQueryTime(delta);
311 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
312 if (update_time_histogram_)
313 update_time_histogram_->AddTime(delta);
314}
315
Victor Costancfbfa602018-08-01 23:24:46316void Database::RecordQueryTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32317 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
318 if (query_time_histogram_)
319 query_time_histogram_->AddTime(delta);
320}
321
Victor Costancfbfa602018-08-01 23:24:46322void Database::RecordTimeAndChanges(const base::TimeDelta& delta,
323 bool read_only) {
shess58b8df82015-06-03 00:19:32324 if (read_only) {
325 RecordQueryTime(delta);
326 } else {
327 const int changes = sqlite3_changes(db_);
328 if (sqlite3_get_autocommit(db_)) {
329 RecordAutoCommitTime(delta);
330 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
331 } else {
332 RecordUpdateTime(delta);
333 RecordEvent(EVENT_CHANGES, changes);
334 }
335 }
336}
337
Victor Costancfbfa602018-08-01 23:24:46338bool Database::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02339 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26340 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49341 if (base::GetFileSize(path, &size_64)) {
Will Harrisb8693592018-08-28 22:58:44342 int sample = base::saturated_cast<int>(size_64 / 1024);
[email protected]348ac8f52013-05-21 03:27:02343 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:46344 base::HistogramBase* histogram = base::Histogram::FactoryGet(
345 full_histogram_name, 1, 1000000, 50,
346 base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]348ac8f52013-05-21 03:27:02347 if (histogram)
348 histogram->Add(sample);
Steven Holte95922222018-09-14 20:06:23349 UMA_HISTOGRAM_COUNTS_1M("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02350 }
351 }
352
erg102ceb412015-06-20 01:38:13353 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42354}
[email protected]e5ffd0e42009-09-11 21:30:56355
Victor Costancfbfa602018-08-01 23:24:46356bool Database::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50357 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13358 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56359}
360
Victor Costancfbfa602018-08-01 23:24:46361bool Database::OpenTemporary() {
[email protected]8d409412013-07-19 18:25:30362 return OpenInternal("", NO_RETRY);
363}
364
Victor Costancfbfa602018-08-01 23:24:46365void Database::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47366 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
367 // will delete the -journal file. For ChromiumOS or other more
368 // embedded systems, this is probably not appropriate, whereas on
369 // desktop it might make some sense.
370
[email protected]4b350052012-02-24 20:40:48371 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48372
[email protected]41a97c812013-02-07 02:35:38373 // Release cached statements.
374 statement_cache_.clear();
375
376 // With cached statements released, in-use statements will remain.
377 // Closing the database while statements are in use is an API
378 // violation, except for forced close (which happens from within a
379 // statement's error handler).
380 DCHECK(forced || open_statements_.empty());
381
382 // Deactivate any outstanding statements so sqlite3_close() works.
Victor Costanc7e7f2e2018-07-18 20:07:55383 for (StatementRef* statement_ref : open_statements_)
384 statement_ref->Close(forced);
[email protected]41a97c812013-02-07 02:35:38385 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48386
[email protected]e5ffd0e42009-09-11 21:30:56387 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50388 // Call to AssertIOAllowed() cannot go at the beginning of the function
389 // because Close() must be called from destructor to clean
390 // statement_cache_, it won't cause any disk access and it most probably
391 // will happen on thread not allowing disk access.
392 // TODO([email protected]): This should move to the beginning
393 // of the function. http://crbug.com/136655.
394 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28395
ssid3be5b1ec2016-01-13 14:21:57396 // Reseting acquires a lock to ensure no dump is happening on the database
397 // at the same time. Unregister takes ownership of provider and it is safe
398 // since the db is reset. memory_dump_provider_ could be null if db_ was
399 // poisoned.
400 if (memory_dump_provider_) {
401 memory_dump_provider_->ResetDatabase();
402 base::trace_event::MemoryDumpManager::GetInstance()
403 ->UnregisterAndDeleteDumpProviderSoon(
404 std::move(memory_dump_provider_));
405 }
406
[email protected]73fb8d52013-07-24 05:04:28407 int rc = sqlite3_close(db_);
408 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18409 base::UmaHistogramSparse("Sqlite.CloseFailure", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52410 DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage();
[email protected]73fb8d52013-07-24 05:04:28411 }
[email protected]e5ffd0e42009-09-11 21:30:56412 }
Victor Costanbd623112018-07-18 04:17:27413 db_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56414}
415
Victor Costancfbfa602018-08-01 23:24:46416void Database::Close() {
[email protected]41a97c812013-02-07 02:35:38417 // If the database was already closed by RazeAndClose(), then no
418 // need to close again. Clear the |poisoned_| bit so that incorrect
419 // API calls are caught.
420 if (poisoned_) {
421 poisoned_ = false;
422 return;
423 }
424
425 CloseInternal(false);
426}
427
Victor Costancfbfa602018-08-01 23:24:46428void Database::Preload() {
[email protected]35f7e5392012-07-27 19:54:50429 AssertIOAllowed();
430
[email protected]e5ffd0e42009-09-11 21:30:56431 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52432 DCHECK(poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56433 return;
434 }
435
Victor Costan7f6abbbe2018-07-29 02:57:27436 // The constructor and set_page_size() ensure that page_size_ is never zero.
437 const int page_size = page_size_;
438 DCHECK(page_size);
439
[email protected]8ada10f2013-12-21 00:42:34440 // Use local settings if provided, otherwise use documented defaults. The
441 // actual results could be fetching via PRAGMA calls.
[email protected]8ada10f2013-12-21 00:42:34442 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
443 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56444 return;
445
Victor Costanbd623112018-07-18 04:17:27446 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:34447 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42448 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34449 if (rc != SQLITE_OK)
450 return;
451
452 // Don't preload more than the file contains.
453 if (preload_size > file_size)
454 preload_size = file_size;
455
mostynbd82cd9952016-04-11 20:05:34456 std::unique_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46457 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34458 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31459
460 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34461 if (rc != SQLITE_OK)
462 return;
463 }
[email protected]e5ffd0e42009-09-11 21:30:56464}
465
Victor Costancfbfa602018-08-01 23:24:46466// SQLite keeps unused pages associated with a database in a cache. It asks
shess7dbd4dee2015-10-06 17:39:16467// the cache for pages by an id, and if the page is present and the database is
468// unchanged, it considers the content of the page valid and doesn't read it
469// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
470// structures created from the memory map data before consulting the cache. On
471// write SQLite creates a new in-memory page structure, copies the data from the
472// memory map, and later writes it, releasing the updated page back to the
473// cache.
474//
475// This means that in memory-mapped mode, the contents of the cached pages are
476// not re-used for reads, but they are re-used for writes if the re-written page
477// is still in the cache. The implementation of sqlite3_db_release_memory() as
478// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
Victor Costancfbfa602018-08-01 23:24:46479// database, so it should free these pages.
shess7dbd4dee2015-10-06 17:39:16480//
481// Unfortunately, the zero page is also freed. That page is never accessed
482// using memory-mapped I/O, and the cached copy can be re-used after verifying
483// the file change counter on disk. Also, fresh pages from cache receive some
484// pager-level initialization before they can be used. Since the information
485// involved will immediately be accessed in various ways, it is unclear if the
486// additional overhead is material, or just moving processor cache effects
487// around.
488//
489// TODO(shess): It would be better to release the pages immediately when they
490// are no longer needed. This would basically happen after SQLite commits a
491// transaction. I had implemented a pcache wrapper to do this, but it involved
492// layering violations, and it had to be setup before any other sqlite call,
493// which was brittle. Also, for large files it would actually make sense to
494// maintain the existing pcache behavior for blocks past the memory-mapped
495// segment. I think drh would accept a reasonable implementation of the overall
496// concept for upstreaming to SQLite core.
497//
498// TODO(shess): Another possibility would be to set the cache size small, which
499// would keep the zero page around, plus some pre-initialized pages, and SQLite
500// can manage things. The downside is that updates larger than the cache would
501// spill to the journal. That could be compensated by setting cache_spill to
502// false. The downside then is that it allows open-ended use of memory for
503// large transactions.
Victor Costancfbfa602018-08-01 23:24:46504void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
shess644fc8a2016-02-26 18:15:58505 // The database could have been closed during a transaction as part of error
506 // recovery.
507 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:46508 DCHECK(poisoned_) << "Illegal use of Database without a db";
shess644fc8a2016-02-26 18:15:58509 return;
510 }
shess7dbd4dee2015-10-06 17:39:16511
512 // If memory-mapping is not enabled, the page cache helps performance.
513 if (!mmap_enabled_)
514 return;
515
516 // On caller request, force the change comparison to fail. Done before the
517 // transaction-nesting test so that the signal can carry to transaction
518 // commit.
519 if (implicit_change_performed)
520 --total_changes_at_last_release_;
521
522 // Cached pages may be re-used within the same transaction.
523 if (transaction_nesting())
524 return;
525
526 // If no changes have been made, skip flushing. This allows the first page of
527 // the database to remain in cache across multiple reads.
528 const int total_changes = sqlite3_total_changes(db_);
529 if (total_changes == total_changes_at_last_release_)
530 return;
531
532 total_changes_at_last_release_ = total_changes;
533 sqlite3_db_release_memory(db_);
534}
535
Victor Costancfbfa602018-08-01 23:24:46536base::FilePath Database::DbPath() const {
shessc8cd2a162015-10-22 20:30:46537 if (!is_open())
538 return base::FilePath();
539
540 const char* path = sqlite3_db_filename(db_, "main");
541 const base::StringPiece db_path(path);
542#if defined(OS_WIN)
jdoerrie6312bf62019-02-01 22:03:42543 return base::FilePath(base::UTF8ToUTF16(db_path));
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18544#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46545 return base::FilePath(db_path);
546#else
547 NOTREACHED();
548 return base::FilePath();
549#endif
550}
551
552// Data is persisted in a file shared between databases in the same directory.
553// The "sqlite-diag" file contains a dictionary with the version number, and an
554// array of histogram tags for databases which have been dumped.
Victor Costancfbfa602018-08-01 23:24:46555bool Database::RegisterIntentToUpload() const {
shessc8cd2a162015-10-22 20:30:46556 static const char* kVersionKey = "version";
557 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
558 static int kVersion = 1;
559
560 AssertIOAllowed();
561
562 if (histogram_tag_.empty())
563 return false;
564
565 if (!is_open())
566 return false;
567
568 if (in_memory_)
569 return false;
570
571 const base::FilePath db_path = DbPath();
572 if (db_path.empty())
573 return false;
574
575 // Put the collection of diagnostic data next to the databases. In most
576 // cases, this is the profile directory, but safe-browsing stores a Cookies
577 // file in the directory above the profile directory.
Victor Costance678e72018-07-24 10:25:00578 base::FilePath breadcrumb_path = db_path.DirName().AppendASCII("sqlite-diag");
shessc8cd2a162015-10-22 20:30:46579
580 // Lock against multiple updates to the diagnostics file. This code should
581 // seldom be called in the first place, and when called it should seldom be
582 // called for multiple databases, and when called for multiple databases there
583 // is _probably_ something systemic wrong with the user's system. So the lock
584 // should never be contended, but when it is the database experience is
585 // already bad.
Victor Costan3653df62018-02-08 21:38:16586 static base::NoDestructor<base::Lock> lock;
587 base::AutoLock auto_lock(*lock);
shessc8cd2a162015-10-22 20:30:46588
mostynbd82cd9952016-04-11 20:05:34589 std::unique_ptr<base::Value> root;
shessc8cd2a162015-10-22 20:30:46590 if (!base::PathExists(breadcrumb_path)) {
mostynbd82cd9952016-04-11 20:05:34591 std::unique_ptr<base::DictionaryValue> root_dict(
592 new base::DictionaryValue());
shessc8cd2a162015-10-22 20:30:46593 root_dict->SetInteger(kVersionKey, kVersion);
594
mostynbd82cd9952016-04-11 20:05:34595 std::unique_ptr<base::ListValue> dumps(new base::ListValue);
shessc8cd2a162015-10-22 20:30:46596 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50597 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46598
dchenge48600452015-12-28 02:24:50599 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46600 } else {
601 // Failure to read a valid dictionary implies that something is going wrong
602 // on the system.
603 JSONFileValueDeserializer deserializer(breadcrumb_path);
mostynbd82cd9952016-04-11 20:05:34604 std::unique_ptr<base::Value> read_root(
shessc8cd2a162015-10-22 20:30:46605 deserializer.Deserialize(nullptr, nullptr));
606 if (!read_root.get())
607 return false;
mostynbd82cd9952016-04-11 20:05:34608 std::unique_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50609 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46610 if (!root_dict)
611 return false;
612
613 // Don't upload if the version is missing or newer.
614 int version = 0;
615 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
616 return false;
617
618 base::ListValue* dumps = nullptr;
619 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
620 return false;
621
622 const size_t size = dumps->GetSize();
623 for (size_t i = 0; i < size; ++i) {
624 std::string s;
625
626 // Don't upload if the value isn't a string, or indicates a prior upload.
627 if (!dumps->GetString(i, &s) || s == histogram_tag_)
628 return false;
629 }
630
631 // Record intention to proceed with upload.
632 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50633 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46634 }
635
636 const base::FilePath breadcrumb_new =
637 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
638 base::DeleteFile(breadcrumb_new, false);
639
640 // No upload if the breadcrumb file cannot be updated.
641 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
642 // the data on disk. For now, losing the data is not a big problem, so the
643 // sync overhead would probably not be worth it.
644 JSONFileValueSerializer serializer(breadcrumb_new);
645 if (!serializer.Serialize(*root))
646 return false;
647 if (!base::PathExists(breadcrumb_new))
648 return false;
649 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
650 base::DeleteFile(breadcrumb_new, false);
651 return false;
652 }
653
654 return true;
655}
656
Victor Costancfbfa602018-08-01 23:24:46657std::string Database::CollectErrorInfo(int error, Statement* stmt) const {
shessc8cd2a162015-10-22 20:30:46658 // Buffer for accumulating debugging info about the error. Place
659 // more-relevant information earlier, in case things overflow the
660 // fixed-size reporting buffer.
661 std::string debug_info;
662
663 // The error message from the failed operation.
Victor Costancfbfa602018-08-01 23:24:46664 base::StringAppendF(&debug_info, "db error: %d/%s\n", GetErrorCode(),
665 GetErrorMessage());
shessc8cd2a162015-10-22 20:30:46666
667 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
668 // reading code does not entirely convince me. Remove if they turn out to be
669 // the same.
670 if (error != GetErrorCode())
671 base::StringAppendF(&debug_info, "reported error: %d\n", error);
672
Victor Costancfbfa602018-08-01 23:24:46673// System error information. Interpretation of Windows errors is different
674// from posix.
shessc8cd2a162015-10-22 20:30:46675#if defined(OS_WIN)
676 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18677#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46678 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
679#else
680 NOTREACHED(); // Add appropriate log info.
681#endif
682
683 if (stmt) {
684 base::StringAppendF(&debug_info, "statement: %s\n",
685 stmt->GetSQLStatement());
686 } else {
687 base::StringAppendF(&debug_info, "statement: NULL\n");
688 }
689
690 // SQLITE_ERROR often indicates some sort of mismatch between the statement
691 // and the schema, possibly due to a failed schema migration.
692 if (error == SQLITE_ERROR) {
693 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
694 sqlite3_stmt* s;
695 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
696 if (rc == SQLITE_OK) {
697 rc = sqlite3_step(s);
698 if (rc == SQLITE_ROW) {
699 base::StringAppendF(&debug_info, "version: %d\n",
700 sqlite3_column_int(s, 0));
701 } else if (rc == SQLITE_DONE) {
702 debug_info += "version: none\n";
703 } else {
704 base::StringAppendF(&debug_info, "version: error %d\n", rc);
705 }
706 sqlite3_finalize(s);
707 } else {
708 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
709 }
710
711 debug_info += "schema:\n";
712
713 // sqlite_master has columns:
714 // type - "index" or "table".
715 // name - name of created element.
716 // tbl_name - name of element, or target table in case of index.
717 // rootpage - root page of the element in database file.
718 // sql - SQL to create the element.
719 // In general, the |sql| column is sufficient to derive the other columns.
720 // |rootpage| is not interesting for debugging, without the contents of the
721 // database. The COALESCE is because certain automatic elements will have a
722 // |name| but no |sql|,
723 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
724 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
725 if (rc == SQLITE_OK) {
726 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
727 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
728 }
729 if (rc != SQLITE_DONE)
730 base::StringAppendF(&debug_info, "error %d\n", rc);
731 sqlite3_finalize(s);
732 } else {
733 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
734 }
735 }
736
737 return debug_info;
738}
739
740// TODO(shess): Since this is only called in an error situation, it might be
741// prudent to rewrite in terms of SQLite API calls, and mark the function const.
Victor Costancfbfa602018-08-01 23:24:46742std::string Database::CollectCorruptionInfo() {
shessc8cd2a162015-10-22 20:30:46743 AssertIOAllowed();
744
745 // If the file cannot be accessed it is unlikely that an integrity check will
746 // turn up actionable information.
747 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19748 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46749 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
750 return std::string();
751
752 // Buffer for accumulating debugging info about the error. Place
753 // more-relevant information earlier, in case things overflow the
754 // fixed-size reporting buffer.
755 std::string debug_info;
756 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
757 db_size);
758
759 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19760 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46761 if (db_size > kMaxIntegrityCheckSize) {
762 debug_info += "integrity_check skipped due to size\n";
763 } else {
764 std::vector<std::string> messages;
765
766 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
767 // into a string. Probably should be refactored.
768 const base::TimeTicks before = base::TimeTicks::Now();
769 FullIntegrityCheck(&messages);
770 base::StringAppendF(
Victor Costancfbfa602018-08-01 23:24:46771 &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
772 (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
shessc8cd2a162015-10-22 20:30:46773
774 // SQLite returns up to 100 messages by default, trim deeper to
775 // keep close to the 2000-character size limit for dumping.
776 const size_t kMaxMessages = 20;
777 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
778 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
779 }
780 }
781
782 return debug_info;
783}
784
Victor Costancfbfa602018-08-01 23:24:46785bool Database::GetMmapAltStatus(int64_t* status) {
shessa62504d2016-11-07 19:26:12786 // The [meta] version uses a missing table as a signal for a fresh database.
787 // That will not work for the view, which would not exist in either a new or
788 // an existing database. A new database _should_ be only one page long, so
789 // just don't bother optimizing this case (start at offset 0).
790 // TODO(shess): Could the [meta] case also get simpler, then?
791 if (!DoesViewExist("MmapStatus")) {
792 *status = 0;
793 return true;
794 }
795
796 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
797 Statement s(GetUniqueStatement(kMmapStatusSql));
798 if (s.Step())
799 *status = s.ColumnInt64(0);
800 return s.Succeeded();
801}
802
Victor Costancfbfa602018-08-01 23:24:46803bool Database::SetMmapAltStatus(int64_t status) {
shessa62504d2016-11-07 19:26:12804 if (!BeginTransaction())
805 return false;
806
807 // View may not exist on first run.
808 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
809 RollbackTransaction();
810 return false;
811 }
812
813 // Views live in the schema, so they cannot be parameterized. For an integer
814 // value, this construct should be safe from SQL injection, if the value
815 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
816 // value.
Victor Costancfbfa602018-08-01 23:24:46817 const std::string create_view_sql = base::StringPrintf(
818 "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
819 if (!Execute(create_view_sql.c_str())) {
shessa62504d2016-11-07 19:26:12820 RollbackTransaction();
821 return false;
822 }
823
824 return CommitTransaction();
825}
826
Victor Costancfbfa602018-08-01 23:24:46827size_t Database::GetAppropriateMmapSize() {
shessd90aeea82015-11-13 02:24:31828 AssertIOAllowed();
829
shess9bf2c672015-12-18 01:18:08830 // How much to map if no errors are found. 50MB encompasses the 99th
831 // percentile of Chrome databases in the wild, so this should be good.
832 const size_t kMmapEverything = 256 * 1024 * 1024;
833
shessa62504d2016-11-07 19:26:12834 // Progress information is tracked in the [meta] table for databases which use
835 // sql::MetaTable, otherwise it is tracked in a special view.
836 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08837 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12838 if (mmap_alt_status_) {
839 if (!GetMmapAltStatus(&mmap_ofs)) {
840 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
841 return 0;
842 }
843 } else {
844 // If [meta] doesn't exist, yet, it's a new database, assume the best.
845 // sql::MetaTable::Init() will preload kMmapSuccess.
846 if (!MetaTable::DoesTableExist(this)) {
847 RecordOneEvent(EVENT_MMAP_META_MISSING);
848 return kMmapEverything;
849 }
850
851 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
852 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
853 return 0;
854 }
shessd90aeea82015-11-13 02:24:31855 }
856
857 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08858 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31859 RecordOneEvent(EVENT_MMAP_FAILED);
860 return 0;
shess9bf2c672015-12-18 01:18:08861 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31862 // Continue reading from previous offset.
863 DCHECK_GE(mmap_ofs, 0);
864
865 // TODO(shess): Could this reading code be shared with Preload()? It would
866 // require locking twice (this code wouldn't be able to access |db_size| so
867 // the helper would have to return amount read).
868
869 // Read more of the database looking for errors. The VFS interface is used
870 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
871 // to limit checking to 20MB per run of Chromium.
Victor Costanbd623112018-07-18 04:17:27872 sqlite3_file* file = nullptr;
shessd90aeea82015-11-13 02:24:31873 sqlite3_int64 db_size = 0;
874 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
875 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
876 return 0;
877 }
878
879 // Read the data left, or |g_reads_allowed|, whichever is smaller.
880 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
881 // in a single Chromium run.
882 sqlite3_int64 amount = db_size - mmap_ofs;
883 if (amount < 0)
884 amount = 0;
885 if (amount > 0) {
Victor Costan3653df62018-02-08 21:38:16886 static base::NoDestructor<base::Lock> lock;
887 base::AutoLock auto_lock(*lock);
shessd90aeea82015-11-13 02:24:31888 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
889 if (g_reads_allowed < amount)
890 amount = g_reads_allowed;
891 g_reads_allowed -= amount;
892 }
893
894 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
895 // database was truncated after a previous pass.
896 if (amount <= 0 && mmap_ofs < db_size) {
897 DCHECK_EQ(0, amount);
898 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
899 } else {
900 static const int kPageSize = 4096;
901 char buf[kPageSize];
902 while (amount > 0) {
903 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
904 if (rc == SQLITE_OK) {
905 mmap_ofs += sizeof(buf);
906 amount -= sizeof(buf);
907 } else if (rc == SQLITE_IOERR_SHORT_READ) {
908 // Reached EOF for a database with page size < |kPageSize|.
909 mmap_ofs = db_size;
910 break;
911 } else {
912 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08913 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31914 break;
915 }
916 }
917
918 // Log these events after update to distinguish meta update failure.
919 Events event;
920 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08921 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31922 event = EVENT_MMAP_SUCCESS_NEW;
923 } else if (mmap_ofs > 0) {
924 event = EVENT_MMAP_SUCCESS_PARTIAL;
925 } else {
shess9bf2c672015-12-18 01:18:08926 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31927 event = EVENT_MMAP_FAILED_NEW;
928 }
929
shessa62504d2016-11-07 19:26:12930 if (mmap_alt_status_) {
931 if (!SetMmapAltStatus(mmap_ofs)) {
932 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
933 return 0;
934 }
935 } else {
936 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
937 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
938 return 0;
939 }
shessd90aeea82015-11-13 02:24:31940 }
941
942 RecordOneEvent(event);
943 }
944 }
945
shess9bf2c672015-12-18 01:18:08946 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31947 return 0;
shess9bf2c672015-12-18 01:18:08948 if (mmap_ofs == MetaTable::kMmapSuccess)
949 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31950 return mmap_ofs;
951}
952
Victor Costan52bef812018-12-05 07:41:49953void Database::TrimMemory() {
[email protected]be7995f12013-07-18 18:49:14954 if (!db_)
955 return;
956
Victor Costan52bef812018-12-05 07:41:49957 sqlite3_db_release_memory(db_);
[email protected]be7995f12013-07-18 18:49:14958
Victor Costan52bef812018-12-05 07:41:49959 // It is tempting to use sqlite3_release_memory() here as well. However, the
960 // API is documented to be a no-op unless SQLite is built with
961 // SQLITE_ENABLE_MEMORY_MANAGEMENT. We do not use this option, because it is
962 // incompatible with per-database page cache pools. Behind the scenes,
963 // SQLITE_ENABLE_MEMORY_MANAGEMENT causes SQLite to use a global page cache
964 // pool, and sqlite3_release_memory() releases unused pages from this global
965 // pool.
[email protected]be7995f12013-07-18 18:49:14966}
967
[email protected]8e0c01282012-04-06 19:36:49968// Create an in-memory database with the existing database's page
969// size, then backup that database over the existing database.
Victor Costancfbfa602018-08-01 23:24:46970bool Database::Raze() {
[email protected]35f7e5392012-07-27 19:54:50971 AssertIOAllowed();
972
[email protected]8e0c01282012-04-06 19:36:49973 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52974 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49975 return false;
976 }
977
978 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52979 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:49980 return false;
981 }
982
Victor Costancfbfa602018-08-01 23:24:46983 sql::Database null_db;
[email protected]8e0c01282012-04-06 19:36:49984 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52985 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:49986 return false;
987 }
988
Victor Costan7f6abbbe2018-07-29 02:57:27989 const std::string sql = base::StringPrintf("PRAGMA page_size=%d", page_size_);
990 if (!null_db.Execute(sql.c_str()))
991 return false;
[email protected]69c58452012-08-06 19:22:42992
[email protected]6d42f152012-11-10 00:38:24993#if defined(OS_ANDROID)
994 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
995 // in-memory databases do not respect this define.
996 // TODO(shess): Figure out a way to set this without using platform
997 // specific code. AFAICT from sqlite3.c, the only way to do it
998 // would be to create an actual filesystem database, which is
999 // unfortunate.
1000 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1001 return false;
1002#endif
[email protected]8e0c01282012-04-06 19:36:491003
1004 // The page size doesn't take effect until a database has pages, and
1005 // at this point the null database has none. Changing the schema
1006 // version will create the first page. This will not affect the
1007 // schema version in the resulting database, as SQLite's backup
1008 // implementation propagates the schema version from the original
Victor Costancfbfa602018-08-01 23:24:461009 // database to the new version of the database, incremented by one
[email protected]8e0c01282012-04-06 19:36:491010 // so that other readers see the schema change and act accordingly.
1011 if (!null_db.Execute("PRAGMA schema_version = 1"))
1012 return false;
1013
[email protected]6d42f152012-11-10 00:38:241014 // SQLite tracks the expected number of database pages in the first
1015 // page, and if it does not match the total retrieved from a
1016 // filesystem call, treats the database as corrupt. This situation
1017 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1018 // used to hint to SQLite to soldier on in that case, specifically
1019 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1020 // sqlite3.c lockBtree().]
1021 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1022 // page_size" can be used to query such a database.
1023 ScopedWritableSchema writable_schema(db_);
1024
shess92a6fb22017-04-23 04:33:301025#if defined(OS_WIN)
1026 // On Windows, truncate silently fails when applied to memory-mapped files.
1027 // Disable memory-mapping so that the truncate succeeds. Note that other
Victor Costancfbfa602018-08-01 23:24:461028 // Database connections may have memory-mapped the file, so this may not
1029 // entirely prevent the problem.
shess92a6fb22017-04-23 04:33:301030 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1031 ignore_result(Execute("PRAGMA mmap_size = 0"));
1032#endif
1033
[email protected]7bae5742013-07-10 20:46:161034 const char* kMain = "main";
1035 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181036 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:491037
1038 // The destination database was locked.
1039 if (rc == SQLITE_BUSY) {
1040 return false;
1041 }
1042
[email protected]7bae5742013-07-10 20:46:161043 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1044 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1045 // isn't even big enough for one page. Either way, reach in and
1046 // truncate it before trying again.
1047 // TODO(shess): Maybe it would be worthwhile to just truncate from
1048 // the get-go?
1049 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
Victor Costanbd623112018-07-18 04:17:271050 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:341051 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161052 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521053 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:161054 return false;
[email protected]7bae5742013-07-10 20:46:161055 }
1056
1057 rc = file->pMethods->xTruncate(file, 0);
1058 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181059 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521060 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:161061 return false;
1062 }
1063
1064 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181065 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:161066
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521067 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:161068 }
1069
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521070 // TODO(shess): Figure out which other cases can happen.
1071 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
1072
[email protected]8e0c01282012-04-06 19:36:491073 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521074 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:491075}
1076
Victor Costancfbfa602018-08-01 23:24:461077bool Database::RazeAndClose() {
[email protected]41a97c812013-02-07 02:35:381078 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521079 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:381080 return false;
1081 }
1082
1083 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301084 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381085
1086 bool result = Raze();
1087
1088 CloseInternal(true);
1089
1090 // Mark the database so that future API calls fail appropriately,
1091 // but don't DCHECK (because after calling this function they are
1092 // expected to fail).
1093 poisoned_ = true;
1094
1095 return result;
1096}
1097
Victor Costancfbfa602018-08-01 23:24:461098void Database::Poison() {
[email protected]8d409412013-07-19 18:25:301099 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521100 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:301101 return;
1102 }
1103
1104 RollbackAllTransactions();
1105 CloseInternal(true);
1106
1107 // Mark the database so that future API calls fail appropriately,
1108 // but don't DCHECK (because after calling this function they are
1109 // expected to fail).
1110 poisoned_ = true;
1111}
1112
[email protected]8d2e39e2013-06-24 05:55:081113// TODO(shess): To the extent possible, figure out the optimal
Victor Costancfbfa602018-08-01 23:24:461114// ordering for these deletes which will prevent other Database connections
[email protected]8d2e39e2013-06-24 05:55:081115// from seeing odd behavior. For instance, it may be necessary to
1116// manually lock the main database file in a SQLite-compatible fashion
1117// (to prevent other processes from opening it), then delete the
1118// journal files, then delete the main database file. Another option
1119// might be to lock the main database file and poison the header with
1120// junk to prevent other processes from opening it successfully (like
1121// Gears "SQLite poison 3" trick).
1122//
1123// static
Victor Costancfbfa602018-08-01 23:24:461124bool Database::Delete(const base::FilePath& path) {
Etienne Pierre-Doray0400dfb62018-12-03 19:12:251125 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
[email protected]8d2e39e2013-06-24 05:55:081126
Victor Costancfbfa602018-08-01 23:24:461127 base::FilePath journal_path = Database::JournalPath(path);
1128 base::FilePath wal_path = Database::WriteAheadLogPath(path);
[email protected]8d2e39e2013-06-24 05:55:081129
erg102ceb412015-06-20 01:38:131130 std::string journal_str = AsUTF8ForSQL(journal_path);
1131 std::string wal_str = AsUTF8ForSQL(wal_path);
1132 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081133
Victor Costan3653df62018-02-08 21:38:161134 EnsureSqliteInitialized();
shess702467622015-09-16 19:04:551135
Victor Costanbd623112018-07-18 04:17:271136 sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
erg102ceb412015-06-20 01:38:131137 CHECK(vfs);
1138 CHECK(vfs->xDelete);
1139 CHECK(vfs->xAccess);
1140
1141 // We only work with unix, win32 and mojo filesystems. If you're trying to
1142 // use this code with any other VFS, you're not in a good place.
1143 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1144 strncmp(vfs->zName, "win32", 5) == 0 ||
1145 strcmp(vfs->zName, "mojo") == 0);
1146
1147 vfs->xDelete(vfs, journal_str.c_str(), 0);
1148 vfs->xDelete(vfs, wal_str.c_str(), 0);
1149 vfs->xDelete(vfs, path_str.c_str(), 0);
1150
1151 int journal_exists = 0;
Victor Costance678e72018-07-24 10:25:001152 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
erg102ceb412015-06-20 01:38:131153
1154 int wal_exists = 0;
Victor Costance678e72018-07-24 10:25:001155 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
erg102ceb412015-06-20 01:38:131156
1157 int path_exists = 0;
Victor Costance678e72018-07-24 10:25:001158 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
erg102ceb412015-06-20 01:38:131159
1160 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081161}
1162
Victor Costancfbfa602018-08-01 23:24:461163bool Database::BeginTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561164 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331165 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561166
1167 // When we're going to rollback, fail on this begin and don't actually
1168 // mark us as entering the nested transaction.
1169 return false;
1170 }
1171
1172 bool success = true;
1173 if (!transaction_nesting_) {
1174 needs_rollback_ = false;
1175
1176 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321177 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591178 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561179 return false;
1180 }
1181 transaction_nesting_++;
1182 return success;
1183}
1184
Victor Costancfbfa602018-08-01 23:24:461185void Database::RollbackTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561186 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521187 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561188 return;
1189 }
1190
1191 transaction_nesting_--;
1192
1193 if (transaction_nesting_ > 0) {
1194 // Mark the outermost transaction as needing rollback.
1195 needs_rollback_ = true;
1196 return;
1197 }
1198
1199 DoRollback();
1200}
1201
Victor Costancfbfa602018-08-01 23:24:461202bool Database::CommitTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561203 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521204 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561205 return false;
1206 }
1207 transaction_nesting_--;
1208
1209 if (transaction_nesting_ > 0) {
1210 // Mark any nested transactions as failing after we've already got one.
1211 return !needs_rollback_;
1212 }
1213
1214 if (needs_rollback_) {
1215 DoRollback();
1216 return false;
1217 }
1218
1219 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321220
1221 // Collect the commit time manually, sql::Statement would register it as query
1222 // time only.
Victor Costan87cf8c72018-07-19 19:36:041223 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321224 bool ret = commit.RunWithoutTimers();
Victor Costan87cf8c72018-07-19 19:36:041225 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321226
1227 RecordCommitTime(delta);
1228 RecordOneEvent(EVENT_COMMIT);
1229
shess7dbd4dee2015-10-06 17:39:161230 // Release dirty cache pages after the transaction closes.
1231 ReleaseCacheMemoryIfNeeded(false);
1232
shess58b8df82015-06-03 00:19:321233 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561234}
1235
Victor Costancfbfa602018-08-01 23:24:461236void Database::RollbackAllTransactions() {
[email protected]8d409412013-07-19 18:25:301237 if (transaction_nesting_ > 0) {
1238 transaction_nesting_ = 0;
1239 DoRollback();
1240 }
1241}
1242
Victor Costancfbfa602018-08-01 23:24:461243bool Database::AttachDatabase(const base::FilePath& other_db_path,
1244 const char* attachment_point,
1245 InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301246 DCHECK(ValidAttachmentPoint(attachment_point));
1247
1248 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1249#if OS_WIN
1250 s.BindString16(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181251#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberibd1301f2018-05-18 21:00:091252 s.BindString(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181253#else
1254#error Unsupported platform
[email protected]8d409412013-07-19 18:25:301255#endif
1256 s.BindString(1, attachment_point);
1257 return s.Run();
1258}
1259
Victor Costancfbfa602018-08-01 23:24:461260bool Database::DetachDatabase(const char* attachment_point, InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301261 DCHECK(ValidAttachmentPoint(attachment_point));
1262
1263 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1264 s.BindString(0, attachment_point);
1265 return s.Run();
1266}
1267
shess58b8df82015-06-03 00:19:321268// TODO(shess): Consider changing this to execute exactly one statement. If a
1269// caller wishes to execute multiple statements, that should be explicit, and
1270// perhaps tucked into an explicit transaction with rollback in case of error.
Victor Costancfbfa602018-08-01 23:24:461271int Database::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501272 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381273 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461274 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381275 return SQLITE_ERROR;
1276 }
shess58b8df82015-06-03 00:19:321277 DCHECK(sql);
1278
1279 RecordOneEvent(EVENT_EXECUTE);
1280 int rc = SQLITE_OK;
1281 while ((rc == SQLITE_OK) && *sql) {
Victor Costanbd623112018-07-18 04:17:271282 sqlite3_stmt* stmt = nullptr;
Victor Costancfbfa602018-08-01 23:24:461283 const char* leftover_sql;
shess58b8df82015-06-03 00:19:321284
Victor Costan87cf8c72018-07-19 19:36:041285 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321286 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1287 sql = leftover_sql;
1288
1289 // Stop if an error is encountered.
1290 if (rc != SQLITE_OK)
1291 break;
1292
1293 // This happens if |sql| originally only contained comments or whitespace.
1294 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1295 // extraneous comments and whitespace in the SQL statements increases
1296 // runtime cost and can easily be shifted out to the C++ layer.
1297 if (!stmt)
1298 continue;
1299
1300 // Save for use after statement is finalized.
1301 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1302
Victor Costancfbfa602018-08-01 23:24:461303 RecordOneEvent(Database::EVENT_STATEMENT_RUN);
shess58b8df82015-06-03 00:19:321304 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1305 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1306 // is the only legitimate case for this.
Victor Costancfbfa602018-08-01 23:24:461307 RecordOneEvent(Database::EVENT_STATEMENT_ROWS);
shess58b8df82015-06-03 00:19:321308 }
1309
1310 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1311 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1312 rc = sqlite3_finalize(stmt);
1313 if (rc == SQLITE_OK)
Victor Costancfbfa602018-08-01 23:24:461314 RecordOneEvent(Database::EVENT_STATEMENT_SUCCESS);
shess58b8df82015-06-03 00:19:321315
1316 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1317 // trailing whitespace.
1318 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021319 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321320 sql++;
1321 }
1322
Victor Costan87cf8c72018-07-19 19:36:041323 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321324 RecordTimeAndChanges(delta, read_only);
1325 }
shess7dbd4dee2015-10-06 17:39:161326
1327 // Most calls to Execute() modify the database. The main exceptions would be
1328 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1329 // but sometimes don't.
1330 ReleaseCacheMemoryIfNeeded(true);
1331
shess58b8df82015-06-03 00:19:321332 return rc;
[email protected]eff1fa522011-12-12 23:50:591333}
1334
Victor Costancfbfa602018-08-01 23:24:461335bool Database::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381336 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461337 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381338 return false;
1339 }
1340
[email protected]eff1fa522011-12-12 23:50:591341 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001342 if (error != SQLITE_OK)
Victor Costanbd623112018-07-18 04:17:271343 error = OnSqliteError(error, nullptr, sql);
[email protected]473ad792012-11-10 00:55:001344
[email protected]28fe0ff2012-02-25 00:40:331345 // This needs to be a FATAL log because the error case of arriving here is
1346 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101347 // a change alters the schema but not all queries adjust. This can happen
1348 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521349 DCHECK_NE(error, SQLITE_ERROR)
1350 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591351 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561352}
1353
Victor Costancfbfa602018-08-01 23:24:461354bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381355 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461356 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]5b96f3772010-09-28 16:30:571357 return false;
[email protected]41a97c812013-02-07 02:35:381358 }
[email protected]5b96f3772010-09-28 16:30:571359
1360 ScopedBusyTimeout busy_timeout(db_);
1361 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591362 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571363}
1364
Victor Costancfbfa602018-08-01 23:24:461365scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
Victor Costan12daa3ac92018-07-19 01:05:581366 StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:561367 const char* sql) {
Victor Costanc7e7f2e2018-07-18 20:07:551368 auto it = statement_cache_.find(id);
1369 if (it != statement_cache_.end()) {
Victor Costan613b4302018-11-20 05:32:431370 // Statement is in the cache. It should still be valid. We're the only
1371 // entity invalidating cached statements, and we remove them from the cache
Victor Costan87cf8c72018-07-19 19:36:041372 // when we do that.
Victor Costanc7e7f2e2018-07-18 20:07:551373 DCHECK(it->second->is_valid());
Victor Costan613b4302018-11-20 05:32:431374 DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
Victor Costan87cf8c72018-07-19 19:36:041375 << "GetCachedStatement used with same ID but different SQL";
1376
1377 // Reset the statement so it can be reused.
Victor Costanc7e7f2e2018-07-18 20:07:551378 sqlite3_reset(it->second->stmt());
1379 return it->second;
[email protected]e5ffd0e42009-09-11 21:30:561380 }
1381
1382 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
Victor Costan613b4302018-11-20 05:32:431383 if (statement->is_valid()) {
[email protected]e5ffd0e42009-09-11 21:30:561384 statement_cache_[id] = statement; // Only cache valid statements.
Victor Costan613b4302018-11-20 05:32:431385 DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
1386 << "Input SQL does not match SQLite's normalized version";
1387 }
[email protected]e5ffd0e42009-09-11 21:30:561388 return statement;
1389}
1390
Victor Costancfbfa602018-08-01 23:24:461391scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
[email protected]e5ffd0e42009-09-11 21:30:561392 const char* sql) {
shess9e77283d2016-06-13 23:53:201393 return GetStatementImpl(this, sql);
1394}
1395
Victor Costancfbfa602018-08-01 23:24:461396scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1397 sql::Database* tracking_db,
1398 const char* sql) const {
[email protected]35f7e5392012-07-27 19:54:501399 AssertIOAllowed();
shess9e77283d2016-06-13 23:53:201400 DCHECK(sql);
Victor Costan87cf8c72018-07-19 19:36:041401 DCHECK(!tracking_db || tracking_db == this);
[email protected]35f7e5392012-07-27 19:54:501402
[email protected]41a97c812013-02-07 02:35:381403 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561404 if (!db_)
Victor Costan3b02cdf2018-07-18 00:39:561405 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561406
Victor Costanbd623112018-07-18 04:17:271407 sqlite3_stmt* stmt = nullptr;
1408 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
[email protected]473ad792012-11-10 00:55:001409 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591410 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521411 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001412
1413 // It could also be database corruption.
Victor Costanbd623112018-07-18 04:17:271414 OnSqliteError(rc, nullptr, sql);
Victor Costan3b02cdf2018-07-18 00:39:561415 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
[email protected]e5ffd0e42009-09-11 21:30:561416 }
Victor Costan3b02cdf2018-07-18 00:39:561417 return base::MakeRefCounted<StatementRef>(tracking_db, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561418}
1419
Victor Costancfbfa602018-08-01 23:24:461420scoped_refptr<Database::StatementRef> Database::GetUntrackedStatement(
[email protected]2eec0a22012-07-24 01:59:581421 const char* sql) const {
Victor Costanbd623112018-07-18 04:17:271422 return GetStatementImpl(nullptr, sql);
[email protected]2eec0a22012-07-24 01:59:581423}
1424
Victor Costancfbfa602018-08-01 23:24:461425std::string Database::GetSchema() const {
[email protected]92cd00a2013-08-16 11:09:581426 // The ORDER BY should not be necessary, but relying on organic
1427 // order for something like this is questionable.
Victor Costan87cf8c72018-07-19 19:36:041428 static const char kSql[] =
[email protected]92cd00a2013-08-16 11:09:581429 "SELECT type, name, tbl_name, sql "
1430 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1431 Statement statement(GetUntrackedStatement(kSql));
1432
1433 std::string schema;
1434 while (statement.Step()) {
1435 schema += statement.ColumnString(0);
1436 schema += '|';
1437 schema += statement.ColumnString(1);
1438 schema += '|';
1439 schema += statement.ColumnString(2);
1440 schema += '|';
1441 schema += statement.ColumnString(3);
1442 schema += '\n';
1443 }
1444
1445 return schema;
1446}
1447
Victor Costancfbfa602018-08-01 23:24:461448bool Database::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501449 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381450 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461451 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381452 return false;
1453 }
1454
Victor Costanbd623112018-07-18 04:17:271455 sqlite3_stmt* stmt = nullptr;
1456 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK)
[email protected]eff1fa522011-12-12 23:50:591457 return false;
1458
1459 sqlite3_finalize(stmt);
1460 return true;
1461}
1462
Victor Costancfbfa602018-08-01 23:24:461463bool Database::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121464 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531465}
1466
Victor Costancfbfa602018-08-01 23:24:461467bool Database::DoesTableExist(const char* table_name) const {
shessa62504d2016-11-07 19:26:121468 return DoesSchemaItemExist(table_name, "table");
1469}
1470
Victor Costancfbfa602018-08-01 23:24:461471bool Database::DoesViewExist(const char* view_name) const {
shessa62504d2016-11-07 19:26:121472 return DoesSchemaItemExist(view_name, "view");
1473}
1474
Victor Costancfbfa602018-08-01 23:24:461475bool Database::DoesSchemaItemExist(const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471476 const char* kSql =
1477 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581478 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471479
shess976814402016-06-21 06:56:251480 // This can happen if the database is corrupt and the error is a test
1481 // expectation.
shess92a2ab12015-04-09 01:59:471482 if (!statement.is_valid())
1483 return false;
1484
[email protected]e2cadec82011-12-13 02:00:531485 statement.BindString(0, type);
1486 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331487
[email protected]e5ffd0e42009-09-11 21:30:561488 return statement.Step(); // Table exists if any row was returned.
1489}
1490
Victor Costancfbfa602018-08-01 23:24:461491bool Database::DoesColumnExist(const char* table_name,
1492 const char* column_name) const {
Victor Costan1ff47e92018-12-07 11:10:431493 // sqlite3_table_column_metadata uses out-params to return column definition
1494 // details, such as the column type and whether it allows NULL values. These
1495 // aren't needed to compute the current method's result, so we pass in nullptr
1496 // for all the out-params.
1497 int error = sqlite3_table_column_metadata(
1498 db_, "main", table_name, column_name, /* pzDataType= */ nullptr,
1499 /* pzCollSeq= */ nullptr, /* pNotNull= */ nullptr,
1500 /* pPrimaryKey= */ nullptr, /* pAutoinc= */ nullptr);
1501 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561502}
1503
Victor Costancfbfa602018-08-01 23:24:461504int64_t Database::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561505 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461506 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]e5ffd0e42009-09-11 21:30:561507 return 0;
1508 }
1509 return sqlite3_last_insert_rowid(db_);
1510}
1511
Victor Costancfbfa602018-08-01 23:24:461512int Database::GetLastChangeCount() const {
[email protected]1ed78a32009-09-15 20:24:171513 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461514 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]1ed78a32009-09-15 20:24:171515 return 0;
1516 }
1517 return sqlite3_changes(db_);
1518}
1519
Victor Costancfbfa602018-08-01 23:24:461520int Database::GetErrorCode() const {
[email protected]e5ffd0e42009-09-11 21:30:561521 if (!db_)
1522 return SQLITE_ERROR;
1523 return sqlite3_errcode(db_);
1524}
1525
Victor Costancfbfa602018-08-01 23:24:461526int Database::GetLastErrno() const {
[email protected]767718e52010-09-21 23:18:491527 if (!db_)
1528 return -1;
1529
1530 int err = 0;
Victor Costanbd623112018-07-18 04:17:271531 if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
[email protected]767718e52010-09-21 23:18:491532 return -2;
1533
1534 return err;
1535}
1536
Victor Costancfbfa602018-08-01 23:24:461537const char* Database::GetErrorMessage() const {
[email protected]e5ffd0e42009-09-11 21:30:561538 if (!db_)
Victor Costancfbfa602018-08-01 23:24:461539 return "sql::Database is not opened.";
[email protected]e5ffd0e42009-09-11 21:30:561540 return sqlite3_errmsg(db_);
1541}
1542
Victor Costancfbfa602018-08-01 23:24:461543bool Database::OpenInternal(const std::string& file_name,
1544 Database::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501545 AssertIOAllowed();
1546
[email protected]9cfbc922009-11-17 20:13:171547 if (db_) {
Victor Costancfbfa602018-08-01 23:24:461548 DLOG(DCHECK) << "sql::Database is already open.";
[email protected]9cfbc922009-11-17 20:13:171549 return false;
1550 }
1551
Victor Costan3653df62018-02-08 21:38:161552 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181553
shess58b8df82015-06-03 00:19:321554 // Setup the stats histograms immediately rather than allocating lazily.
Victor Costancfbfa602018-08-01 23:24:461555 // Databases which won't exercise all of these probably shouldn't exist.
shess58b8df82015-06-03 00:19:321556 if (!histogram_tag_.empty()) {
Victor Costancfbfa602018-08-01 23:24:461557 stats_histogram_ = base::LinearHistogram::FactoryGet(
1558 "Sqlite.Stats." + histogram_tag_, 1, EVENT_MAX_VALUE,
1559 EVENT_MAX_VALUE + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
shess58b8df82015-06-03 00:19:321560
1561 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1562 // unreasonable time for any single operation, so there is not much value to
1563 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1564 // things are entirely busted.
1565 commit_time_histogram_ =
1566 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1567
1568 autocommit_time_histogram_ =
1569 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1570
1571 update_time_histogram_ =
1572 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1573
1574 query_time_histogram_ =
1575 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1576 }
1577
[email protected]41a97c812013-02-07 02:35:381578 // If |poisoned_| is set, it means an error handler called
1579 // RazeAndClose(). Until regular Close() is called, the caller
1580 // should be treating the database as open, but is_open() currently
1581 // only considers the sqlite3 handle's state.
1582 // TODO(shess): Revise is_open() to consider poisoned_, and review
1583 // to see if any non-testing code even depends on it.
Victor Costancfbfa602018-08-01 23:24:461584 DCHECK(!poisoned_) << "sql::Database is already open.";
[email protected]7bae5742013-07-10 20:46:161585 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381586
shess5f2c3442017-01-24 02:15:101587 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1588 sqlite3_vfs* vfs = VFSWrapper();
1589 const char* vfs_name = (vfs ? vfs->zName : nullptr);
Victor Costanc6d3a862018-11-20 18:41:231590
1591 // The flags are documented at https://www.sqlite.org/c3ref/open.html.
1592 //
1593 // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
1594 // disparate features with their own databases, and having separate page
1595 // caches makes it easier to reason about each feature's performance in
1596 // isolation.
1597 int err = sqlite3_open_v2(
1598 file_name.c_str(), &db_,
1599 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_PRIVATECACHE,
1600 vfs_name);
[email protected]765b44502009-10-02 05:01:421601 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281602 // Extended error codes cannot be enabled until a handle is
1603 // available, fetch manually.
1604 err = sqlite3_extended_errcode(db_);
1605
[email protected]bd2ccdb4a2012-12-07 22:14:501606 // Histogram failures specific to initial open for debugging
1607 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181608 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501609
Victor Costanbd623112018-07-18 04:17:271610 OnSqliteError(err, nullptr, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131611 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291612 Close();
[email protected]fed734a2013-07-17 04:45:131613
1614 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1615 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421616 return false;
1617 }
1618
[email protected]73fb8d52013-07-24 05:04:281619 // Enable extended result codes to provide more color on I/O errors.
1620 // Not having extended result codes is not a fatal problem, as
1621 // Chromium code does not attempt to handle I/O errors anyhow. The
1622 // current implementation always returns SQLITE_OK, the DCHECK is to
1623 // quickly notify someone if SQLite changes.
1624 err = sqlite3_extended_result_codes(db_, 1);
1625 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1626
shessbccd300e2016-08-20 00:06:561627 // sqlite3_open() does not actually read the database file (unless a hot
1628 // journal is found). Successfully executing this pragma on an existing
1629 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1630 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501631 // TODO(shess): For now, just probing to see what the lay of the
1632 // land is. If it's mostly SQLITE_NOTADB, then the database should
1633 // be razed.
1634 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561635 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181636 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561637 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1638
1639 // Retry or bail out if the error handler poisoned the handle.
Victor Costanf1e9443b2018-12-05 04:35:531640 // TODO(shess): Move this handling to one place (see also sqlite3_open).
1641 // Possibly a wrapper function?
shessbccd300e2016-08-20 00:06:561642 if (poisoned_) {
1643 Close();
1644 if (retry_flag == RETRY_ON_POISON)
1645 return OpenInternal(file_name, NO_RETRY);
1646 return false;
1647 }
1648 }
[email protected]658f8332010-09-18 04:40:431649
[email protected]5b96f3772010-09-28 16:30:571650 // If indicated, lock up the database before doing anything else, so
1651 // that the following code doesn't have to deal with locking.
1652 // TODO(shess): This code is brittle. Find the cases where code
1653 // doesn't request |exclusive_locking_| and audit that it does the
1654 // right thing with SQLITE_BUSY, and that it doesn't make
1655 // assumptions about who might change things in the database.
1656 // http://crbug.com/56559
1657 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101658 // TODO(shess): This should probably be a failure. Code which
1659 // requests exclusive locking but doesn't get it is almost certain
1660 // to be ill-tested.
1661 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571662 }
1663
Victor Costan4c2f3e922018-08-21 04:47:591664 if (base::FeatureList::IsEnabled(features::kSqlTempStoreMemory)) {
1665 err = ExecuteAndReturnErrorCode("PRAGMA temp_store=MEMORY");
1666 // This operates on in-memory configuration, so it should not fail.
1667 DCHECK_EQ(err, SQLITE_OK) << "Failed switching to in-RAM temporary storage";
1668 }
1669
[email protected]4e179ba2012-03-17 16:06:471670 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1671 // DELETE (default) - delete -journal file to commit.
1672 // TRUNCATE - truncate -journal file to commit.
1673 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091674 // TRUNCATE should be faster than DELETE because it won't need directory
1675 // changes for each transaction. PERSIST may break the spirit of using
1676 // secure_delete.
Victor Costan4c2f3e922018-08-21 04:47:591677 ignore_result(Execute("PRAGMA journal_mode=TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471678
[email protected]c68ce172011-11-24 22:30:271679 const base::TimeDelta kBusyTimeout =
Victor Costancfbfa602018-08-01 23:24:461680 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
[email protected]c68ce172011-11-24 22:30:271681
Victor Costancfbfa602018-08-01 23:24:461682 const std::string page_size_sql =
1683 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1684 ignore_result(ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421685
1686 if (cache_size_ != 0) {
Victor Costancfbfa602018-08-01 23:24:461687 const std::string cache_size_sql =
[email protected]7d3cbc92013-03-18 22:33:041688 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
Victor Costancfbfa602018-08-01 23:24:461689 ignore_result(ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421690 }
1691
Victor Costanf1e9443b2018-12-05 04:35:531692 static_assert(SQLITE_SECURE_DELETE == 1,
1693 "Chrome assumes secure_delete is on by default.");
[email protected]6e0b1442011-08-09 23:23:581694
shess5dac334f2015-11-05 20:47:421695 // Set a reasonable chunk size for larger files. This reduces churn from
1696 // remapping memory on size changes. It also reduces filesystem
1697 // fragmentation.
1698 // TODO(shess): It may make sense to have this be hinted by the client.
1699 // Database sizes seem to be bimodal, some clients have consistently small
1700 // databases (<20k) while other clients have a broad distribution of sizes
1701 // (hundreds of kilobytes to many megabytes).
Victor Costanbd623112018-07-18 04:17:271702 sqlite3_file* file = nullptr;
shess5dac334f2015-11-05 20:47:421703 sqlite3_int64 db_size = 0;
1704 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1705 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1706 int chunk_size = 4 * 1024;
1707 if (db_size > 128 * 1024)
1708 chunk_size = 32 * 1024;
Victor Costanbd623112018-07-18 04:17:271709 sqlite3_file_control(db_, nullptr, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
shess5dac334f2015-11-05 20:47:421710 }
1711
shess2f3a814b2015-11-05 18:11:101712 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311713 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1714 // safe range to memory-map based on past regular I/O. This value will be
1715 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1716 // 64-bit platforms.
1717 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1718 std::string mmap_sql =
Victor Costan4c2f3e922018-08-21 04:47:591719 base::StringPrintf("PRAGMA mmap_size=%" PRIuS, mmap_size);
shessd90aeea82015-11-13 02:24:311720 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101721
1722 // Determine if memory-mapping has actually been enabled. The Execute() above
1723 // can succeed without changing the amount mapped.
1724 mmap_enabled_ = false;
1725 {
1726 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1727 if (s.Step() && s.ColumnInt64(0) > 0)
1728 mmap_enabled_ = true;
1729 }
1730
ssid3be5b1ec2016-01-13 14:21:571731 DCHECK(!memory_dump_provider_);
1732 memory_dump_provider_.reset(
Victor Costancfbfa602018-08-01 23:24:461733 new DatabaseMemoryDumpProvider(db_, histogram_tag_));
ssid3be5b1ec2016-01-13 14:21:571734 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
Victor Costancfbfa602018-08-01 23:24:461735 memory_dump_provider_.get(), "sql::Database", nullptr);
ssid3be5b1ec2016-01-13 14:21:571736
[email protected]765b44502009-10-02 05:01:421737 return true;
1738}
1739
Victor Costancfbfa602018-08-01 23:24:461740void Database::DoRollback() {
[email protected]e5ffd0e42009-09-11 21:30:561741 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321742
1743 // Collect the rollback time manually, sql::Statement would register it as
1744 // query time only.
Victor Costan87cf8c72018-07-19 19:36:041745 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321746 rollback.RunWithoutTimers();
Victor Costan87cf8c72018-07-19 19:36:041747 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321748
1749 RecordUpdateTime(delta);
1750 RecordOneEvent(EVENT_ROLLBACK);
1751
shess7dbd4dee2015-10-06 17:39:161752 // The cache may have been accumulating dirty pages for commit. Note that in
1753 // some cases sql::Transaction can fire rollback after a database is closed.
1754 if (is_open())
1755 ReleaseCacheMemoryIfNeeded(false);
1756
[email protected]44ad7d902012-03-23 00:09:051757 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561758}
1759
Victor Costancfbfa602018-08-01 23:24:461760void Database::StatementRefCreated(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551761 DCHECK(!open_statements_.count(ref))
1762 << __func__ << " already called with this statement";
[email protected]e5ffd0e42009-09-11 21:30:561763 open_statements_.insert(ref);
1764}
1765
Victor Costancfbfa602018-08-01 23:24:461766void Database::StatementRefDeleted(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551767 DCHECK(open_statements_.count(ref))
1768 << __func__ << " called with non-existing statement";
1769 open_statements_.erase(ref);
[email protected]e5ffd0e42009-09-11 21:30:561770}
1771
Victor Costancfbfa602018-08-01 23:24:461772void Database::set_histogram_tag(const std::string& tag) {
shess58b8df82015-06-03 00:19:321773 DCHECK(!is_open());
Victor Costan87cf8c72018-07-19 19:36:041774
shess58b8df82015-06-03 00:19:321775 histogram_tag_ = tag;
1776}
1777
Will Harrisb8693592018-08-28 22:58:441778void Database::AddTaggedHistogram(const std::string& name, int sample) const {
[email protected]210ce0af2013-05-15 09:10:391779 if (histogram_tag_.empty())
1780 return;
1781
1782 // TODO(shess): The histogram macros create a bit of static storage
1783 // for caching the histogram object. This code shouldn't execute
1784 // often enough for such caching to be crucial. If it becomes an
1785 // issue, the object could be cached alongside histogram_prefix_.
1786 std::string full_histogram_name = name + "." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:461787 base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
1788 full_histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]210ce0af2013-05-15 09:10:391789 if (histogram)
1790 histogram->Add(sample);
1791}
1792
Victor Costancfbfa602018-08-01 23:24:461793int Database::OnSqliteError(int err,
1794 sql::Statement* stmt,
1795 const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181796 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391797 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141798
1799 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581800 if (!sql && stmt)
1801 sql = stmt->GetSQLStatement();
1802 if (!sql)
1803 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061804
1805 std::string id = histogram_tag_;
1806 if (id.empty())
1807 id = DbPath().BaseName().AsUTF8Unsafe();
Victor Costancfbfa602018-08-01 23:24:461808 LOG(ERROR) << id << " sqlite error " << err << ", errno " << GetLastErrno()
1809 << ": " << GetErrorMessage() << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141810
[email protected]c3881b372013-05-17 08:39:461811 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561812 // Fire from a copy of the callback in case of reentry into
1813 // re/set_error_callback().
1814 // TODO(shess): <http://crbug.com/254584>
1815 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461816 return err;
1817 }
1818
[email protected]faa604e2009-09-25 22:38:591819 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251820 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521821 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591822 return err;
1823}
1824
Victor Costancfbfa602018-08-01 23:24:461825bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
[email protected]579446c2013-12-16 18:36:521826 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1827}
1828
Victor Costancfbfa602018-08-01 23:24:461829bool Database::QuickIntegrityCheck() {
[email protected]579446c2013-12-16 18:36:521830 std::vector<std::string> messages;
1831 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1832 return false;
1833 return messages.size() == 1 && messages[0] == "ok";
1834}
1835
Victor Costancfbfa602018-08-01 23:24:461836std::string Database::GetDiagnosticInfo(int extended_error,
1837 Statement* statement) {
afakhry7c9abe72016-08-05 17:33:191838 // Prevent reentrant calls to the error callback.
1839 ErrorCallback original_callback = std::move(error_callback_);
1840 reset_error_callback();
1841
1842 // Trim extended error codes.
1843 const int error = (extended_error & 0xFF);
Victor Costancfbfa602018-08-01 23:24:461844 // CollectCorruptionInfo() is implemented in terms of sql::Database,
afakhry7c9abe72016-08-05 17:33:191845 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1846 std::string result = (error == SQLITE_CORRUPT)
1847 ? CollectCorruptionInfo()
1848 : CollectErrorInfo(extended_error, statement);
1849
1850 // The following queries must be executed after CollectErrorInfo() above, so
1851 // if they result in their own errors, they don't interfere with
1852 // CollectErrorInfo().
1853 const bool has_valid_header =
1854 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1855 const bool select_sqlite_master_result =
1856 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1857 SQLITE_OK);
1858
1859 // Restore the original error callback.
1860 error_callback_ = std::move(original_callback);
1861
1862 base::StringAppendF(&result, "Has valid header: %s\n",
1863 (has_valid_header ? "Yes" : "No"));
1864 base::StringAppendF(&result, "Has valid schema: %s\n",
1865 (select_sqlite_master_result ? "Yes" : "No"));
1866
1867 return result;
1868}
1869
[email protected]80abf152013-05-22 12:42:421870// TODO(shess): Allow specifying maximum results (default 100 lines).
Victor Costancfbfa602018-08-01 23:24:461871bool Database::IntegrityCheckHelper(const char* pragma_sql,
1872 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421873 messages->clear();
1874
[email protected]4658e2a02013-06-06 23:05:001875 // This has the side effect of setting SQLITE_RecoveryMode, which
1876 // allows SQLite to process through certain cases of corruption.
1877 // Failing to set this pragma probably means that the database is
1878 // beyond recovery.
Victor Costan4c2f3e922018-08-21 04:47:591879 static const char kWritableSchemaSql[] = "PRAGMA writable_schema=ON";
Victor Costan1d868352018-06-26 19:06:481880 if (!Execute(kWritableSchemaSql))
[email protected]4658e2a02013-06-06 23:05:001881 return false;
1882
1883 bool ret = false;
1884 {
[email protected]579446c2013-12-16 18:36:521885 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001886
1887 // The pragma appears to return all results (up to 100 by default)
1888 // as a single string. This doesn't appear to be an API contract,
1889 // it could return separate lines, so loop _and_ split.
1890 while (stmt.Step()) {
1891 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181892 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1893 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001894 }
1895 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421896 }
[email protected]4658e2a02013-06-06 23:05:001897
1898 // Best effort to put things back as they were before.
Victor Costan4c2f3e922018-08-21 04:47:591899 static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema=OFF";
Victor Costan1d868352018-06-26 19:06:481900 ignore_result(Execute(kNoWritableSchemaSql));
[email protected]4658e2a02013-06-06 23:05:001901
1902 return ret;
[email protected]80abf152013-05-22 12:42:421903}
1904
Victor Costancfbfa602018-08-01 23:24:461905bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1906 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131907 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381908 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131909}
1910
[email protected]e5ffd0e42009-09-11 21:30:561911} // namespace sql