blob: 4fd3d41f4b6cb4a65b8959a044f7219ca1956936 [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());
171#elif defined(OS_POSIX)
172 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));
545#elif defined(OS_POSIX)
546 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());
679#elif defined(OS_POSIX)
680 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());
1287#else
1288 s.BindString(0, other_db_path.value());
1289#endif
1290 s.BindString(1, attachment_point);
1291 return s.Run();
1292}
1293
1294bool Connection::DetachDatabase(const char* attachment_point) {
1295 DCHECK(ValidAttachmentPoint(attachment_point));
1296
1297 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1298 s.BindString(0, attachment_point);
1299 return s.Run();
1300}
1301
shess58b8df82015-06-03 00:19:321302// TODO(shess): Consider changing this to execute exactly one statement. If a
1303// caller wishes to execute multiple statements, that should be explicit, and
1304// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591305int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501306 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381307 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521308 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381309 return SQLITE_ERROR;
1310 }
shess58b8df82015-06-03 00:19:321311 DCHECK(sql);
1312
1313 RecordOneEvent(EVENT_EXECUTE);
1314 int rc = SQLITE_OK;
1315 while ((rc == SQLITE_OK) && *sql) {
1316 sqlite3_stmt *stmt = NULL;
1317 const char *leftover_sql;
1318
1319 const base::TimeTicks before = Now();
1320 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1321 sql = leftover_sql;
1322
1323 // Stop if an error is encountered.
1324 if (rc != SQLITE_OK)
1325 break;
1326
1327 // This happens if |sql| originally only contained comments or whitespace.
1328 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1329 // extraneous comments and whitespace in the SQL statements increases
1330 // runtime cost and can easily be shifted out to the C++ layer.
1331 if (!stmt)
1332 continue;
1333
1334 // Save for use after statement is finalized.
1335 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1336
1337 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1338 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1339 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1340 // is the only legitimate case for this.
1341 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1342 }
1343
1344 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1345 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1346 rc = sqlite3_finalize(stmt);
1347 if (rc == SQLITE_OK)
1348 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1349
1350 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1351 // trailing whitespace.
1352 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021353 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321354 sql++;
1355 }
1356
1357 const base::TimeDelta delta = Now() - before;
1358 RecordTimeAndChanges(delta, read_only);
1359 }
shess7dbd4dee2015-10-06 17:39:161360
1361 // Most calls to Execute() modify the database. The main exceptions would be
1362 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1363 // but sometimes don't.
1364 ReleaseCacheMemoryIfNeeded(true);
1365
shess58b8df82015-06-03 00:19:321366 return rc;
[email protected]eff1fa522011-12-12 23:50:591367}
1368
1369bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381370 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521371 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381372 return false;
1373 }
1374
[email protected]eff1fa522011-12-12 23:50:591375 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001376 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581377 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001378
[email protected]28fe0ff2012-02-25 00:40:331379 // This needs to be a FATAL log because the error case of arriving here is
1380 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101381 // a change alters the schema but not all queries adjust. This can happen
1382 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521383 DCHECK_NE(error, SQLITE_ERROR)
1384 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591385 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561386}
1387
[email protected]5b96f3772010-09-28 16:30:571388bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381389 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521390 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571391 return false;
[email protected]41a97c812013-02-07 02:35:381392 }
[email protected]5b96f3772010-09-28 16:30:571393
1394 ScopedBusyTimeout busy_timeout(db_);
1395 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591396 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571397}
1398
[email protected]e5ffd0e42009-09-11 21:30:561399bool Connection::HasCachedStatement(const StatementID& id) const {
1400 return statement_cache_.find(id) != statement_cache_.end();
1401}
1402
1403scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1404 const StatementID& id,
1405 const char* sql) {
1406 CachedStatementMap::iterator i = statement_cache_.find(id);
1407 if (i != statement_cache_.end()) {
1408 // Statement is in the cache. It should still be active (we're the only
1409 // one invalidating cached statements, and we'll remove it from the cache
1410 // if we do that. Make sure we reset it before giving out the cached one in
1411 // case it still has some stuff bound.
1412 DCHECK(i->second->is_valid());
1413 sqlite3_reset(i->second->stmt());
1414 return i->second;
1415 }
1416
1417 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1418 if (statement->is_valid())
1419 statement_cache_[id] = statement; // Only cache valid statements.
1420 return statement;
1421}
1422
1423scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1424 const char* sql) {
shess9e77283d2016-06-13 23:53:201425 return GetStatementImpl(this, sql);
1426}
1427
1428scoped_refptr<Connection::StatementRef> Connection::GetStatementImpl(
1429 sql::Connection* tracking_db, const char* sql) const {
[email protected]35f7e5392012-07-27 19:54:501430 AssertIOAllowed();
shess9e77283d2016-06-13 23:53:201431 DCHECK(sql);
1432 DCHECK(!tracking_db || const_cast<Connection*>(tracking_db)==this);
[email protected]35f7e5392012-07-27 19:54:501433
[email protected]41a97c812013-02-07 02:35:381434 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561435 if (!db_)
[email protected]41a97c812013-02-07 02:35:381436 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561437
1438 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001439 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1440 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591441 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521442 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001443
1444 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581445 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381446 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561447 }
shess9e77283d2016-06-13 23:53:201448 return new StatementRef(tracking_db, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561449}
1450
[email protected]2eec0a22012-07-24 01:59:581451scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1452 const char* sql) const {
shess9e77283d2016-06-13 23:53:201453 return GetStatementImpl(NULL, sql);
[email protected]2eec0a22012-07-24 01:59:581454}
1455
[email protected]92cd00a2013-08-16 11:09:581456std::string Connection::GetSchema() const {
1457 // The ORDER BY should not be necessary, but relying on organic
1458 // order for something like this is questionable.
1459 const char* kSql =
1460 "SELECT type, name, tbl_name, sql "
1461 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1462 Statement statement(GetUntrackedStatement(kSql));
1463
1464 std::string schema;
1465 while (statement.Step()) {
1466 schema += statement.ColumnString(0);
1467 schema += '|';
1468 schema += statement.ColumnString(1);
1469 schema += '|';
1470 schema += statement.ColumnString(2);
1471 schema += '|';
1472 schema += statement.ColumnString(3);
1473 schema += '\n';
1474 }
1475
1476 return schema;
1477}
1478
[email protected]eff1fa522011-12-12 23:50:591479bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501480 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381481 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521482 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381483 return false;
1484 }
1485
[email protected]eff1fa522011-12-12 23:50:591486 sqlite3_stmt* stmt = NULL;
1487 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1488 return false;
1489
1490 sqlite3_finalize(stmt);
1491 return true;
1492}
1493
[email protected]e2cadec82011-12-13 02:00:531494bool Connection::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121495 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531496}
1497
shessa62504d2016-11-07 19:26:121498bool Connection::DoesTableExist(const char* table_name) const {
1499 return DoesSchemaItemExist(table_name, "table");
1500}
1501
1502bool Connection::DoesViewExist(const char* view_name) const {
1503 return DoesSchemaItemExist(view_name, "view");
1504}
1505
1506bool Connection::DoesSchemaItemExist(
[email protected]e2cadec82011-12-13 02:00:531507 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471508 const char* kSql =
1509 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581510 Statement statement(GetUntrackedStatement(kSql));
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]e2cadec82011-12-13 02:00:531517 statement.BindString(0, type);
1518 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331519
[email protected]e5ffd0e42009-09-11 21:30:561520 return statement.Step(); // Table exists if any row was returned.
1521}
1522
1523bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171524 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561525 std::string sql("PRAGMA TABLE_INFO(");
1526 sql.append(table_name);
1527 sql.append(")");
1528
[email protected]2eec0a22012-07-24 01:59:581529 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471530
shess976814402016-06-21 06:56:251531 // This can happen if the database is corrupt and the error is a test
1532 // expectation.
shess92a2ab12015-04-09 01:59:471533 if (!statement.is_valid())
1534 return false;
1535
[email protected]e5ffd0e42009-09-11 21:30:561536 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331537 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1538 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561539 return true;
1540 }
1541 return false;
1542}
1543
tfarina720d4f32015-05-11 22:31:261544int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561545 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521546 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561547 return 0;
1548 }
1549 return sqlite3_last_insert_rowid(db_);
1550}
1551
[email protected]1ed78a32009-09-15 20:24:171552int Connection::GetLastChangeCount() const {
1553 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521554 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171555 return 0;
1556 }
1557 return sqlite3_changes(db_);
1558}
1559
[email protected]e5ffd0e42009-09-11 21:30:561560int Connection::GetErrorCode() const {
1561 if (!db_)
1562 return SQLITE_ERROR;
1563 return sqlite3_errcode(db_);
1564}
1565
[email protected]767718e52010-09-21 23:18:491566int Connection::GetLastErrno() const {
1567 if (!db_)
1568 return -1;
1569
1570 int err = 0;
1571 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1572 return -2;
1573
1574 return err;
1575}
1576
[email protected]e5ffd0e42009-09-11 21:30:561577const char* Connection::GetErrorMessage() const {
1578 if (!db_)
1579 return "sql::Connection has no connection.";
1580 return sqlite3_errmsg(db_);
1581}
1582
[email protected]fed734a2013-07-17 04:45:131583bool Connection::OpenInternal(const std::string& file_name,
1584 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501585 AssertIOAllowed();
1586
[email protected]9cfbc922009-11-17 20:13:171587 if (db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521588 DLOG(DCHECK) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171589 return false;
1590 }
1591
Victor Costan3653df62018-02-08 21:38:161592 EnsureSqliteInitialized();
[email protected]a7ec1292013-07-22 22:02:181593
shess58b8df82015-06-03 00:19:321594 // Setup the stats histograms immediately rather than allocating lazily.
1595 // Connections which won't exercise all of these probably shouldn't exist.
1596 if (!histogram_tag_.empty()) {
1597 stats_histogram_ =
1598 base::LinearHistogram::FactoryGet(
1599 "Sqlite.Stats." + histogram_tag_,
1600 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1601 base::HistogramBase::kUmaTargetedHistogramFlag);
1602
1603 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1604 // unreasonable time for any single operation, so there is not much value to
1605 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1606 // things are entirely busted.
1607 commit_time_histogram_ =
1608 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1609
1610 autocommit_time_histogram_ =
1611 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1612
1613 update_time_histogram_ =
1614 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1615
1616 query_time_histogram_ =
1617 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1618 }
1619
[email protected]41a97c812013-02-07 02:35:381620 // If |poisoned_| is set, it means an error handler called
1621 // RazeAndClose(). Until regular Close() is called, the caller
1622 // should be treating the database as open, but is_open() currently
1623 // only considers the sqlite3 handle's state.
1624 // TODO(shess): Revise is_open() to consider poisoned_, and review
1625 // to see if any non-testing code even depends on it.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521626 DCHECK(!poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161627 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381628
shess5f2c3442017-01-24 02:15:101629 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1630 sqlite3_vfs* vfs = VFSWrapper();
1631 const char* vfs_name = (vfs ? vfs->zName : nullptr);
1632 int err = sqlite3_open_v2(file_name.c_str(), &db_,
1633 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
1634 vfs_name);
[email protected]765b44502009-10-02 05:01:421635 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281636 // Extended error codes cannot be enabled until a handle is
1637 // available, fetch manually.
1638 err = sqlite3_extended_errcode(db_);
1639
[email protected]bd2ccdb4a2012-12-07 22:14:501640 // Histogram failures specific to initial open for debugging
1641 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181642 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501643
[email protected]2f496b42013-09-26 18:36:581644 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131645 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291646 Close();
[email protected]fed734a2013-07-17 04:45:131647
1648 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1649 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421650 return false;
1651 }
1652
[email protected]81a2a602013-07-17 19:10:361653 // TODO(shess): OS_WIN support?
Kevin Marshalla9f05ec2017-07-14 02:10:051654#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]81a2a602013-07-17 19:10:361655 if (restrict_to_user_) {
1656 DCHECK_NE(file_name, std::string(":memory"));
1657 base::FilePath file_path(file_name);
1658 int mode = 0;
1659 // TODO(shess): Arguably, failure to retrieve and change
1660 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081661 if (base::GetPosixFilePermissions(file_path, &mode)) {
1662 mode &= base::FILE_PERMISSION_USER_MASK;
1663 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361664
1665 // SQLite sets the permissions on these files from the main
1666 // database on create. Set them here in case they already exist
1667 // at this point. Failure to set these permissions should not
1668 // be fatal unless the file doesn't exist.
1669 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1670 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081671 base::SetPosixFilePermissions(journal_path, mode);
1672 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361673 }
1674 }
Kevin Marshalla9f05ec2017-07-14 02:10:051675#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]81a2a602013-07-17 19:10:361676
[email protected]affa2da2013-06-06 22:20:341677 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1678 // Chromium already depends on small mallocs being efficient, so we disable
1679 // this to avoid the extra memory overhead.
1680 // This must be called immediatly after opening the database before any SQL
1681 // statements are run.
1682 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1683
[email protected]73fb8d52013-07-24 05:04:281684 // Enable extended result codes to provide more color on I/O errors.
1685 // Not having extended result codes is not a fatal problem, as
1686 // Chromium code does not attempt to handle I/O errors anyhow. The
1687 // current implementation always returns SQLITE_OK, the DCHECK is to
1688 // quickly notify someone if SQLite changes.
1689 err = sqlite3_extended_result_codes(db_, 1);
1690 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1691
shessbccd300e2016-08-20 00:06:561692 // sqlite3_open() does not actually read the database file (unless a hot
1693 // journal is found). Successfully executing this pragma on an existing
1694 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1695 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501696 // TODO(shess): For now, just probing to see what the lay of the
1697 // land is. If it's mostly SQLITE_NOTADB, then the database should
1698 // be razed.
1699 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561700 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181701 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561702 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1703
1704 // Retry or bail out if the error handler poisoned the handle.
1705 // TODO(shess): Move this handling to one place (see also sqlite3_open and
1706 // secure_delete). Possibly a wrapper function?
1707 if (poisoned_) {
1708 Close();
1709 if (retry_flag == RETRY_ON_POISON)
1710 return OpenInternal(file_name, NO_RETRY);
1711 return false;
1712 }
1713 }
[email protected]658f8332010-09-18 04:40:431714
[email protected]2e1cee762013-07-09 14:40:001715#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1716 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1717 // REGEXP support. Add it in dynamically.
1718 err = sqlite3IcuInit(db_);
1719 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1720#endif // OS_IOS && USE_SYSTEM_SQLITE
1721
[email protected]5b96f3772010-09-28 16:30:571722 // If indicated, lock up the database before doing anything else, so
1723 // that the following code doesn't have to deal with locking.
1724 // TODO(shess): This code is brittle. Find the cases where code
1725 // doesn't request |exclusive_locking_| and audit that it does the
1726 // right thing with SQLITE_BUSY, and that it doesn't make
1727 // assumptions about who might change things in the database.
1728 // http://crbug.com/56559
1729 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101730 // TODO(shess): This should probably be a failure. Code which
1731 // requests exclusive locking but doesn't get it is almost certain
1732 // to be ill-tested.
1733 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571734 }
1735
[email protected]4e179ba2012-03-17 16:06:471736 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1737 // DELETE (default) - delete -journal file to commit.
1738 // TRUNCATE - truncate -journal file to commit.
1739 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091740 // TRUNCATE should be faster than DELETE because it won't need directory
1741 // changes for each transaction. PERSIST may break the spirit of using
1742 // secure_delete.
1743 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471744
[email protected]c68ce172011-11-24 22:30:271745 const base::TimeDelta kBusyTimeout =
1746 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1747
[email protected]765b44502009-10-02 05:01:421748 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571749 // Enforce SQLite restrictions on |page_size_|.
1750 DCHECK(!(page_size_ & (page_size_ - 1)))
1751 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241752 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571753 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041754 const std::string sql =
1755 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101756 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421757 }
1758
1759 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041760 const std::string sql =
1761 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101762 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421763 }
1764
[email protected]6e0b1442011-08-09 23:23:581765 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131766 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581767 Close();
[email protected]fed734a2013-07-17 04:45:131768 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1769 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581770 return false;
1771 }
1772
shess5dac334f2015-11-05 20:47:421773 // Set a reasonable chunk size for larger files. This reduces churn from
1774 // remapping memory on size changes. It also reduces filesystem
1775 // fragmentation.
1776 // TODO(shess): It may make sense to have this be hinted by the client.
1777 // Database sizes seem to be bimodal, some clients have consistently small
1778 // databases (<20k) while other clients have a broad distribution of sizes
1779 // (hundreds of kilobytes to many megabytes).
1780 sqlite3_file* file = NULL;
1781 sqlite3_int64 db_size = 0;
1782 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1783 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1784 int chunk_size = 4 * 1024;
1785 if (db_size > 128 * 1024)
1786 chunk_size = 32 * 1024;
1787 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1788 }
1789
shess2f3a814b2015-11-05 18:11:101790 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311791 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1792 // safe range to memory-map based on past regular I/O. This value will be
1793 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1794 // 64-bit platforms.
1795 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1796 std::string mmap_sql =
1797 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1798 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101799
1800 // Determine if memory-mapping has actually been enabled. The Execute() above
1801 // can succeed without changing the amount mapped.
1802 mmap_enabled_ = false;
1803 {
1804 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1805 if (s.Step() && s.ColumnInt64(0) > 0)
1806 mmap_enabled_ = true;
1807 }
1808
ssid3be5b1ec2016-01-13 14:21:571809 DCHECK(!memory_dump_provider_);
1810 memory_dump_provider_.reset(
1811 new ConnectionMemoryDumpProvider(db_, histogram_tag_));
1812 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1813 memory_dump_provider_.get(), "sql::Connection", nullptr);
1814
[email protected]765b44502009-10-02 05:01:421815 return true;
1816}
1817
[email protected]e5ffd0e42009-09-11 21:30:561818void Connection::DoRollback() {
1819 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321820
1821 // Collect the rollback time manually, sql::Statement would register it as
1822 // query time only.
1823 const base::TimeTicks before = Now();
1824 rollback.RunWithoutTimers();
1825 const base::TimeDelta delta = Now() - before;
1826
1827 RecordUpdateTime(delta);
1828 RecordOneEvent(EVENT_ROLLBACK);
1829
shess7dbd4dee2015-10-06 17:39:161830 // The cache may have been accumulating dirty pages for commit. Note that in
1831 // some cases sql::Transaction can fire rollback after a database is closed.
1832 if (is_open())
1833 ReleaseCacheMemoryIfNeeded(false);
1834
[email protected]44ad7d902012-03-23 00:09:051835 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561836}
1837
1838void Connection::StatementRefCreated(StatementRef* ref) {
1839 DCHECK(open_statements_.find(ref) == open_statements_.end());
1840 open_statements_.insert(ref);
1841}
1842
1843void Connection::StatementRefDeleted(StatementRef* ref) {
1844 StatementRefSet::iterator i = open_statements_.find(ref);
1845 if (i == open_statements_.end())
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521846 DLOG(DCHECK) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561847 else
1848 open_statements_.erase(i);
1849}
1850
shess58b8df82015-06-03 00:19:321851void Connection::set_histogram_tag(const std::string& tag) {
1852 DCHECK(!is_open());
1853 histogram_tag_ = tag;
1854}
1855
[email protected]210ce0af2013-05-15 09:10:391856void Connection::AddTaggedHistogram(const std::string& name,
1857 size_t sample) const {
1858 if (histogram_tag_.empty())
1859 return;
1860
1861 // TODO(shess): The histogram macros create a bit of static storage
1862 // for caching the histogram object. This code shouldn't execute
1863 // often enough for such caching to be crucial. If it becomes an
1864 // issue, the object could be cached alongside histogram_prefix_.
1865 std::string full_histogram_name = name + "." + histogram_tag_;
1866 base::HistogramBase* histogram =
1867 base::SparseHistogram::FactoryGet(
1868 full_histogram_name,
1869 base::HistogramBase::kUmaTargetedHistogramFlag);
1870 if (histogram)
1871 histogram->Add(sample);
1872}
1873
shess9e77283d2016-06-13 23:53:201874int Connection::OnSqliteError(
1875 int err, sql::Statement *stmt, const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181876 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391877 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141878
1879 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581880 if (!sql && stmt)
1881 sql = stmt->GetSQLStatement();
1882 if (!sql)
1883 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061884
1885 std::string id = histogram_tag_;
1886 if (id.empty())
1887 id = DbPath().BaseName().AsUTF8Unsafe();
1888 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141889 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581890 << ": " << GetErrorMessage()
1891 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141892
[email protected]c3881b372013-05-17 08:39:461893 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561894 // Fire from a copy of the callback in case of reentry into
1895 // re/set_error_callback().
1896 // TODO(shess): <http://crbug.com/254584>
1897 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461898 return err;
1899 }
1900
[email protected]faa604e2009-09-25 22:38:591901 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251902 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521903 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591904 return err;
1905}
1906
[email protected]579446c2013-12-16 18:36:521907bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1908 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1909}
1910
1911bool Connection::QuickIntegrityCheck() {
1912 std::vector<std::string> messages;
1913 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1914 return false;
1915 return messages.size() == 1 && messages[0] == "ok";
1916}
1917
afakhry7c9abe72016-08-05 17:33:191918std::string Connection::GetDiagnosticInfo(int extended_error,
1919 Statement* statement) {
1920 // Prevent reentrant calls to the error callback.
1921 ErrorCallback original_callback = std::move(error_callback_);
1922 reset_error_callback();
1923
1924 // Trim extended error codes.
1925 const int error = (extended_error & 0xFF);
1926 // CollectCorruptionInfo() is implemented in terms of sql::Connection,
1927 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1928 std::string result = (error == SQLITE_CORRUPT)
1929 ? CollectCorruptionInfo()
1930 : CollectErrorInfo(extended_error, statement);
1931
1932 // The following queries must be executed after CollectErrorInfo() above, so
1933 // if they result in their own errors, they don't interfere with
1934 // CollectErrorInfo().
1935 const bool has_valid_header =
1936 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1937 const bool select_sqlite_master_result =
1938 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1939 SQLITE_OK);
1940
1941 // Restore the original error callback.
1942 error_callback_ = std::move(original_callback);
1943
1944 base::StringAppendF(&result, "Has valid header: %s\n",
1945 (has_valid_header ? "Yes" : "No"));
1946 base::StringAppendF(&result, "Has valid schema: %s\n",
1947 (select_sqlite_master_result ? "Yes" : "No"));
1948
1949 return result;
1950}
1951
[email protected]80abf152013-05-22 12:42:421952// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521953bool Connection::IntegrityCheckHelper(
1954 const char* pragma_sql,
1955 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421956 messages->clear();
1957
[email protected]4658e2a02013-06-06 23:05:001958 // This has the side effect of setting SQLITE_RecoveryMode, which
1959 // allows SQLite to process through certain cases of corruption.
1960 // Failing to set this pragma probably means that the database is
1961 // beyond recovery.
1962 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1963 if (!Execute(kWritableSchema))
1964 return false;
1965
1966 bool ret = false;
1967 {
[email protected]579446c2013-12-16 18:36:521968 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001969
1970 // The pragma appears to return all results (up to 100 by default)
1971 // as a single string. This doesn't appear to be an API contract,
1972 // it could return separate lines, so loop _and_ split.
1973 while (stmt.Step()) {
1974 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181975 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1976 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001977 }
1978 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421979 }
[email protected]4658e2a02013-06-06 23:05:001980
1981 // Best effort to put things back as they were before.
1982 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1983 ignore_result(Execute(kNoWritableSchema));
1984
1985 return ret;
[email protected]80abf152013-05-22 12:42:421986}
1987
ssid1f4e5362016-12-08 20:41:381988bool Connection::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
1989 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:131990 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:381991 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:131992}
1993
shess58b8df82015-06-03 00:19:321994base::TimeTicks TimeSource::Now() {
1995 return base::TimeTicks::Now();
1996}
1997
[email protected]e5ffd0e42009-09-11 21:30:561998} // namespace sql