blob: 25691db5f882942f1491f5ff87ead9690de9ff45 [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
[email protected]f0a54b22011-07-19 18:40:215#include "sql/connection.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
dchenge48600452015-12-28 02:24:5012#include <utility>
[email protected]e5ffd0e42009-09-11 21:30:5613
tzikb9dae932017-02-10 03:57:3014#include "base/debug/alias.h"
shessc8cd2a162015-10-22 20:30:4615#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5216#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4417#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4618#include "base/format_macros.h"
19#include "base/json/json_file_value_serializer.h"
fdoray2dfa76452016-06-07 13:11:2220#include "base/location.h"
[email protected]e5ffd0e42009-09-11 21:30:5621#include "base/logging.h"
Ilya Sherman1c811db2017-12-14 10:36:1822#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0823#include "base/metrics/histogram_macros.h"
[email protected]210ce0af2013-05-15 09:10:3924#include "base/metrics/sparse_histogram.h"
Victor Costan3653df62018-02-08 21:38:1625#include "base/no_destructor.h"
fdoray2dfa76452016-06-07 13:11:2226#include "base/single_thread_task_runner.h"
[email protected]80abf152013-05-22 12:42:4227#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1928#include "base/strings/string_util.h"
29#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4530#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1831#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0332#include "base/trace_event/memory_dump_manager.h"
Kevin Marshalla9f05ec2017-07-14 02:10:0533#include "build/build_config.h"
ssid3be5b1ec2016-01-13 14:21:5734#include "sql/connection_memory_dump_provider.h"
Victor Costan3653df62018-02-08 21:38:1635#include "sql/initialization.h"
shess9bf2c672015-12-18 01:18:0836#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2137#include "sql/statement.h"
shess5f2c3442017-01-24 02:15:1038#include "sql/vfs_wrapper.h"
[email protected]e33cba42010-08-18 23:37:0339#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5640
[email protected]2e1cee762013-07-09 14:40:0041#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
rohitrao83d6b83a2016-06-21 07:25:5742#include "base/ios/ios_util.h"
[email protected]2e1cee762013-07-09 14:40:0043#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
44#endif
45
[email protected]5b96f3772010-09-28 16:30:5746namespace {
47
48// Spin for up to a second waiting for the lock to clear when setting
49// up the database.
50// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2751const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5752
53class ScopedBusyTimeout {
54 public:
55 explicit ScopedBusyTimeout(sqlite3* db)
56 : db_(db) {
57 }
58 ~ScopedBusyTimeout() {
59 sqlite3_busy_timeout(db_, 0);
60 }
61
62 int SetTimeout(base::TimeDelta timeout) {
63 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
64 return sqlite3_busy_timeout(db_,
65 static_cast<int>(timeout.InMilliseconds()));
66 }
67
68 private:
69 sqlite3* db_;
70};
71
[email protected]6d42f152012-11-10 00:38:2472// Helper to "safely" enable writable_schema. No error checking
73// because it is reasonable to just forge ahead in case of an error.
74// If turning it on fails, then most likely nothing will work, whereas
75// if turning it off fails, it only matters if some code attempts to
76// continue working with the database and tries to modify the
77// sqlite_master table (none of our code does this).
78class ScopedWritableSchema {
79 public:
80 explicit ScopedWritableSchema(sqlite3* db)
81 : db_(db) {
82 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
83 }
84 ~ScopedWritableSchema() {
85 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
86 }
87
88 private:
89 sqlite3* db_;
90};
91
[email protected]7bae5742013-07-10 20:46:1692// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
93// SQLite error code from running the backup step.
94int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
95 DCHECK_NE(src, dst);
96 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
97 if (!backup) {
98 // Since this call only sets things up, this indicates a gross
99 // error in SQLite.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52100 DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
[email protected]7bae5742013-07-10 20:46:16101 return sqlite3_errcode(dst);
102 }
103
104 // -1 backs up the entire database.
105 int rc = sqlite3_backup_step(backup, -1);
106 int pages = sqlite3_backup_pagecount(backup);
107 sqlite3_backup_finish(backup);
108
109 // If successful, exactly one page should have been backed up. If
110 // this breaks, check this function to make sure assumptions aren't
111 // being broken.
112 if (rc == SQLITE_DONE)
113 DCHECK_EQ(pages, 1);
114
115 return rc;
116}
117
[email protected]8d409412013-07-19 18:25:30118// Be very strict on attachment point. SQLite can handle a much wider
119// character set with appropriate quoting, but Chromium code should
120// just use clean names to start with.
121bool ValidAttachmentPoint(const char* attachment_point) {
122 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20123 if (!(base::IsAsciiDigit(attachment_point[i]) ||
124 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30125 attachment_point[i] == '_')) {
126 return false;
127 }
128 }
129 return true;
130}
131
[email protected]8ada10f2013-12-21 00:42:34132// Helper to get the sqlite3_file* associated with the "main" database.
133int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
134 *file = NULL;
135 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
136 if (rc != SQLITE_OK)
137 return rc;
138
139 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
140 // content_unittests, even though it should not be possible.
141 // http://crbug.com/329982
142 if (!*file || !(*file)->pMethods)
143 return SQLITE_ERROR;
144
145 return rc;
146}
147
shess5dac334f2015-11-05 20:47:42148// Convenience to get the sqlite3_file* and the size for the "main" database.
149int GetSqlite3FileAndSize(sqlite3* db,
150 sqlite3_file** file, sqlite3_int64* db_size) {
151 int rc = GetSqlite3File(db, file);
152 if (rc != SQLITE_OK)
153 return rc;
154
155 return (*file)->pMethods->xFileSize(*file, db_size);
156}
157
shess58b8df82015-06-03 00:19:32158// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
159base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
160 return base::Histogram::FactoryTimeGet(
161 name,
162 base::TimeDelta::FromMilliseconds(10),
163 base::TimeDelta::FromMinutes(3),
164 50,
165 base::HistogramBase::kUmaTargetedHistogramFlag);
166}
167
erg102ceb412015-06-20 01:38:13168std::string AsUTF8ForSQL(const base::FilePath& path) {
169#if defined(OS_WIN)
170 return base::WideToUTF8(path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18171#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
erg102ceb412015-06-20 01:38:13172 return path.value();
173#endif
174}
175
[email protected]5b96f3772010-09-28 16:30:57176} // namespace
177
[email protected]e5ffd0e42009-09-11 21:30:56178namespace sql {
179
[email protected]4350e322013-06-18 22:18:10180// static
shess976814402016-06-21 06:56:25181Connection::ErrorExpecterCallback* Connection::current_expecter_cb_ = NULL;
[email protected]4350e322013-06-18 22:18:10182
183// static
shess976814402016-06-21 06:56:25184bool Connection::IsExpectedSqliteError(int error) {
185 if (!current_expecter_cb_)
[email protected]4350e322013-06-18 22:18:10186 return false;
shess976814402016-06-21 06:56:25187 return current_expecter_cb_->Run(error);
[email protected]4350e322013-06-18 22:18:10188}
189
shessc8cd2a162015-10-22 20:30:46190void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
191 AssertIOAllowed();
192
afakhry7c9abe72016-08-05 17:33:19193 std::string debug_info = GetDiagnosticInfo(extended_error, stmt);
shessc8cd2a162015-10-22 20:30:46194 if (!debug_info.empty() && RegisterIntentToUpload()) {
Lukasz Anforowicz68c21772018-01-13 03:42:44195 DEBUG_ALIAS_FOR_CSTR(debug_buf, debug_info.c_str(), 2000);
shessc8cd2a162015-10-22 20:30:46196 base::debug::DumpWithoutCrashing();
197 }
198}
199
[email protected]4350e322013-06-18 22:18:10200// static
shess976814402016-06-21 06:56:25201void Connection::SetErrorExpecter(Connection::ErrorExpecterCallback* cb) {
202 CHECK(current_expecter_cb_ == NULL);
203 current_expecter_cb_ = cb;
[email protected]4350e322013-06-18 22:18:10204}
205
206// static
shess976814402016-06-21 06:56:25207void Connection::ResetErrorExpecter() {
208 CHECK(current_expecter_cb_);
209 current_expecter_cb_ = NULL;
[email protected]4350e322013-06-18 22:18:10210}
211
[email protected]e5ffd0e42009-09-11 21:30:56212bool StatementID::operator<(const StatementID& other) const {
213 if (number_ != other.number_)
214 return number_ < other.number_;
215 return strcmp(str_, other.str_) < 0;
216}
217
[email protected]e5ffd0e42009-09-11 21:30:56218Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38219 sqlite3_stmt* stmt,
220 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56221 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38222 stmt_(stmt),
223 was_valid_(was_valid) {
224 if (connection)
225 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56226}
227
228Connection::StatementRef::~StatementRef() {
229 if (connection_)
230 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38231 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56232}
233
[email protected]41a97c812013-02-07 02:35:38234void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56235 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50236 // Call to AssertIOAllowed() cannot go at the beginning of the function
237 // because Close() is called unconditionally from destructor to clean
238 // connection_. And if this is inactive statement this won't cause any
239 // disk access and destructor most probably will be called on thread
240 // not allowing disk access.
241 // TODO([email protected]): This should move to the beginning
242 // of the function. http://crbug.com/136655.
243 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56244 sqlite3_finalize(stmt_);
245 stmt_ = NULL;
246 }
247 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38248
249 // Forced close is expected to happen from a statement error
250 // handler. In that case maintain the sense of |was_valid_| which
251 // previously held for this ref.
252 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56253}
254
255Connection::Connection()
256 : db_(NULL),
257 page_size_(0),
258 cache_size_(0),
259 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36260 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56261 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),
shess58b8df82015-06-03 00:19:32269 stats_histogram_(NULL),
270 commit_time_histogram_(NULL),
271 autocommit_time_histogram_(NULL),
272 update_time_histogram_(NULL),
273 query_time_histogram_(NULL),
274 clock_(new TimeSource()) {
[email protected]526b4662013-06-14 04:09:12275}
[email protected]e5ffd0e42009-09-11 21:30:56276
277Connection::~Connection() {
278 Close();
279}
280
shess58b8df82015-06-03 00:19:32281void Connection::RecordEvent(Events event, size_t count) {
282 for (size_t i = 0; i < count; ++i) {
283 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
284 }
285
286 if (stats_histogram_) {
287 for (size_t i = 0; i < count; ++i) {
288 stats_histogram_->Add(event);
289 }
290 }
291}
292
293void Connection::RecordCommitTime(const base::TimeDelta& delta) {
294 RecordUpdateTime(delta);
295 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
296 if (commit_time_histogram_)
297 commit_time_histogram_->AddTime(delta);
298}
299
300void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
301 RecordUpdateTime(delta);
302 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
303 if (autocommit_time_histogram_)
304 autocommit_time_histogram_->AddTime(delta);
305}
306
307void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
308 RecordQueryTime(delta);
309 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
310 if (update_time_histogram_)
311 update_time_histogram_->AddTime(delta);
312}
313
314void Connection::RecordQueryTime(const base::TimeDelta& delta) {
315 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
316 if (query_time_histogram_)
317 query_time_histogram_->AddTime(delta);
318}
319
320void Connection::RecordTimeAndChanges(
321 const base::TimeDelta& delta, bool read_only) {
322 if (read_only) {
323 RecordQueryTime(delta);
324 } else {
325 const int changes = sqlite3_changes(db_);
326 if (sqlite3_get_autocommit(db_)) {
327 RecordAutoCommitTime(delta);
328 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
329 } else {
330 RecordUpdateTime(delta);
331 RecordEvent(EVENT_CHANGES, changes);
332 }
333 }
334}
335
[email protected]a3ef4832013-02-02 05:12:33336bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02337 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26338 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49339 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02340 size_t sample = static_cast<size_t>(size_64 / 1024);
341 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
342 base::HistogramBase* histogram =
343 base::Histogram::FactoryGet(
344 full_histogram_name, 1, 1000000, 50,
345 base::HistogramBase::kUmaTargetedHistogramFlag);
346 if (histogram)
347 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08348 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02349 }
350 }
351
erg102ceb412015-06-20 01:38:13352 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42353}
[email protected]e5ffd0e42009-09-11 21:30:56354
[email protected]765b44502009-10-02 05:01:42355bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50356 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13357 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56358}
359
[email protected]8d409412013-07-19 18:25:30360bool Connection::OpenTemporary() {
361 return OpenInternal("", NO_RETRY);
362}
363
[email protected]41a97c812013-02-07 02:35:38364void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47365 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
366 // will delete the -journal file. For ChromiumOS or other more
367 // embedded systems, this is probably not appropriate, whereas on
368 // desktop it might make some sense.
369
[email protected]4b350052012-02-24 20:40:48370 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48371
[email protected]41a97c812013-02-07 02:35:38372 // Release cached statements.
373 statement_cache_.clear();
374
375 // With cached statements released, in-use statements will remain.
376 // Closing the database while statements are in use is an API
377 // violation, except for forced close (which happens from within a
378 // statement's error handler).
379 DCHECK(forced || open_statements_.empty());
380
381 // Deactivate any outstanding statements so sqlite3_close() works.
382 for (StatementRefSet::iterator i = open_statements_.begin();
383 i != open_statements_.end(); ++i)
384 (*i)->Close(forced);
385 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48386
[email protected]e5ffd0e42009-09-11 21:30:56387 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50388 // Call to AssertIOAllowed() cannot go at the beginning of the function
389 // because Close() must be called from destructor to clean
390 // statement_cache_, it won't cause any disk access and it most probably
391 // will happen on thread not allowing disk access.
392 // TODO([email protected]): This should move to the beginning
393 // of the function. http://crbug.com/136655.
394 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28395
ssid3be5b1ec2016-01-13 14:21:57396 // Reseting acquires a lock to ensure no dump is happening on the database
397 // at the same time. Unregister takes ownership of provider and it is safe
398 // since the db is reset. memory_dump_provider_ could be null if db_ was
399 // poisoned.
400 if (memory_dump_provider_) {
401 memory_dump_provider_->ResetDatabase();
402 base::trace_event::MemoryDumpManager::GetInstance()
403 ->UnregisterAndDeleteDumpProviderSoon(
404 std::move(memory_dump_provider_));
405 }
406
[email protected]73fb8d52013-07-24 05:04:28407 int rc = sqlite3_close(db_);
408 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18409 base::UmaHistogramSparse("Sqlite.CloseFailure", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52410 DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage();
[email protected]73fb8d52013-07-24 05:04:28411 }
[email protected]e5ffd0e42009-09-11 21:30:56412 }
[email protected]fed734a2013-07-17 04:45:13413 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56414}
415
[email protected]41a97c812013-02-07 02:35:38416void Connection::Close() {
417 // If the database was already closed by RazeAndClose(), then no
418 // need to close again. Clear the |poisoned_| bit so that incorrect
419 // API calls are caught.
420 if (poisoned_) {
421 poisoned_ = false;
422 return;
423 }
424
425 CloseInternal(false);
426}
427
[email protected]e5ffd0e42009-09-11 21:30:56428void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50429 AssertIOAllowed();
430
[email protected]e5ffd0e42009-09-11 21:30:56431 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52432 DCHECK(poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56433 return;
434 }
435
[email protected]8ada10f2013-12-21 00:42:34436 // Use local settings if provided, otherwise use documented defaults. The
437 // actual results could be fetching via PRAGMA calls.
438 const int page_size = page_size_ ? page_size_ : 1024;
439 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
[email protected]8ada10f2013-12-21 00:42:34443 sqlite3_file* file = NULL;
[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
shess7dbd4dee2015-10-06 17:39:16463// SQLite keeps unused pages associated with a connection in a cache. It asks
464// 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
476// connection, so it should free these pages.
477//
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.
505void Connection::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_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52509 DCHECK(poisoned_) << "Illegal use of connection 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
shessc8cd2a162015-10-22 20:30:46537base::FilePath Connection::DbPath() const {
538 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.
556bool Connection::RegisterIntentToUpload() const {
557 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.
579 base::FilePath breadcrumb_path(
580 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
581
582 // Lock against multiple updates to the diagnostics file. This code should
583 // seldom be called in the first place, and when called it should seldom be
584 // called for multiple databases, and when called for multiple databases there
585 // is _probably_ something systemic wrong with the user's system. So the lock
586 // should never be contended, but when it is the database experience is
587 // already bad.
Victor Costan3653df62018-02-08 21:38:16588 static base::NoDestructor<base::Lock> lock;
589 base::AutoLock auto_lock(*lock);
shessc8cd2a162015-10-22 20:30:46590
mostynbd82cd9952016-04-11 20:05:34591 std::unique_ptr<base::Value> root;
shessc8cd2a162015-10-22 20:30:46592 if (!base::PathExists(breadcrumb_path)) {
mostynbd82cd9952016-04-11 20:05:34593 std::unique_ptr<base::DictionaryValue> root_dict(
594 new base::DictionaryValue());
shessc8cd2a162015-10-22 20:30:46595 root_dict->SetInteger(kVersionKey, kVersion);
596
mostynbd82cd9952016-04-11 20:05:34597 std::unique_ptr<base::ListValue> dumps(new base::ListValue);
shessc8cd2a162015-10-22 20:30:46598 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50599 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46600
dchenge48600452015-12-28 02:24:50601 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46602 } else {
603 // Failure to read a valid dictionary implies that something is going wrong
604 // on the system.
605 JSONFileValueDeserializer deserializer(breadcrumb_path);
mostynbd82cd9952016-04-11 20:05:34606 std::unique_ptr<base::Value> read_root(
shessc8cd2a162015-10-22 20:30:46607 deserializer.Deserialize(nullptr, nullptr));
608 if (!read_root.get())
609 return false;
mostynbd82cd9952016-04-11 20:05:34610 std::unique_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50611 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46612 if (!root_dict)
613 return false;
614
615 // Don't upload if the version is missing or newer.
616 int version = 0;
617 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
618 return false;
619
620 base::ListValue* dumps = nullptr;
621 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
622 return false;
623
624 const size_t size = dumps->GetSize();
625 for (size_t i = 0; i < size; ++i) {
626 std::string s;
627
628 // Don't upload if the value isn't a string, or indicates a prior upload.
629 if (!dumps->GetString(i, &s) || s == histogram_tag_)
630 return false;
631 }
632
633 // Record intention to proceed with upload.
634 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50635 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46636 }
637
638 const base::FilePath breadcrumb_new =
639 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
640 base::DeleteFile(breadcrumb_new, false);
641
642 // No upload if the breadcrumb file cannot be updated.
643 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
644 // the data on disk. For now, losing the data is not a big problem, so the
645 // sync overhead would probably not be worth it.
646 JSONFileValueSerializer serializer(breadcrumb_new);
647 if (!serializer.Serialize(*root))
648 return false;
649 if (!base::PathExists(breadcrumb_new))
650 return false;
651 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
652 base::DeleteFile(breadcrumb_new, false);
653 return false;
654 }
655
656 return true;
657}
658
659std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
660 // Buffer for accumulating debugging info about the error. Place
661 // more-relevant information earlier, in case things overflow the
662 // fixed-size reporting buffer.
663 std::string debug_info;
664
665 // The error message from the failed operation.
666 base::StringAppendF(&debug_info, "db error: %d/%s\n",
667 GetErrorCode(), GetErrorMessage());
668
669 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
670 // reading code does not entirely convince me. Remove if they turn out to be
671 // the same.
672 if (error != GetErrorCode())
673 base::StringAppendF(&debug_info, "reported error: %d\n", error);
674
675 // System error information. Interpretation of Windows errors is different
676 // from posix.
677#if defined(OS_WIN)
678 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18679#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
shessc8cd2a162015-10-22 20:30:46680 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
681#else
682 NOTREACHED(); // Add appropriate log info.
683#endif
684
685 if (stmt) {
686 base::StringAppendF(&debug_info, "statement: %s\n",
687 stmt->GetSQLStatement());
688 } else {
689 base::StringAppendF(&debug_info, "statement: NULL\n");
690 }
691
692 // SQLITE_ERROR often indicates some sort of mismatch between the statement
693 // and the schema, possibly due to a failed schema migration.
694 if (error == SQLITE_ERROR) {
695 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
696 sqlite3_stmt* s;
697 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
698 if (rc == SQLITE_OK) {
699 rc = sqlite3_step(s);
700 if (rc == SQLITE_ROW) {
701 base::StringAppendF(&debug_info, "version: %d\n",
702 sqlite3_column_int(s, 0));
703 } else if (rc == SQLITE_DONE) {
704 debug_info += "version: none\n";
705 } else {
706 base::StringAppendF(&debug_info, "version: error %d\n", rc);
707 }
708 sqlite3_finalize(s);
709 } else {
710 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
711 }
712
713 debug_info += "schema:\n";
714
715 // sqlite_master has columns:
716 // type - "index" or "table".
717 // name - name of created element.
718 // tbl_name - name of element, or target table in case of index.
719 // rootpage - root page of the element in database file.
720 // sql - SQL to create the element.
721 // In general, the |sql| column is sufficient to derive the other columns.
722 // |rootpage| is not interesting for debugging, without the contents of the
723 // database. The COALESCE is because certain automatic elements will have a
724 // |name| but no |sql|,
725 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
726 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
727 if (rc == SQLITE_OK) {
728 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
729 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
730 }
731 if (rc != SQLITE_DONE)
732 base::StringAppendF(&debug_info, "error %d\n", rc);
733 sqlite3_finalize(s);
734 } else {
735 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
736 }
737 }
738
739 return debug_info;
740}
741
742// TODO(shess): Since this is only called in an error situation, it might be
743// prudent to rewrite in terms of SQLite API calls, and mark the function const.
744std::string Connection::CollectCorruptionInfo() {
745 AssertIOAllowed();
746
747 // If the file cannot be accessed it is unlikely that an integrity check will
748 // turn up actionable information.
749 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19750 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46751 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
752 return std::string();
753
754 // Buffer for accumulating debugging info about the error. Place
755 // more-relevant information earlier, in case things overflow the
756 // fixed-size reporting buffer.
757 std::string debug_info;
758 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
759 db_size);
760
761 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19762 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46763 if (db_size > kMaxIntegrityCheckSize) {
764 debug_info += "integrity_check skipped due to size\n";
765 } else {
766 std::vector<std::string> messages;
767
768 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
769 // into a string. Probably should be refactored.
770 const base::TimeTicks before = base::TimeTicks::Now();
771 FullIntegrityCheck(&messages);
772 base::StringAppendF(
773 &debug_info,
774 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
775 (base::TimeTicks::Now() - before).InMilliseconds(),
776 messages.size());
777
778 // SQLite returns up to 100 messages by default, trim deeper to
779 // keep close to the 2000-character size limit for dumping.
780 const size_t kMaxMessages = 20;
781 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
782 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
783 }
784 }
785
786 return debug_info;
787}
788
shessa62504d2016-11-07 19:26:12789bool Connection::GetMmapAltStatus(int64_t* status) {
790 // The [meta] version uses a missing table as a signal for a fresh database.
791 // That will not work for the view, which would not exist in either a new or
792 // an existing database. A new database _should_ be only one page long, so
793 // just don't bother optimizing this case (start at offset 0).
794 // TODO(shess): Could the [meta] case also get simpler, then?
795 if (!DoesViewExist("MmapStatus")) {
796 *status = 0;
797 return true;
798 }
799
800 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
801 Statement s(GetUniqueStatement(kMmapStatusSql));
802 if (s.Step())
803 *status = s.ColumnInt64(0);
804 return s.Succeeded();
805}
806
807bool Connection::SetMmapAltStatus(int64_t status) {
808 if (!BeginTransaction())
809 return false;
810
811 // View may not exist on first run.
812 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
813 RollbackTransaction();
814 return false;
815 }
816
817 // Views live in the schema, so they cannot be parameterized. For an integer
818 // value, this construct should be safe from SQL injection, if the value
819 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
820 // value.
821 const std::string createViewSql =
822 base::StringPrintf("CREATE VIEW MmapStatus (value) AS SELECT %" PRId64,
823 status);
824 if (!Execute(createViewSql.c_str())) {
825 RollbackTransaction();
826 return false;
827 }
828
829 return CommitTransaction();
830}
831
shessd90aeea82015-11-13 02:24:31832size_t Connection::GetAppropriateMmapSize() {
833 AssertIOAllowed();
834
rohitrao83d6b83a2016-06-21 07:25:57835#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
836 if (!base::ios::IsRunningOnIOS10OrLater()) {
837 // iOS SQLite does not support memory mapping.
838 return 0;
839 }
shessd90aeea82015-11-13 02:24:31840#endif
841
shess9bf2c672015-12-18 01:18:08842 // How much to map if no errors are found. 50MB encompasses the 99th
843 // percentile of Chrome databases in the wild, so this should be good.
844 const size_t kMmapEverything = 256 * 1024 * 1024;
845
shessa62504d2016-11-07 19:26:12846 // Progress information is tracked in the [meta] table for databases which use
847 // sql::MetaTable, otherwise it is tracked in a special view.
848 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08849 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12850 if (mmap_alt_status_) {
851 if (!GetMmapAltStatus(&mmap_ofs)) {
852 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
853 return 0;
854 }
855 } else {
856 // If [meta] doesn't exist, yet, it's a new database, assume the best.
857 // sql::MetaTable::Init() will preload kMmapSuccess.
858 if (!MetaTable::DoesTableExist(this)) {
859 RecordOneEvent(EVENT_MMAP_META_MISSING);
860 return kMmapEverything;
861 }
862
863 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
864 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
865 return 0;
866 }
shessd90aeea82015-11-13 02:24:31867 }
868
869 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08870 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31871 RecordOneEvent(EVENT_MMAP_FAILED);
872 return 0;
shess9bf2c672015-12-18 01:18:08873 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31874 // Continue reading from previous offset.
875 DCHECK_GE(mmap_ofs, 0);
876
877 // TODO(shess): Could this reading code be shared with Preload()? It would
878 // require locking twice (this code wouldn't be able to access |db_size| so
879 // the helper would have to return amount read).
880
881 // Read more of the database looking for errors. The VFS interface is used
882 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
883 // to limit checking to 20MB per run of Chromium.
884 sqlite3_file* file = NULL;
885 sqlite3_int64 db_size = 0;
886 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
887 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
888 return 0;
889 }
890
891 // Read the data left, or |g_reads_allowed|, whichever is smaller.
892 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
893 // in a single Chromium run.
894 sqlite3_int64 amount = db_size - mmap_ofs;
895 if (amount < 0)
896 amount = 0;
897 if (amount > 0) {
Victor Costan3653df62018-02-08 21:38:16898 static base::NoDestructor<base::Lock> lock;
899 base::AutoLock auto_lock(*lock);
shessd90aeea82015-11-13 02:24:31900 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
901 if (g_reads_allowed < amount)
902 amount = g_reads_allowed;
903 g_reads_allowed -= amount;
904 }
905
906 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
907 // database was truncated after a previous pass.
908 if (amount <= 0 && mmap_ofs < db_size) {
909 DCHECK_EQ(0, amount);
910 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
911 } else {
912 static const int kPageSize = 4096;
913 char buf[kPageSize];
914 while (amount > 0) {
915 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
916 if (rc == SQLITE_OK) {
917 mmap_ofs += sizeof(buf);
918 amount -= sizeof(buf);
919 } else if (rc == SQLITE_IOERR_SHORT_READ) {
920 // Reached EOF for a database with page size < |kPageSize|.
921 mmap_ofs = db_size;
922 break;
923 } else {
924 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08925 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31926 break;
927 }
928 }
929
930 // Log these events after update to distinguish meta update failure.
931 Events event;
932 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08933 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31934 event = EVENT_MMAP_SUCCESS_NEW;
935 } else if (mmap_ofs > 0) {
936 event = EVENT_MMAP_SUCCESS_PARTIAL;
937 } else {
shess9bf2c672015-12-18 01:18:08938 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31939 event = EVENT_MMAP_FAILED_NEW;
940 }
941
shessa62504d2016-11-07 19:26:12942 if (mmap_alt_status_) {
943 if (!SetMmapAltStatus(mmap_ofs)) {
944 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
945 return 0;
946 }
947 } else {
948 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
949 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
950 return 0;
951 }
shessd90aeea82015-11-13 02:24:31952 }
953
954 RecordOneEvent(event);
955 }
956 }
957
shess9bf2c672015-12-18 01:18:08958 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31959 return 0;
shess9bf2c672015-12-18 01:18:08960 if (mmap_ofs == MetaTable::kMmapSuccess)
961 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31962 return mmap_ofs;
963}
964
[email protected]be7995f12013-07-18 18:49:14965void Connection::TrimMemory(bool aggressively) {
966 if (!db_)
967 return;
968
969 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
970 int original_cache_size;
971 {
972 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
973 if (!sql_get_original.Step()) {
974 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
975 return;
976 }
977 original_cache_size = sql_get_original.ColumnInt(0);
978 }
979 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
980
981 // Force sqlite to try to reduce page cache usage.
982 const std::string sql_shrink =
983 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
984 if (!Execute(sql_shrink.c_str()))
985 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
986
987 // Restore cache size.
988 const std::string sql_restore =
989 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
990 if (!Execute(sql_restore.c_str()))
991 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
992}
993
[email protected]8e0c01282012-04-06 19:36:49994// Create an in-memory database with the existing database's page
995// size, then backup that database over the existing database.
996bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50997 AssertIOAllowed();
998
[email protected]8e0c01282012-04-06 19:36:49999 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521000 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491001 return false;
1002 }
1003
1004 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521005 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:491006 return false;
1007 }
1008
1009 sql::Connection null_db;
1010 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521011 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:491012 return false;
1013 }
1014
[email protected]6d42f152012-11-10 00:38:241015 if (page_size_) {
1016 // Enforce SQLite restrictions on |page_size_|.
1017 DCHECK(!(page_size_ & (page_size_ - 1)))
1018 << " page_size_ " << page_size_ << " is not a power of two.";
1019 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1020 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041021 const std::string sql =
1022 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421023 if (!null_db.Execute(sql.c_str()))
1024 return false;
1025 }
1026
[email protected]6d42f152012-11-10 00:38:241027#if defined(OS_ANDROID)
1028 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1029 // in-memory databases do not respect this define.
1030 // TODO(shess): Figure out a way to set this without using platform
1031 // specific code. AFAICT from sqlite3.c, the only way to do it
1032 // would be to create an actual filesystem database, which is
1033 // unfortunate.
1034 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1035 return false;
1036#endif
[email protected]8e0c01282012-04-06 19:36:491037
1038 // The page size doesn't take effect until a database has pages, and
1039 // at this point the null database has none. Changing the schema
1040 // version will create the first page. This will not affect the
1041 // schema version in the resulting database, as SQLite's backup
1042 // implementation propagates the schema version from the original
1043 // connection to the new version of the database, incremented by one
1044 // so that other readers see the schema change and act accordingly.
1045 if (!null_db.Execute("PRAGMA schema_version = 1"))
1046 return false;
1047
[email protected]6d42f152012-11-10 00:38:241048 // SQLite tracks the expected number of database pages in the first
1049 // page, and if it does not match the total retrieved from a
1050 // filesystem call, treats the database as corrupt. This situation
1051 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1052 // used to hint to SQLite to soldier on in that case, specifically
1053 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1054 // sqlite3.c lockBtree().]
1055 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1056 // page_size" can be used to query such a database.
1057 ScopedWritableSchema writable_schema(db_);
1058
shess92a6fb22017-04-23 04:33:301059#if defined(OS_WIN)
1060 // On Windows, truncate silently fails when applied to memory-mapped files.
1061 // Disable memory-mapping so that the truncate succeeds. Note that other
1062 // connections may have memory-mapped the file, so this may not entirely
1063 // prevent the problem.
1064 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1065 ignore_result(Execute("PRAGMA mmap_size = 0"));
1066#endif
1067
[email protected]7bae5742013-07-10 20:46:161068 const char* kMain = "main";
1069 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181070 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:491071
1072 // The destination database was locked.
1073 if (rc == SQLITE_BUSY) {
1074 return false;
1075 }
1076
[email protected]7bae5742013-07-10 20:46:161077 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1078 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1079 // isn't even big enough for one page. Either way, reach in and
1080 // truncate it before trying again.
1081 // TODO(shess): Maybe it would be worthwhile to just truncate from
1082 // the get-go?
1083 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1084 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341085 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161086 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521087 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:161088 return false;
[email protected]7bae5742013-07-10 20:46:161089 }
1090
1091 rc = file->pMethods->xTruncate(file, 0);
1092 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181093 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521094 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:161095 return false;
1096 }
1097
1098 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181099 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:161100
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521101 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:161102 }
1103
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521104 // TODO(shess): Figure out which other cases can happen.
1105 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
1106
[email protected]8e0c01282012-04-06 19:36:491107 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521108 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:491109}
1110
[email protected]41a97c812013-02-07 02:35:381111bool Connection::RazeAndClose() {
1112 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521113 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:381114 return false;
1115 }
1116
1117 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301118 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381119
1120 bool result = Raze();
1121
1122 CloseInternal(true);
1123
1124 // Mark the database so that future API calls fail appropriately,
1125 // but don't DCHECK (because after calling this function they are
1126 // expected to fail).
1127 poisoned_ = true;
1128
1129 return result;
1130}
1131
[email protected]8d409412013-07-19 18:25:301132void Connection::Poison() {
1133 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521134 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:301135 return;
1136 }
1137
1138 RollbackAllTransactions();
1139 CloseInternal(true);
1140
1141 // Mark the database so that future API calls fail appropriately,
1142 // but don't DCHECK (because after calling this function they are
1143 // expected to fail).
1144 poisoned_ = true;
1145}
1146
[email protected]8d2e39e2013-06-24 05:55:081147// TODO(shess): To the extent possible, figure out the optimal
1148// ordering for these deletes which will prevent other connections
1149// from seeing odd behavior. For instance, it may be necessary to
1150// manually lock the main database file in a SQLite-compatible fashion
1151// (to prevent other processes from opening it), then delete the
1152// journal files, then delete the main database file. Another option
1153// might be to lock the main database file and poison the header with
1154// junk to prevent other processes from opening it successfully (like
1155// Gears "SQLite poison 3" trick).
1156//
1157// static
1158bool Connection::Delete(const base::FilePath& path) {
Francois Doray66bdfd82017-10-20 13:50:371159 base::AssertBlockingAllowed();
[email protected]8d2e39e2013-06-24 05:55:081160
1161 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1162 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1163
erg102ceb412015-06-20 01:38:131164 std::string journal_str = AsUTF8ForSQL(journal_path);
1165 std::string wal_str = AsUTF8ForSQL(wal_path);
1166 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081167
Victor Costan3653df62018-02-08 21:38:161168 EnsureSqliteInitialized();
shess702467622015-09-16 19:04:551169
erg102ceb412015-06-20 01:38:131170 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1171 CHECK(vfs);
1172 CHECK(vfs->xDelete);
1173 CHECK(vfs->xAccess);
1174
1175 // We only work with unix, win32 and mojo filesystems. If you're trying to
1176 // use this code with any other VFS, you're not in a good place.
1177 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1178 strncmp(vfs->zName, "win32", 5) == 0 ||
1179 strcmp(vfs->zName, "mojo") == 0);
1180
1181 vfs->xDelete(vfs, journal_str.c_str(), 0);
1182 vfs->xDelete(vfs, wal_str.c_str(), 0);
1183 vfs->xDelete(vfs, path_str.c_str(), 0);
1184
1185 int journal_exists = 0;
1186 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1187 &journal_exists);
1188
1189 int wal_exists = 0;
1190 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1191 &wal_exists);
1192
1193 int path_exists = 0;
1194 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1195 &path_exists);
1196
1197 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081198}
1199
[email protected]e5ffd0e42009-09-11 21:30:561200bool Connection::BeginTransaction() {
1201 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331202 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561203
1204 // When we're going to rollback, fail on this begin and don't actually
1205 // mark us as entering the nested transaction.
1206 return false;
1207 }
1208
1209 bool success = true;
1210 if (!transaction_nesting_) {
1211 needs_rollback_ = false;
1212
1213 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321214 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591215 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561216 return false;
1217 }
1218 transaction_nesting_++;
1219 return success;
1220}
1221
1222void Connection::RollbackTransaction() {
1223 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521224 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561225 return;
1226 }
1227
1228 transaction_nesting_--;
1229
1230 if (transaction_nesting_ > 0) {
1231 // Mark the outermost transaction as needing rollback.
1232 needs_rollback_ = true;
1233 return;
1234 }
1235
1236 DoRollback();
1237}
1238
1239bool Connection::CommitTransaction() {
1240 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521241 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561242 return false;
1243 }
1244 transaction_nesting_--;
1245
1246 if (transaction_nesting_ > 0) {
1247 // Mark any nested transactions as failing after we've already got one.
1248 return !needs_rollback_;
1249 }
1250
1251 if (needs_rollback_) {
1252 DoRollback();
1253 return false;
1254 }
1255
1256 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321257
1258 // Collect the commit time manually, sql::Statement would register it as query
1259 // time only.
1260 const base::TimeTicks before = Now();
1261 bool ret = commit.RunWithoutTimers();
1262 const base::TimeDelta delta = Now() - before;
1263
1264 RecordCommitTime(delta);
1265 RecordOneEvent(EVENT_COMMIT);
1266
shess7dbd4dee2015-10-06 17:39:161267 // Release dirty cache pages after the transaction closes.
1268 ReleaseCacheMemoryIfNeeded(false);
1269
shess58b8df82015-06-03 00:19:321270 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561271}
1272
[email protected]8d409412013-07-19 18:25:301273void Connection::RollbackAllTransactions() {
1274 if (transaction_nesting_ > 0) {
1275 transaction_nesting_ = 0;
1276 DoRollback();
1277 }
1278}
1279
1280bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1281 const char* attachment_point) {
1282 DCHECK(ValidAttachmentPoint(attachment_point));
1283
1284 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1285#if OS_WIN
1286 s.BindString16(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181287#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberibd1301f2018-05-18 21:00:091288 s.BindString(0, other_db_path.value());
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181289#else
1290#error Unsupported platform
[email protected]8d409412013-07-19 18:25:301291#endif
1292 s.BindString(1, attachment_point);
1293 return s.Run();
1294}
1295
1296bool Connection::DetachDatabase(const char* attachment_point) {
1297 DCHECK(ValidAttachmentPoint(attachment_point));
1298
1299 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1300 s.BindString(0, attachment_point);
1301 return s.Run();
1302}
1303
shess58b8df82015-06-03 00:19:321304// TODO(shess): Consider changing this to execute exactly one statement. If a
1305// caller wishes to execute multiple statements, that should be explicit, and
1306// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591307int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501308 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381309 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521310 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381311 return SQLITE_ERROR;
1312 }
shess58b8df82015-06-03 00:19:321313 DCHECK(sql);
1314
1315 RecordOneEvent(EVENT_EXECUTE);
1316 int rc = SQLITE_OK;
1317 while ((rc == SQLITE_OK) && *sql) {
1318 sqlite3_stmt *stmt = NULL;
1319 const char *leftover_sql;
1320
1321 const base::TimeTicks before = Now();
1322 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1323 sql = leftover_sql;
1324
1325 // Stop if an error is encountered.
1326 if (rc != SQLITE_OK)
1327 break;
1328
1329 // This happens if |sql| originally only contained comments or whitespace.
1330 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1331 // extraneous comments and whitespace in the SQL statements increases
1332 // runtime cost and can easily be shifted out to the C++ layer.
1333 if (!stmt)
1334 continue;
1335
1336 // Save for use after statement is finalized.
1337 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1338
1339 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1340 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1341 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1342 // is the only legitimate case for this.
1343 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1344 }
1345
1346 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1347 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1348 rc = sqlite3_finalize(stmt);
1349 if (rc == SQLITE_OK)
1350 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1351
1352 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1353 // trailing whitespace.
1354 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021355 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321356 sql++;
1357 }
1358
1359 const base::TimeDelta delta = Now() - before;
1360 RecordTimeAndChanges(delta, read_only);
1361 }
shess7dbd4dee2015-10-06 17:39:161362
1363 // Most calls to Execute() modify the database. The main exceptions would be
1364 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1365 // but sometimes don't.
1366 ReleaseCacheMemoryIfNeeded(true);
1367
shess58b8df82015-06-03 00:19:321368 return rc;
[email protected]eff1fa522011-12-12 23:50:591369}
1370
1371bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381372 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521373 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381374 return false;
1375 }
1376
[email protected]eff1fa522011-12-12 23:50:591377 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001378 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581379 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001380
[email protected]28fe0ff2012-02-25 00:40:331381 // This needs to be a FATAL log because the error case of arriving here is
1382 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101383 // a change alters the schema but not all queries adjust. This can happen
1384 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521385 DCHECK_NE(error, SQLITE_ERROR)
1386 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591387 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561388}
1389
[email protected]5b96f3772010-09-28 16:30:571390bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381391 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521392 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571393 return false;
[email protected]41a97c812013-02-07 02:35:381394 }
[email protected]5b96f3772010-09-28 16:30:571395
1396 ScopedBusyTimeout busy_timeout(db_);
1397 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591398 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571399}
1400
[email protected]e5ffd0e42009-09-11 21:30:561401bool Connection::HasCachedStatement(const StatementID& id) const {
1402 return statement_cache_.find(id) != statement_cache_.end();
1403}
1404
1405scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1406 const StatementID& id,
1407 const char* sql) {
1408 CachedStatementMap::iterator i = statement_cache_.find(id);
1409 if (i != statement_cache_.end()) {
1410 // Statement is in the cache. It should still be active (we're the only
1411 // one invalidating cached statements, and we'll remove it from the cache
1412 // if we do that. Make sure we reset it before giving out the cached one in
1413 // case it still has some stuff bound.
1414 DCHECK(i->second->is_valid());
1415 sqlite3_reset(i->second->stmt());
1416 return i->second;
1417 }
1418
1419 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1420 if (statement->is_valid())
1421 statement_cache_[id] = statement; // Only cache valid statements.
1422 return statement;
1423}
1424
1425scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1426 const char* sql) {
shess9e77283d2016-06-13 23:53:201427 return GetStatementImpl(this, sql);
1428}
1429
1430scoped_refptr<Connection::StatementRef> Connection::GetStatementImpl(
1431 sql::Connection* tracking_db, const char* sql) const {
[email protected]35f7e5392012-07-27 19:54:501432 AssertIOAllowed();
shess9e77283d2016-06-13 23:53:201433 DCHECK(sql);
1434 DCHECK(!tracking_db || const_cast<Connection*>(tracking_db)==this);
[email protected]35f7e5392012-07-27 19:54:501435
[email protected]41a97c812013-02-07 02:35:381436 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561437 if (!db_)
Victor Costan3b02cdf2018-07-18 00:39:561438 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561439
1440 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001441 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1442 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591443 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521444 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001445
1446 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581447 OnSqliteError(rc, NULL, sql);
Victor Costan3b02cdf2018-07-18 00:39:561448 return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false);
[email protected]e5ffd0e42009-09-11 21:30:561449 }
Victor Costan3b02cdf2018-07-18 00:39:561450 return base::MakeRefCounted<StatementRef>(tracking_db, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561451}
1452
[email protected]2eec0a22012-07-24 01:59:581453scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1454 const char* sql) const {
shess9e77283d2016-06-13 23:53:201455 return GetStatementImpl(NULL, sql);
[email protected]2eec0a22012-07-24 01:59:581456}
1457
[email protected]92cd00a2013-08-16 11:09:581458std::string Connection::GetSchema() const {
1459 // The ORDER BY should not be necessary, but relying on organic
1460 // order for something like this is questionable.
1461 const char* kSql =
1462 "SELECT type, name, tbl_name, sql "
1463 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1464 Statement statement(GetUntrackedStatement(kSql));
1465
1466 std::string schema;
1467 while (statement.Step()) {
1468 schema += statement.ColumnString(0);
1469 schema += '|';
1470 schema += statement.ColumnString(1);
1471 schema += '|';
1472 schema += statement.ColumnString(2);
1473 schema += '|';
1474 schema += statement.ColumnString(3);
1475 schema += '\n';
1476 }
1477
1478 return schema;
1479}
1480
[email protected]eff1fa522011-12-12 23:50:591481bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501482 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381483 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521484 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381485 return false;
1486 }
1487
[email protected]eff1fa522011-12-12 23:50:591488 sqlite3_stmt* stmt = NULL;
1489 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1490 return false;
1491
1492 sqlite3_finalize(stmt);
1493 return true;
1494}
1495
[email protected]e2cadec82011-12-13 02:00:531496bool Connection::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121497 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531498}
1499
shessa62504d2016-11-07 19:26:121500bool Connection::DoesTableExist(const char* table_name) const {
1501 return DoesSchemaItemExist(table_name, "table");
1502}
1503
1504bool Connection::DoesViewExist(const char* view_name) const {
1505 return DoesSchemaItemExist(view_name, "view");
1506}
1507
1508bool Connection::DoesSchemaItemExist(
[email protected]e2cadec82011-12-13 02:00:531509 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471510 const char* kSql =
1511 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581512 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471513
shess976814402016-06-21 06:56:251514 // This can happen if the database is corrupt and the error is a test
1515 // expectation.
shess92a2ab12015-04-09 01:59:471516 if (!statement.is_valid())
1517 return false;
1518
[email protected]e2cadec82011-12-13 02:00:531519 statement.BindString(0, type);
1520 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331521
[email protected]e5ffd0e42009-09-11 21:30:561522 return statement.Step(); // Table exists if any row was returned.
1523}
1524
1525bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171526 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561527 std::string sql("PRAGMA TABLE_INFO(");
1528 sql.append(table_name);
1529 sql.append(")");
1530
[email protected]2eec0a22012-07-24 01:59:581531 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471532
shess976814402016-06-21 06:56:251533 // This can happen if the database is corrupt and the error is a test
1534 // expectation.
shess92a2ab12015-04-09 01:59:471535 if (!statement.is_valid())
1536 return false;
1537
[email protected]e5ffd0e42009-09-11 21:30:561538 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331539 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1540 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561541 return true;
1542 }
1543 return false;
1544}
1545
tfarina720d4f32015-05-11 22:31:261546int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561547 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521548 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561549 return 0;
1550 }
1551 return sqlite3_last_insert_rowid(db_);
1552}
1553
[email protected]1ed78a32009-09-15 20:24:171554int Connection::GetLastChangeCount() const {
1555 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521556 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171557 return 0;
1558 }
1559 return sqlite3_changes(db_);
1560}
1561
[email protected]e5ffd0e42009-09-11 21:30:561562int Connection::GetErrorCode() const {
1563 if (!db_)
1564 return SQLITE_ERROR;
1565 return sqlite3_errcode(db_);
1566}
1567
[email protected]767718e52010-09-21 23:18:491568int Connection::GetLastErrno() const {
1569 if (!db_)
1570 return -1;
1571
1572 int err = 0;
1573 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1574 return -2;
1575
1576 return err;
1577}
1578
[email protected]e5ffd0e42009-09-11 21:30:561579const char* Connection::GetErrorMessage() const {
1580 if (!db_)
1581 return "sql::Connection has no connection.";
1582 return sqlite3_errmsg(db_);
1583}
1584
[email protected]fed734a2013-07-17 04:45:131585bool Connection::OpenInternal(const std::string& file_name,
1586 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501587 AssertIOAllowed();
1588
[email protected]9cfbc922009-11-17 20:13:171589 if (db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521590 DLOG(DCHECK) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171591 return false;
1592 }
1593
Victor Costan3653df62018-02-08 21:38:161594 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181595
shess58b8df82015-06-03 00:19:321596 // Setup the stats histograms immediately rather than allocating lazily.
1597 // Connections which won't exercise all of these probably shouldn't exist.
1598 if (!histogram_tag_.empty()) {
1599 stats_histogram_ =
1600 base::LinearHistogram::FactoryGet(
1601 "Sqlite.Stats." + histogram_tag_,
1602 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1603 base::HistogramBase::kUmaTargetedHistogramFlag);
1604
1605 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1606 // unreasonable time for any single operation, so there is not much value to
1607 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1608 // things are entirely busted.
1609 commit_time_histogram_ =
1610 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1611
1612 autocommit_time_histogram_ =
1613 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1614
1615 update_time_histogram_ =
1616 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1617
1618 query_time_histogram_ =
1619 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1620 }
1621
[email protected]41a97c812013-02-07 02:35:381622 // If |poisoned_| is set, it means an error handler called
1623 // RazeAndClose(). Until regular Close() is called, the caller
1624 // should be treating the database as open, but is_open() currently
1625 // only considers the sqlite3 handle's state.
1626 // TODO(shess): Revise is_open() to consider poisoned_, and review
1627 // to see if any non-testing code even depends on it.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521628 DCHECK(!poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161629 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381630
shess5f2c3442017-01-24 02:15:101631 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1632 sqlite3_vfs* vfs = VFSWrapper();
1633 const char* vfs_name = (vfs ? vfs->zName : nullptr);
1634 int err = sqlite3_open_v2(file_name.c_str(), &db_,
1635 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
1636 vfs_name);
[email protected]765b44502009-10-02 05:01:421637 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281638 // Extended error codes cannot be enabled until a handle is
1639 // available, fetch manually.
1640 err = sqlite3_extended_errcode(db_);
1641
[email protected]bd2ccdb4a2012-12-07 22:14:501642 // Histogram failures specific to initial open for debugging
1643 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181644 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501645
[email protected]2f496b42013-09-26 18:36:581646 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131647 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291648 Close();
[email protected]fed734a2013-07-17 04:45:131649
1650 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1651 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421652 return false;
1653 }
1654
[email protected]81a2a602013-07-17 19:10:361655 // TODO(shess): OS_WIN support?
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181656#if defined(OS_POSIX)
[email protected]81a2a602013-07-17 19:10:361657 if (restrict_to_user_) {
1658 DCHECK_NE(file_name, std::string(":memory"));
1659 base::FilePath file_path(file_name);
1660 int mode = 0;
1661 // TODO(shess): Arguably, failure to retrieve and change
1662 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081663 if (base::GetPosixFilePermissions(file_path, &mode)) {
1664 mode &= base::FILE_PERMISSION_USER_MASK;
1665 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361666
1667 // SQLite sets the permissions on these files from the main
1668 // database on create. Set them here in case they already exist
1669 // at this point. Failure to set these permissions should not
1670 // be fatal unless the file doesn't exist.
1671 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1672 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081673 base::SetPosixFilePermissions(journal_path, mode);
1674 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361675 }
1676 }
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181677#endif // defined(OS_POSIX)
[email protected]81a2a602013-07-17 19:10:361678
[email protected]affa2da2013-06-06 22:20:341679 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1680 // Chromium already depends on small mallocs being efficient, so we disable
1681 // this to avoid the extra memory overhead.
1682 // This must be called immediatly after opening the database before any SQL
1683 // statements are run.
1684 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1685
[email protected]73fb8d52013-07-24 05:04:281686 // Enable extended result codes to provide more color on I/O errors.
1687 // Not having extended result codes is not a fatal problem, as
1688 // Chromium code does not attempt to handle I/O errors anyhow. The
1689 // current implementation always returns SQLITE_OK, the DCHECK is to
1690 // quickly notify someone if SQLite changes.
1691 err = sqlite3_extended_result_codes(db_, 1);
1692 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1693
shessbccd300e2016-08-20 00:06:561694 // sqlite3_open() does not actually read the database file (unless a hot
1695 // journal is found). Successfully executing this pragma on an existing
1696 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1697 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501698 // TODO(shess): For now, just probing to see what the lay of the
1699 // land is. If it's mostly SQLITE_NOTADB, then the database should
1700 // be razed.
1701 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561702 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181703 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561704 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1705
1706 // Retry or bail out if the error handler poisoned the handle.
1707 // TODO(shess): Move this handling to one place (see also sqlite3_open and
1708 // secure_delete). Possibly a wrapper function?
1709 if (poisoned_) {
1710 Close();
1711 if (retry_flag == RETRY_ON_POISON)
1712 return OpenInternal(file_name, NO_RETRY);
1713 return false;
1714 }
1715 }
[email protected]658f8332010-09-18 04:40:431716
[email protected]2e1cee762013-07-09 14:40:001717#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1718 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1719 // REGEXP support. Add it in dynamically.
1720 err = sqlite3IcuInit(db_);
1721 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1722#endif // OS_IOS && USE_SYSTEM_SQLITE
1723
[email protected]5b96f3772010-09-28 16:30:571724 // If indicated, lock up the database before doing anything else, so
1725 // that the following code doesn't have to deal with locking.
1726 // TODO(shess): This code is brittle. Find the cases where code
1727 // doesn't request |exclusive_locking_| and audit that it does the
1728 // right thing with SQLITE_BUSY, and that it doesn't make
1729 // assumptions about who might change things in the database.
1730 // http://crbug.com/56559
1731 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101732 // TODO(shess): This should probably be a failure. Code which
1733 // requests exclusive locking but doesn't get it is almost certain
1734 // to be ill-tested.
1735 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571736 }
1737
[email protected]4e179ba2012-03-17 16:06:471738 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1739 // DELETE (default) - delete -journal file to commit.
1740 // TRUNCATE - truncate -journal file to commit.
1741 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091742 // TRUNCATE should be faster than DELETE because it won't need directory
1743 // changes for each transaction. PERSIST may break the spirit of using
1744 // secure_delete.
1745 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471746
[email protected]c68ce172011-11-24 22:30:271747 const base::TimeDelta kBusyTimeout =
1748 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1749
[email protected]765b44502009-10-02 05:01:421750 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571751 // Enforce SQLite restrictions on |page_size_|.
1752 DCHECK(!(page_size_ & (page_size_ - 1)))
1753 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241754 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571755 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041756 const std::string sql =
1757 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101758 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421759 }
1760
1761 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041762 const std::string sql =
1763 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101764 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421765 }
1766
[email protected]6e0b1442011-08-09 23:23:581767 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131768 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581769 Close();
[email protected]fed734a2013-07-17 04:45:131770 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1771 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581772 return false;
1773 }
1774
shess5dac334f2015-11-05 20:47:421775 // Set a reasonable chunk size for larger files. This reduces churn from
1776 // remapping memory on size changes. It also reduces filesystem
1777 // fragmentation.
1778 // TODO(shess): It may make sense to have this be hinted by the client.
1779 // Database sizes seem to be bimodal, some clients have consistently small
1780 // databases (<20k) while other clients have a broad distribution of sizes
1781 // (hundreds of kilobytes to many megabytes).
1782 sqlite3_file* file = NULL;
1783 sqlite3_int64 db_size = 0;
1784 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1785 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1786 int chunk_size = 4 * 1024;
1787 if (db_size > 128 * 1024)
1788 chunk_size = 32 * 1024;
1789 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1790 }
1791
shess2f3a814b2015-11-05 18:11:101792 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311793 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1794 // safe range to memory-map based on past regular I/O. This value will be
1795 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1796 // 64-bit platforms.
1797 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1798 std::string mmap_sql =
1799 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1800 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101801
1802 // Determine if memory-mapping has actually been enabled. The Execute() above
1803 // can succeed without changing the amount mapped.
1804 mmap_enabled_ = false;
1805 {
1806 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1807 if (s.Step() && s.ColumnInt64(0) > 0)
1808 mmap_enabled_ = true;
1809 }
1810
ssid3be5b1ec2016-01-13 14:21:571811 DCHECK(!memory_dump_provider_);
1812 memory_dump_provider_.reset(
1813 new ConnectionMemoryDumpProvider(db_, histogram_tag_));
1814 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1815 memory_dump_provider_.get(), "sql::Connection", nullptr);
1816
[email protected]765b44502009-10-02 05:01:421817 return true;
1818}
1819
[email protected]e5ffd0e42009-09-11 21:30:561820void Connection::DoRollback() {
1821 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321822
1823 // Collect the rollback time manually, sql::Statement would register it as
1824 // query time only.
1825 const base::TimeTicks before = Now();
1826 rollback.RunWithoutTimers();
1827 const base::TimeDelta delta = Now() - before;
1828
1829 RecordUpdateTime(delta);
1830 RecordOneEvent(EVENT_ROLLBACK);
1831
shess7dbd4dee2015-10-06 17:39:161832 // The cache may have been accumulating dirty pages for commit. Note that in
1833 // some cases sql::Transaction can fire rollback after a database is closed.
1834 if (is_open())
1835 ReleaseCacheMemoryIfNeeded(false);
1836
[email protected]44ad7d902012-03-23 00:09:051837 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561838}
1839
1840void Connection::StatementRefCreated(StatementRef* ref) {
1841 DCHECK(open_statements_.find(ref) == open_statements_.end());
1842 open_statements_.insert(ref);
1843}
1844
1845void Connection::StatementRefDeleted(StatementRef* ref) {
1846 StatementRefSet::iterator i = open_statements_.find(ref);
1847 if (i == open_statements_.end())
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521848 DLOG(DCHECK) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561849 else
1850 open_statements_.erase(i);
1851}
1852
shess58b8df82015-06-03 00:19:321853void Connection::set_histogram_tag(const std::string& tag) {
1854 DCHECK(!is_open());
1855 histogram_tag_ = tag;
1856}
1857
[email protected]210ce0af2013-05-15 09:10:391858void Connection::AddTaggedHistogram(const std::string& name,
1859 size_t sample) const {
1860 if (histogram_tag_.empty())
1861 return;
1862
1863 // TODO(shess): The histogram macros create a bit of static storage
1864 // for caching the histogram object. This code shouldn't execute
1865 // often enough for such caching to be crucial. If it becomes an
1866 // issue, the object could be cached alongside histogram_prefix_.
1867 std::string full_histogram_name = name + "." + histogram_tag_;
1868 base::HistogramBase* histogram =
1869 base::SparseHistogram::FactoryGet(
1870 full_histogram_name,
1871 base::HistogramBase::kUmaTargetedHistogramFlag);
1872 if (histogram)
1873 histogram->Add(sample);
1874}
1875
shess9e77283d2016-06-13 23:53:201876int Connection::OnSqliteError(
1877 int err, sql::Statement *stmt, const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181878 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391879 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141880
1881 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581882 if (!sql && stmt)
1883 sql = stmt->GetSQLStatement();
1884 if (!sql)
1885 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061886
1887 std::string id = histogram_tag_;
1888 if (id.empty())
1889 id = DbPath().BaseName().AsUTF8Unsafe();
1890 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141891 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581892 << ": " << GetErrorMessage()
1893 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141894
[email protected]c3881b372013-05-17 08:39:461895 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561896 // Fire from a copy of the callback in case of reentry into
1897 // re/set_error_callback().
1898 // TODO(shess): <http://crbug.com/254584>
1899 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461900 return err;
1901 }
1902
[email protected]faa604e2009-09-25 22:38:591903 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251904 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521905 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591906 return err;
1907}
1908
[email protected]579446c2013-12-16 18:36:521909bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1910 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1911}
1912
1913bool Connection::QuickIntegrityCheck() {
1914 std::vector<std::string> messages;
1915 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1916 return false;
1917 return messages.size() == 1 && messages[0] == "ok";
1918}
1919
afakhry7c9abe72016-08-05 17:33:191920std::string Connection::GetDiagnosticInfo(int extended_error,
1921 Statement* statement) {
1922 // Prevent reentrant calls to the error callback.
1923 ErrorCallback original_callback = std::move(error_callback_);
1924 reset_error_callback();
1925
1926 // Trim extended error codes.
1927 const int error = (extended_error & 0xFF);
1928 // CollectCorruptionInfo() is implemented in terms of sql::Connection,
1929 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1930 std::string result = (error == SQLITE_CORRUPT)
1931 ? CollectCorruptionInfo()
1932 : CollectErrorInfo(extended_error, statement);
1933
1934 // The following queries must be executed after CollectErrorInfo() above, so
1935 // if they result in their own errors, they don't interfere with
1936 // CollectErrorInfo().
1937 const bool has_valid_header =
1938 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1939 const bool select_sqlite_master_result =
1940 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1941 SQLITE_OK);
1942
1943 // Restore the original error callback.
1944 error_callback_ = std::move(original_callback);
1945
1946 base::StringAppendF(&result, "Has valid header: %s\n",
1947 (has_valid_header ? "Yes" : "No"));
1948 base::StringAppendF(&result, "Has valid schema: %s\n",
1949 (select_sqlite_master_result ? "Yes" : "No"));
1950
1951 return result;
1952}
1953
[email protected]80abf152013-05-22 12:42:421954// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521955bool Connection::IntegrityCheckHelper(
1956 const char* pragma_sql,
1957 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421958 messages->clear();
1959
[email protected]4658e2a02013-06-06 23:05:001960 // This has the side effect of setting SQLITE_RecoveryMode, which
1961 // allows SQLite to process through certain cases of corruption.
1962 // Failing to set this pragma probably means that the database is
1963 // beyond recovery.
Victor Costan1d868352018-06-26 19:06:481964 static const char kWritableSchemaSql[] = "PRAGMA writable_schema = ON";
1965 if (!Execute(kWritableSchemaSql))
[email protected]4658e2a02013-06-06 23:05:001966 return false;
1967
1968 bool ret = false;
1969 {
[email protected]579446c2013-12-16 18:36:521970 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001971
1972 // The pragma appears to return all results (up to 100 by default)
1973 // as a single string. This doesn't appear to be an API contract,
1974 // it could return separate lines, so loop _and_ split.
1975 while (stmt.Step()) {
1976 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181977 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1978 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001979 }
1980 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421981 }
[email protected]4658e2a02013-06-06 23:05:001982
1983 // Best effort to put things back as they were before.
Victor Costan1d868352018-06-26 19:06:481984 static const char kNoWritableSchemaSql[] = "PRAGMA writable_schema = OFF";
1985 ignore_result(Execute(kNoWritableSchemaSql));
[email protected]4658e2a02013-06-06 23:05:001986
1987 return ret;
[email protected]80abf152013-05-22 12:42:421988}
1989
ssid1f4e5362016-12-08 20:41:381990bool Connection::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1991 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131992 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381993 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131994}
1995
shess58b8df82015-06-03 00:19:321996base::TimeTicks TimeSource::Now() {
1997 return base::TimeTicks::Now();
1998}
1999
[email protected]e5ffd0e42009-09-11 21:30:562000} // namespace sql