blob: 66bf05b49dc97d9a7964d2eb9002e33492d95934 [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Victor Costancfbfa602018-08-01 23:24:465#include "sql/database.h"
[email protected]e5ffd0e42009-09-11 21:30:566
avi51ba3e692015-12-26 17:30:507#include <limits.h>
avi0b519202015-12-21 07:25:198#include <stddef.h>
9#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:5610#include <string.h>
mostynbd82cd9952016-04-11 20:05:3411
tzikb9dae932017-02-10 03:57:3012#include "base/debug/alias.h"
shessc8cd2a162015-10-22 20:30:4613#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5214#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4415#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4616#include "base/format_macros.h"
17#include "base/json/json_file_value_serializer.h"
fdoray2dfa76452016-06-07 13:11:2218#include "base/location.h"
[email protected]e5ffd0e42009-09-11 21:30:5619#include "base/logging.h"
Ilya Sherman1c811db2017-12-14 10:36:1820#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0821#include "base/metrics/histogram_macros.h"
[email protected]210ce0af2013-05-15 09:10:3922#include "base/metrics/sparse_histogram.h"
Victor Costan3653df62018-02-08 21:38:1623#include "base/no_destructor.h"
fdoray2dfa76452016-06-07 13:11:2224#include "base/single_thread_task_runner.h"
[email protected]80abf152013-05-22 12:42:4225#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1926#include "base/strings/string_util.h"
27#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4528#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1829#include "base/synchronization/lock.h"
Victor Costan87cf8c72018-07-19 19:36:0430#include "base/time/default_tick_clock.h"
ssid9f8022f2015-10-12 17:49:0331#include "base/trace_event/memory_dump_manager.h"
Kevin Marshalla9f05ec2017-07-14 02:10:0532#include "build/build_config.h"
Victor Costancfbfa602018-08-01 23:24:4633#include "sql/database_memory_dump_provider.h"
Victor Costan3653df62018-02-08 21:38:1634#include "sql/initialization.h"
shess9bf2c672015-12-18 01:18:0835#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2136#include "sql/statement.h"
shess5f2c3442017-01-24 02:15:1037#include "sql/vfs_wrapper.h"
[email protected]e33cba42010-08-18 23:37:0338#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5639
[email protected]5b96f3772010-09-28 16:30:5740namespace {
41
42// Spin for up to a second waiting for the lock to clear when setting
43// up the database.
44// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2745const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5746
47class ScopedBusyTimeout {
48 public:
Victor Costancfbfa602018-08-01 23:24:4649 explicit ScopedBusyTimeout(sqlite3* db) : db_(db) {}
50 ~ScopedBusyTimeout() { sqlite3_busy_timeout(db_, 0); }
[email protected]5b96f3772010-09-28 16:30:5751
52 int SetTimeout(base::TimeDelta timeout) {
53 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
54 return sqlite3_busy_timeout(db_,
55 static_cast<int>(timeout.InMilliseconds()));
56 }
57
58 private:
59 sqlite3* db_;
60};
61
[email protected]6d42f152012-11-10 00:38:2462// Helper to "safely" enable writable_schema. No error checking
63// because it is reasonable to just forge ahead in case of an error.
64// If turning it on fails, then most likely nothing will work, whereas
65// if turning it off fails, it only matters if some code attempts to
66// continue working with the database and tries to modify the
67// sqlite_master table (none of our code does this).
68class ScopedWritableSchema {
69 public:
Victor Costancfbfa602018-08-01 23:24:4670 explicit ScopedWritableSchema(sqlite3* db) : db_(db) {
Victor Costanbd623112018-07-18 04:17:2771 sqlite3_exec(db_, "PRAGMA writable_schema=1", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2472 }
73 ~ScopedWritableSchema() {
Victor Costanbd623112018-07-18 04:17:2774 sqlite3_exec(db_, "PRAGMA writable_schema=0", nullptr, nullptr, nullptr);
[email protected]6d42f152012-11-10 00:38:2475 }
76
77 private:
78 sqlite3* db_;
79};
80
[email protected]7bae5742013-07-10 20:46:1681// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
82// SQLite error code from running the backup step.
83int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
84 DCHECK_NE(src, dst);
85 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
86 if (!backup) {
87 // Since this call only sets things up, this indicates a gross
88 // error in SQLite.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:5289 DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
[email protected]7bae5742013-07-10 20:46:1690 return sqlite3_errcode(dst);
91 }
92
93 // -1 backs up the entire database.
94 int rc = sqlite3_backup_step(backup, -1);
95 int pages = sqlite3_backup_pagecount(backup);
96 sqlite3_backup_finish(backup);
97
98 // If successful, exactly one page should have been backed up. If
99 // this breaks, check this function to make sure assumptions aren't
100 // being broken.
101 if (rc == SQLITE_DONE)
102 DCHECK_EQ(pages, 1);
103
104 return rc;
105}
106
[email protected]8d409412013-07-19 18:25:30107// Be very strict on attachment point. SQLite can handle a much wider
108// character set with appropriate quoting, but Chromium code should
109// just use clean names to start with.
110bool ValidAttachmentPoint(const char* attachment_point) {
111 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20112 if (!(base::IsAsciiDigit(attachment_point[i]) ||
113 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30114 attachment_point[i] == '_')) {
115 return false;
116 }
117 }
118 return true;
119}
120
[email protected]8ada10f2013-12-21 00:42:34121// Helper to get the sqlite3_file* associated with the "main" database.
122int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
Victor Costanbd623112018-07-18 04:17:27123 *file = nullptr;
124 int rc = sqlite3_file_control(db, nullptr, SQLITE_FCNTL_FILE_POINTER, file);
[email protected]8ada10f2013-12-21 00:42:34125 if (rc != SQLITE_OK)
126 return rc;
127
Victor Costanbd623112018-07-18 04:17:27128 // TODO(shess): null in file->pMethods has been observed on android_dbg
[email protected]8ada10f2013-12-21 00:42:34129 // content_unittests, even though it should not be possible.
130 // http://crbug.com/329982
131 if (!*file || !(*file)->pMethods)
132 return SQLITE_ERROR;
133
134 return rc;
135}
136
shess5dac334f2015-11-05 20:47:42137// Convenience to get the sqlite3_file* and the size for the "main" database.
138int GetSqlite3FileAndSize(sqlite3* db,
Victor Costancfbfa602018-08-01 23:24:46139 sqlite3_file** file,
140 sqlite3_int64* db_size) {
shess5dac334f2015-11-05 20:47:42141 int rc = GetSqlite3File(db, file);
142 if (rc != SQLITE_OK)
143 return rc;
144
145 return (*file)->pMethods->xFileSize(*file, db_size);
146}
147
shess58b8df82015-06-03 00:19:32148// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
149base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
150 return base::Histogram::FactoryTimeGet(
Victor Costancfbfa602018-08-01 23:24:46151 name, base::TimeDelta::FromMilliseconds(10),
152 base::TimeDelta::FromMinutes(3), 50,
shess58b8df82015-06-03 00:19:32153 base::HistogramBase::kUmaTargetedHistogramFlag);
154}
155
erg102ceb412015-06-20 01:38:13156std::string AsUTF8ForSQL(const base::FilePath& path) {
157#if defined(OS_WIN)
158 return base::WideToUTF8(path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18159#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
erg102ceb412015-06-20 01:38:13160 return path.value();
161#endif
162}
163
[email protected]5b96f3772010-09-28 16:30:57164} // namespace
165
[email protected]e5ffd0e42009-09-11 21:30:56166namespace sql {
167
[email protected]4350e322013-06-18 22:18:10168// static
Victor Costancfbfa602018-08-01 23:24:46169Database::ErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10170
171// static
Victor Costancfbfa602018-08-01 23:24:46172bool Database::IsExpectedSqliteError(int error) {
shess976814402016-06-21 06:56:25173 if (!current_expecter_cb_)
[email protected]4350e322013-06-18 22:18:10174 return false;
shess976814402016-06-21 06:56:25175 return current_expecter_cb_->Run(error);
[email protected]4350e322013-06-18 22:18:10176}
177
Victor Costancfbfa602018-08-01 23:24:46178void Database::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
shessc8cd2a162015-10-22 20:30:46179 AssertIOAllowed();
180
afakhry7c9abe72016-08-05 17:33:19181 std::string debug_info = GetDiagnosticInfo(extended_error, stmt);
shessc8cd2a162015-10-22 20:30:46182 if (!debug_info.empty() && RegisterIntentToUpload()) {
Lukasz Anforowicz68c21772018-01-13 03:42:44183 DEBUG_ALIAS_FOR_CSTR(debug_buf, debug_info.c_str(), 2000);
shessc8cd2a162015-10-22 20:30:46184 base::debug::DumpWithoutCrashing();
185 }
186}
187
[email protected]4350e322013-06-18 22:18:10188// static
Victor Costancfbfa602018-08-01 23:24:46189void Database::SetErrorExpecter(Database::ErrorExpecterCallback* cb) {
Victor Costanbd623112018-07-18 04:17:27190 CHECK(!current_expecter_cb_);
shess976814402016-06-21 06:56:25191 current_expecter_cb_ = cb;
[email protected]4350e322013-06-18 22:18:10192}
193
194// static
Victor Costancfbfa602018-08-01 23:24:46195void Database::ResetErrorExpecter() {
shess976814402016-06-21 06:56:25196 CHECK(current_expecter_cb_);
Victor Costanbd623112018-07-18 04:17:27197 current_expecter_cb_ = nullptr;
[email protected]4350e322013-06-18 22:18:10198}
199
Victor Costance678e72018-07-24 10:25:00200// static
Victor Costancfbfa602018-08-01 23:24:46201base::FilePath Database::JournalPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00202 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
203}
204
205// static
Victor Costancfbfa602018-08-01 23:24:46206base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00207 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
208}
209
210// static
Victor Costancfbfa602018-08-01 23:24:46211base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
Victor Costance678e72018-07-24 10:25:00212 return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
213}
214
Victor Costancfbfa602018-08-01 23:24:46215Database::StatementRef::StatementRef(Database* database,
216 sqlite3_stmt* stmt,
217 bool was_valid)
218 : database_(database), stmt_(stmt), was_valid_(was_valid) {
219 if (database)
220 database_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56221}
222
Victor Costancfbfa602018-08-01 23:24:46223Database::StatementRef::~StatementRef() {
224 if (database_)
225 database_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38226 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56227}
228
Victor Costancfbfa602018-08-01 23:24:46229void Database::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56230 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50231 // Call to AssertIOAllowed() cannot go at the beginning of the function
232 // because Close() is called unconditionally from destructor to clean
Victor Costancfbfa602018-08-01 23:24:46233 // database_. And if this is inactive statement this won't cause any
[email protected]35f7e5392012-07-27 19:54:50234 // disk access and destructor most probably will be called on thread
235 // not allowing disk access.
236 // TODO([email protected]): This should move to the beginning
237 // of the function. http://crbug.com/136655.
238 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56239 sqlite3_finalize(stmt_);
Victor Costanbd623112018-07-18 04:17:27240 stmt_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56241 }
Victor Costancfbfa602018-08-01 23:24:46242 database_ = nullptr; // The Database may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38243
244 // Forced close is expected to happen from a statement error
245 // handler. In that case maintain the sense of |was_valid_| which
246 // previously held for this ref.
247 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56248}
249
Victor Costan7f6abbbe2018-07-29 02:57:27250static_assert(
Victor Costancfbfa602018-08-01 23:24:46251 Database::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
252 "Database::kDefaultPageSize must match the value configured into SQLite");
Victor Costan7f6abbbe2018-07-29 02:57:27253
Victor Costancfbfa602018-08-01 23:24:46254constexpr int Database::kDefaultPageSize;
Victor Costan7f6abbbe2018-07-29 02:57:27255
Victor Costancfbfa602018-08-01 23:24:46256Database::Database()
Victor Costanbd623112018-07-18 04:17:27257 : db_(nullptr),
Victor Costan7f6abbbe2018-07-29 02:57:27258 page_size_(kDefaultPageSize),
[email protected]e5ffd0e42009-09-11 21:30:56259 cache_size_(0),
260 exclusive_locking_(false),
261 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50262 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16263 in_memory_(false),
shess58b8df82015-06-03 00:19:32264 poisoned_(false),
shessa62504d2016-11-07 19:26:12265 mmap_alt_status_(false),
kerz42ff2a012016-04-27 04:50:06266 mmap_disabled_(false),
shess7dbd4dee2015-10-06 17:39:16267 mmap_enabled_(false),
268 total_changes_at_last_release_(0),
Victor Costanbd623112018-07-18 04:17:27269 stats_histogram_(nullptr),
270 commit_time_histogram_(nullptr),
271 autocommit_time_histogram_(nullptr),
272 update_time_histogram_(nullptr),
273 query_time_histogram_(nullptr),
Victor Costan87cf8c72018-07-19 19:36:04274 clock_(std::make_unique<base::DefaultTickClock>()) {}
[email protected]e5ffd0e42009-09-11 21:30:56275
Victor Costancfbfa602018-08-01 23:24:46276Database::~Database() {
[email protected]e5ffd0e42009-09-11 21:30:56277 Close();
278}
279
Victor Costancfbfa602018-08-01 23:24:46280void Database::RecordEvent(Events event, size_t count) {
shess58b8df82015-06-03 00:19:32281 for (size_t i = 0; i < count; ++i) {
282 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
283 }
284
285 if (stats_histogram_) {
286 for (size_t i = 0; i < count; ++i) {
287 stats_histogram_->Add(event);
288 }
289 }
290}
291
Victor Costancfbfa602018-08-01 23:24:46292void Database::RecordCommitTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32293 RecordUpdateTime(delta);
294 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
295 if (commit_time_histogram_)
296 commit_time_histogram_->AddTime(delta);
297}
298
Victor Costancfbfa602018-08-01 23:24:46299void Database::RecordAutoCommitTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32300 RecordUpdateTime(delta);
301 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
302 if (autocommit_time_histogram_)
303 autocommit_time_histogram_->AddTime(delta);
304}
305
Victor Costancfbfa602018-08-01 23:24:46306void Database::RecordUpdateTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32307 RecordQueryTime(delta);
308 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
309 if (update_time_histogram_)
310 update_time_histogram_->AddTime(delta);
311}
312
Victor Costancfbfa602018-08-01 23:24:46313void Database::RecordQueryTime(const base::TimeDelta& delta) {
shess58b8df82015-06-03 00:19:32314 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
315 if (query_time_histogram_)
316 query_time_histogram_->AddTime(delta);
317}
318
Victor Costancfbfa602018-08-01 23:24:46319void Database::RecordTimeAndChanges(const base::TimeDelta& delta,
320 bool read_only) {
shess58b8df82015-06-03 00:19:32321 if (read_only) {
322 RecordQueryTime(delta);
323 } else {
324 const int changes = sqlite3_changes(db_);
325 if (sqlite3_get_autocommit(db_)) {
326 RecordAutoCommitTime(delta);
327 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
328 } else {
329 RecordUpdateTime(delta);
330 RecordEvent(EVENT_CHANGES, changes);
331 }
332 }
333}
334
Victor Costancfbfa602018-08-01 23:24:46335bool Database::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02336 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26337 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49338 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02339 size_t sample = static_cast<size_t>(size_64 / 1024);
340 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:46341 base::HistogramBase* histogram = base::Histogram::FactoryGet(
342 full_histogram_name, 1, 1000000, 50,
343 base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]348ac8f52013-05-21 03:27:02344 if (histogram)
345 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08346 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02347 }
348 }
349
erg102ceb412015-06-20 01:38:13350 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42351}
[email protected]e5ffd0e42009-09-11 21:30:56352
Victor Costancfbfa602018-08-01 23:24:46353bool Database::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50354 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13355 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56356}
357
Victor Costancfbfa602018-08-01 23:24:46358bool Database::OpenTemporary() {
[email protected]8d409412013-07-19 18:25:30359 return OpenInternal("", NO_RETRY);
360}
361
Victor Costancfbfa602018-08-01 23:24:46362void Database::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47363 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
364 // will delete the -journal file. For ChromiumOS or other more
365 // embedded systems, this is probably not appropriate, whereas on
366 // desktop it might make some sense.
367
[email protected]4b350052012-02-24 20:40:48368 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48369
[email protected]41a97c812013-02-07 02:35:38370 // Release cached statements.
371 statement_cache_.clear();
372
373 // With cached statements released, in-use statements will remain.
374 // Closing the database while statements are in use is an API
375 // violation, except for forced close (which happens from within a
376 // statement's error handler).
377 DCHECK(forced || open_statements_.empty());
378
379 // Deactivate any outstanding statements so sqlite3_close() works.
Victor Costanc7e7f2e2018-07-18 20:07:55380 for (StatementRef* statement_ref : open_statements_)
381 statement_ref->Close(forced);
[email protected]41a97c812013-02-07 02:35:38382 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48383
[email protected]e5ffd0e42009-09-11 21:30:56384 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50385 // Call to AssertIOAllowed() cannot go at the beginning of the function
386 // because Close() must be called from destructor to clean
387 // statement_cache_, it won't cause any disk access and it most probably
388 // will happen on thread not allowing disk access.
389 // TODO([email protected]): This should move to the beginning
390 // of the function. http://crbug.com/136655.
391 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28392
ssid3be5b1ec2016-01-13 14:21:57393 // Reseting acquires a lock to ensure no dump is happening on the database
394 // at the same time. Unregister takes ownership of provider and it is safe
395 // since the db is reset. memory_dump_provider_ could be null if db_ was
396 // poisoned.
397 if (memory_dump_provider_) {
398 memory_dump_provider_->ResetDatabase();
399 base::trace_event::MemoryDumpManager::GetInstance()
400 ->UnregisterAndDeleteDumpProviderSoon(
401 std::move(memory_dump_provider_));
402 }
403
[email protected]73fb8d52013-07-24 05:04:28404 int rc = sqlite3_close(db_);
405 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18406 base::UmaHistogramSparse("Sqlite.CloseFailure", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52407 DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage();
[email protected]73fb8d52013-07-24 05:04:28408 }
[email protected]e5ffd0e42009-09-11 21:30:56409 }
Victor Costanbd623112018-07-18 04:17:27410 db_ = nullptr;
[email protected]e5ffd0e42009-09-11 21:30:56411}
412
Victor Costancfbfa602018-08-01 23:24:46413void Database::Close() {
[email protected]41a97c812013-02-07 02:35:38414 // If the database was already closed by RazeAndClose(), then no
415 // need to close again. Clear the |poisoned_| bit so that incorrect
416 // API calls are caught.
417 if (poisoned_) {
418 poisoned_ = false;
419 return;
420 }
421
422 CloseInternal(false);
423}
424
Victor Costancfbfa602018-08-01 23:24:46425void Database::Preload() {
[email protected]35f7e5392012-07-27 19:54:50426 AssertIOAllowed();
427
[email protected]e5ffd0e42009-09-11 21:30:56428 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52429 DCHECK(poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56430 return;
431 }
432
Victor Costan7f6abbbe2018-07-29 02:57:27433 // The constructor and set_page_size() ensure that page_size_ is never zero.
434 const int page_size = page_size_;
435 DCHECK(page_size);
436
[email protected]8ada10f2013-12-21 00:42:34437 // Use local settings if provided, otherwise use documented defaults. The
438 // actual results could be fetching via PRAGMA calls.
[email protected]8ada10f2013-12-21 00:42:34439 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
440 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56441 return;
442
Victor Costanbd623112018-07-18 04:17:27443 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:34444 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42445 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34446 if (rc != SQLITE_OK)
447 return;
448
449 // Don't preload more than the file contains.
450 if (preload_size > file_size)
451 preload_size = file_size;
452
mostynbd82cd9952016-04-11 20:05:34453 std::unique_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46454 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34455 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31456
457 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34458 if (rc != SQLITE_OK)
459 return;
460 }
[email protected]e5ffd0e42009-09-11 21:30:56461}
462
Victor Costancfbfa602018-08-01 23:24:46463// SQLite keeps unused pages associated with a database in a cache. It asks
shess7dbd4dee2015-10-06 17:39:16464// the cache for pages by an id, and if the page is present and the database is
465// unchanged, it considers the content of the page valid and doesn't read it
466// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
467// structures created from the memory map data before consulting the cache. On
468// write SQLite creates a new in-memory page structure, copies the data from the
469// memory map, and later writes it, releasing the updated page back to the
470// cache.
471//
472// This means that in memory-mapped mode, the contents of the cached pages are
473// not re-used for reads, but they are re-used for writes if the re-written page
474// is still in the cache. The implementation of sqlite3_db_release_memory() as
475// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
Victor Costancfbfa602018-08-01 23:24:46476// database, so it should free these pages.
shess7dbd4dee2015-10-06 17:39:16477//
478// Unfortunately, the zero page is also freed. That page is never accessed
479// using memory-mapped I/O, and the cached copy can be re-used after verifying
480// the file change counter on disk. Also, fresh pages from cache receive some
481// pager-level initialization before they can be used. Since the information
482// involved will immediately be accessed in various ways, it is unclear if the
483// additional overhead is material, or just moving processor cache effects
484// around.
485//
486// TODO(shess): It would be better to release the pages immediately when they
487// are no longer needed. This would basically happen after SQLite commits a
488// transaction. I had implemented a pcache wrapper to do this, but it involved
489// layering violations, and it had to be setup before any other sqlite call,
490// which was brittle. Also, for large files it would actually make sense to
491// maintain the existing pcache behavior for blocks past the memory-mapped
492// segment. I think drh would accept a reasonable implementation of the overall
493// concept for upstreaming to SQLite core.
494//
495// TODO(shess): Another possibility would be to set the cache size small, which
496// would keep the zero page around, plus some pre-initialized pages, and SQLite
497// can manage things. The downside is that updates larger than the cache would
498// spill to the journal. That could be compensated by setting cache_spill to
499// false. The downside then is that it allows open-ended use of memory for
500// large transactions.
501//
502// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
503// work. There could be two prepared statements, one for cache_size=1 one for
504// cache_size=goal.
Victor Costancfbfa602018-08-01 23:24:46505void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
shess644fc8a2016-02-26 18:15:58506 // The database could have been closed during a transaction as part of error
507 // recovery.
508 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:46509 DCHECK(poisoned_) << "Illegal use of Database without a db";
shess644fc8a2016-02-26 18:15:58510 return;
511 }
shess7dbd4dee2015-10-06 17:39:16512
513 // If memory-mapping is not enabled, the page cache helps performance.
514 if (!mmap_enabled_)
515 return;
516
517 // On caller request, force the change comparison to fail. Done before the
518 // transaction-nesting test so that the signal can carry to transaction
519 // commit.
520 if (implicit_change_performed)
521 --total_changes_at_last_release_;
522
523 // Cached pages may be re-used within the same transaction.
524 if (transaction_nesting())
525 return;
526
527 // If no changes have been made, skip flushing. This allows the first page of
528 // the database to remain in cache across multiple reads.
529 const int total_changes = sqlite3_total_changes(db_);
530 if (total_changes == total_changes_at_last_release_)
531 return;
532
533 total_changes_at_last_release_ = total_changes;
534 sqlite3_db_release_memory(db_);
535}
536
Victor Costancfbfa602018-08-01 23:24:46537base::FilePath Database::DbPath() const {
shessc8cd2a162015-10-22 20:30:46538 if (!is_open())
539 return base::FilePath();
540
541 const char* path = sqlite3_db_filename(db_, "main");
542 const base::StringPiece db_path(path);
543#if defined(OS_WIN)
544 return base::FilePath(base::UTF8ToWide(db_path));
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18545#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46546 return base::FilePath(db_path);
547#else
548 NOTREACHED();
549 return base::FilePath();
550#endif
551}
552
553// Data is persisted in a file shared between databases in the same directory.
554// The "sqlite-diag" file contains a dictionary with the version number, and an
555// array of histogram tags for databases which have been dumped.
Victor Costancfbfa602018-08-01 23:24:46556bool Database::RegisterIntentToUpload() const {
shessc8cd2a162015-10-22 20:30:46557 static const char* kVersionKey = "version";
558 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
559 static int kVersion = 1;
560
561 AssertIOAllowed();
562
563 if (histogram_tag_.empty())
564 return false;
565
566 if (!is_open())
567 return false;
568
569 if (in_memory_)
570 return false;
571
572 const base::FilePath db_path = DbPath();
573 if (db_path.empty())
574 return false;
575
576 // Put the collection of diagnostic data next to the databases. In most
577 // cases, this is the profile directory, but safe-browsing stores a Cookies
578 // file in the directory above the profile directory.
Victor Costance678e72018-07-24 10:25:00579 base::FilePath breadcrumb_path = db_path.DirName().AppendASCII("sqlite-diag");
shessc8cd2a162015-10-22 20:30:46580
581 // Lock against multiple updates to the diagnostics file. This code should
582 // seldom be called in the first place, and when called it should seldom be
583 // called for multiple databases, and when called for multiple databases there
584 // is _probably_ something systemic wrong with the user's system. So the lock
585 // should never be contended, but when it is the database experience is
586 // already bad.
Victor Costan3653df62018-02-08 21:38:16587 static base::NoDestructor<base::Lock> lock;
588 base::AutoLock auto_lock(*lock);
shessc8cd2a162015-10-22 20:30:46589
mostynbd82cd9952016-04-11 20:05:34590 std::unique_ptr<base::Value> root;
shessc8cd2a162015-10-22 20:30:46591 if (!base::PathExists(breadcrumb_path)) {
mostynbd82cd9952016-04-11 20:05:34592 std::unique_ptr<base::DictionaryValue> root_dict(
593 new base::DictionaryValue());
shessc8cd2a162015-10-22 20:30:46594 root_dict->SetInteger(kVersionKey, kVersion);
595
mostynbd82cd9952016-04-11 20:05:34596 std::unique_ptr<base::ListValue> dumps(new base::ListValue);
shessc8cd2a162015-10-22 20:30:46597 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50598 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46599
dchenge48600452015-12-28 02:24:50600 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46601 } else {
602 // Failure to read a valid dictionary implies that something is going wrong
603 // on the system.
604 JSONFileValueDeserializer deserializer(breadcrumb_path);
mostynbd82cd9952016-04-11 20:05:34605 std::unique_ptr<base::Value> read_root(
shessc8cd2a162015-10-22 20:30:46606 deserializer.Deserialize(nullptr, nullptr));
607 if (!read_root.get())
608 return false;
mostynbd82cd9952016-04-11 20:05:34609 std::unique_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50610 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46611 if (!root_dict)
612 return false;
613
614 // Don't upload if the version is missing or newer.
615 int version = 0;
616 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
617 return false;
618
619 base::ListValue* dumps = nullptr;
620 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
621 return false;
622
623 const size_t size = dumps->GetSize();
624 for (size_t i = 0; i < size; ++i) {
625 std::string s;
626
627 // Don't upload if the value isn't a string, or indicates a prior upload.
628 if (!dumps->GetString(i, &s) || s == histogram_tag_)
629 return false;
630 }
631
632 // Record intention to proceed with upload.
633 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50634 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46635 }
636
637 const base::FilePath breadcrumb_new =
638 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
639 base::DeleteFile(breadcrumb_new, false);
640
641 // No upload if the breadcrumb file cannot be updated.
642 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
643 // the data on disk. For now, losing the data is not a big problem, so the
644 // sync overhead would probably not be worth it.
645 JSONFileValueSerializer serializer(breadcrumb_new);
646 if (!serializer.Serialize(*root))
647 return false;
648 if (!base::PathExists(breadcrumb_new))
649 return false;
650 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
651 base::DeleteFile(breadcrumb_new, false);
652 return false;
653 }
654
655 return true;
656}
657
Victor Costancfbfa602018-08-01 23:24:46658std::string Database::CollectErrorInfo(int error, Statement* stmt) const {
shessc8cd2a162015-10-22 20:30:46659 // Buffer for accumulating debugging info about the error. Place
660 // more-relevant information earlier, in case things overflow the
661 // fixed-size reporting buffer.
662 std::string debug_info;
663
664 // The error message from the failed operation.
Victor Costancfbfa602018-08-01 23:24:46665 base::StringAppendF(&debug_info, "db error: %d/%s\n", GetErrorCode(),
666 GetErrorMessage());
shessc8cd2a162015-10-22 20:30:46667
668 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
669 // reading code does not entirely convince me. Remove if they turn out to be
670 // the same.
671 if (error != GetErrorCode())
672 base::StringAppendF(&debug_info, "reported error: %d\n", error);
673
Victor Costancfbfa602018-08-01 23:24:46674// System error information. Interpretation of Windows errors is different
675// from posix.
shessc8cd2a162015-10-22 20:30:46676#if defined(OS_WIN)
677 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18678#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46679 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
680#else
681 NOTREACHED(); // Add appropriate log info.
682#endif
683
684 if (stmt) {
685 base::StringAppendF(&debug_info, "statement: %s\n",
686 stmt->GetSQLStatement());
687 } else {
688 base::StringAppendF(&debug_info, "statement: NULL\n");
689 }
690
691 // SQLITE_ERROR often indicates some sort of mismatch between the statement
692 // and the schema, possibly due to a failed schema migration.
693 if (error == SQLITE_ERROR) {
694 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
695 sqlite3_stmt* s;
696 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
697 if (rc == SQLITE_OK) {
698 rc = sqlite3_step(s);
699 if (rc == SQLITE_ROW) {
700 base::StringAppendF(&debug_info, "version: %d\n",
701 sqlite3_column_int(s, 0));
702 } else if (rc == SQLITE_DONE) {
703 debug_info += "version: none\n";
704 } else {
705 base::StringAppendF(&debug_info, "version: error %d\n", rc);
706 }
707 sqlite3_finalize(s);
708 } else {
709 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
710 }
711
712 debug_info += "schema:\n";
713
714 // sqlite_master has columns:
715 // type - "index" or "table".
716 // name - name of created element.
717 // tbl_name - name of element, or target table in case of index.
718 // rootpage - root page of the element in database file.
719 // sql - SQL to create the element.
720 // In general, the |sql| column is sufficient to derive the other columns.
721 // |rootpage| is not interesting for debugging, without the contents of the
722 // database. The COALESCE is because certain automatic elements will have a
723 // |name| but no |sql|,
724 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
725 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
726 if (rc == SQLITE_OK) {
727 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
728 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
729 }
730 if (rc != SQLITE_DONE)
731 base::StringAppendF(&debug_info, "error %d\n", rc);
732 sqlite3_finalize(s);
733 } else {
734 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
735 }
736 }
737
738 return debug_info;
739}
740
741// TODO(shess): Since this is only called in an error situation, it might be
742// prudent to rewrite in terms of SQLite API calls, and mark the function const.
Victor Costancfbfa602018-08-01 23:24:46743std::string Database::CollectCorruptionInfo() {
shessc8cd2a162015-10-22 20:30:46744 AssertIOAllowed();
745
746 // If the file cannot be accessed it is unlikely that an integrity check will
747 // turn up actionable information.
748 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19749 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46750 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
751 return std::string();
752
753 // Buffer for accumulating debugging info about the error. Place
754 // more-relevant information earlier, in case things overflow the
755 // fixed-size reporting buffer.
756 std::string debug_info;
757 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
758 db_size);
759
760 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19761 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46762 if (db_size > kMaxIntegrityCheckSize) {
763 debug_info += "integrity_check skipped due to size\n";
764 } else {
765 std::vector<std::string> messages;
766
767 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
768 // into a string. Probably should be refactored.
769 const base::TimeTicks before = base::TimeTicks::Now();
770 FullIntegrityCheck(&messages);
771 base::StringAppendF(
Victor Costancfbfa602018-08-01 23:24:46772 &debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
773 (base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
shessc8cd2a162015-10-22 20:30:46774
775 // SQLite returns up to 100 messages by default, trim deeper to
776 // keep close to the 2000-character size limit for dumping.
777 const size_t kMaxMessages = 20;
778 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
779 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
780 }
781 }
782
783 return debug_info;
784}
785
Victor Costancfbfa602018-08-01 23:24:46786bool Database::GetMmapAltStatus(int64_t* status) {
shessa62504d2016-11-07 19:26:12787 // The [meta] version uses a missing table as a signal for a fresh database.
788 // That will not work for the view, which would not exist in either a new or
789 // an existing database. A new database _should_ be only one page long, so
790 // just don't bother optimizing this case (start at offset 0).
791 // TODO(shess): Could the [meta] case also get simpler, then?
792 if (!DoesViewExist("MmapStatus")) {
793 *status = 0;
794 return true;
795 }
796
797 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
798 Statement s(GetUniqueStatement(kMmapStatusSql));
799 if (s.Step())
800 *status = s.ColumnInt64(0);
801 return s.Succeeded();
802}
803
Victor Costancfbfa602018-08-01 23:24:46804bool Database::SetMmapAltStatus(int64_t status) {
shessa62504d2016-11-07 19:26:12805 if (!BeginTransaction())
806 return false;
807
808 // View may not exist on first run.
809 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
810 RollbackTransaction();
811 return false;
812 }
813
814 // Views live in the schema, so they cannot be parameterized. For an integer
815 // value, this construct should be safe from SQL injection, if the value
816 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
817 // value.
Victor Costancfbfa602018-08-01 23:24:46818 const std::string create_view_sql = base::StringPrintf(
819 "CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
820 if (!Execute(create_view_sql.c_str())) {
shessa62504d2016-11-07 19:26:12821 RollbackTransaction();
822 return false;
823 }
824
825 return CommitTransaction();
826}
827
Victor Costancfbfa602018-08-01 23:24:46828size_t Database::GetAppropriateMmapSize() {
shessd90aeea82015-11-13 02:24:31829 AssertIOAllowed();
830
shess9bf2c672015-12-18 01:18:08831 // How much to map if no errors are found. 50MB encompasses the 99th
832 // percentile of Chrome databases in the wild, so this should be good.
833 const size_t kMmapEverything = 256 * 1024 * 1024;
834
shessa62504d2016-11-07 19:26:12835 // Progress information is tracked in the [meta] table for databases which use
836 // sql::MetaTable, otherwise it is tracked in a special view.
837 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08838 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12839 if (mmap_alt_status_) {
840 if (!GetMmapAltStatus(&mmap_ofs)) {
841 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
842 return 0;
843 }
844 } else {
845 // If [meta] doesn't exist, yet, it's a new database, assume the best.
846 // sql::MetaTable::Init() will preload kMmapSuccess.
847 if (!MetaTable::DoesTableExist(this)) {
848 RecordOneEvent(EVENT_MMAP_META_MISSING);
849 return kMmapEverything;
850 }
851
852 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
853 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
854 return 0;
855 }
shessd90aeea82015-11-13 02:24:31856 }
857
858 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08859 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31860 RecordOneEvent(EVENT_MMAP_FAILED);
861 return 0;
shess9bf2c672015-12-18 01:18:08862 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31863 // Continue reading from previous offset.
864 DCHECK_GE(mmap_ofs, 0);
865
866 // TODO(shess): Could this reading code be shared with Preload()? It would
867 // require locking twice (this code wouldn't be able to access |db_size| so
868 // the helper would have to return amount read).
869
870 // Read more of the database looking for errors. The VFS interface is used
871 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
872 // to limit checking to 20MB per run of Chromium.
Victor Costanbd623112018-07-18 04:17:27873 sqlite3_file* file = nullptr;
shessd90aeea82015-11-13 02:24:31874 sqlite3_int64 db_size = 0;
875 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
876 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
877 return 0;
878 }
879
880 // Read the data left, or |g_reads_allowed|, whichever is smaller.
881 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
882 // in a single Chromium run.
883 sqlite3_int64 amount = db_size - mmap_ofs;
884 if (amount < 0)
885 amount = 0;
886 if (amount > 0) {
Victor Costan3653df62018-02-08 21:38:16887 static base::NoDestructor<base::Lock> lock;
888 base::AutoLock auto_lock(*lock);
shessd90aeea82015-11-13 02:24:31889 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
890 if (g_reads_allowed < amount)
891 amount = g_reads_allowed;
892 g_reads_allowed -= amount;
893 }
894
895 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
896 // database was truncated after a previous pass.
897 if (amount <= 0 && mmap_ofs < db_size) {
898 DCHECK_EQ(0, amount);
899 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
900 } else {
901 static const int kPageSize = 4096;
902 char buf[kPageSize];
903 while (amount > 0) {
904 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
905 if (rc == SQLITE_OK) {
906 mmap_ofs += sizeof(buf);
907 amount -= sizeof(buf);
908 } else if (rc == SQLITE_IOERR_SHORT_READ) {
909 // Reached EOF for a database with page size < |kPageSize|.
910 mmap_ofs = db_size;
911 break;
912 } else {
913 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08914 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31915 break;
916 }
917 }
918
919 // Log these events after update to distinguish meta update failure.
920 Events event;
921 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08922 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31923 event = EVENT_MMAP_SUCCESS_NEW;
924 } else if (mmap_ofs > 0) {
925 event = EVENT_MMAP_SUCCESS_PARTIAL;
926 } else {
shess9bf2c672015-12-18 01:18:08927 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31928 event = EVENT_MMAP_FAILED_NEW;
929 }
930
shessa62504d2016-11-07 19:26:12931 if (mmap_alt_status_) {
932 if (!SetMmapAltStatus(mmap_ofs)) {
933 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
934 return 0;
935 }
936 } else {
937 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
938 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
939 return 0;
940 }
shessd90aeea82015-11-13 02:24:31941 }
942
943 RecordOneEvent(event);
944 }
945 }
946
shess9bf2c672015-12-18 01:18:08947 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31948 return 0;
shess9bf2c672015-12-18 01:18:08949 if (mmap_ofs == MetaTable::kMmapSuccess)
950 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31951 return mmap_ofs;
952}
953
Victor Costancfbfa602018-08-01 23:24:46954void Database::TrimMemory(bool aggressively) {
[email protected]be7995f12013-07-18 18:49:14955 if (!db_)
956 return;
957
958 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
959 int original_cache_size;
960 {
961 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
962 if (!sql_get_original.Step()) {
963 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
964 return;
965 }
966 original_cache_size = sql_get_original.ColumnInt(0);
967 }
968 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
969
970 // Force sqlite to try to reduce page cache usage.
971 const std::string sql_shrink =
972 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
973 if (!Execute(sql_shrink.c_str()))
974 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
975
976 // Restore cache size.
977 const std::string sql_restore =
978 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
979 if (!Execute(sql_restore.c_str()))
980 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
981}
982
[email protected]8e0c01282012-04-06 19:36:49983// Create an in-memory database with the existing database's page
984// size, then backup that database over the existing database.
Victor Costancfbfa602018-08-01 23:24:46985bool Database::Raze() {
[email protected]35f7e5392012-07-27 19:54:50986 AssertIOAllowed();
987
[email protected]8e0c01282012-04-06 19:36:49988 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52989 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49990 return false;
991 }
992
993 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52994 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:49995 return false;
996 }
997
Victor Costancfbfa602018-08-01 23:24:46998 sql::Database null_db;
[email protected]8e0c01282012-04-06 19:36:49999 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521000 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:491001 return false;
1002 }
1003
Victor Costan7f6abbbe2018-07-29 02:57:271004 const std::string sql = base::StringPrintf("PRAGMA page_size=%d", page_size_);
1005 if (!null_db.Execute(sql.c_str()))
1006 return false;
[email protected]69c58452012-08-06 19:22:421007
[email protected]6d42f152012-11-10 00:38:241008#if defined(OS_ANDROID)
1009 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1010 // in-memory databases do not respect this define.
1011 // TODO(shess): Figure out a way to set this without using platform
1012 // specific code. AFAICT from sqlite3.c, the only way to do it
1013 // would be to create an actual filesystem database, which is
1014 // unfortunate.
1015 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1016 return false;
1017#endif
[email protected]8e0c01282012-04-06 19:36:491018
1019 // The page size doesn't take effect until a database has pages, and
1020 // at this point the null database has none. Changing the schema
1021 // version will create the first page. This will not affect the
1022 // schema version in the resulting database, as SQLite's backup
1023 // implementation propagates the schema version from the original
Victor Costancfbfa602018-08-01 23:24:461024 // database to the new version of the database, incremented by one
[email protected]8e0c01282012-04-06 19:36:491025 // so that other readers see the schema change and act accordingly.
1026 if (!null_db.Execute("PRAGMA schema_version = 1"))
1027 return false;
1028
[email protected]6d42f152012-11-10 00:38:241029 // SQLite tracks the expected number of database pages in the first
1030 // page, and if it does not match the total retrieved from a
1031 // filesystem call, treats the database as corrupt. This situation
1032 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1033 // used to hint to SQLite to soldier on in that case, specifically
1034 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1035 // sqlite3.c lockBtree().]
1036 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1037 // page_size" can be used to query such a database.
1038 ScopedWritableSchema writable_schema(db_);
1039
shess92a6fb22017-04-23 04:33:301040#if defined(OS_WIN)
1041 // On Windows, truncate silently fails when applied to memory-mapped files.
1042 // Disable memory-mapping so that the truncate succeeds. Note that other
Victor Costancfbfa602018-08-01 23:24:461043 // Database connections may have memory-mapped the file, so this may not
1044 // entirely prevent the problem.
shess92a6fb22017-04-23 04:33:301045 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1046 ignore_result(Execute("PRAGMA mmap_size = 0"));
1047#endif
1048
[email protected]7bae5742013-07-10 20:46:161049 const char* kMain = "main";
1050 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181051 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:491052
1053 // The destination database was locked.
1054 if (rc == SQLITE_BUSY) {
1055 return false;
1056 }
1057
[email protected]7bae5742013-07-10 20:46:161058 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1059 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1060 // isn't even big enough for one page. Either way, reach in and
1061 // truncate it before trying again.
1062 // TODO(shess): Maybe it would be worthwhile to just truncate from
1063 // the get-go?
1064 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
Victor Costanbd623112018-07-18 04:17:271065 sqlite3_file* file = nullptr;
[email protected]8ada10f2013-12-21 00:42:341066 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161067 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521068 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:161069 return false;
[email protected]7bae5742013-07-10 20:46:161070 }
1071
1072 rc = file->pMethods->xTruncate(file, 0);
1073 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181074 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521075 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:161076 return false;
1077 }
1078
1079 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181080 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:161081
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521082 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:161083 }
1084
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521085 // TODO(shess): Figure out which other cases can happen.
1086 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
1087
[email protected]8e0c01282012-04-06 19:36:491088 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521089 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:491090}
1091
Victor Costancfbfa602018-08-01 23:24:461092bool Database::RazeAndClose() {
[email protected]41a97c812013-02-07 02:35:381093 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521094 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:381095 return false;
1096 }
1097
1098 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301099 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381100
1101 bool result = Raze();
1102
1103 CloseInternal(true);
1104
1105 // Mark the database so that future API calls fail appropriately,
1106 // but don't DCHECK (because after calling this function they are
1107 // expected to fail).
1108 poisoned_ = true;
1109
1110 return result;
1111}
1112
Victor Costancfbfa602018-08-01 23:24:461113void Database::Poison() {
[email protected]8d409412013-07-19 18:25:301114 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521115 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:301116 return;
1117 }
1118
1119 RollbackAllTransactions();
1120 CloseInternal(true);
1121
1122 // Mark the database so that future API calls fail appropriately,
1123 // but don't DCHECK (because after calling this function they are
1124 // expected to fail).
1125 poisoned_ = true;
1126}
1127
[email protected]8d2e39e2013-06-24 05:55:081128// TODO(shess): To the extent possible, figure out the optimal
Victor Costancfbfa602018-08-01 23:24:461129// ordering for these deletes which will prevent other Database connections
[email protected]8d2e39e2013-06-24 05:55:081130// from seeing odd behavior. For instance, it may be necessary to
1131// manually lock the main database file in a SQLite-compatible fashion
1132// (to prevent other processes from opening it), then delete the
1133// journal files, then delete the main database file. Another option
1134// might be to lock the main database file and poison the header with
1135// junk to prevent other processes from opening it successfully (like
1136// Gears "SQLite poison 3" trick).
1137//
1138// static
Victor Costancfbfa602018-08-01 23:24:461139bool Database::Delete(const base::FilePath& path) {
Francois Doray66bdfd82017-10-20 13:50:371140 base::AssertBlockingAllowed();
[email protected]8d2e39e2013-06-24 05:55:081141
Victor Costancfbfa602018-08-01 23:24:461142 base::FilePath journal_path = Database::JournalPath(path);
1143 base::FilePath wal_path = Database::WriteAheadLogPath(path);
[email protected]8d2e39e2013-06-24 05:55:081144
erg102ceb412015-06-20 01:38:131145 std::string journal_str = AsUTF8ForSQL(journal_path);
1146 std::string wal_str = AsUTF8ForSQL(wal_path);
1147 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081148
Victor Costan3653df62018-02-08 21:38:161149 EnsureSqliteInitialized();
shess702467622015-09-16 19:04:551150
Victor Costanbd623112018-07-18 04:17:271151 sqlite3_vfs* vfs = sqlite3_vfs_find(nullptr);
erg102ceb412015-06-20 01:38:131152 CHECK(vfs);
1153 CHECK(vfs->xDelete);
1154 CHECK(vfs->xAccess);
1155
1156 // We only work with unix, win32 and mojo filesystems. If you're trying to
1157 // use this code with any other VFS, you're not in a good place.
1158 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1159 strncmp(vfs->zName, "win32", 5) == 0 ||
1160 strcmp(vfs->zName, "mojo") == 0);
1161
1162 vfs->xDelete(vfs, journal_str.c_str(), 0);
1163 vfs->xDelete(vfs, wal_str.c_str(), 0);
1164 vfs->xDelete(vfs, path_str.c_str(), 0);
1165
1166 int journal_exists = 0;
Victor Costance678e72018-07-24 10:25:001167 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS, &journal_exists);
erg102ceb412015-06-20 01:38:131168
1169 int wal_exists = 0;
Victor Costance678e72018-07-24 10:25:001170 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS, &wal_exists);
erg102ceb412015-06-20 01:38:131171
1172 int path_exists = 0;
Victor Costance678e72018-07-24 10:25:001173 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS, &path_exists);
erg102ceb412015-06-20 01:38:131174
1175 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081176}
1177
Victor Costancfbfa602018-08-01 23:24:461178bool Database::BeginTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561179 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331180 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561181
1182 // When we're going to rollback, fail on this begin and don't actually
1183 // mark us as entering the nested transaction.
1184 return false;
1185 }
1186
1187 bool success = true;
1188 if (!transaction_nesting_) {
1189 needs_rollback_ = false;
1190
1191 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321192 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591193 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561194 return false;
1195 }
1196 transaction_nesting_++;
1197 return success;
1198}
1199
Victor Costancfbfa602018-08-01 23:24:461200void Database::RollbackTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561201 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521202 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561203 return;
1204 }
1205
1206 transaction_nesting_--;
1207
1208 if (transaction_nesting_ > 0) {
1209 // Mark the outermost transaction as needing rollback.
1210 needs_rollback_ = true;
1211 return;
1212 }
1213
1214 DoRollback();
1215}
1216
Victor Costancfbfa602018-08-01 23:24:461217bool Database::CommitTransaction() {
[email protected]e5ffd0e42009-09-11 21:30:561218 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521219 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561220 return false;
1221 }
1222 transaction_nesting_--;
1223
1224 if (transaction_nesting_ > 0) {
1225 // Mark any nested transactions as failing after we've already got one.
1226 return !needs_rollback_;
1227 }
1228
1229 if (needs_rollback_) {
1230 DoRollback();
1231 return false;
1232 }
1233
1234 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321235
1236 // Collect the commit time manually, sql::Statement would register it as query
1237 // time only.
Victor Costan87cf8c72018-07-19 19:36:041238 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321239 bool ret = commit.RunWithoutTimers();
Victor Costan87cf8c72018-07-19 19:36:041240 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321241
1242 RecordCommitTime(delta);
1243 RecordOneEvent(EVENT_COMMIT);
1244
shess7dbd4dee2015-10-06 17:39:161245 // Release dirty cache pages after the transaction closes.
1246 ReleaseCacheMemoryIfNeeded(false);
1247
shess58b8df82015-06-03 00:19:321248 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561249}
1250
Victor Costancfbfa602018-08-01 23:24:461251void Database::RollbackAllTransactions() {
[email protected]8d409412013-07-19 18:25:301252 if (transaction_nesting_ > 0) {
1253 transaction_nesting_ = 0;
1254 DoRollback();
1255 }
1256}
1257
Victor Costancfbfa602018-08-01 23:24:461258bool Database::AttachDatabase(const base::FilePath& other_db_path,
1259 const char* attachment_point,
1260 InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301261 DCHECK(ValidAttachmentPoint(attachment_point));
1262
1263 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1264#if OS_WIN
1265 s.BindString16(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181266#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberibd1301f2018-05-18 21:00:091267 s.BindString(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181268#else
1269#error Unsupported platform
[email protected]8d409412013-07-19 18:25:301270#endif
1271 s.BindString(1, attachment_point);
1272 return s.Run();
1273}
1274
Victor Costancfbfa602018-08-01 23:24:461275bool Database::DetachDatabase(const char* attachment_point, InternalApiToken) {
[email protected]8d409412013-07-19 18:25:301276 DCHECK(ValidAttachmentPoint(attachment_point));
1277
1278 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1279 s.BindString(0, attachment_point);
1280 return s.Run();
1281}
1282
shess58b8df82015-06-03 00:19:321283// TODO(shess): Consider changing this to execute exactly one statement. If a
1284// caller wishes to execute multiple statements, that should be explicit, and
1285// perhaps tucked into an explicit transaction with rollback in case of error.
Victor Costancfbfa602018-08-01 23:24:461286int Database::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501287 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381288 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461289 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381290 return SQLITE_ERROR;
1291 }
shess58b8df82015-06-03 00:19:321292 DCHECK(sql);
1293
1294 RecordOneEvent(EVENT_EXECUTE);
1295 int rc = SQLITE_OK;
1296 while ((rc == SQLITE_OK) && *sql) {
Victor Costanbd623112018-07-18 04:17:271297 sqlite3_stmt* stmt = nullptr;
Victor Costancfbfa602018-08-01 23:24:461298 const char* leftover_sql;
shess58b8df82015-06-03 00:19:321299
Victor Costan87cf8c72018-07-19 19:36:041300 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321301 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1302 sql = leftover_sql;
1303
1304 // Stop if an error is encountered.
1305 if (rc != SQLITE_OK)
1306 break;
1307
1308 // This happens if |sql| originally only contained comments or whitespace.
1309 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1310 // extraneous comments and whitespace in the SQL statements increases
1311 // runtime cost and can easily be shifted out to the C++ layer.
1312 if (!stmt)
1313 continue;
1314
1315 // Save for use after statement is finalized.
1316 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1317
Victor Costancfbfa602018-08-01 23:24:461318 RecordOneEvent(Database::EVENT_STATEMENT_RUN);
shess58b8df82015-06-03 00:19:321319 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1320 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1321 // is the only legitimate case for this.
Victor Costancfbfa602018-08-01 23:24:461322 RecordOneEvent(Database::EVENT_STATEMENT_ROWS);
shess58b8df82015-06-03 00:19:321323 }
1324
1325 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1326 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1327 rc = sqlite3_finalize(stmt);
1328 if (rc == SQLITE_OK)
Victor Costancfbfa602018-08-01 23:24:461329 RecordOneEvent(Database::EVENT_STATEMENT_SUCCESS);
shess58b8df82015-06-03 00:19:321330
1331 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1332 // trailing whitespace.
1333 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021334 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321335 sql++;
1336 }
1337
Victor Costan87cf8c72018-07-19 19:36:041338 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321339 RecordTimeAndChanges(delta, read_only);
1340 }
shess7dbd4dee2015-10-06 17:39:161341
1342 // Most calls to Execute() modify the database. The main exceptions would be
1343 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1344 // but sometimes don't.
1345 ReleaseCacheMemoryIfNeeded(true);
1346
shess58b8df82015-06-03 00:19:321347 return rc;
[email protected]eff1fa522011-12-12 23:50:591348}
1349
Victor Costancfbfa602018-08-01 23:24:461350bool Database::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381351 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461352 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381353 return false;
1354 }
1355
[email protected]eff1fa522011-12-12 23:50:591356 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001357 if (error != SQLITE_OK)
Victor Costanbd623112018-07-18 04:17:271358 error = OnSqliteError(error, nullptr, sql);
[email protected]473ad792012-11-10 00:55:001359
[email protected]28fe0ff2012-02-25 00:40:331360 // This needs to be a FATAL log because the error case of arriving here is
1361 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101362 // a change alters the schema but not all queries adjust. This can happen
1363 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521364 DCHECK_NE(error, SQLITE_ERROR)
1365 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591366 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561367}
1368
Victor Costancfbfa602018-08-01 23:24:461369bool Database::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381370 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461371 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]5b96f3772010-09-28 16:30:571372 return false;
[email protected]41a97c812013-02-07 02:35:381373 }
[email protected]5b96f3772010-09-28 16:30:571374
1375 ScopedBusyTimeout busy_timeout(db_);
1376 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591377 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571378}
1379
Victor Costancfbfa602018-08-01 23:24:461380scoped_refptr<Database::StatementRef> Database::GetCachedStatement(
Victor Costan12daa3ac92018-07-19 01:05:581381 StatementID id,
[email protected]e5ffd0e42009-09-11 21:30:561382 const char* sql) {
Victor Costanc7e7f2e2018-07-18 20:07:551383 auto it = statement_cache_.find(id);
1384 if (it != statement_cache_.end()) {
Victor Costan87cf8c72018-07-19 19:36:041385 // Statement is in the cache. It should still be active. We're the only
1386 // one invalidating cached statements, and we remove them from the cache
1387 // when we do that.
Victor Costanc7e7f2e2018-07-18 20:07:551388 DCHECK(it->second->is_valid());
Victor Costan87cf8c72018-07-19 19:36:041389
1390 DCHECK_EQ(std::string(sql), std::string(sqlite3_sql(it->second->stmt())))
1391 << "GetCachedStatement used with same ID but different SQL";
1392
1393 // Reset the statement so it can be reused.
Victor Costanc7e7f2e2018-07-18 20:07:551394 sqlite3_reset(it->second->stmt());
1395 return it->second;
[email protected]e5ffd0e42009-09-11 21:30:561396 }
1397
1398 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1399 if (statement->is_valid())
1400 statement_cache_[id] = statement; // Only cache valid statements.
1401 return statement;
1402}
1403
Victor Costancfbfa602018-08-01 23:24:461404scoped_refptr<Database::StatementRef> Database::GetUniqueStatement(
[email protected]e5ffd0e42009-09-11 21:30:561405 const char* sql) {
shess9e77283d2016-06-13 23:53:201406 return GetStatementImpl(this, sql);
1407}
1408
Victor Costancfbfa602018-08-01 23:24:461409scoped_refptr<Database::StatementRef> Database::GetStatementImpl(
1410 sql::Database* tracking_db,
1411 const char* sql) const {
[email protected]35f7e5392012-07-27 19:54:501412 AssertIOAllowed();
shess9e77283d2016-06-13 23:53:201413 DCHECK(sql);
Victor Costan87cf8c72018-07-19 19:36:041414 DCHECK(!tracking_db || tracking_db == this);
[email protected]35f7e5392012-07-27 19:54:501415
[email protected]41a97c812013-02-07 02:35:381416 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561417 if (!db_)
Victor Costan3b02cdf2018-07-18 00:39:561418 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561419
Victor Costanbd623112018-07-18 04:17:271420 sqlite3_stmt* stmt = nullptr;
1421 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
[email protected]473ad792012-11-10 00:55:001422 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591423 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521424 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001425
1426 // It could also be database corruption.
Victor Costanbd623112018-07-18 04:17:271427 OnSqliteError(rc, nullptr, sql);
Victor Costan3b02cdf2018-07-18 00:39:561428 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
[email protected]e5ffd0e42009-09-11 21:30:561429 }
Victor Costan3b02cdf2018-07-18 00:39:561430 return base::MakeRefCounted<StatementRef>(tracking_db, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561431}
1432
Victor Costancfbfa602018-08-01 23:24:461433scoped_refptr<Database::StatementRef> Database::GetUntrackedStatement(
[email protected]2eec0a22012-07-24 01:59:581434 const char* sql) const {
Victor Costanbd623112018-07-18 04:17:271435 return GetStatementImpl(nullptr, sql);
[email protected]2eec0a22012-07-24 01:59:581436}
1437
Victor Costancfbfa602018-08-01 23:24:461438std::string Database::GetSchema() const {
[email protected]92cd00a2013-08-16 11:09:581439 // The ORDER BY should not be necessary, but relying on organic
1440 // order for something like this is questionable.
Victor Costan87cf8c72018-07-19 19:36:041441 static const char kSql[] =
[email protected]92cd00a2013-08-16 11:09:581442 "SELECT type, name, tbl_name, sql "
1443 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1444 Statement statement(GetUntrackedStatement(kSql));
1445
1446 std::string schema;
1447 while (statement.Step()) {
1448 schema += statement.ColumnString(0);
1449 schema += '|';
1450 schema += statement.ColumnString(1);
1451 schema += '|';
1452 schema += statement.ColumnString(2);
1453 schema += '|';
1454 schema += statement.ColumnString(3);
1455 schema += '\n';
1456 }
1457
1458 return schema;
1459}
1460
Victor Costancfbfa602018-08-01 23:24:461461bool Database::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501462 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381463 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461464 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]41a97c812013-02-07 02:35:381465 return false;
1466 }
1467
Victor Costanbd623112018-07-18 04:17:271468 sqlite3_stmt* stmt = nullptr;
1469 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK)
[email protected]eff1fa522011-12-12 23:50:591470 return false;
1471
1472 sqlite3_finalize(stmt);
1473 return true;
1474}
1475
Victor Costancfbfa602018-08-01 23:24:461476bool Database::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121477 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531478}
1479
Victor Costancfbfa602018-08-01 23:24:461480bool Database::DoesTableExist(const char* table_name) const {
shessa62504d2016-11-07 19:26:121481 return DoesSchemaItemExist(table_name, "table");
1482}
1483
Victor Costancfbfa602018-08-01 23:24:461484bool Database::DoesViewExist(const char* view_name) const {
shessa62504d2016-11-07 19:26:121485 return DoesSchemaItemExist(view_name, "view");
1486}
1487
Victor Costancfbfa602018-08-01 23:24:461488bool Database::DoesSchemaItemExist(const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471489 const char* kSql =
1490 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581491 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471492
shess976814402016-06-21 06:56:251493 // This can happen if the database is corrupt and the error is a test
1494 // expectation.
shess92a2ab12015-04-09 01:59:471495 if (!statement.is_valid())
1496 return false;
1497
[email protected]e2cadec82011-12-13 02:00:531498 statement.BindString(0, type);
1499 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331500
[email protected]e5ffd0e42009-09-11 21:30:561501 return statement.Step(); // Table exists if any row was returned.
1502}
1503
Victor Costancfbfa602018-08-01 23:24:461504bool Database::DoesColumnExist(const char* table_name,
1505 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561506 std::string sql("PRAGMA TABLE_INFO(");
1507 sql.append(table_name);
1508 sql.append(")");
1509
[email protected]2eec0a22012-07-24 01:59:581510 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471511
shess976814402016-06-21 06:56:251512 // This can happen if the database is corrupt and the error is a test
1513 // expectation.
shess92a2ab12015-04-09 01:59:471514 if (!statement.is_valid())
1515 return false;
1516
[email protected]e5ffd0e42009-09-11 21:30:561517 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331518 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1519 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561520 return true;
1521 }
1522 return false;
1523}
1524
Victor Costancfbfa602018-08-01 23:24:461525int64_t Database::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561526 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461527 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]e5ffd0e42009-09-11 21:30:561528 return 0;
1529 }
1530 return sqlite3_last_insert_rowid(db_);
1531}
1532
Victor Costancfbfa602018-08-01 23:24:461533int Database::GetLastChangeCount() const {
[email protected]1ed78a32009-09-15 20:24:171534 if (!db_) {
Victor Costancfbfa602018-08-01 23:24:461535 DCHECK(poisoned_) << "Illegal use of Database without a db";
[email protected]1ed78a32009-09-15 20:24:171536 return 0;
1537 }
1538 return sqlite3_changes(db_);
1539}
1540
Victor Costancfbfa602018-08-01 23:24:461541int Database::GetErrorCode() const {
[email protected]e5ffd0e42009-09-11 21:30:561542 if (!db_)
1543 return SQLITE_ERROR;
1544 return sqlite3_errcode(db_);
1545}
1546
Victor Costancfbfa602018-08-01 23:24:461547int Database::GetLastErrno() const {
[email protected]767718e52010-09-21 23:18:491548 if (!db_)
1549 return -1;
1550
1551 int err = 0;
Victor Costanbd623112018-07-18 04:17:271552 if (SQLITE_OK != sqlite3_file_control(db_, nullptr, SQLITE_LAST_ERRNO, &err))
[email protected]767718e52010-09-21 23:18:491553 return -2;
1554
1555 return err;
1556}
1557
Victor Costancfbfa602018-08-01 23:24:461558const char* Database::GetErrorMessage() const {
[email protected]e5ffd0e42009-09-11 21:30:561559 if (!db_)
Victor Costancfbfa602018-08-01 23:24:461560 return "sql::Database is not opened.";
[email protected]e5ffd0e42009-09-11 21:30:561561 return sqlite3_errmsg(db_);
1562}
1563
Victor Costancfbfa602018-08-01 23:24:461564bool Database::OpenInternal(const std::string& file_name,
1565 Database::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501566 AssertIOAllowed();
1567
[email protected]9cfbc922009-11-17 20:13:171568 if (db_) {
Victor Costancfbfa602018-08-01 23:24:461569 DLOG(DCHECK) << "sql::Database is already open.";
[email protected]9cfbc922009-11-17 20:13:171570 return false;
1571 }
1572
Victor Costan3653df62018-02-08 21:38:161573 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181574
shess58b8df82015-06-03 00:19:321575 // Setup the stats histograms immediately rather than allocating lazily.
Victor Costancfbfa602018-08-01 23:24:461576 // Databases which won't exercise all of these probably shouldn't exist.
shess58b8df82015-06-03 00:19:321577 if (!histogram_tag_.empty()) {
Victor Costancfbfa602018-08-01 23:24:461578 stats_histogram_ = base::LinearHistogram::FactoryGet(
1579 "Sqlite.Stats." + histogram_tag_, 1, EVENT_MAX_VALUE,
1580 EVENT_MAX_VALUE + 1, base::HistogramBase::kUmaTargetedHistogramFlag);
shess58b8df82015-06-03 00:19:321581
1582 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1583 // unreasonable time for any single operation, so there is not much value to
1584 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1585 // things are entirely busted.
1586 commit_time_histogram_ =
1587 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1588
1589 autocommit_time_histogram_ =
1590 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1591
1592 update_time_histogram_ =
1593 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1594
1595 query_time_histogram_ =
1596 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1597 }
1598
[email protected]41a97c812013-02-07 02:35:381599 // If |poisoned_| is set, it means an error handler called
1600 // RazeAndClose(). Until regular Close() is called, the caller
1601 // should be treating the database as open, but is_open() currently
1602 // only considers the sqlite3 handle's state.
1603 // TODO(shess): Revise is_open() to consider poisoned_, and review
1604 // to see if any non-testing code even depends on it.
Victor Costancfbfa602018-08-01 23:24:461605 DCHECK(!poisoned_) << "sql::Database is already open.";
[email protected]7bae5742013-07-10 20:46:161606 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381607
shess5f2c3442017-01-24 02:15:101608 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1609 sqlite3_vfs* vfs = VFSWrapper();
1610 const char* vfs_name = (vfs ? vfs->zName : nullptr);
Victor Costancfbfa602018-08-01 23:24:461611 int err =
1612 sqlite3_open_v2(file_name.c_str(), &db_,
1613 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, vfs_name);
[email protected]765b44502009-10-02 05:01:421614 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281615 // Extended error codes cannot be enabled until a handle is
1616 // available, fetch manually.
1617 err = sqlite3_extended_errcode(db_);
1618
[email protected]bd2ccdb4a2012-12-07 22:14:501619 // Histogram failures specific to initial open for debugging
1620 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181621 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501622
Victor Costanbd623112018-07-18 04:17:271623 OnSqliteError(err, nullptr, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131624 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291625 Close();
[email protected]fed734a2013-07-17 04:45:131626
1627 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1628 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421629 return false;
1630 }
1631
[email protected]73fb8d52013-07-24 05:04:281632 // Enable extended result codes to provide more color on I/O errors.
1633 // Not having extended result codes is not a fatal problem, as
1634 // Chromium code does not attempt to handle I/O errors anyhow. The
1635 // current implementation always returns SQLITE_OK, the DCHECK is to
1636 // quickly notify someone if SQLite changes.
1637 err = sqlite3_extended_result_codes(db_, 1);
1638 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1639
shessbccd300e2016-08-20 00:06:561640 // sqlite3_open() does not actually read the database file (unless a hot
1641 // journal is found). Successfully executing this pragma on an existing
1642 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1643 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501644 // TODO(shess): For now, just probing to see what the lay of the
1645 // land is. If it's mostly SQLITE_NOTADB, then the database should
1646 // be razed.
1647 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561648 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181649 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561650 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1651
1652 // Retry or bail out if the error handler poisoned the handle.
1653 // TODO(shess): Move this handling to one place (see also sqlite3_open and
1654 // secure_delete). Possibly a wrapper function?
1655 if (poisoned_) {
1656 Close();
1657 if (retry_flag == RETRY_ON_POISON)
1658 return OpenInternal(file_name, NO_RETRY);
1659 return false;
1660 }
1661 }
[email protected]658f8332010-09-18 04:40:431662
[email protected]5b96f3772010-09-28 16:30:571663 // If indicated, lock up the database before doing anything else, so
1664 // that the following code doesn't have to deal with locking.
1665 // TODO(shess): This code is brittle. Find the cases where code
1666 // doesn't request |exclusive_locking_| and audit that it does the
1667 // right thing with SQLITE_BUSY, and that it doesn't make
1668 // assumptions about who might change things in the database.
1669 // http://crbug.com/56559
1670 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101671 // TODO(shess): This should probably be a failure. Code which
1672 // requests exclusive locking but doesn't get it is almost certain
1673 // to be ill-tested.
1674 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571675 }
1676
[email protected]4e179ba2012-03-17 16:06:471677 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1678 // DELETE (default) - delete -journal file to commit.
1679 // TRUNCATE - truncate -journal file to commit.
1680 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091681 // TRUNCATE should be faster than DELETE because it won't need directory
1682 // changes for each transaction. PERSIST may break the spirit of using
1683 // secure_delete.
1684 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471685
[email protected]c68ce172011-11-24 22:30:271686 const base::TimeDelta kBusyTimeout =
Victor Costancfbfa602018-08-01 23:24:461687 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
[email protected]c68ce172011-11-24 22:30:271688
Victor Costancfbfa602018-08-01 23:24:461689 const std::string page_size_sql =
1690 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1691 ignore_result(ExecuteWithTimeout(page_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421692
1693 if (cache_size_ != 0) {
Victor Costancfbfa602018-08-01 23:24:461694 const std::string cache_size_sql =
[email protected]7d3cbc92013-03-18 22:33:041695 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
Victor Costancfbfa602018-08-01 23:24:461696 ignore_result(ExecuteWithTimeout(cache_size_sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421697 }
1698
[email protected]6e0b1442011-08-09 23:23:581699 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131700 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581701 Close();
[email protected]fed734a2013-07-17 04:45:131702 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1703 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581704 return false;
1705 }
1706
shess5dac334f2015-11-05 20:47:421707 // Set a reasonable chunk size for larger files. This reduces churn from
1708 // remapping memory on size changes. It also reduces filesystem
1709 // fragmentation.
1710 // TODO(shess): It may make sense to have this be hinted by the client.
1711 // Database sizes seem to be bimodal, some clients have consistently small
1712 // databases (<20k) while other clients have a broad distribution of sizes
1713 // (hundreds of kilobytes to many megabytes).
Victor Costanbd623112018-07-18 04:17:271714 sqlite3_file* file = nullptr;
shess5dac334f2015-11-05 20:47:421715 sqlite3_int64 db_size = 0;
1716 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1717 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1718 int chunk_size = 4 * 1024;
1719 if (db_size > 128 * 1024)
1720 chunk_size = 32 * 1024;
Victor Costanbd623112018-07-18 04:17:271721 sqlite3_file_control(db_, nullptr, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
shess5dac334f2015-11-05 20:47:421722 }
1723
shess2f3a814b2015-11-05 18:11:101724 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311725 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1726 // safe range to memory-map based on past regular I/O. This value will be
1727 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1728 // 64-bit platforms.
1729 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1730 std::string mmap_sql =
1731 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1732 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101733
1734 // Determine if memory-mapping has actually been enabled. The Execute() above
1735 // can succeed without changing the amount mapped.
1736 mmap_enabled_ = false;
1737 {
1738 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1739 if (s.Step() && s.ColumnInt64(0) > 0)
1740 mmap_enabled_ = true;
1741 }
1742
ssid3be5b1ec2016-01-13 14:21:571743 DCHECK(!memory_dump_provider_);
1744 memory_dump_provider_.reset(
Victor Costancfbfa602018-08-01 23:24:461745 new DatabaseMemoryDumpProvider(db_, histogram_tag_));
ssid3be5b1ec2016-01-13 14:21:571746 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
Victor Costancfbfa602018-08-01 23:24:461747 memory_dump_provider_.get(), "sql::Database", nullptr);
ssid3be5b1ec2016-01-13 14:21:571748
[email protected]765b44502009-10-02 05:01:421749 return true;
1750}
1751
Victor Costancfbfa602018-08-01 23:24:461752void Database::DoRollback() {
[email protected]e5ffd0e42009-09-11 21:30:561753 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321754
1755 // Collect the rollback time manually, sql::Statement would register it as
1756 // query time only.
Victor Costan87cf8c72018-07-19 19:36:041757 const base::TimeTicks before = NowTicks();
shess58b8df82015-06-03 00:19:321758 rollback.RunWithoutTimers();
Victor Costan87cf8c72018-07-19 19:36:041759 const base::TimeDelta delta = NowTicks() - before;
shess58b8df82015-06-03 00:19:321760
1761 RecordUpdateTime(delta);
1762 RecordOneEvent(EVENT_ROLLBACK);
1763
shess7dbd4dee2015-10-06 17:39:161764 // The cache may have been accumulating dirty pages for commit. Note that in
1765 // some cases sql::Transaction can fire rollback after a database is closed.
1766 if (is_open())
1767 ReleaseCacheMemoryIfNeeded(false);
1768
[email protected]44ad7d902012-03-23 00:09:051769 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561770}
1771
Victor Costancfbfa602018-08-01 23:24:461772void Database::StatementRefCreated(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551773 DCHECK(!open_statements_.count(ref))
1774 << __func__ << " already called with this statement";
[email protected]e5ffd0e42009-09-11 21:30:561775 open_statements_.insert(ref);
1776}
1777
Victor Costancfbfa602018-08-01 23:24:461778void Database::StatementRefDeleted(StatementRef* ref) {
Victor Costanc7e7f2e2018-07-18 20:07:551779 DCHECK(open_statements_.count(ref))
1780 << __func__ << " called with non-existing statement";
1781 open_statements_.erase(ref);
[email protected]e5ffd0e42009-09-11 21:30:561782}
1783
Victor Costancfbfa602018-08-01 23:24:461784void Database::set_histogram_tag(const std::string& tag) {
shess58b8df82015-06-03 00:19:321785 DCHECK(!is_open());
Victor Costan87cf8c72018-07-19 19:36:041786
shess58b8df82015-06-03 00:19:321787 histogram_tag_ = tag;
1788}
1789
Victor Costancfbfa602018-08-01 23:24:461790void Database::AddTaggedHistogram(const std::string& name,
1791 size_t sample) const {
[email protected]210ce0af2013-05-15 09:10:391792 if (histogram_tag_.empty())
1793 return;
1794
1795 // TODO(shess): The histogram macros create a bit of static storage
1796 // for caching the histogram object. This code shouldn't execute
1797 // often enough for such caching to be crucial. If it becomes an
1798 // issue, the object could be cached alongside histogram_prefix_.
1799 std::string full_histogram_name = name + "." + histogram_tag_;
Victor Costancfbfa602018-08-01 23:24:461800 base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
1801 full_histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]210ce0af2013-05-15 09:10:391802 if (histogram)
1803 histogram->Add(sample);
1804}
1805
Victor Costancfbfa602018-08-01 23:24:461806int Database::OnSqliteError(int err,
1807 sql::Statement* stmt,
1808 const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181809 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391810 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141811
1812 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581813 if (!sql && stmt)
1814 sql = stmt->GetSQLStatement();
1815 if (!sql)
1816 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061817
1818 std::string id = histogram_tag_;
1819 if (id.empty())
1820 id = DbPath().BaseName().AsUTF8Unsafe();
Victor Costancfbfa602018-08-01 23:24:461821 LOG(ERROR) << id << " sqlite error " << err << ", errno " << GetLastErrno()
1822 << ": " << GetErrorMessage() << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141823
[email protected]c3881b372013-05-17 08:39:461824 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561825 // Fire from a copy of the callback in case of reentry into
1826 // re/set_error_callback().
1827 // TODO(shess): <http://crbug.com/254584>
1828 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461829 return err;
1830 }
1831
[email protected]faa604e2009-09-25 22:38:591832 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251833 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521834 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591835 return err;
1836}
1837
Victor Costancfbfa602018-08-01 23:24:461838bool Database::FullIntegrityCheck(std::vector<std::string>* messages) {
[email protected]579446c2013-12-16 18:36:521839 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1840}
1841
Victor Costancfbfa602018-08-01 23:24:461842bool Database::QuickIntegrityCheck() {
[email protected]579446c2013-12-16 18:36:521843 std::vector<std::string> messages;
1844 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1845 return false;
1846 return messages.size() == 1 && messages[0] == "ok";
1847}
1848
Victor Costancfbfa602018-08-01 23:24:461849std::string Database::GetDiagnosticInfo(int extended_error,
1850 Statement* statement) {
afakhry7c9abe72016-08-05 17:33:191851 // Prevent reentrant calls to the error callback.
1852 ErrorCallback original_callback = std::move(error_callback_);
1853 reset_error_callback();
1854
1855 // Trim extended error codes.
1856 const int error = (extended_error & 0xFF);
Victor Costancfbfa602018-08-01 23:24:461857 // CollectCorruptionInfo() is implemented in terms of sql::Database,
afakhry7c9abe72016-08-05 17:33:191858 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1859 std::string result = (error == SQLITE_CORRUPT)
1860 ? CollectCorruptionInfo()
1861 : CollectErrorInfo(extended_error, statement);
1862
1863 // The following queries must be executed after CollectErrorInfo() above, so
1864 // if they result in their own errors, they don't interfere with
1865 // CollectErrorInfo().
1866 const bool has_valid_header =
1867 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1868 const bool select_sqlite_master_result =
1869 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1870 SQLITE_OK);
1871
1872 // Restore the original error callback.
1873 error_callback_ = std::move(original_callback);
1874
1875 base::StringAppendF(&result, "Has valid header: %s\n",
1876 (has_valid_header ? "Yes" : "No"));
1877 base::StringAppendF(&result, "Has valid schema: %s\n",
1878 (select_sqlite_master_result ? "Yes" : "No"));
1879
1880 return result;
1881}
1882
[email protected]80abf152013-05-22 12:42:421883// TODO(shess): Allow specifying maximum results (default 100 lines).
Victor Costancfbfa602018-08-01 23:24:461884bool Database::IntegrityCheckHelper(const char* pragma_sql,
1885 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421886 messages->clear();
1887
[email protected]4658e2a02013-06-06 23:05:001888 // This has the side effect of setting SQLITE_RecoveryMode, which
1889 // allows SQLite to process through certain cases of corruption.
1890 // Failing to set this pragma probably means that the database is
1891 // beyond recovery.
Victor Costan1d868352018-06-26 19:06:481892 static const char kWritableSchemaSql[] = "PRAGMA writable_schema = ON";
1893 if (!Execute(kWritableSchemaSql))
[email protected]4658e2a02013-06-06 23:05:001894 return false;
1895
1896 bool ret = false;
1897 {
[email protected]579446c2013-12-16 18:36:521898 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001899
1900 // The pragma appears to return all results (up to 100 by default)
1901 // as a single string. This doesn't appear to be an API contract,
1902 // it could return separate lines, so loop _and_ split.
1903 while (stmt.Step()) {
1904 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181905 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1906 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001907 }
1908 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421909 }
[email protected]4658e2a02013-06-06 23:05:001910
1911 // Best effort to put things back as they were before.
Victor Costan1d868352018-06-26 19:06:481912 static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema = OFF";
1913 ignore_result(Execute(kNoWritableSchemaSql));
[email protected]4658e2a02013-06-06 23:05:001914
1915 return ret;
[email protected]80abf152013-05-22 12:42:421916}
1917
Victor Costancfbfa602018-08-01 23:24:461918bool Database::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1919 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131920 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381921 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131922}
1923
[email protected]e5ffd0e42009-09-11 21:30:561924} // namespace sql