blob: 623bd8bddbafc5e1fa65bac71392c6c207ef3177 [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"
asvitkine3033081a2016-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)
161 return base::WideToUTF8(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]4e179ba62012-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.
504//
505// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
506// work. There could be two prepared statements, one for cache_size=1 one for
507// cache_size=goal.
Victor Costancfbfa602018-08-01 23:24:46508void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
shess644fc8a2016-02-26 18:15:58509 // The database could have been closed during a transaction as part of error
510 // recovery.
511 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:46512 DCHECK(poisoned_) << "Illegal use of Database without a db";
shess644fc8a2016-02-26 18:15:58513 return;
514 }
shess7dbd4dee2015-10-06 17:39:16515
516 // If memory-mapping is not enabled, the page cache helps performance.
517 if (!mmap_enabled_)
518 return;
519
520 // On caller request, force the change comparison to fail. Done before the
521 // transaction-nesting test so that the signal can carry to transaction
522 // commit.
523 if (implicit_change_performed)
524 --total_changes_at_last_release_;
525
526 // Cached pages may be re-used within the same transaction.
527 if (transaction_nesting())
528 return;
529
530 // If no changes have been made, skip flushing. This allows the first page of
531 // the database to remain in cache across multiple reads.
532 const int total_changes = sqlite3_total_changes(db_);
533 if (total_changes == total_changes_at_last_release_)
534 return;
535
536 total_changes_at_last_release_ = total_changes;
537 sqlite3_db_release_memory(db_);
538}
539
Victor Costancfbfa602018-08-01 23:24:46540base::FilePath Database::DbPath() const {
shessc8cd2a162015-10-22 20:30:46541 if (!is_open())
542 return base::FilePath();
543
544 const char* path = sqlite3_db_filename(db_, "main");
545 const base::StringPiece db_path(path);
546#if defined(OS_WIN)
547 return base::FilePath(base::UTF8ToWide(db_path));
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18548#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46549 return base::FilePath(db_path);
550#else
551 NOTREACHED();
552 return base::FilePath();
553#endif
554}
555
556// Data is persisted in a file shared between databases in the same directory.
557// The "sqlite-diag" file contains a dictionary with the version number, and an
558// array of histogram tags for databases which have been dumped.
Victor Costancfbfa602018-08-01 23:24:46559bool Database::RegisterIntentToUpload() const {
shessc8cd2a162015-10-22 20:30:46560 static const char* kVersionKey = "version";
561 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
562 static int kVersion = 1;
563
564 AssertIOAllowed();
565
566 if (histogram_tag_.empty())
567 return false;
568
569 if (!is_open())
570 return false;
571
572 if (in_memory_)
573 return false;
574
575 const base::FilePath db_path = DbPath();
576 if (db_path.empty())
577 return false;
578
579 // Put the collection of diagnostic data next to the databases. In most
580 // cases, this is the profile directory, but safe-browsing stores a Cookies
581 // file in the directory above the profile directory.
Victor Costance678e72018-07-24 10:25:00582 base::FilePath breadcrumb_path = db_path.DirName().AppendASCII("sqlite-diag");
shessc8cd2a162015-10-22 20:30:46583
584 // Lock against multiple updates to the diagnostics file. This code should
585 // seldom be called in the first place, and when called it should seldom be
586 // called for multiple databases, and when called for multiple databases there
587 // is _probably_ something systemic wrong with the user's system. So the lock
588 // should never be contended, but when it is the database experience is
589 // already bad.
Victor Costan3653df62018-02-08 21:38:16590 static base::NoDestructor<base::Lock> lock;
591 base::AutoLock auto_lock(*lock);
shessc8cd2a162015-10-22 20:30:46592
mostynbd82cd9952016-04-11 20:05:34593 std::unique_ptr<base::Value> root;
shessc8cd2a162015-10-22 20:30:46594 if (!base::PathExists(breadcrumb_path)) {
mostynbd82cd9952016-04-11 20:05:34595 std::unique_ptr<base::DictionaryValue> root_dict(
596 new base::DictionaryValue());
shessc8cd2a162015-10-22 20:30:46597 root_dict->SetInteger(kVersionKey, kVersion);
598
mostynbd82cd9952016-04-11 20:05:34599 std::unique_ptr<base::ListValue> dumps(new base::ListValue);
shessc8cd2a162015-10-22 20:30:46600 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50601 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46602
dchenge48600452015-12-28 02:24:50603 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46604 } else {
605 // Failure to read a valid dictionary implies that something is going wrong
606 // on the system.
607 JSONFileValueDeserializer deserializer(breadcrumb_path);
mostynbd82cd9952016-04-11 20:05:34608 std::unique_ptr<base::Value> read_root(
shessc8cd2a162015-10-22 20:30:46609 deserializer.Deserialize(nullptr, nullptr));
610 if (!read_root.get())
611 return false;
mostynbd82cd9952016-04-11 20:05:34612 std::unique_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50613 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46614 if (!root_dict)
615 return false;
616
617 // Don't upload if the version is missing or newer.
618 int version = 0;
619 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
620 return false;
621
622 base::ListValue* dumps = nullptr;
623 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
624 return false;
625
626 const size_t size = dumps->GetSize();
627 for (size_t i = 0; i < size; ++i) {
628 std::string s;
629
630 // Don't upload if the value isn't a string, or indicates a prior upload.
631 if (!dumps->GetString(i, &s) || s == histogram_tag_)
632 return false;
633 }
634
635 // Record intention to proceed with upload.
636 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50637 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46638 }
639
640 const base::FilePath breadcrumb_new =
641 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
642 base::DeleteFile(breadcrumb_new, false);
643
644 // No upload if the breadcrumb file cannot be updated.
645 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
646 // the data on disk. For now, losing the data is not a big problem, so the
647 // sync overhead would probably not be worth it.
648 JSONFileValueSerializer serializer(breadcrumb_new);
649 if (!serializer.Serialize(*root))
650 return false;
651 if (!base::PathExists(breadcrumb_new))
652 return false;
653 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
654 base::DeleteFile(breadcrumb_new, false);
655 return false;
656 }
657
658 return true;
659}
660
Victor Costancfbfa602018-08-01 23:24:46661std::string Database::CollectErrorInfo(int error, Statement* stmt) const {
shessc8cd2a162015-10-22 20:30:46662 // Buffer for accumulating debugging info about the error. Place
663 // more-relevant information earlier, in case things overflow the
664 // fixed-size reporting buffer.
665 std::string debug_info;
666
667 // The error message from the failed operation.
Victor Costancfbfa602018-08-01 23:24:46668 base::StringAppendF(&debug_info, "db error: %d/%s\n", GetErrorCode(),
669 GetErrorMessage());
shessc8cd2a162015-10-22 20:30:46670
671 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
672 // reading code does not entirely convince me. Remove if they turn out to be
673 // the same.
674 if (error != GetErrorCode())
675 base::StringAppendF(&debug_info, "reported error: %d\n", error);
676
Victor Costancfbfa602018-08-01 23:24:46677// System error information. Interpretation of Windows errors is different
678// from posix.
shessc8cd2a162015-10-22 20:30:46679#if defined(OS_WIN)
680 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18681#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46682 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
683#else
684 NOTREACHED(); // Add appropriate log info.
685#endif
686
687 if (stmt) {
688 base::StringAppendF(&debug_info, "statement: %s\n",
689 stmt->GetSQLStatement());
690 } else {
691 base::StringAppendF(&debug_info, "statement: NULL\n");
692 }
693
694 // SQLITE_ERROR often indicates some sort of mismatch between the statement
695 // and the schema, possibly due to a failed schema migration.
696 if (error == SQLITE_ERROR) {
697 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
698 sqlite3_stmt* s;
699 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
700 if (rc == SQLITE_OK) {
701 rc = sqlite3_step(s);
702 if (rc == SQLITE_ROW) {
703 base::StringAppendF(&debug_info, "version: %d\n",
704 sqlite3_column_int(s, 0));
705 } else if (rc == SQLITE_DONE) {
706 debug_info += "version: none\n";
707 } else {
708 base::StringAppendF(&debug_info, "version: error %d\n", rc);
709 }
710 sqlite3_finalize(s);
711 } else {
712 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
713 }
714
715 debug_info += "schema:\n";
716
717 // sqlite_master has columns:
718 // type - "index" or "table".
719 // name - name of created element.
720 // tbl_name - name of element, or target table in case of index.
721 // rootpage - root page of the element in database file.
722 // sql - SQL to create the element.
723 // In general, the |sql| column is sufficient to derive the other columns.
724 // |rootpage| is not interesting for debugging, without the contents of the
725 // database. The COALESCE is because certain automatic elements will have a
726 // |name| but no |sql|,
727 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
728 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
729 if (rc == SQLITE_OK) {
730 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
731 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
732 }
733 if (rc != SQLITE_DONE)
734 base::StringAppendF(&debug_info, "error %d\n", rc);
735 sqlite3_finalize(s);
736 } else {
737 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
738 }
739 }
740
741 return debug_info;
742}
743
744// TODO(shess): Since this is only called in an error situation, it might be
745// prudent to rewrite in terms of SQLite API calls, and mark the function const.
Victor Costancfbfa602018-08-01 23:24:46746std::string Database::CollectCorruptionInfo() {
shessc8cd2a162015-10-22 20:30:46747 AssertIOAllowed();
748
749 // If the file cannot be accessed it is unlikely that an integrity check will
750 // turn up actionable information.
751 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19752 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46753 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
754 return std::string();
755
756 // Buffer for accumulating debugging info about the error. Place
757 // more-relevant information earlier, in case things overflow the
758 // fixed-size reporting buffer.
759 std::string debug_info;
760 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
761 db_size);
762
763 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19764 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46765 if (db_size > kMaxIntegrityCheckSize) {
766 debug_info += "integrity_check skipped due to size\n";
767 } else {
768 std::vector<std::string> messages;
769
770 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
771 // into a string. Probably should be refactored.
772 const base::TimeTicks before = base::TimeTicks::Now();
773 FullIntegrityCheck(&messages);
774 base::StringAppendF(
Victor Costancfbfa602018-08-01 23:24:46775 &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
776 (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
shessc8cd2a162015-10-22 20:30:46777
778 // SQLite returns up to 100 messages by default, trim deeper to
779 // keep close to the 2000-character size limit for dumping.
780 const size_t kMaxMessages = 20;
781 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
782 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
783 }
784 }
785
786 return debug_info;
787}
788
Victor Costancfbfa602018-08-01 23:24:46789bool Database::GetMmapAltStatus(int64_t* status) {
shessa62504d2016-11-07 19:26:12790 // The [meta] version uses a missing table as a signal for a fresh database.
791 // That will not work for the view, which would not exist in either a new or
792 // an existing database. A new database _should_ be only one page long, so
793 // just don't bother optimizing this case (start at offset 0).
794 // TODO(shess): Could the [meta] case also get simpler, then?
795 if (!DoesViewExist("MmapStatus")) {
796 *status = 0;
797 return true;
798 }
799
800 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
801 Statement s(GetUniqueStatement(kMmapStatusSql));
802 if (s.Step())
803 *status = s.ColumnInt64(0);
804 return s.Succeeded();
805}
806
Victor Costancfbfa602018-08-01 23:24:46807bool Database::SetMmapAltStatus(int64_t status) {
shessa62504d2016-11-07 19:26:12808 if (!BeginTransaction())
809 return false;
810
811 // View may not exist on first run.
812 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
813 RollbackTransaction();
814 return false;
815 }
816
817 // Views live in the schema, so they cannot be parameterized. For an integer
818 // value, this construct should be safe from SQL injection, if the value
819 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
820 // value.
Victor Costancfbfa602018-08-01 23:24:46821 const std::string create_view_sql = base::StringPrintf(
822 "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
823 if (!Execute(create_view_sql.c_str())) {
shessa62504d2016-11-07 19:26:12824 RollbackTransaction();
825 return false;
826 }
827
828 return CommitTransaction();
829}
830
Victor Costancfbfa602018-08-01 23:24:46831size_t Database::GetAppropriateMmapSize() {
shessd90aeea82015-11-13 02:24:31832 AssertIOAllowed();
833
shess9bf2c672015-12-18 01:18:08834 // How much to map if no errors are found. 50MB encompasses the 99th
835 // percentile of Chrome databases in the wild, so this should be good.
836 const size_t kMmapEverything = 256 * 1024 * 1024;
837
shessa62504d2016-11-07 19:26:12838 // Progress information is tracked in the [meta] table for databases which use
839 // sql::MetaTable, otherwise it is tracked in a special view.
840 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08841 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12842 if (mmap_alt_status_) {
843 if (!GetMmapAltStatus(&mmap_ofs)) {
844 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
845 return 0;
846 }
847 } else {
848 // If [meta] doesn't exist, yet, it's a new database, assume the best.
849 // sql::MetaTable::Init() will preload kMmapSuccess.
850 if (!MetaTable::DoesTableExist(this)) {
851 RecordOneEvent(EVENT_MMAP_META_MISSING);
852 return kMmapEverything;
853 }
854
855 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
856 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
857 return 0;
858 }
shessd90aeea82015-11-13 02:24:31859 }
860
861 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08862 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31863 RecordOneEvent(EVENT_MMAP_FAILED);
864 return 0;
shess9bf2c672015-12-18 01:18:08865 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31866 // Continue reading from previous offset.
867 DCHECK_GE(mmap_ofs, 0);
868
869 // TODO(shess): Could this reading code be shared with Preload()? It would
870 // require locking twice (this code wouldn't be able to access |db_size| so
871 // the helper would have to return amount read).
872
873 // Read more of the database looking for errors. The VFS interface is used
874 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
875 // to limit checking to 20MB per run of Chromium.
Victor Costanbd623112018-07-18 04:17:27876 sqlite3_file* file = nullptr;
shessd90aeea82015-11-13 02:24:31877 sqlite3_int64 db_size = 0;
878 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
879 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
880 return 0;
881 }
882
883 // Read the data left, or |g_reads_allowed|, whichever is smaller.
884 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
885 // in a single Chromium run.
886 sqlite3_int64 amount = db_size - mmap_ofs;
887 if (amount < 0)
888 amount = 0;
889 if (amount > 0) {
Victor Costan3653df62018-02-08 21:38:16890 static base::NoDestructor<base::Lock> lock;
891 base::AutoLock auto_lock(*lock);
shessd90aeea82015-11-13 02:24:31892 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
893 if (g_reads_allowed < amount)
894 amount = g_reads_allowed;
895 g_reads_allowed -= amount;
896 }
897
898 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
899 // database was truncated after a previous pass.
900 if (amount <= 0 && mmap_ofs < db_size) {
901 DCHECK_EQ(0, amount);
902 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
903 } else {
904 static const int kPageSize = 4096;
905 char buf[kPageSize];
906 while (amount > 0) {
907 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
908 if (rc == SQLITE_OK) {
909 mmap_ofs += sizeof(buf);
910 amount -= sizeof(buf);
911 } else if (rc == SQLITE_IOERR_SHORT_READ) {
912 // Reached EOF for a database with page size < |kPageSize|.
913 mmap_ofs = db_size;
914 break;
915 } else {
916 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08917 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31918 break;
919 }
920 }
921
922 // Log these events after update to distinguish meta update failure.
923 Events event;
924 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08925 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31926 event = EVENT_MMAP_SUCCESS_NEW;
927 } else if (mmap_ofs > 0) {
928 event = EVENT_MMAP_SUCCESS_PARTIAL;
929 } else {
shess9bf2c672015-12-18 01:18:08930 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31931 event = EVENT_MMAP_FAILED_NEW;
932 }
933
shessa62504d2016-11-07 19:26:12934 if (mmap_alt_status_) {
935 if (!SetMmapAltStatus(mmap_ofs)) {
936 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
937 return 0;
938 }
939 } else {
940 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
941 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
942 return 0;
943 }
shessd90aeea82015-11-13 02:24:31944 }
945
946 RecordOneEvent(event);
947 }
948 }
949
shess9bf2c672015-12-18 01:18:08950 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31951 return 0;
shess9bf2c672015-12-18 01:18:08952 if (mmap_ofs == MetaTable::kMmapSuccess)
953 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31954 return mmap_ofs;
955}
956
Victor Costancfbfa602018-08-01 23:24:46957void Database::TrimMemory(bool aggressively) {
[email protected]be7995f12013-07-18 18:49:14958 if (!db_)
959 return;
960
961 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
962 int original_cache_size;
963 {
964 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
965 if (!sql_get_original.Step()) {
966 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
967 return;
968 }
969 original_cache_size = sql_get_original.ColumnInt(0);
970 }
971 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
972
973 // Force sqlite to try to reduce page cache usage.
974 const std::string sql_shrink =
975 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
976 if (!Execute(sql_shrink.c_str()))
977 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
978
979 // Restore cache size.
980 const std::string sql_restore =
981 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
982 if (!Execute(sql_restore.c_str()))
983 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
984}
985
[email protected]8e0c01282012-04-06 19:36:49986// Create an in-memory database with the existing database's page
987// size, then backup that database over the existing database.
Victor Costancfbfa602018-08-01 23:24:46988bool Database::Raze() {
[email protected]35f7e5392012-07-27 19:54:50989 AssertIOAllowed();
990
[email protected]8e0c01282012-04-06 19:36:49991 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52992 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49993 return false;
994 }
995
996 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52997 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:49998 return false;
999 }
1000
Victor Costancfbfa602018-08-01 23:24:461001 sql::Database null_db;
[email protected]8e0c01282012-04-06 19:36:491002 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521003 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:491004 return false;
1005 }
1006
Victor Costan7f6abbbe2018-07-29 02:57:271007 const std::string sql = base::StringPrintf("PRAGMA page_size=%d", page_size_);
1008 if (!null_db.Execute(sql.c_str()))
1009 return false;
[email protected]69c58452012-08-06 19:22:421010
[email protected]6d42f152012-11-10 00:38:241011#if defined(OS_ANDROID)
1012 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1013 // in-memory databases do not respect this define.
1014 // TODO(shess): Figure out a way to set this without using platform
1015 // specific code. AFAICT from sqlite3.c, the only way to do it
1016 // would be to create an actual filesystem database, which is
1017 // unfortunate.
1018 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1019 return false;
1020#endif
[email protected]8e0c01282012-04-06 19:36:491021
1022 // The page size doesn't take effect until a database has pages, and
1023 // at this point the null database has none. Changing the schema
1024 // version will create the first page. This will not affect the
1025 // schema version in the resulting database, as SQLite's backup
1026 // implementation propagates the schema version from the original
Victor Costancfbfa602018-08-01 23:24:461027 // database to the new version of the database, incremented by one
[email protected]8e0c01282012-04-06 19:36:491028 // so that other readers see the schema change and act accordingly.
1029 if (!null_db.Execute("PRAGMA schema_version = 1"))
1030 return false;
1031
[email protected]6d42f152012-11-10 00:38:241032 // SQLite tracks the expected number of database pages in the first
1033 // page, and if it does not match the total retrieved from a
1034 // filesystem call, treats the database as corrupt. This situation
1035 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1036 // used to hint to SQLite to soldier on in that case, specifically
1037 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1038 // sqlite3.c lockBtree().]
1039 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1040 // page_size" can be used to query such a database.
1041 ScopedWritableSchema writable_schema(db_);
1042
shess92a6fb22017-04-23 04:33:301043#if defined(OS_WIN)
1044 // On Windows, truncate silently fails when applied to memory-mapped files.
1045 // Disable memory-mapping so that the truncate succeeds. Note that other
Victor Costancfbfa602018-08-01 23:24:461046 // Database connections may have memory-mapped the file, so this may not
1047 // entirely prevent the problem.
shess92a6fb22017-04-23 04:33:301048 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1049 ignore_result(Execute("PRAGMA mmap_size = 0"));
1050#endif
1051
[email protected]7bae5742013-07-10 20:46:161052 const char* kMain = "main";
1053 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181054 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:491055
1056 // The destination database was locked.
1057 if (rc == SQLITE_BUSY) {
1058 return false;
1059 }
1060
[email protected]7bae5742013-07-10 20:46:161061 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1062 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1063 // isn't even big enough for one page. Either way, reach in and
1064 // truncate it before trying again.
1065 // TODO(shess): Maybe it would be worthwhile to just truncate from
1066 // the get-go?
1067 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
Victor Costanbd623112018-07-18 04:17:271068 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:341069 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161070 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521071 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:161072 return false;
[email protected]7bae5742013-07-10 20:46:161073 }
1074
1075 rc = file->pMethods->xTruncate(file, 0);
1076 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181077 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521078 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:161079 return false;
1080 }
1081
1082 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181083 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:161084
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521085 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:161086 }
1087
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521088 // TODO(shess): Figure out which other cases can happen.
1089 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
1090
[email protected]8e0c01282012-04-06 19:36:491091 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521092 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:491093}
1094
Victor Costancfbfa602018-08-01 23:24:461095bool Database::RazeAndClose() {
[email protected]41a97c812013-02-07 02:35:381096 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521097 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:381098 return false;
1099 }
1100
1101 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301102 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381103
1104 bool result = Raze();
1105
1106 CloseInternal(true);
1107
1108 // Mark the database so that future API calls fail appropriately,
1109 // but don't DCHECK (because after calling this function they are
1110 // expected to fail).
1111 poisoned_ = true;
1112
1113 return result;
1114}
1115
Victor Costancfbfa602018-08-01 23:24:461116void Database::Poison() {
[email protected]8d409412013-07-19 18:25:301117 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521118 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:301119 return;
1120 }
1121
1122 RollbackAllTransactions();
1123 CloseInternal(true);
1124
1125 // Mark the database so that future API calls fail appropriately,
1126 // but don't DCHECK (because after calling this function they are
1127 // expected to fail).
1128 poisoned_ = true;
1129}
1130
[email protected]8d2e39e2013-06-24 05:55:081131// TODO(shess): To the extent possible, figure out the optimal
Victor Costancfbfa602018-08-01 23:24:461132// ordering for these deletes which will prevent other Database connections
[email protected]8d2e39e2013-06-24 05:55:081133// from seeing odd behavior. For instance, it may be necessary to
1134// manually lock the main database file in a SQLite-compatible fashion
1135// (to prevent other processes from opening it), then delete the
1136// journal files, then delete the main database file. Another option
1137// might be to lock the main database file and poison the header with
1138// junk to prevent other processes from opening it successfully (like
1139// Gears "SQLite poison 3" trick).
1140//
1141// static
Victor Costancfbfa602018-08-01 23:24:461142bool Database::Delete(const base::FilePath& path) {
Etienne Pierre-Doray0400dfb62018-12-03 19:12:251143 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
[email protected]8d2e39e2013-06-24 05:55:081144
Victor Costancfbfa602018-08-01 23:24:461145 base::FilePath journal_path = Database::JournalPath(path);
1146 base::FilePath wal_path = Database::WriteAheadLogPath(path);
[email protected]8d2e39e2013-06-24 05:55:081147
erg102ceb412015-06-20 01:38:131148 std::string journal_str = AsUTF8ForSQL(journal_path);
1149 std::string wal_str = AsUTF8ForSQL(wal_path);
1150 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081151
Victor Costan3653df62018-02-08 21:38:161152 EnsureSqliteInitialized();
shess702467622015-09-16 19:04:551153
Victor Costanbd623112018-07-18 04:17:271154 sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
erg102ceb412015-06-20 01:38:131155 CHECK(vfs);
1156 CHECK(vfs->xDelete);
1157 CHECK(vfs->xAccess);
1158
1159 // We only work with unix, win32 and mojo filesystems. If you're trying to
1160 // use this code with any other VFS, you're not in a good place.
1161 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1162 strncmp(vfs->zName, "win32", 5) == 0 ||
1163 strcmp(vfs->zName, "mojo") == 0);
1164
1165 vfs->xDelete(vfs, journal_str.c_str(), 0);
1166 vfs->xDelete(vfs, wal_str.c_str(), 0);
1167 vfs->xDelete(vfs, path_str.c_str(), 0);
1168
1169 int journal_exists = 0;
Victor Costance678e72018-07-24 10:25:001170 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
erg102ceb412015-06-20 01:38:131171
1172 int wal_exists = 0;
Victor Costance678e72018-07-24 10:25:001173 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
erg102ceb412015-06-20 01:38:131174
1175 int path_exists = 0;
Victor Costance678e72018-07-24 10:25:001176 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
erg102ceb412015-06-20 01:38:131177
1178 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081179}
1180
Victor Costancfbfa602018-08-01 23:24:461181bool Database::BeginTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561182 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331183 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561184
1185 // When we're going to rollback, fail on this begin and don't actually
1186 // mark us as entering the nested transaction.
1187 return false;
1188 }
1189
1190 bool success = true;
1191 if (!transaction_nesting_) {
1192 needs_rollback_ = false;
1193
1194 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321195 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591196 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561197 return false;
1198 }
1199 transaction_nesting_++;
1200 return success;
1201}
1202
Victor Costancfbfa602018-08-01 23:24:461203void Database::RollbackTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561204 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521205 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561206 return;
1207 }
1208
1209 transaction_nesting_--;
1210
1211 if (transaction_nesting_ > 0) {
1212 // Mark the outermost transaction as needing rollback.
1213 needs_rollback_ = true;
1214 return;
1215 }
1216
1217 DoRollback();
1218}
1219
Victor Costancfbfa602018-08-01 23:24:461220bool Database::CommitTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561221 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521222 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561223 return false;
1224 }
1225 transaction_nesting_--;
1226
1227 if (transaction_nesting_ > 0) {
1228 // Mark any nested transactions as failing after we've already got one.
1229 return !needs_rollback_;
1230 }
1231
1232 if (needs_rollback_) {
1233 DoRollback();
1234 return false;
1235 }
1236
1237 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321238
1239 // Collect the commit time manually, sql::Statement would register it as query
1240 // time only.
Victor Costan87cf8c72018-07-19 19:36:041241 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321242 bool ret = commit.RunWithoutTimers();
Victor Costan87cf8c72018-07-19 19:36:041243 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321244
1245 RecordCommitTime(delta);
1246 RecordOneEvent(EVENT_COMMIT);
1247
shess7dbd4dee2015-10-06 17:39:161248 // Release dirty cache pages after the transaction closes.
1249 ReleaseCacheMemoryIfNeeded(false);
1250
shess58b8df82015-06-03 00:19:321251 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561252}
1253
Victor Costancfbfa602018-08-01 23:24:461254void Database::RollbackAllTransactions() {
[email protected]8d409412013-07-19 18:25:301255 if (transaction_nesting_ > 0) {
1256 transaction_nesting_ = 0;
1257 DoRollback();
1258 }
1259}
1260
Victor Costancfbfa602018-08-01 23:24:461261bool Database::AttachDatabase(const base::FilePath& other_db_path,
1262 const char* attachment_point,
1263 InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301264 DCHECK(ValidAttachmentPoint(attachment_point));
1265
1266 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1267#if OS_WIN
1268 s.BindString16(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181269#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberibd1301f2018-05-18 21:00:091270 s.BindString(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181271#else
1272#error Unsupported platform
[email protected]8d409412013-07-19 18:25:301273#endif
1274 s.BindString(1, attachment_point);
1275 return s.Run();
1276}
1277
Victor Costancfbfa602018-08-01 23:24:461278bool Database::DetachDatabase(const char* attachment_point, InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301279 DCHECK(ValidAttachmentPoint(attachment_point));
1280
1281 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1282 s.BindString(0, attachment_point);
1283 return s.Run();
1284}
1285
shess58b8df82015-06-03 00:19:321286// TODO(shess): Consider changing this to execute exactly one statement. If a
1287// caller wishes to execute multiple statements, that should be explicit, and
1288// perhaps tucked into an explicit transaction with rollback in case of error.
Victor Costancfbfa602018-08-01 23:24:461289int Database::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501290 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381291 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461292 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381293 return SQLITE_ERROR;
1294 }
shess58b8df82015-06-03 00:19:321295 DCHECK(sql);
1296
1297 RecordOneEvent(EVENT_EXECUTE);
1298 int rc = SQLITE_OK;
1299 while ((rc == SQLITE_OK) && *sql) {
Victor Costanbd623112018-07-18 04:17:271300 sqlite3_stmt* stmt = nullptr;
Victor Costancfbfa602018-08-01 23:24:461301 const char* leftover_sql;
shess58b8df82015-06-03 00:19:321302
Victor Costan87cf8c72018-07-19 19:36:041303 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321304 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1305 sql = leftover_sql;
1306
1307 // Stop if an error is encountered.
1308 if (rc != SQLITE_OK)
1309 break;
1310
1311 // This happens if |sql| originally only contained comments or whitespace.
1312 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1313 // extraneous comments and whitespace in the SQL statements increases
1314 // runtime cost and can easily be shifted out to the C++ layer.
1315 if (!stmt)
1316 continue;
1317
1318 // Save for use after statement is finalized.
1319 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1320
Victor Costancfbfa602018-08-01 23:24:461321 RecordOneEvent(Database::EVENT_STATEMENT_RUN);
shess58b8df82015-06-03 00:19:321322 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1323 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1324 // is the only legitimate case for this.
Victor Costancfbfa602018-08-01 23:24:461325 RecordOneEvent(Database::EVENT_STATEMENT_ROWS);
shess58b8df82015-06-03 00:19:321326 }
1327
1328 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1329 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1330 rc = sqlite3_finalize(stmt);
1331 if (rc == SQLITE_OK)
Victor Costancfbfa602018-08-01 23:24:461332 RecordOneEvent(Database::EVENT_STATEMENT_SUCCESS);
shess58b8df82015-06-03 00:19:321333
1334 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1335 // trailing whitespace.
1336 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021337 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321338 sql++;
1339 }
1340
Victor Costan87cf8c72018-07-19 19:36:041341 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321342 RecordTimeAndChanges(delta, read_only);
1343 }
shess7dbd4dee2015-10-06 17:39:161344
1345 // Most calls to Execute() modify the database. The main exceptions would be
1346 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1347 // but sometimes don't.
1348 ReleaseCacheMemoryIfNeeded(true);
1349
shess58b8df82015-06-03 00:19:321350 return rc;
[email protected]eff1fa522011-12-12 23:50:591351}
1352
Victor Costancfbfa602018-08-01 23:24:461353bool Database::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381354 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461355 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381356 return false;
1357 }
1358
[email protected]eff1fa522011-12-12 23:50:591359 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001360 if (error != SQLITE_OK)
Victor Costanbd623112018-07-18 04:17:271361 error = OnSqliteError(error, nullptr, sql);
[email protected]473ad792012-11-10 00:55:001362
[email protected]28fe0ff2012-02-25 00:40:331363 // This needs to be a FATAL log because the error case of arriving here is
1364 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101365 // a change alters the schema but not all queries adjust. This can happen
1366 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521367 DCHECK_NE(error, SQLITE_ERROR)
1368 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591369 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561370}
1371
Victor Costancfbfa602018-08-01 23:24:461372bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381373 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461374 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]5b96f3772010-09-28 16:30:571375 return false;
[email protected]41a97c812013-02-07 02:35:381376 }
[email protected]5b96f3772010-09-28 16:30:571377
1378 ScopedBusyTimeout busy_timeout(db_);
1379 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591380 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571381}
1382
Victor Costancfbfa602018-08-01 23:24:461383scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
Victor Costan12daa3ac92018-07-19 01:05:581384 StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:561385 const char* sql) {
Victor Costanc7e7f2e2018-07-18 20:07:551386 auto it = statement_cache_.find(id);
1387 if (it != statement_cache_.end()) {
Victor Costan613b4302018-11-20 05:32:431388 // Statement is in the cache. It should still be valid. We're the only
1389 // entity invalidating cached statements, and we remove them from the cache
Victor Costan87cf8c72018-07-19 19:36:041390 // when we do that.
Victor Costanc7e7f2e2018-07-18 20:07:551391 DCHECK(it->second->is_valid());
Victor Costan613b4302018-11-20 05:32:431392 DCHECK_EQ(std::string(sqlite3_sql(it->second->stmt())), std::string(sql))
Victor Costan87cf8c72018-07-19 19:36:041393 << "GetCachedStatement used with same ID but different SQL";
1394
1395 // Reset the statement so it can be reused.
Victor Costanc7e7f2e2018-07-18 20:07:551396 sqlite3_reset(it->second->stmt());
1397 return it->second;
[email protected]e5ffd0e42009-09-11 21:30:561398 }
1399
1400 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
Victor Costan613b4302018-11-20 05:32:431401 if (statement->is_valid()) {
[email protected]e5ffd0e42009-09-11 21:30:561402 statement_cache_[id] = statement; // Only cache valid statements.
Victor Costan613b4302018-11-20 05:32:431403 DCHECK_EQ(std::string(sqlite3_sql(statement->stmt())), std::string(sql))
1404 << "Input SQL does not match SQLite's normalized version";
1405 }
[email protected]e5ffd0e42009-09-11 21:30:561406 return statement;
1407}
1408
Victor Costancfbfa602018-08-01 23:24:461409scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
[email protected]e5ffd0e42009-09-11 21:30:561410 const char* sql) {
shess9e77283d2016-06-13 23:53:201411 return GetStatementImpl(this, sql);
1412}
1413
Victor Costancfbfa602018-08-01 23:24:461414scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1415 sql::Database* tracking_db,
1416 const char* sql) const {
[email protected]35f7e5392012-07-27 19:54:501417 AssertIOAllowed();
shess9e77283d2016-06-13 23:53:201418 DCHECK(sql);
Victor Costan87cf8c72018-07-19 19:36:041419 DCHECK(!tracking_db || tracking_db == this);
[email protected]35f7e5392012-07-27 19:54:501420
[email protected]41a97c812013-02-07 02:35:381421 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561422 if (!db_)
Victor Costan3b02cdf2018-07-18 00:39:561423 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561424
Victor Costanbd623112018-07-18 04:17:271425 sqlite3_stmt* stmt = nullptr;
1426 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
[email protected]473ad792012-11-10 00:55:001427 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591428 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521429 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001430
1431 // It could also be database corruption.
Victor Costanbd623112018-07-18 04:17:271432 OnSqliteError(rc, nullptr, sql);
Victor Costan3b02cdf2018-07-18 00:39:561433 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
[email protected]e5ffd0e42009-09-11 21:30:561434 }
Victor Costan3b02cdf2018-07-18 00:39:561435 return base::MakeRefCounted<StatementRef>(tracking_db, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561436}
1437
Victor Costancfbfa602018-08-01 23:24:461438scoped_refptr<Database::StatementRef> Database::GetUntrackedStatement(
[email protected]2eec0a22012-07-24 01:59:581439 const char* sql) const {
Victor Costanbd623112018-07-18 04:17:271440 return GetStatementImpl(nullptr, sql);
[email protected]2eec0a22012-07-24 01:59:581441}
1442
Victor Costancfbfa602018-08-01 23:24:461443std::string Database::GetSchema() const {
[email protected]92cd00a2013-08-16 11:09:581444 // The ORDER BY should not be necessary, but relying on organic
1445 // order for something like this is questionable.
Victor Costan87cf8c72018-07-19 19:36:041446 static const char kSql[] =
[email protected]92cd00a2013-08-16 11:09:581447 "SELECT type, name, tbl_name, sql "
1448 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1449 Statement statement(GetUntrackedStatement(kSql));
1450
1451 std::string schema;
1452 while (statement.Step()) {
1453 schema += statement.ColumnString(0);
1454 schema += '|';
1455 schema += statement.ColumnString(1);
1456 schema += '|';
1457 schema += statement.ColumnString(2);
1458 schema += '|';
1459 schema += statement.ColumnString(3);
1460 schema += '\n';
1461 }
1462
1463 return schema;
1464}
1465
Victor Costancfbfa602018-08-01 23:24:461466bool Database::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501467 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381468 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461469 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381470 return false;
1471 }
1472
Victor Costanbd623112018-07-18 04:17:271473 sqlite3_stmt* stmt = nullptr;
1474 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK)
[email protected]eff1fa522011-12-12 23:50:591475 return false;
1476
1477 sqlite3_finalize(stmt);
1478 return true;
1479}
1480
Victor Costancfbfa602018-08-01 23:24:461481bool Database::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121482 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531483}
1484
Victor Costancfbfa602018-08-01 23:24:461485bool Database::DoesTableExist(const char* table_name) const {
shessa62504d2016-11-07 19:26:121486 return DoesSchemaItemExist(table_name, "table");
1487}
1488
Victor Costancfbfa602018-08-01 23:24:461489bool Database::DoesViewExist(const char* view_name) const {
shessa62504d2016-11-07 19:26:121490 return DoesSchemaItemExist(view_name, "view");
1491}
1492
Victor Costancfbfa602018-08-01 23:24:461493bool Database::DoesSchemaItemExist(const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471494 const char* kSql =
1495 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581496 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471497
shess976814402016-06-21 06:56:251498 // This can happen if the database is corrupt and the error is a test
1499 // expectation.
shess92a2ab12015-04-09 01:59:471500 if (!statement.is_valid())
1501 return false;
1502
[email protected]e2cadec82011-12-13 02:00:531503 statement.BindString(0, type);
1504 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331505
[email protected]e5ffd0e42009-09-11 21:30:561506 return statement.Step(); // Table exists if any row was returned.
1507}
1508
Victor Costancfbfa602018-08-01 23:24:461509bool Database::DoesColumnExist(const char* table_name,
1510 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561511 std::string sql("PRAGMA TABLE_INFO(");
1512 sql.append(table_name);
1513 sql.append(")");
1514
[email protected]2eec0a22012-07-24 01:59:581515 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471516
shess976814402016-06-21 06:56:251517 // This can happen if the database is corrupt and the error is a test
1518 // expectation.
shess92a2ab12015-04-09 01:59:471519 if (!statement.is_valid())
1520 return false;
1521
[email protected]e5ffd0e42009-09-11 21:30:561522 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331523 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1524 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561525 return true;
1526 }
1527 return false;
1528}
1529
Victor Costancfbfa602018-08-01 23:24:461530int64_t Database::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561531 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461532 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]e5ffd0e42009-09-11 21:30:561533 return 0;
1534 }
1535 return sqlite3_last_insert_rowid(db_);
1536}
1537
Victor Costancfbfa602018-08-01 23:24:461538int Database::GetLastChangeCount() const {
[email protected]1ed78a32009-09-15 20:24:171539 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461540 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]1ed78a32009-09-15 20:24:171541 return 0;
1542 }
1543 return sqlite3_changes(db_);
1544}
1545
Victor Costancfbfa602018-08-01 23:24:461546int Database::GetErrorCode() const {
[email protected]e5ffd0e42009-09-11 21:30:561547 if (!db_)
1548 return SQLITE_ERROR;
1549 return sqlite3_errcode(db_);
1550}
1551
Victor Costancfbfa602018-08-01 23:24:461552int Database::GetLastErrno() const {
[email protected]767718e52010-09-21 23:18:491553 if (!db_)
1554 return -1;
1555
1556 int err = 0;
Victor Costanbd623112018-07-18 04:17:271557 if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
[email protected]767718e52010-09-21 23:18:491558 return -2;
1559
1560 return err;
1561}
1562
Victor Costancfbfa602018-08-01 23:24:461563const char* Database::GetErrorMessage() const {
[email protected]e5ffd0e42009-09-11 21:30:561564 if (!db_)
Victor Costancfbfa602018-08-01 23:24:461565 return "sql::Database is not opened.";
[email protected]e5ffd0e42009-09-11 21:30:561566 return sqlite3_errmsg(db_);
1567}
1568
Victor Costancfbfa602018-08-01 23:24:461569bool Database::OpenInternal(const std::string& file_name,
1570 Database::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501571 AssertIOAllowed();
1572
[email protected]9cfbc922009-11-17 20:13:171573 if (db_) {
Victor Costancfbfa602018-08-01 23:24:461574 DLOG(DCHECK) << "sql::Database is already open.";
[email protected]9cfbc922009-11-17 20:13:171575 return false;
1576 }
1577
Victor Costan3653df62018-02-08 21:38:161578 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181579
shess58b8df82015-06-03 00:19:321580 // Setup the stats histograms immediately rather than allocating lazily.
Victor Costancfbfa602018-08-01 23:24:461581 // Databases which won't exercise all of these probably shouldn't exist.
shess58b8df82015-06-03 00:19:321582 if (!histogram_tag_.empty()) {
Victor Costancfbfa602018-08-01 23:24:461583 stats_histogram_ = base::LinearHistogram::FactoryGet(
1584 "Sqlite.Stats." + histogram_tag_, 1, EVENT_MAX_VALUE,
1585 EVENT_MAX_VALUE + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
shess58b8df82015-06-03 00:19:321586
1587 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1588 // unreasonable time for any single operation, so there is not much value to
1589 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1590 // things are entirely busted.
1591 commit_time_histogram_ =
1592 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1593
1594 autocommit_time_histogram_ =
1595 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1596
1597 update_time_histogram_ =
1598 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1599
1600 query_time_histogram_ =
1601 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1602 }
1603
[email protected]41a97c812013-02-07 02:35:381604 // If |poisoned_| is set, it means an error handler called
1605 // RazeAndClose(). Until regular Close() is called, the caller
1606 // should be treating the database as open, but is_open() currently
1607 // only considers the sqlite3 handle's state.
1608 // TODO(shess): Revise is_open() to consider poisoned_, and review
1609 // to see if any non-testing code even depends on it.
Victor Costancfbfa602018-08-01 23:24:461610 DCHECK(!poisoned_) << "sql::Database is already open.";
[email protected]7bae5742013-07-10 20:46:161611 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381612
shess5f2c3442017-01-24 02:15:101613 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1614 sqlite3_vfs* vfs = VFSWrapper();
1615 const char* vfs_name = (vfs ? vfs->zName : nullptr);
Victor Costanc6d3a862018-11-20 18:41:231616
1617 // The flags are documented at https://www.sqlite.org/c3ref/open.html.
1618 //
1619 // Chrome uses SQLITE_OPEN_PRIVATECACHE because SQLite is used by many
1620 // disparate features with their own databases, and having separate page
1621 // caches makes it easier to reason about each feature's performance in
1622 // isolation.
1623 int err = sqlite3_open_v2(
1624 file_name.c_str(), &db_,
1625 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_PRIVATECACHE,
1626 vfs_name);
[email protected]765b44502009-10-02 05:01:421627 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281628 // Extended error codes cannot be enabled until a handle is
1629 // available, fetch manually.
1630 err = sqlite3_extended_errcode(db_);
1631
[email protected]bd2ccdb4a2012-12-07 22:14:501632 // Histogram failures specific to initial open for debugging
1633 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181634 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501635
Victor Costanbd623112018-07-18 04:17:271636 OnSqliteError(err, nullptr, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131637 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291638 Close();
[email protected]fed734a2013-07-17 04:45:131639
1640 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1641 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421642 return false;
1643 }
1644
[email protected]73fb8d52013-07-24 05:04:281645 // Enable extended result codes to provide more color on I/O errors.
1646 // Not having extended result codes is not a fatal problem, as
1647 // Chromium code does not attempt to handle I/O errors anyhow. The
1648 // current implementation always returns SQLITE_OK, the DCHECK is to
1649 // quickly notify someone if SQLite changes.
1650 err = sqlite3_extended_result_codes(db_, 1);
1651 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1652
shessbccd300e2016-08-20 00:06:561653 // sqlite3_open() does not actually read the database file (unless a hot
1654 // journal is found). Successfully executing this pragma on an existing
1655 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1656 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501657 // TODO(shess): For now, just probing to see what the lay of the
1658 // land is. If it's mostly SQLITE_NOTADB, then the database should
1659 // be razed.
1660 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561661 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181662 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561663 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1664
1665 // Retry or bail out if the error handler poisoned the handle.
1666 // TODO(shess): Move this handling to one place (see also sqlite3_open and
1667 // secure_delete). Possibly a wrapper function?
1668 if (poisoned_) {
1669 Close();
1670 if (retry_flag == RETRY_ON_POISON)
1671 return OpenInternal(file_name, NO_RETRY);
1672 return false;
1673 }
1674 }
[email protected]658f8332010-09-18 04:40:431675
[email protected]5b96f3772010-09-28 16:30:571676 // If indicated, lock up the database before doing anything else, so
1677 // that the following code doesn't have to deal with locking.
1678 // TODO(shess): This code is brittle. Find the cases where code
1679 // doesn't request |exclusive_locking_| and audit that it does the
1680 // right thing with SQLITE_BUSY, and that it doesn't make
1681 // assumptions about who might change things in the database.
1682 // http://crbug.com/56559
1683 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101684 // TODO(shess): This should probably be a failure. Code which
1685 // requests exclusive locking but doesn't get it is almost certain
1686 // to be ill-tested.
1687 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571688 }
1689
Victor Costan4c2f3e922018-08-21 04:47:591690 if (base::FeatureList::IsEnabled(features::kSqlTempStoreMemory)) {
1691 err = ExecuteAndReturnErrorCode("PRAGMA temp_store=MEMORY");
1692 // This operates on in-memory configuration, so it should not fail.
1693 DCHECK_EQ(err, SQLITE_OK) << "Failed switching to in-RAM temporary storage";
1694 }
1695
[email protected]4e179ba62012-03-17 16:06:471696 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1697 // DELETE (default) - delete -journal file to commit.
1698 // TRUNCATE - truncate -journal file to commit.
1699 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091700 // TRUNCATE should be faster than DELETE because it won't need directory
1701 // changes for each transaction. PERSIST may break the spirit of using
1702 // secure_delete.
Victor Costan4c2f3e922018-08-21 04:47:591703 ignore_result(Execute("PRAGMA journal_mode=TRUNCATE"));
[email protected]4e179ba62012-03-17 16:06:471704
[email protected]c68ce172011-11-24 22:30:271705 const base::TimeDelta kBusyTimeout =
Victor Costancfbfa602018-08-01 23:24:461706 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
[email protected]c68ce172011-11-24 22:30:271707
Victor Costancfbfa602018-08-01 23:24:461708 const std::string page_size_sql =
1709 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1710 ignore_result(ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421711
1712 if (cache_size_ != 0) {
Victor Costancfbfa602018-08-01 23:24:461713 const std::string cache_size_sql =
[email protected]7d3cbc92013-03-18 22:33:041714 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
Victor Costancfbfa602018-08-01 23:24:461715 ignore_result(ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421716 }
1717
[email protected]6e0b1442011-08-09 23:23:581718 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131719 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581720 Close();
[email protected]fed734a2013-07-17 04:45:131721 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1722 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581723 return false;
1724 }
1725
shess5dac334f2015-11-05 20:47:421726 // Set a reasonable chunk size for larger files. This reduces churn from
1727 // remapping memory on size changes. It also reduces filesystem
1728 // fragmentation.
1729 // TODO(shess): It may make sense to have this be hinted by the client.
1730 // Database sizes seem to be bimodal, some clients have consistently small
1731 // databases (<20k) while other clients have a broad distribution of sizes
1732 // (hundreds of kilobytes to many megabytes).
Victor Costanbd623112018-07-18 04:17:271733 sqlite3_file* file = nullptr;
shess5dac334f2015-11-05 20:47:421734 sqlite3_int64 db_size = 0;
1735 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1736 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1737 int chunk_size = 4 * 1024;
1738 if (db_size > 128 * 1024)
1739 chunk_size = 32 * 1024;
Victor Costanbd623112018-07-18 04:17:271740 sqlite3_file_control(db_, nullptr, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
shess5dac334f2015-11-05 20:47:421741 }
1742
shess2f3a814b2015-11-05 18:11:101743 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311744 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1745 // safe range to memory-map based on past regular I/O. This value will be
1746 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1747 // 64-bit platforms.
1748 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1749 std::string mmap_sql =
Victor Costan4c2f3e922018-08-21 04:47:591750 base::StringPrintf("PRAGMA mmap_size=%" PRIuS, mmap_size);
shessd90aeea82015-11-13 02:24:311751 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101752
1753 // Determine if memory-mapping has actually been enabled. The Execute() above
1754 // can succeed without changing the amount mapped.
1755 mmap_enabled_ = false;
1756 {
1757 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1758 if (s.Step() && s.ColumnInt64(0) > 0)
1759 mmap_enabled_ = true;
1760 }
1761
ssid3be5b1ec2016-01-13 14:21:571762 DCHECK(!memory_dump_provider_);
1763 memory_dump_provider_.reset(
Victor Costancfbfa602018-08-01 23:24:461764 new DatabaseMemoryDumpProvider(db_, histogram_tag_));
ssid3be5b1ec2016-01-13 14:21:571765 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
Victor Costancfbfa602018-08-01 23:24:461766 memory_dump_provider_.get(), "sql::Database", nullptr);
ssid3be5b1ec2016-01-13 14:21:571767
[email protected]765b44502009-10-02 05:01:421768 return true;
1769}
1770
Victor Costancfbfa602018-08-01 23:24:461771void Database::DoRollback() {
[email protected]e5ffd0e42009-09-11 21:30:561772 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321773
1774 // Collect the rollback time manually, sql::Statement would register it as
1775 // query time only.
Victor Costan87cf8c72018-07-19 19:36:041776 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321777 rollback.RunWithoutTimers();
Victor Costan87cf8c72018-07-19 19:36:041778 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321779
1780 RecordUpdateTime(delta);
1781 RecordOneEvent(EVENT_ROLLBACK);
1782
shess7dbd4dee2015-10-06 17:39:161783 // The cache may have been accumulating dirty pages for commit. Note that in
1784 // some cases sql::Transaction can fire rollback after a database is closed.
1785 if (is_open())
1786 ReleaseCacheMemoryIfNeeded(false);
1787
[email protected]44ad7d902012-03-23 00:09:051788 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561789}
1790
Victor Costancfbfa602018-08-01 23:24:461791void Database::StatementRefCreated(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551792 DCHECK(!open_statements_.count(ref))
1793 << __func__ << " already called with this statement";
[email protected]e5ffd0e42009-09-11 21:30:561794 open_statements_.insert(ref);
1795}
1796
Victor Costancfbfa602018-08-01 23:24:461797void Database::StatementRefDeleted(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551798 DCHECK(open_statements_.count(ref))
1799 << __func__ << " called with non-existing statement";
1800 open_statements_.erase(ref);
[email protected]e5ffd0e42009-09-11 21:30:561801}
1802
Victor Costancfbfa602018-08-01 23:24:461803void Database::set_histogram_tag(const std::string& tag) {
shess58b8df82015-06-03 00:19:321804 DCHECK(!is_open());
Victor Costan87cf8c72018-07-19 19:36:041805
shess58b8df82015-06-03 00:19:321806 histogram_tag_ = tag;
1807}
1808
Will Harrisb8693592018-08-28 22:58:441809void Database::AddTaggedHistogram(const std::string& name, int sample) const {
[email protected]210ce0af2013-05-15 09:10:391810 if (histogram_tag_.empty())
1811 return;
1812
1813 // TODO(shess): The histogram macros create a bit of static storage
1814 // for caching the histogram object. This code shouldn't execute
1815 // often enough for such caching to be crucial. If it becomes an
1816 // issue, the object could be cached alongside histogram_prefix_.
1817 std::string full_histogram_name = name + "." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:461818 base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
1819 full_histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]210ce0af2013-05-15 09:10:391820 if (histogram)
1821 histogram->Add(sample);
1822}
1823
Victor Costancfbfa602018-08-01 23:24:461824int Database::OnSqliteError(int err,
1825 sql::Statement* stmt,
1826 const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181827 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391828 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141829
1830 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581831 if (!sql && stmt)
1832 sql = stmt->GetSQLStatement();
1833 if (!sql)
1834 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061835
1836 std::string id = histogram_tag_;
1837 if (id.empty())
1838 id = DbPath().BaseName().AsUTF8Unsafe();
Victor Costancfbfa602018-08-01 23:24:461839 LOG(ERROR) << id << " sqlite error " << err << ", errno " << GetLastErrno()
1840 << ": " << GetErrorMessage() << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141841
[email protected]c3881b372013-05-17 08:39:461842 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561843 // Fire from a copy of the callback in case of reentry into
1844 // re/set_error_callback().
1845 // TODO(shess): <http://crbug.com/254584>
1846 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461847 return err;
1848 }
1849
[email protected]faa604e2009-09-25 22:38:591850 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251851 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521852 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591853 return err;
1854}
1855
Victor Costancfbfa602018-08-01 23:24:461856bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
[email protected]579446c2013-12-16 18:36:521857 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1858}
1859
Victor Costancfbfa602018-08-01 23:24:461860bool Database::QuickIntegrityCheck() {
[email protected]579446c2013-12-16 18:36:521861 std::vector<std::string> messages;
1862 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1863 return false;
1864 return messages.size() == 1 && messages[0] == "ok";
1865}
1866
Victor Costancfbfa602018-08-01 23:24:461867std::string Database::GetDiagnosticInfo(int extended_error,
1868 Statement* statement) {
afakhry7c9abe72016-08-05 17:33:191869 // Prevent reentrant calls to the error callback.
1870 ErrorCallback original_callback = std::move(error_callback_);
1871 reset_error_callback();
1872
1873 // Trim extended error codes.
1874 const int error = (extended_error & 0xFF);
Victor Costancfbfa602018-08-01 23:24:461875 // CollectCorruptionInfo() is implemented in terms of sql::Database,
afakhry7c9abe72016-08-05 17:33:191876 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1877 std::string result = (error == SQLITE_CORRUPT)
1878 ? CollectCorruptionInfo()
1879 : CollectErrorInfo(extended_error, statement);
1880
1881 // The following queries must be executed after CollectErrorInfo() above, so
1882 // if they result in their own errors, they don't interfere with
1883 // CollectErrorInfo().
1884 const bool has_valid_header =
1885 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1886 const bool select_sqlite_master_result =
1887 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1888 SQLITE_OK);
1889
1890 // Restore the original error callback.
1891 error_callback_ = std::move(original_callback);
1892
1893 base::StringAppendF(&result, "Has valid header: %s\n",
1894 (has_valid_header ? "Yes" : "No"));
1895 base::StringAppendF(&result, "Has valid schema: %s\n",
1896 (select_sqlite_master_result ? "Yes" : "No"));
1897
1898 return result;
1899}
1900
[email protected]80abf152013-05-22 12:42:421901// TODO(shess): Allow specifying maximum results (default 100 lines).
Victor Costancfbfa602018-08-01 23:24:461902bool Database::IntegrityCheckHelper(const char* pragma_sql,
1903 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421904 messages->clear();
1905
[email protected]4658e2a02013-06-06 23:05:001906 // This has the side effect of setting SQLITE_RecoveryMode, which
1907 // allows SQLite to process through certain cases of corruption.
1908 // Failing to set this pragma probably means that the database is
1909 // beyond recovery.
Victor Costan4c2f3e922018-08-21 04:47:591910 static const char kWritableSchemaSql[] = "PRAGMA writable_schema=ON";
Victor Costan1d868352018-06-26 19:06:481911 if (!Execute(kWritableSchemaSql))
[email protected]4658e2a02013-06-06 23:05:001912 return false;
1913
1914 bool ret = false;
1915 {
[email protected]579446c2013-12-16 18:36:521916 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001917
1918 // The pragma appears to return all results (up to 100 by default)
1919 // as a single string. This doesn't appear to be an API contract,
1920 // it could return separate lines, so loop _and_ split.
1921 while (stmt.Step()) {
1922 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181923 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1924 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001925 }
1926 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421927 }
[email protected]4658e2a02013-06-06 23:05:001928
1929 // Best effort to put things back as they were before.
Victor Costan4c2f3e922018-08-21 04:47:591930 static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema=OFF";
Victor Costan1d868352018-06-26 19:06:481931 ignore_result(Execute(kNoWritableSchemaSql));
[email protected]4658e2a02013-06-06 23:05:001932
1933 return ret;
[email protected]80abf152013-05-22 12:42:421934}
1935
Victor Costancfbfa602018-08-01 23:24:461936bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1937 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131938 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381939 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131940}
1941
[email protected]e5ffd0e42009-09-11 21:30:561942} // namespace sql