blob: 76f9371b7c8dbc02a36dd06cd01d2ec3d5a4be42 [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
shessc9e80ae22015-08-12 21:39:1114#include "base/bind.h"
tzikb9dae932017-02-10 03:57:3015#include "base/debug/alias.h"
shessc8cd2a162015-10-22 20:30:4616#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5217#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4418#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4619#include "base/format_macros.h"
20#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1821#include "base/lazy_instance.h"
fdoray2dfa76452016-06-07 13:11:2222#include "base/location.h"
[email protected]e5ffd0e42009-09-11 21:30:5623#include "base/logging.h"
Ilya Sherman1c811db2017-12-14 10:36:1824#include "base/metrics/histogram_functions.h"
asvitkine30330812016-08-30 04:01:0825#include "base/metrics/histogram_macros.h"
[email protected]210ce0af2013-05-15 09:10:3926#include "base/metrics/sparse_histogram.h"
fdoray2dfa76452016-06-07 13:11:2227#include "base/single_thread_task_runner.h"
[email protected]80abf152013-05-22 12:42:4228#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1929#include "base/strings/string_util.h"
30#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4531#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1832#include "base/synchronization/lock.h"
Joshua Bell607cb142017-07-24 19:17:1633#include "base/threading/sequenced_task_runner_handle.h"
ssid9f8022f2015-10-12 17:49:0334#include "base/trace_event/memory_dump_manager.h"
Kevin Marshalla9f05ec2017-07-14 02:10:0535#include "build/build_config.h"
ssid3be5b1ec2016-01-13 14:21:5736#include "sql/connection_memory_dump_provider.h"
shess9bf2c672015-12-18 01:18:0837#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2138#include "sql/statement.h"
shess5f2c3442017-01-24 02:15:1039#include "sql/vfs_wrapper.h"
[email protected]e33cba42010-08-18 23:37:0340#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5641
[email protected]2e1cee762013-07-09 14:40:0042#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
rohitrao83d6b83a2016-06-21 07:25:5743#include "base/ios/ios_util.h"
[email protected]2e1cee762013-07-09 14:40:0044#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
45#endif
46
[email protected]5b96f3772010-09-28 16:30:5747namespace {
48
49// Spin for up to a second waiting for the lock to clear when setting
50// up the database.
51// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2752const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5753
54class ScopedBusyTimeout {
55 public:
56 explicit ScopedBusyTimeout(sqlite3* db)
57 : db_(db) {
58 }
59 ~ScopedBusyTimeout() {
60 sqlite3_busy_timeout(db_, 0);
61 }
62
63 int SetTimeout(base::TimeDelta timeout) {
64 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
65 return sqlite3_busy_timeout(db_,
66 static_cast<int>(timeout.InMilliseconds()));
67 }
68
69 private:
70 sqlite3* db_;
71};
72
[email protected]6d42f152012-11-10 00:38:2473// Helper to "safely" enable writable_schema. No error checking
74// because it is reasonable to just forge ahead in case of an error.
75// If turning it on fails, then most likely nothing will work, whereas
76// if turning it off fails, it only matters if some code attempts to
77// continue working with the database and tries to modify the
78// sqlite_master table (none of our code does this).
79class ScopedWritableSchema {
80 public:
81 explicit ScopedWritableSchema(sqlite3* db)
82 : db_(db) {
83 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
84 }
85 ~ScopedWritableSchema() {
86 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
87 }
88
89 private:
90 sqlite3* db_;
91};
92
[email protected]7bae5742013-07-10 20:46:1693// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
94// SQLite error code from running the backup step.
95int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
96 DCHECK_NE(src, dst);
97 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
98 if (!backup) {
99 // Since this call only sets things up, this indicates a gross
100 // error in SQLite.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52101 DLOG(DCHECK) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
[email protected]7bae5742013-07-10 20:46:16102 return sqlite3_errcode(dst);
103 }
104
105 // -1 backs up the entire database.
106 int rc = sqlite3_backup_step(backup, -1);
107 int pages = sqlite3_backup_pagecount(backup);
108 sqlite3_backup_finish(backup);
109
110 // If successful, exactly one page should have been backed up. If
111 // this breaks, check this function to make sure assumptions aren't
112 // being broken.
113 if (rc == SQLITE_DONE)
114 DCHECK_EQ(pages, 1);
115
116 return rc;
117}
118
[email protected]8d409412013-07-19 18:25:30119// Be very strict on attachment point. SQLite can handle a much wider
120// character set with appropriate quoting, but Chromium code should
121// just use clean names to start with.
122bool ValidAttachmentPoint(const char* attachment_point) {
123 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20124 if (!(base::IsAsciiDigit(attachment_point[i]) ||
125 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30126 attachment_point[i] == '_')) {
127 return false;
128 }
129 }
130 return true;
131}
132
shessc9e80ae22015-08-12 21:39:11133void RecordSqliteMemory10Min() {
avi0b519202015-12-21 07:25:19134 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11135 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
136}
137
138void RecordSqliteMemoryHour() {
avi0b519202015-12-21 07:25:19139 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11140 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
141}
142
143void RecordSqliteMemoryDay() {
avi0b519202015-12-21 07:25:19144 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11145 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
146}
147
shess2d48e942015-08-25 17:39:51148void RecordSqliteMemoryWeek() {
avi0b519202015-12-21 07:25:19149 const int64_t used = sqlite3_memory_used();
shess2d48e942015-08-25 17:39:51150 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
151}
152
[email protected]a7ec1292013-07-22 22:02:18153// SQLite automatically calls sqlite3_initialize() lazily, but
154// sqlite3_initialize() uses double-checked locking and thus can have
155// data races.
156//
157// TODO(shess): Another alternative would be to have
158// sqlite3_initialize() called as part of process bring-up. If this
159// is changed, remove the dynamic_annotations dependency in sql.gyp.
160base::LazyInstance<base::Lock>::Leaky
161 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
162void InitializeSqlite() {
163 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11164 static bool first_call = true;
165 if (first_call) {
166 sqlite3_initialize();
167
168 // Schedule callback to record memory footprint histograms at 10m, 1h, and
Joshua Bell607cb142017-07-24 19:17:16169 // 1d. There may not be a registered task runner in tests.
170 if (base::SequencedTaskRunnerHandle::IsSet()) {
171 base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
shessc9e80ae22015-08-12 21:39:11172 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
173 base::TimeDelta::FromMinutes(10));
Joshua Bell607cb142017-07-24 19:17:16174 base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
shessc9e80ae22015-08-12 21:39:11175 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
176 base::TimeDelta::FromHours(1));
Joshua Bell607cb142017-07-24 19:17:16177 base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
shessc9e80ae22015-08-12 21:39:11178 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
179 base::TimeDelta::FromDays(1));
Joshua Bell607cb142017-07-24 19:17:16180 base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
shess2d48e942015-08-25 17:39:51181 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
182 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11183 }
184
185 first_call = false;
186 }
[email protected]a7ec1292013-07-22 22:02:18187}
188
[email protected]8ada10f2013-12-21 00:42:34189// Helper to get the sqlite3_file* associated with the "main" database.
190int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
191 *file = NULL;
192 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
193 if (rc != SQLITE_OK)
194 return rc;
195
196 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
197 // content_unittests, even though it should not be possible.
198 // http://crbug.com/329982
199 if (!*file || !(*file)->pMethods)
200 return SQLITE_ERROR;
201
202 return rc;
203}
204
shess5dac334f2015-11-05 20:47:42205// Convenience to get the sqlite3_file* and the size for the "main" database.
206int GetSqlite3FileAndSize(sqlite3* db,
207 sqlite3_file** file, sqlite3_int64* db_size) {
208 int rc = GetSqlite3File(db, file);
209 if (rc != SQLITE_OK)
210 return rc;
211
212 return (*file)->pMethods->xFileSize(*file, db_size);
213}
214
shess58b8df82015-06-03 00:19:32215// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
216base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
217 return base::Histogram::FactoryTimeGet(
218 name,
219 base::TimeDelta::FromMilliseconds(10),
220 base::TimeDelta::FromMinutes(3),
221 50,
222 base::HistogramBase::kUmaTargetedHistogramFlag);
223}
224
erg102ceb412015-06-20 01:38:13225std::string AsUTF8ForSQL(const base::FilePath& path) {
226#if defined(OS_WIN)
227 return base::WideToUTF8(path.value());
228#elif defined(OS_POSIX)
229 return path.value();
230#endif
231}
232
[email protected]5b96f3772010-09-28 16:30:57233} // namespace
234
[email protected]e5ffd0e42009-09-11 21:30:56235namespace sql {
236
[email protected]4350e322013-06-18 22:18:10237// static
shess976814402016-06-21 06:56:25238Connection::ErrorExpecterCallback* Connection::current_expecter_cb_ = NULL;
[email protected]4350e322013-06-18 22:18:10239
240// static
shess976814402016-06-21 06:56:25241bool Connection::IsExpectedSqliteError(int error) {
242 if (!current_expecter_cb_)
[email protected]4350e322013-06-18 22:18:10243 return false;
shess976814402016-06-21 06:56:25244 return current_expecter_cb_->Run(error);
[email protected]4350e322013-06-18 22:18:10245}
246
shessc8cd2a162015-10-22 20:30:46247void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
248 AssertIOAllowed();
249
afakhry7c9abe72016-08-05 17:33:19250 std::string debug_info = GetDiagnosticInfo(extended_error, stmt);
shessc8cd2a162015-10-22 20:30:46251 if (!debug_info.empty() && RegisterIntentToUpload()) {
Lukasz Anforowicz68c21772018-01-13 03:42:44252 DEBUG_ALIAS_FOR_CSTR(debug_buf, debug_info.c_str(), 2000);
shessc8cd2a162015-10-22 20:30:46253 base::debug::DumpWithoutCrashing();
254 }
255}
256
[email protected]4350e322013-06-18 22:18:10257// static
shess976814402016-06-21 06:56:25258void Connection::SetErrorExpecter(Connection::ErrorExpecterCallback* cb) {
259 CHECK(current_expecter_cb_ == NULL);
260 current_expecter_cb_ = cb;
[email protected]4350e322013-06-18 22:18:10261}
262
263// static
shess976814402016-06-21 06:56:25264void Connection::ResetErrorExpecter() {
265 CHECK(current_expecter_cb_);
266 current_expecter_cb_ = NULL;
[email protected]4350e322013-06-18 22:18:10267}
268
[email protected]e5ffd0e42009-09-11 21:30:56269bool StatementID::operator<(const StatementID& other) const {
270 if (number_ != other.number_)
271 return number_ < other.number_;
272 return strcmp(str_, other.str_) < 0;
273}
274
[email protected]e5ffd0e42009-09-11 21:30:56275Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38276 sqlite3_stmt* stmt,
277 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56278 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38279 stmt_(stmt),
280 was_valid_(was_valid) {
281 if (connection)
282 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56283}
284
285Connection::StatementRef::~StatementRef() {
286 if (connection_)
287 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38288 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56289}
290
[email protected]41a97c812013-02-07 02:35:38291void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56292 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50293 // Call to AssertIOAllowed() cannot go at the beginning of the function
294 // because Close() is called unconditionally from destructor to clean
295 // connection_. And if this is inactive statement this won't cause any
296 // disk access and destructor most probably will be called on thread
297 // not allowing disk access.
298 // TODO([email protected]): This should move to the beginning
299 // of the function. http://crbug.com/136655.
300 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56301 sqlite3_finalize(stmt_);
302 stmt_ = NULL;
303 }
304 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38305
306 // Forced close is expected to happen from a statement error
307 // handler. In that case maintain the sense of |was_valid_| which
308 // previously held for this ref.
309 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56310}
311
312Connection::Connection()
313 : db_(NULL),
314 page_size_(0),
315 cache_size_(0),
316 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36317 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56318 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50319 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16320 in_memory_(false),
shess58b8df82015-06-03 00:19:32321 poisoned_(false),
shessa62504d2016-11-07 19:26:12322 mmap_alt_status_(false),
kerz42ff2a012016-04-27 04:50:06323 mmap_disabled_(false),
shess7dbd4dee2015-10-06 17:39:16324 mmap_enabled_(false),
325 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32326 stats_histogram_(NULL),
327 commit_time_histogram_(NULL),
328 autocommit_time_histogram_(NULL),
329 update_time_histogram_(NULL),
330 query_time_histogram_(NULL),
331 clock_(new TimeSource()) {
[email protected]526b4662013-06-14 04:09:12332}
[email protected]e5ffd0e42009-09-11 21:30:56333
334Connection::~Connection() {
335 Close();
336}
337
shess58b8df82015-06-03 00:19:32338void Connection::RecordEvent(Events event, size_t count) {
339 for (size_t i = 0; i < count; ++i) {
340 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
341 }
342
343 if (stats_histogram_) {
344 for (size_t i = 0; i < count; ++i) {
345 stats_histogram_->Add(event);
346 }
347 }
348}
349
350void Connection::RecordCommitTime(const base::TimeDelta& delta) {
351 RecordUpdateTime(delta);
352 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
353 if (commit_time_histogram_)
354 commit_time_histogram_->AddTime(delta);
355}
356
357void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
358 RecordUpdateTime(delta);
359 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
360 if (autocommit_time_histogram_)
361 autocommit_time_histogram_->AddTime(delta);
362}
363
364void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
365 RecordQueryTime(delta);
366 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
367 if (update_time_histogram_)
368 update_time_histogram_->AddTime(delta);
369}
370
371void Connection::RecordQueryTime(const base::TimeDelta& delta) {
372 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
373 if (query_time_histogram_)
374 query_time_histogram_->AddTime(delta);
375}
376
377void Connection::RecordTimeAndChanges(
378 const base::TimeDelta& delta, bool read_only) {
379 if (read_only) {
380 RecordQueryTime(delta);
381 } else {
382 const int changes = sqlite3_changes(db_);
383 if (sqlite3_get_autocommit(db_)) {
384 RecordAutoCommitTime(delta);
385 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
386 } else {
387 RecordUpdateTime(delta);
388 RecordEvent(EVENT_CHANGES, changes);
389 }
390 }
391}
392
[email protected]a3ef4832013-02-02 05:12:33393bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02394 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26395 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49396 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02397 size_t sample = static_cast<size_t>(size_64 / 1024);
398 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
399 base::HistogramBase* histogram =
400 base::Histogram::FactoryGet(
401 full_histogram_name, 1, 1000000, 50,
402 base::HistogramBase::kUmaTargetedHistogramFlag);
403 if (histogram)
404 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08405 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02406 }
407 }
408
erg102ceb412015-06-20 01:38:13409 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42410}
[email protected]e5ffd0e42009-09-11 21:30:56411
[email protected]765b44502009-10-02 05:01:42412bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50413 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13414 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56415}
416
[email protected]8d409412013-07-19 18:25:30417bool Connection::OpenTemporary() {
418 return OpenInternal("", NO_RETRY);
419}
420
[email protected]41a97c812013-02-07 02:35:38421void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47422 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
423 // will delete the -journal file. For ChromiumOS or other more
424 // embedded systems, this is probably not appropriate, whereas on
425 // desktop it might make some sense.
426
[email protected]4b350052012-02-24 20:40:48427 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48428
[email protected]41a97c812013-02-07 02:35:38429 // Release cached statements.
430 statement_cache_.clear();
431
432 // With cached statements released, in-use statements will remain.
433 // Closing the database while statements are in use is an API
434 // violation, except for forced close (which happens from within a
435 // statement's error handler).
436 DCHECK(forced || open_statements_.empty());
437
438 // Deactivate any outstanding statements so sqlite3_close() works.
439 for (StatementRefSet::iterator i = open_statements_.begin();
440 i != open_statements_.end(); ++i)
441 (*i)->Close(forced);
442 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48443
[email protected]e5ffd0e42009-09-11 21:30:56444 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50445 // Call to AssertIOAllowed() cannot go at the beginning of the function
446 // because Close() must be called from destructor to clean
447 // statement_cache_, it won't cause any disk access and it most probably
448 // will happen on thread not allowing disk access.
449 // TODO([email protected]): This should move to the beginning
450 // of the function. http://crbug.com/136655.
451 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28452
ssid3be5b1ec2016-01-13 14:21:57453 // Reseting acquires a lock to ensure no dump is happening on the database
454 // at the same time. Unregister takes ownership of provider and it is safe
455 // since the db is reset. memory_dump_provider_ could be null if db_ was
456 // poisoned.
457 if (memory_dump_provider_) {
458 memory_dump_provider_->ResetDatabase();
459 base::trace_event::MemoryDumpManager::GetInstance()
460 ->UnregisterAndDeleteDumpProviderSoon(
461 std::move(memory_dump_provider_));
462 }
463
[email protected]73fb8d52013-07-24 05:04:28464 int rc = sqlite3_close(db_);
465 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:18466 base::UmaHistogramSparse("Sqlite.CloseFailure", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52467 DLOG(DCHECK) << "sqlite3_close failed: " << GetErrorMessage();
[email protected]73fb8d52013-07-24 05:04:28468 }
[email protected]e5ffd0e42009-09-11 21:30:56469 }
[email protected]fed734a2013-07-17 04:45:13470 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56471}
472
[email protected]41a97c812013-02-07 02:35:38473void Connection::Close() {
474 // If the database was already closed by RazeAndClose(), then no
475 // need to close again. Clear the |poisoned_| bit so that incorrect
476 // API calls are caught.
477 if (poisoned_) {
478 poisoned_ = false;
479 return;
480 }
481
482 CloseInternal(false);
483}
484
[email protected]e5ffd0e42009-09-11 21:30:56485void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50486 AssertIOAllowed();
487
[email protected]e5ffd0e42009-09-11 21:30:56488 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52489 DCHECK(poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56490 return;
491 }
492
[email protected]8ada10f2013-12-21 00:42:34493 // Use local settings if provided, otherwise use documented defaults. The
494 // actual results could be fetching via PRAGMA calls.
495 const int page_size = page_size_ ? page_size_ : 1024;
496 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
497 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56498 return;
499
[email protected]8ada10f2013-12-21 00:42:34500 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34501 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42502 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34503 if (rc != SQLITE_OK)
504 return;
505
506 // Don't preload more than the file contains.
507 if (preload_size > file_size)
508 preload_size = file_size;
509
mostynbd82cd9952016-04-11 20:05:34510 std::unique_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46511 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34512 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31513
514 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34515 if (rc != SQLITE_OK)
516 return;
517 }
[email protected]e5ffd0e42009-09-11 21:30:56518}
519
shess7dbd4dee2015-10-06 17:39:16520// SQLite keeps unused pages associated with a connection in a cache. It asks
521// the cache for pages by an id, and if the page is present and the database is
522// unchanged, it considers the content of the page valid and doesn't read it
523// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
524// structures created from the memory map data before consulting the cache. On
525// write SQLite creates a new in-memory page structure, copies the data from the
526// memory map, and later writes it, releasing the updated page back to the
527// cache.
528//
529// This means that in memory-mapped mode, the contents of the cached pages are
530// not re-used for reads, but they are re-used for writes if the re-written page
531// is still in the cache. The implementation of sqlite3_db_release_memory() as
532// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
533// connection, so it should free these pages.
534//
535// Unfortunately, the zero page is also freed. That page is never accessed
536// using memory-mapped I/O, and the cached copy can be re-used after verifying
537// the file change counter on disk. Also, fresh pages from cache receive some
538// pager-level initialization before they can be used. Since the information
539// involved will immediately be accessed in various ways, it is unclear if the
540// additional overhead is material, or just moving processor cache effects
541// around.
542//
543// TODO(shess): It would be better to release the pages immediately when they
544// are no longer needed. This would basically happen after SQLite commits a
545// transaction. I had implemented a pcache wrapper to do this, but it involved
546// layering violations, and it had to be setup before any other sqlite call,
547// which was brittle. Also, for large files it would actually make sense to
548// maintain the existing pcache behavior for blocks past the memory-mapped
549// segment. I think drh would accept a reasonable implementation of the overall
550// concept for upstreaming to SQLite core.
551//
552// TODO(shess): Another possibility would be to set the cache size small, which
553// would keep the zero page around, plus some pre-initialized pages, and SQLite
554// can manage things. The downside is that updates larger than the cache would
555// spill to the journal. That could be compensated by setting cache_spill to
556// false. The downside then is that it allows open-ended use of memory for
557// large transactions.
558//
559// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
560// work. There could be two prepared statements, one for cache_size=1 one for
561// cache_size=goal.
562void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
shess644fc8a2016-02-26 18:15:58563 // The database could have been closed during a transaction as part of error
564 // recovery.
565 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:52566 DCHECK(poisoned_) << "Illegal use of connection without a db";
shess644fc8a2016-02-26 18:15:58567 return;
568 }
shess7dbd4dee2015-10-06 17:39:16569
570 // If memory-mapping is not enabled, the page cache helps performance.
571 if (!mmap_enabled_)
572 return;
573
574 // On caller request, force the change comparison to fail. Done before the
575 // transaction-nesting test so that the signal can carry to transaction
576 // commit.
577 if (implicit_change_performed)
578 --total_changes_at_last_release_;
579
580 // Cached pages may be re-used within the same transaction.
581 if (transaction_nesting())
582 return;
583
584 // If no changes have been made, skip flushing. This allows the first page of
585 // the database to remain in cache across multiple reads.
586 const int total_changes = sqlite3_total_changes(db_);
587 if (total_changes == total_changes_at_last_release_)
588 return;
589
590 total_changes_at_last_release_ = total_changes;
591 sqlite3_db_release_memory(db_);
592}
593
shessc8cd2a162015-10-22 20:30:46594base::FilePath Connection::DbPath() const {
595 if (!is_open())
596 return base::FilePath();
597
598 const char* path = sqlite3_db_filename(db_, "main");
599 const base::StringPiece db_path(path);
600#if defined(OS_WIN)
601 return base::FilePath(base::UTF8ToWide(db_path));
602#elif defined(OS_POSIX)
603 return base::FilePath(db_path);
604#else
605 NOTREACHED();
606 return base::FilePath();
607#endif
608}
609
610// Data is persisted in a file shared between databases in the same directory.
611// The "sqlite-diag" file contains a dictionary with the version number, and an
612// array of histogram tags for databases which have been dumped.
613bool Connection::RegisterIntentToUpload() const {
614 static const char* kVersionKey = "version";
615 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
616 static int kVersion = 1;
617
618 AssertIOAllowed();
619
620 if (histogram_tag_.empty())
621 return false;
622
623 if (!is_open())
624 return false;
625
626 if (in_memory_)
627 return false;
628
629 const base::FilePath db_path = DbPath();
630 if (db_path.empty())
631 return false;
632
633 // Put the collection of diagnostic data next to the databases. In most
634 // cases, this is the profile directory, but safe-browsing stores a Cookies
635 // file in the directory above the profile directory.
636 base::FilePath breadcrumb_path(
637 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
638
639 // Lock against multiple updates to the diagnostics file. This code should
640 // seldom be called in the first place, and when called it should seldom be
641 // called for multiple databases, and when called for multiple databases there
642 // is _probably_ something systemic wrong with the user's system. So the lock
643 // should never be contended, but when it is the database experience is
644 // already bad.
645 base::AutoLock lock(g_sqlite_init_lock.Get());
646
mostynbd82cd9952016-04-11 20:05:34647 std::unique_ptr<base::Value> root;
shessc8cd2a162015-10-22 20:30:46648 if (!base::PathExists(breadcrumb_path)) {
mostynbd82cd9952016-04-11 20:05:34649 std::unique_ptr<base::DictionaryValue> root_dict(
650 new base::DictionaryValue());
shessc8cd2a162015-10-22 20:30:46651 root_dict->SetInteger(kVersionKey, kVersion);
652
mostynbd82cd9952016-04-11 20:05:34653 std::unique_ptr<base::ListValue> dumps(new base::ListValue);
shessc8cd2a162015-10-22 20:30:46654 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50655 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46656
dchenge48600452015-12-28 02:24:50657 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46658 } else {
659 // Failure to read a valid dictionary implies that something is going wrong
660 // on the system.
661 JSONFileValueDeserializer deserializer(breadcrumb_path);
mostynbd82cd9952016-04-11 20:05:34662 std::unique_ptr<base::Value> read_root(
shessc8cd2a162015-10-22 20:30:46663 deserializer.Deserialize(nullptr, nullptr));
664 if (!read_root.get())
665 return false;
mostynbd82cd9952016-04-11 20:05:34666 std::unique_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50667 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46668 if (!root_dict)
669 return false;
670
671 // Don't upload if the version is missing or newer.
672 int version = 0;
673 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
674 return false;
675
676 base::ListValue* dumps = nullptr;
677 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
678 return false;
679
680 const size_t size = dumps->GetSize();
681 for (size_t i = 0; i < size; ++i) {
682 std::string s;
683
684 // Don't upload if the value isn't a string, or indicates a prior upload.
685 if (!dumps->GetString(i, &s) || s == histogram_tag_)
686 return false;
687 }
688
689 // Record intention to proceed with upload.
690 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50691 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46692 }
693
694 const base::FilePath breadcrumb_new =
695 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
696 base::DeleteFile(breadcrumb_new, false);
697
698 // No upload if the breadcrumb file cannot be updated.
699 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
700 // the data on disk. For now, losing the data is not a big problem, so the
701 // sync overhead would probably not be worth it.
702 JSONFileValueSerializer serializer(breadcrumb_new);
703 if (!serializer.Serialize(*root))
704 return false;
705 if (!base::PathExists(breadcrumb_new))
706 return false;
707 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
708 base::DeleteFile(breadcrumb_new, false);
709 return false;
710 }
711
712 return true;
713}
714
715std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
716 // Buffer for accumulating debugging info about the error. Place
717 // more-relevant information earlier, in case things overflow the
718 // fixed-size reporting buffer.
719 std::string debug_info;
720
721 // The error message from the failed operation.
722 base::StringAppendF(&debug_info, "db error: %d/%s\n",
723 GetErrorCode(), GetErrorMessage());
724
725 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
726 // reading code does not entirely convince me. Remove if they turn out to be
727 // the same.
728 if (error != GetErrorCode())
729 base::StringAppendF(&debug_info, "reported error: %d\n", error);
730
731 // System error information. Interpretation of Windows errors is different
732 // from posix.
733#if defined(OS_WIN)
734 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
735#elif defined(OS_POSIX)
736 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
737#else
738 NOTREACHED(); // Add appropriate log info.
739#endif
740
741 if (stmt) {
742 base::StringAppendF(&debug_info, "statement: %s\n",
743 stmt->GetSQLStatement());
744 } else {
745 base::StringAppendF(&debug_info, "statement: NULL\n");
746 }
747
748 // SQLITE_ERROR often indicates some sort of mismatch between the statement
749 // and the schema, possibly due to a failed schema migration.
750 if (error == SQLITE_ERROR) {
751 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
752 sqlite3_stmt* s;
753 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
754 if (rc == SQLITE_OK) {
755 rc = sqlite3_step(s);
756 if (rc == SQLITE_ROW) {
757 base::StringAppendF(&debug_info, "version: %d\n",
758 sqlite3_column_int(s, 0));
759 } else if (rc == SQLITE_DONE) {
760 debug_info += "version: none\n";
761 } else {
762 base::StringAppendF(&debug_info, "version: error %d\n", rc);
763 }
764 sqlite3_finalize(s);
765 } else {
766 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
767 }
768
769 debug_info += "schema:\n";
770
771 // sqlite_master has columns:
772 // type - "index" or "table".
773 // name - name of created element.
774 // tbl_name - name of element, or target table in case of index.
775 // rootpage - root page of the element in database file.
776 // sql - SQL to create the element.
777 // In general, the |sql| column is sufficient to derive the other columns.
778 // |rootpage| is not interesting for debugging, without the contents of the
779 // database. The COALESCE is because certain automatic elements will have a
780 // |name| but no |sql|,
781 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
782 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
783 if (rc == SQLITE_OK) {
784 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
785 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
786 }
787 if (rc != SQLITE_DONE)
788 base::StringAppendF(&debug_info, "error %d\n", rc);
789 sqlite3_finalize(s);
790 } else {
791 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
792 }
793 }
794
795 return debug_info;
796}
797
798// TODO(shess): Since this is only called in an error situation, it might be
799// prudent to rewrite in terms of SQLite API calls, and mark the function const.
800std::string Connection::CollectCorruptionInfo() {
801 AssertIOAllowed();
802
803 // If the file cannot be accessed it is unlikely that an integrity check will
804 // turn up actionable information.
805 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19806 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46807 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
808 return std::string();
809
810 // Buffer for accumulating debugging info about the error. Place
811 // more-relevant information earlier, in case things overflow the
812 // fixed-size reporting buffer.
813 std::string debug_info;
814 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
815 db_size);
816
817 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19818 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46819 if (db_size > kMaxIntegrityCheckSize) {
820 debug_info += "integrity_check skipped due to size\n";
821 } else {
822 std::vector<std::string> messages;
823
824 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
825 // into a string. Probably should be refactored.
826 const base::TimeTicks before = base::TimeTicks::Now();
827 FullIntegrityCheck(&messages);
828 base::StringAppendF(
829 &debug_info,
830 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
831 (base::TimeTicks::Now() - before).InMilliseconds(),
832 messages.size());
833
834 // SQLite returns up to 100 messages by default, trim deeper to
835 // keep close to the 2000-character size limit for dumping.
836 const size_t kMaxMessages = 20;
837 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
838 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
839 }
840 }
841
842 return debug_info;
843}
844
shessa62504d2016-11-07 19:26:12845bool Connection::GetMmapAltStatus(int64_t* status) {
846 // The [meta] version uses a missing table as a signal for a fresh database.
847 // That will not work for the view, which would not exist in either a new or
848 // an existing database. A new database _should_ be only one page long, so
849 // just don't bother optimizing this case (start at offset 0).
850 // TODO(shess): Could the [meta] case also get simpler, then?
851 if (!DoesViewExist("MmapStatus")) {
852 *status = 0;
853 return true;
854 }
855
856 const char* kMmapStatusSql = "SELECT * FROM MmapStatus";
857 Statement s(GetUniqueStatement(kMmapStatusSql));
858 if (s.Step())
859 *status = s.ColumnInt64(0);
860 return s.Succeeded();
861}
862
863bool Connection::SetMmapAltStatus(int64_t status) {
864 if (!BeginTransaction())
865 return false;
866
867 // View may not exist on first run.
868 if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
869 RollbackTransaction();
870 return false;
871 }
872
873 // Views live in the schema, so they cannot be parameterized. For an integer
874 // value, this construct should be safe from SQL injection, if the value
875 // becomes more complicated use "SELECT quote(?)" to generate a safe quoted
876 // value.
877 const std::string createViewSql =
878 base::StringPrintf("CREATE VIEW MmapStatus (value) AS SELECT %" PRId64,
879 status);
880 if (!Execute(createViewSql.c_str())) {
881 RollbackTransaction();
882 return false;
883 }
884
885 return CommitTransaction();
886}
887
shessd90aeea82015-11-13 02:24:31888size_t Connection::GetAppropriateMmapSize() {
889 AssertIOAllowed();
890
rohitrao83d6b83a2016-06-21 07:25:57891#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
892 if (!base::ios::IsRunningOnIOS10OrLater()) {
893 // iOS SQLite does not support memory mapping.
894 return 0;
895 }
shessd90aeea82015-11-13 02:24:31896#endif
897
shess9bf2c672015-12-18 01:18:08898 // How much to map if no errors are found. 50MB encompasses the 99th
899 // percentile of Chrome databases in the wild, so this should be good.
900 const size_t kMmapEverything = 256 * 1024 * 1024;
901
shessa62504d2016-11-07 19:26:12902 // Progress information is tracked in the [meta] table for databases which use
903 // sql::MetaTable, otherwise it is tracked in a special view.
904 // TODO(shess): Move all cases to the view implementation.
shess9bf2c672015-12-18 01:18:08905 int64_t mmap_ofs = 0;
shessa62504d2016-11-07 19:26:12906 if (mmap_alt_status_) {
907 if (!GetMmapAltStatus(&mmap_ofs)) {
908 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_READ);
909 return 0;
910 }
911 } else {
912 // If [meta] doesn't exist, yet, it's a new database, assume the best.
913 // sql::MetaTable::Init() will preload kMmapSuccess.
914 if (!MetaTable::DoesTableExist(this)) {
915 RecordOneEvent(EVENT_MMAP_META_MISSING);
916 return kMmapEverything;
917 }
918
919 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
920 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
921 return 0;
922 }
shessd90aeea82015-11-13 02:24:31923 }
924
925 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08926 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31927 RecordOneEvent(EVENT_MMAP_FAILED);
928 return 0;
shess9bf2c672015-12-18 01:18:08929 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31930 // Continue reading from previous offset.
931 DCHECK_GE(mmap_ofs, 0);
932
933 // TODO(shess): Could this reading code be shared with Preload()? It would
934 // require locking twice (this code wouldn't be able to access |db_size| so
935 // the helper would have to return amount read).
936
937 // Read more of the database looking for errors. The VFS interface is used
938 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
939 // to limit checking to 20MB per run of Chromium.
940 sqlite3_file* file = NULL;
941 sqlite3_int64 db_size = 0;
942 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
943 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
944 return 0;
945 }
946
947 // Read the data left, or |g_reads_allowed|, whichever is smaller.
948 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
949 // in a single Chromium run.
950 sqlite3_int64 amount = db_size - mmap_ofs;
951 if (amount < 0)
952 amount = 0;
953 if (amount > 0) {
954 base::AutoLock lock(g_sqlite_init_lock.Get());
955 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
956 if (g_reads_allowed < amount)
957 amount = g_reads_allowed;
958 g_reads_allowed -= amount;
959 }
960
961 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
962 // database was truncated after a previous pass.
963 if (amount <= 0 && mmap_ofs < db_size) {
964 DCHECK_EQ(0, amount);
965 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
966 } else {
967 static const int kPageSize = 4096;
968 char buf[kPageSize];
969 while (amount > 0) {
970 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
971 if (rc == SQLITE_OK) {
972 mmap_ofs += sizeof(buf);
973 amount -= sizeof(buf);
974 } else if (rc == SQLITE_IOERR_SHORT_READ) {
975 // Reached EOF for a database with page size < |kPageSize|.
976 mmap_ofs = db_size;
977 break;
978 } else {
979 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08980 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31981 break;
982 }
983 }
984
985 // Log these events after update to distinguish meta update failure.
986 Events event;
987 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08988 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31989 event = EVENT_MMAP_SUCCESS_NEW;
990 } else if (mmap_ofs > 0) {
991 event = EVENT_MMAP_SUCCESS_PARTIAL;
992 } else {
shess9bf2c672015-12-18 01:18:08993 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31994 event = EVENT_MMAP_FAILED_NEW;
995 }
996
shessa62504d2016-11-07 19:26:12997 if (mmap_alt_status_) {
998 if (!SetMmapAltStatus(mmap_ofs)) {
999 RecordOneEvent(EVENT_MMAP_STATUS_FAILURE_UPDATE);
1000 return 0;
1001 }
1002 } else {
1003 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
1004 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
1005 return 0;
1006 }
shessd90aeea82015-11-13 02:24:311007 }
1008
1009 RecordOneEvent(event);
1010 }
1011 }
1012
shess9bf2c672015-12-18 01:18:081013 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:311014 return 0;
shess9bf2c672015-12-18 01:18:081015 if (mmap_ofs == MetaTable::kMmapSuccess)
1016 return kMmapEverything;
shessd90aeea82015-11-13 02:24:311017 return mmap_ofs;
1018}
1019
[email protected]be7995f12013-07-18 18:49:141020void Connection::TrimMemory(bool aggressively) {
1021 if (!db_)
1022 return;
1023
1024 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1025 int original_cache_size;
1026 {
1027 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1028 if (!sql_get_original.Step()) {
1029 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1030 return;
1031 }
1032 original_cache_size = sql_get_original.ColumnInt(0);
1033 }
1034 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1035
1036 // Force sqlite to try to reduce page cache usage.
1037 const std::string sql_shrink =
1038 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1039 if (!Execute(sql_shrink.c_str()))
1040 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1041
1042 // Restore cache size.
1043 const std::string sql_restore =
1044 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1045 if (!Execute(sql_restore.c_str()))
1046 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1047}
1048
[email protected]8e0c01282012-04-06 19:36:491049// Create an in-memory database with the existing database's page
1050// size, then backup that database over the existing database.
1051bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501052 AssertIOAllowed();
1053
[email protected]8e0c01282012-04-06 19:36:491054 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521055 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491056 return false;
1057 }
1058
1059 if (transaction_nesting_ > 0) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521060 DLOG(DCHECK) << "Cannot raze within a transaction";
[email protected]8e0c01282012-04-06 19:36:491061 return false;
1062 }
1063
1064 sql::Connection null_db;
1065 if (!null_db.OpenInMemory()) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521066 DLOG(DCHECK) << "Unable to open in-memory database.";
[email protected]8e0c01282012-04-06 19:36:491067 return false;
1068 }
1069
[email protected]6d42f152012-11-10 00:38:241070 if (page_size_) {
1071 // Enforce SQLite restrictions on |page_size_|.
1072 DCHECK(!(page_size_ & (page_size_ - 1)))
1073 << " page_size_ " << page_size_ << " is not a power of two.";
1074 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1075 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041076 const std::string sql =
1077 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421078 if (!null_db.Execute(sql.c_str()))
1079 return false;
1080 }
1081
[email protected]6d42f152012-11-10 00:38:241082#if defined(OS_ANDROID)
1083 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1084 // in-memory databases do not respect this define.
1085 // TODO(shess): Figure out a way to set this without using platform
1086 // specific code. AFAICT from sqlite3.c, the only way to do it
1087 // would be to create an actual filesystem database, which is
1088 // unfortunate.
1089 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1090 return false;
1091#endif
[email protected]8e0c01282012-04-06 19:36:491092
1093 // The page size doesn't take effect until a database has pages, and
1094 // at this point the null database has none. Changing the schema
1095 // version will create the first page. This will not affect the
1096 // schema version in the resulting database, as SQLite's backup
1097 // implementation propagates the schema version from the original
1098 // connection to the new version of the database, incremented by one
1099 // so that other readers see the schema change and act accordingly.
1100 if (!null_db.Execute("PRAGMA schema_version = 1"))
1101 return false;
1102
[email protected]6d42f152012-11-10 00:38:241103 // SQLite tracks the expected number of database pages in the first
1104 // page, and if it does not match the total retrieved from a
1105 // filesystem call, treats the database as corrupt. This situation
1106 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1107 // used to hint to SQLite to soldier on in that case, specifically
1108 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1109 // sqlite3.c lockBtree().]
1110 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1111 // page_size" can be used to query such a database.
1112 ScopedWritableSchema writable_schema(db_);
1113
shess92a6fb22017-04-23 04:33:301114#if defined(OS_WIN)
1115 // On Windows, truncate silently fails when applied to memory-mapped files.
1116 // Disable memory-mapping so that the truncate succeeds. Note that other
1117 // connections may have memory-mapped the file, so this may not entirely
1118 // prevent the problem.
1119 // [Source: <https://sqlite.org/mmap.html> plus experiments.]
1120 ignore_result(Execute("PRAGMA mmap_size = 0"));
1121#endif
1122
[email protected]7bae5742013-07-10 20:46:161123 const char* kMain = "main";
1124 int rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181125 base::UmaHistogramSparse("Sqlite.RazeDatabase", rc);
[email protected]8e0c01282012-04-06 19:36:491126
1127 // The destination database was locked.
1128 if (rc == SQLITE_BUSY) {
1129 return false;
1130 }
1131
[email protected]7bae5742013-07-10 20:46:161132 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1133 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1134 // isn't even big enough for one page. Either way, reach in and
1135 // truncate it before trying again.
1136 // TODO(shess): Maybe it would be worthwhile to just truncate from
1137 // the get-go?
1138 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1139 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341140 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161141 if (rc != SQLITE_OK) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521142 DLOG(DCHECK) << "Failure getting file handle.";
[email protected]7bae5742013-07-10 20:46:161143 return false;
[email protected]7bae5742013-07-10 20:46:161144 }
1145
1146 rc = file->pMethods->xTruncate(file, 0);
1147 if (rc != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181148 base::UmaHistogramSparse("Sqlite.RazeDatabaseTruncate", rc);
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521149 DLOG(DCHECK) << "Failed to truncate file.";
[email protected]7bae5742013-07-10 20:46:161150 return false;
1151 }
1152
1153 rc = BackupDatabase(null_db.db_, db_, kMain);
Ilya Sherman1c811db2017-12-14 10:36:181154 base::UmaHistogramSparse("Sqlite.RazeDatabase2", rc);
[email protected]7bae5742013-07-10 20:46:161155
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521156 DCHECK_EQ(rc, SQLITE_DONE) << "Failed retrying Raze().";
[email protected]7bae5742013-07-10 20:46:161157 }
1158
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521159 // TODO(shess): Figure out which other cases can happen.
1160 DCHECK_EQ(rc, SQLITE_DONE) << "Unable to copy entire null database.";
1161
[email protected]8e0c01282012-04-06 19:36:491162 // The entire database should have been backed up.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521163 return rc == SQLITE_DONE;
[email protected]8e0c01282012-04-06 19:36:491164}
1165
[email protected]41a97c812013-02-07 02:35:381166bool Connection::RazeAndClose() {
1167 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521168 DCHECK(poisoned_) << "Cannot raze null db";
[email protected]41a97c812013-02-07 02:35:381169 return false;
1170 }
1171
1172 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301173 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381174
1175 bool result = Raze();
1176
1177 CloseInternal(true);
1178
1179 // Mark the database so that future API calls fail appropriately,
1180 // but don't DCHECK (because after calling this function they are
1181 // expected to fail).
1182 poisoned_ = true;
1183
1184 return result;
1185}
1186
[email protected]8d409412013-07-19 18:25:301187void Connection::Poison() {
1188 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521189 DCHECK(poisoned_) << "Cannot poison null db";
[email protected]8d409412013-07-19 18:25:301190 return;
1191 }
1192
1193 RollbackAllTransactions();
1194 CloseInternal(true);
1195
1196 // Mark the database so that future API calls fail appropriately,
1197 // but don't DCHECK (because after calling this function they are
1198 // expected to fail).
1199 poisoned_ = true;
1200}
1201
[email protected]8d2e39e2013-06-24 05:55:081202// TODO(shess): To the extent possible, figure out the optimal
1203// ordering for these deletes which will prevent other connections
1204// from seeing odd behavior. For instance, it may be necessary to
1205// manually lock the main database file in a SQLite-compatible fashion
1206// (to prevent other processes from opening it), then delete the
1207// journal files, then delete the main database file. Another option
1208// might be to lock the main database file and poison the header with
1209// junk to prevent other processes from opening it successfully (like
1210// Gears "SQLite poison 3" trick).
1211//
1212// static
1213bool Connection::Delete(const base::FilePath& path) {
Francois Doray66bdfd82017-10-20 13:50:371214 base::AssertBlockingAllowed();
[email protected]8d2e39e2013-06-24 05:55:081215
1216 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1217 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1218
erg102ceb412015-06-20 01:38:131219 std::string journal_str = AsUTF8ForSQL(journal_path);
1220 std::string wal_str = AsUTF8ForSQL(wal_path);
1221 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081222
shess702467622015-09-16 19:04:551223 // Make sure sqlite3_initialize() is called before anything else.
1224 InitializeSqlite();
1225
erg102ceb412015-06-20 01:38:131226 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1227 CHECK(vfs);
1228 CHECK(vfs->xDelete);
1229 CHECK(vfs->xAccess);
1230
1231 // We only work with unix, win32 and mojo filesystems. If you're trying to
1232 // use this code with any other VFS, you're not in a good place.
1233 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1234 strncmp(vfs->zName, "win32", 5) == 0 ||
1235 strcmp(vfs->zName, "mojo") == 0);
1236
1237 vfs->xDelete(vfs, journal_str.c_str(), 0);
1238 vfs->xDelete(vfs, wal_str.c_str(), 0);
1239 vfs->xDelete(vfs, path_str.c_str(), 0);
1240
1241 int journal_exists = 0;
1242 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1243 &journal_exists);
1244
1245 int wal_exists = 0;
1246 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1247 &wal_exists);
1248
1249 int path_exists = 0;
1250 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1251 &path_exists);
1252
1253 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081254}
1255
[email protected]e5ffd0e42009-09-11 21:30:561256bool Connection::BeginTransaction() {
1257 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331258 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561259
1260 // When we're going to rollback, fail on this begin and don't actually
1261 // mark us as entering the nested transaction.
1262 return false;
1263 }
1264
1265 bool success = true;
1266 if (!transaction_nesting_) {
1267 needs_rollback_ = false;
1268
1269 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321270 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591271 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561272 return false;
1273 }
1274 transaction_nesting_++;
1275 return success;
1276}
1277
1278void Connection::RollbackTransaction() {
1279 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521280 DCHECK(poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561281 return;
1282 }
1283
1284 transaction_nesting_--;
1285
1286 if (transaction_nesting_ > 0) {
1287 // Mark the outermost transaction as needing rollback.
1288 needs_rollback_ = true;
1289 return;
1290 }
1291
1292 DoRollback();
1293}
1294
1295bool Connection::CommitTransaction() {
1296 if (!transaction_nesting_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521297 DCHECK(poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561298 return false;
1299 }
1300 transaction_nesting_--;
1301
1302 if (transaction_nesting_ > 0) {
1303 // Mark any nested transactions as failing after we've already got one.
1304 return !needs_rollback_;
1305 }
1306
1307 if (needs_rollback_) {
1308 DoRollback();
1309 return false;
1310 }
1311
1312 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321313
1314 // Collect the commit time manually, sql::Statement would register it as query
1315 // time only.
1316 const base::TimeTicks before = Now();
1317 bool ret = commit.RunWithoutTimers();
1318 const base::TimeDelta delta = Now() - before;
1319
1320 RecordCommitTime(delta);
1321 RecordOneEvent(EVENT_COMMIT);
1322
shess7dbd4dee2015-10-06 17:39:161323 // Release dirty cache pages after the transaction closes.
1324 ReleaseCacheMemoryIfNeeded(false);
1325
shess58b8df82015-06-03 00:19:321326 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561327}
1328
[email protected]8d409412013-07-19 18:25:301329void Connection::RollbackAllTransactions() {
1330 if (transaction_nesting_ > 0) {
1331 transaction_nesting_ = 0;
1332 DoRollback();
1333 }
1334}
1335
1336bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1337 const char* attachment_point) {
1338 DCHECK(ValidAttachmentPoint(attachment_point));
1339
1340 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1341#if OS_WIN
1342 s.BindString16(0, other_db_path.value());
1343#else
1344 s.BindString(0, other_db_path.value());
1345#endif
1346 s.BindString(1, attachment_point);
1347 return s.Run();
1348}
1349
1350bool Connection::DetachDatabase(const char* attachment_point) {
1351 DCHECK(ValidAttachmentPoint(attachment_point));
1352
1353 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1354 s.BindString(0, attachment_point);
1355 return s.Run();
1356}
1357
shess58b8df82015-06-03 00:19:321358// TODO(shess): Consider changing this to execute exactly one statement. If a
1359// caller wishes to execute multiple statements, that should be explicit, and
1360// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591361int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501362 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381363 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521364 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381365 return SQLITE_ERROR;
1366 }
shess58b8df82015-06-03 00:19:321367 DCHECK(sql);
1368
1369 RecordOneEvent(EVENT_EXECUTE);
1370 int rc = SQLITE_OK;
1371 while ((rc == SQLITE_OK) && *sql) {
1372 sqlite3_stmt *stmt = NULL;
1373 const char *leftover_sql;
1374
1375 const base::TimeTicks before = Now();
1376 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1377 sql = leftover_sql;
1378
1379 // Stop if an error is encountered.
1380 if (rc != SQLITE_OK)
1381 break;
1382
1383 // This happens if |sql| originally only contained comments or whitespace.
1384 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1385 // extraneous comments and whitespace in the SQL statements increases
1386 // runtime cost and can easily be shifted out to the C++ layer.
1387 if (!stmt)
1388 continue;
1389
1390 // Save for use after statement is finalized.
1391 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1392
1393 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1394 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1395 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1396 // is the only legitimate case for this.
1397 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1398 }
1399
1400 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1401 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1402 rc = sqlite3_finalize(stmt);
1403 if (rc == SQLITE_OK)
1404 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1405
1406 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1407 // trailing whitespace.
1408 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021409 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321410 sql++;
1411 }
1412
1413 const base::TimeDelta delta = Now() - before;
1414 RecordTimeAndChanges(delta, read_only);
1415 }
shess7dbd4dee2015-10-06 17:39:161416
1417 // Most calls to Execute() modify the database. The main exceptions would be
1418 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1419 // but sometimes don't.
1420 ReleaseCacheMemoryIfNeeded(true);
1421
shess58b8df82015-06-03 00:19:321422 return rc;
[email protected]eff1fa522011-12-12 23:50:591423}
1424
1425bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381426 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521427 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381428 return false;
1429 }
1430
[email protected]eff1fa522011-12-12 23:50:591431 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001432 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581433 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001434
[email protected]28fe0ff2012-02-25 00:40:331435 // This needs to be a FATAL log because the error case of arriving here is
1436 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101437 // a change alters the schema but not all queries adjust. This can happen
1438 // in production if the schema is corrupted.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521439 DCHECK_NE(error, SQLITE_ERROR)
1440 << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591441 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561442}
1443
[email protected]5b96f3772010-09-28 16:30:571444bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381445 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521446 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571447 return false;
[email protected]41a97c812013-02-07 02:35:381448 }
[email protected]5b96f3772010-09-28 16:30:571449
1450 ScopedBusyTimeout busy_timeout(db_);
1451 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591452 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571453}
1454
[email protected]e5ffd0e42009-09-11 21:30:561455bool Connection::HasCachedStatement(const StatementID& id) const {
1456 return statement_cache_.find(id) != statement_cache_.end();
1457}
1458
1459scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1460 const StatementID& id,
1461 const char* sql) {
1462 CachedStatementMap::iterator i = statement_cache_.find(id);
1463 if (i != statement_cache_.end()) {
1464 // Statement is in the cache. It should still be active (we're the only
1465 // one invalidating cached statements, and we'll remove it from the cache
1466 // if we do that. Make sure we reset it before giving out the cached one in
1467 // case it still has some stuff bound.
1468 DCHECK(i->second->is_valid());
1469 sqlite3_reset(i->second->stmt());
1470 return i->second;
1471 }
1472
1473 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1474 if (statement->is_valid())
1475 statement_cache_[id] = statement; // Only cache valid statements.
1476 return statement;
1477}
1478
1479scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1480 const char* sql) {
shess9e77283d2016-06-13 23:53:201481 return GetStatementImpl(this, sql);
1482}
1483
1484scoped_refptr<Connection::StatementRef> Connection::GetStatementImpl(
1485 sql::Connection* tracking_db, const char* sql) const {
[email protected]35f7e5392012-07-27 19:54:501486 AssertIOAllowed();
shess9e77283d2016-06-13 23:53:201487 DCHECK(sql);
1488 DCHECK(!tracking_db || const_cast<Connection*>(tracking_db)==this);
[email protected]35f7e5392012-07-27 19:54:501489
[email protected]41a97c812013-02-07 02:35:381490 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561491 if (!db_)
[email protected]41a97c812013-02-07 02:35:381492 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561493
1494 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001495 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1496 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591497 // This is evidence of a syntax error in the incoming SQL.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521498 DCHECK_NE(rc, SQLITE_ERROR) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001499
1500 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581501 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381502 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561503 }
shess9e77283d2016-06-13 23:53:201504 return new StatementRef(tracking_db, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561505}
1506
[email protected]2eec0a22012-07-24 01:59:581507scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1508 const char* sql) const {
shess9e77283d2016-06-13 23:53:201509 return GetStatementImpl(NULL, sql);
[email protected]2eec0a22012-07-24 01:59:581510}
1511
[email protected]92cd00a2013-08-16 11:09:581512std::string Connection::GetSchema() const {
1513 // The ORDER BY should not be necessary, but relying on organic
1514 // order for something like this is questionable.
1515 const char* kSql =
1516 "SELECT type, name, tbl_name, sql "
1517 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1518 Statement statement(GetUntrackedStatement(kSql));
1519
1520 std::string schema;
1521 while (statement.Step()) {
1522 schema += statement.ColumnString(0);
1523 schema += '|';
1524 schema += statement.ColumnString(1);
1525 schema += '|';
1526 schema += statement.ColumnString(2);
1527 schema += '|';
1528 schema += statement.ColumnString(3);
1529 schema += '\n';
1530 }
1531
1532 return schema;
1533}
1534
[email protected]eff1fa522011-12-12 23:50:591535bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501536 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381537 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521538 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]41a97c812013-02-07 02:35:381539 return false;
1540 }
1541
[email protected]eff1fa522011-12-12 23:50:591542 sqlite3_stmt* stmt = NULL;
1543 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1544 return false;
1545
1546 sqlite3_finalize(stmt);
1547 return true;
1548}
1549
[email protected]e2cadec82011-12-13 02:00:531550bool Connection::DoesIndexExist(const char* index_name) const {
shessa62504d2016-11-07 19:26:121551 return DoesSchemaItemExist(index_name, "index");
[email protected]e2cadec82011-12-13 02:00:531552}
1553
shessa62504d2016-11-07 19:26:121554bool Connection::DoesTableExist(const char* table_name) const {
1555 return DoesSchemaItemExist(table_name, "table");
1556}
1557
1558bool Connection::DoesViewExist(const char* view_name) const {
1559 return DoesSchemaItemExist(view_name, "view");
1560}
1561
1562bool Connection::DoesSchemaItemExist(
[email protected]e2cadec82011-12-13 02:00:531563 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471564 const char* kSql =
1565 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581566 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471567
shess976814402016-06-21 06:56:251568 // This can happen if the database is corrupt and the error is a test
1569 // expectation.
shess92a2ab12015-04-09 01:59:471570 if (!statement.is_valid())
1571 return false;
1572
[email protected]e2cadec82011-12-13 02:00:531573 statement.BindString(0, type);
1574 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331575
[email protected]e5ffd0e42009-09-11 21:30:561576 return statement.Step(); // Table exists if any row was returned.
1577}
1578
1579bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171580 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561581 std::string sql("PRAGMA TABLE_INFO(");
1582 sql.append(table_name);
1583 sql.append(")");
1584
[email protected]2eec0a22012-07-24 01:59:581585 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471586
shess976814402016-06-21 06:56:251587 // This can happen if the database is corrupt and the error is a test
1588 // expectation.
shess92a2ab12015-04-09 01:59:471589 if (!statement.is_valid())
1590 return false;
1591
[email protected]e5ffd0e42009-09-11 21:30:561592 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331593 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1594 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561595 return true;
1596 }
1597 return false;
1598}
1599
tfarina720d4f32015-05-11 22:31:261600int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561601 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521602 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561603 return 0;
1604 }
1605 return sqlite3_last_insert_rowid(db_);
1606}
1607
[email protected]1ed78a32009-09-15 20:24:171608int Connection::GetLastChangeCount() const {
1609 if (!db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521610 DCHECK(poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171611 return 0;
1612 }
1613 return sqlite3_changes(db_);
1614}
1615
[email protected]e5ffd0e42009-09-11 21:30:561616int Connection::GetErrorCode() const {
1617 if (!db_)
1618 return SQLITE_ERROR;
1619 return sqlite3_errcode(db_);
1620}
1621
[email protected]767718e52010-09-21 23:18:491622int Connection::GetLastErrno() const {
1623 if (!db_)
1624 return -1;
1625
1626 int err = 0;
1627 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1628 return -2;
1629
1630 return err;
1631}
1632
[email protected]e5ffd0e42009-09-11 21:30:561633const char* Connection::GetErrorMessage() const {
1634 if (!db_)
1635 return "sql::Connection has no connection.";
1636 return sqlite3_errmsg(db_);
1637}
1638
[email protected]fed734a2013-07-17 04:45:131639bool Connection::OpenInternal(const std::string& file_name,
1640 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501641 AssertIOAllowed();
1642
[email protected]9cfbc922009-11-17 20:13:171643 if (db_) {
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521644 DLOG(DCHECK) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171645 return false;
1646 }
1647
[email protected]a7ec1292013-07-22 22:02:181648 // Make sure sqlite3_initialize() is called before anything else.
1649 InitializeSqlite();
1650
shess58b8df82015-06-03 00:19:321651 // Setup the stats histograms immediately rather than allocating lazily.
1652 // Connections which won't exercise all of these probably shouldn't exist.
1653 if (!histogram_tag_.empty()) {
1654 stats_histogram_ =
1655 base::LinearHistogram::FactoryGet(
1656 "Sqlite.Stats." + histogram_tag_,
1657 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1658 base::HistogramBase::kUmaTargetedHistogramFlag);
1659
1660 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1661 // unreasonable time for any single operation, so there is not much value to
1662 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1663 // things are entirely busted.
1664 commit_time_histogram_ =
1665 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1666
1667 autocommit_time_histogram_ =
1668 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1669
1670 update_time_histogram_ =
1671 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1672
1673 query_time_histogram_ =
1674 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1675 }
1676
[email protected]41a97c812013-02-07 02:35:381677 // If |poisoned_| is set, it means an error handler called
1678 // RazeAndClose(). Until regular Close() is called, the caller
1679 // should be treating the database as open, but is_open() currently
1680 // only considers the sqlite3 handle's state.
1681 // TODO(shess): Revise is_open() to consider poisoned_, and review
1682 // to see if any non-testing code even depends on it.
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521683 DCHECK(!poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161684 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381685
shess5f2c3442017-01-24 02:15:101686 // Custom memory-mapping VFS which reads pages using regular I/O on first hit.
1687 sqlite3_vfs* vfs = VFSWrapper();
1688 const char* vfs_name = (vfs ? vfs->zName : nullptr);
1689 int err = sqlite3_open_v2(file_name.c_str(), &db_,
1690 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
1691 vfs_name);
[email protected]765b44502009-10-02 05:01:421692 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281693 // Extended error codes cannot be enabled until a handle is
1694 // available, fetch manually.
1695 err = sqlite3_extended_errcode(db_);
1696
[email protected]bd2ccdb4a2012-12-07 22:14:501697 // Histogram failures specific to initial open for debugging
1698 // purposes.
Ilya Sherman1c811db2017-12-14 10:36:181699 base::UmaHistogramSparse("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501700
[email protected]2f496b42013-09-26 18:36:581701 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131702 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291703 Close();
[email protected]fed734a2013-07-17 04:45:131704
1705 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1706 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421707 return false;
1708 }
1709
[email protected]81a2a602013-07-17 19:10:361710 // TODO(shess): OS_WIN support?
Kevin Marshalla9f05ec2017-07-14 02:10:051711#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]81a2a602013-07-17 19:10:361712 if (restrict_to_user_) {
1713 DCHECK_NE(file_name, std::string(":memory"));
1714 base::FilePath file_path(file_name);
1715 int mode = 0;
1716 // TODO(shess): Arguably, failure to retrieve and change
1717 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081718 if (base::GetPosixFilePermissions(file_path, &mode)) {
1719 mode &= base::FILE_PERMISSION_USER_MASK;
1720 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361721
1722 // SQLite sets the permissions on these files from the main
1723 // database on create. Set them here in case they already exist
1724 // at this point. Failure to set these permissions should not
1725 // be fatal unless the file doesn't exist.
1726 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1727 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081728 base::SetPosixFilePermissions(journal_path, mode);
1729 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361730 }
1731 }
Kevin Marshalla9f05ec2017-07-14 02:10:051732#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]81a2a602013-07-17 19:10:361733
[email protected]affa2da2013-06-06 22:20:341734 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1735 // Chromium already depends on small mallocs being efficient, so we disable
1736 // this to avoid the extra memory overhead.
1737 // This must be called immediatly after opening the database before any SQL
1738 // statements are run.
1739 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1740
[email protected]73fb8d52013-07-24 05:04:281741 // Enable extended result codes to provide more color on I/O errors.
1742 // Not having extended result codes is not a fatal problem, as
1743 // Chromium code does not attempt to handle I/O errors anyhow. The
1744 // current implementation always returns SQLITE_OK, the DCHECK is to
1745 // quickly notify someone if SQLite changes.
1746 err = sqlite3_extended_result_codes(db_, 1);
1747 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1748
shessbccd300e2016-08-20 00:06:561749 // sqlite3_open() does not actually read the database file (unless a hot
1750 // journal is found). Successfully executing this pragma on an existing
1751 // database requires a valid header on page 1. ExecuteAndReturnErrorCode() to
1752 // get the error code before error callback (potentially) overwrites.
[email protected]bd2ccdb4a2012-12-07 22:14:501753 // TODO(shess): For now, just probing to see what the lay of the
1754 // land is. If it's mostly SQLITE_NOTADB, then the database should
1755 // be razed.
1756 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
shessbccd300e2016-08-20 00:06:561757 if (err != SQLITE_OK) {
Ilya Sherman1c811db2017-12-14 10:36:181758 base::UmaHistogramSparse("Sqlite.OpenProbeFailure", err);
shessbccd300e2016-08-20 00:06:561759 OnSqliteError(err, nullptr, "PRAGMA auto_vacuum");
1760
1761 // Retry or bail out if the error handler poisoned the handle.
1762 // TODO(shess): Move this handling to one place (see also sqlite3_open and
1763 // secure_delete). Possibly a wrapper function?
1764 if (poisoned_) {
1765 Close();
1766 if (retry_flag == RETRY_ON_POISON)
1767 return OpenInternal(file_name, NO_RETRY);
1768 return false;
1769 }
1770 }
[email protected]658f8332010-09-18 04:40:431771
[email protected]2e1cee762013-07-09 14:40:001772#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1773 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1774 // REGEXP support. Add it in dynamically.
1775 err = sqlite3IcuInit(db_);
1776 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1777#endif // OS_IOS && USE_SYSTEM_SQLITE
1778
[email protected]5b96f3772010-09-28 16:30:571779 // If indicated, lock up the database before doing anything else, so
1780 // that the following code doesn't have to deal with locking.
1781 // TODO(shess): This code is brittle. Find the cases where code
1782 // doesn't request |exclusive_locking_| and audit that it does the
1783 // right thing with SQLITE_BUSY, and that it doesn't make
1784 // assumptions about who might change things in the database.
1785 // http://crbug.com/56559
1786 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101787 // TODO(shess): This should probably be a failure. Code which
1788 // requests exclusive locking but doesn't get it is almost certain
1789 // to be ill-tested.
1790 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571791 }
1792
[email protected]4e179ba2012-03-17 16:06:471793 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1794 // DELETE (default) - delete -journal file to commit.
1795 // TRUNCATE - truncate -journal file to commit.
1796 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091797 // TRUNCATE should be faster than DELETE because it won't need directory
1798 // changes for each transaction. PERSIST may break the spirit of using
1799 // secure_delete.
1800 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471801
[email protected]c68ce172011-11-24 22:30:271802 const base::TimeDelta kBusyTimeout =
1803 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1804
[email protected]765b44502009-10-02 05:01:421805 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571806 // Enforce SQLite restrictions on |page_size_|.
1807 DCHECK(!(page_size_ & (page_size_ - 1)))
1808 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241809 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571810 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041811 const std::string sql =
1812 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101813 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421814 }
1815
1816 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041817 const std::string sql =
1818 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101819 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421820 }
1821
[email protected]6e0b1442011-08-09 23:23:581822 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131823 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581824 Close();
[email protected]fed734a2013-07-17 04:45:131825 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1826 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581827 return false;
1828 }
1829
shess5dac334f2015-11-05 20:47:421830 // Set a reasonable chunk size for larger files. This reduces churn from
1831 // remapping memory on size changes. It also reduces filesystem
1832 // fragmentation.
1833 // TODO(shess): It may make sense to have this be hinted by the client.
1834 // Database sizes seem to be bimodal, some clients have consistently small
1835 // databases (<20k) while other clients have a broad distribution of sizes
1836 // (hundreds of kilobytes to many megabytes).
1837 sqlite3_file* file = NULL;
1838 sqlite3_int64 db_size = 0;
1839 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1840 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1841 int chunk_size = 4 * 1024;
1842 if (db_size > 128 * 1024)
1843 chunk_size = 32 * 1024;
1844 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1845 }
1846
shess2f3a814b2015-11-05 18:11:101847 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311848 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1849 // safe range to memory-map based on past regular I/O. This value will be
1850 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1851 // 64-bit platforms.
1852 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1853 std::string mmap_sql =
1854 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1855 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101856
1857 // Determine if memory-mapping has actually been enabled. The Execute() above
1858 // can succeed without changing the amount mapped.
1859 mmap_enabled_ = false;
1860 {
1861 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1862 if (s.Step() && s.ColumnInt64(0) > 0)
1863 mmap_enabled_ = true;
1864 }
1865
ssid3be5b1ec2016-01-13 14:21:571866 DCHECK(!memory_dump_provider_);
1867 memory_dump_provider_.reset(
1868 new ConnectionMemoryDumpProvider(db_, histogram_tag_));
1869 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1870 memory_dump_provider_.get(), "sql::Connection", nullptr);
1871
[email protected]765b44502009-10-02 05:01:421872 return true;
1873}
1874
[email protected]e5ffd0e42009-09-11 21:30:561875void Connection::DoRollback() {
1876 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321877
1878 // Collect the rollback time manually, sql::Statement would register it as
1879 // query time only.
1880 const base::TimeTicks before = Now();
1881 rollback.RunWithoutTimers();
1882 const base::TimeDelta delta = Now() - before;
1883
1884 RecordUpdateTime(delta);
1885 RecordOneEvent(EVENT_ROLLBACK);
1886
shess7dbd4dee2015-10-06 17:39:161887 // The cache may have been accumulating dirty pages for commit. Note that in
1888 // some cases sql::Transaction can fire rollback after a database is closed.
1889 if (is_open())
1890 ReleaseCacheMemoryIfNeeded(false);
1891
[email protected]44ad7d902012-03-23 00:09:051892 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561893}
1894
1895void Connection::StatementRefCreated(StatementRef* ref) {
1896 DCHECK(open_statements_.find(ref) == open_statements_.end());
1897 open_statements_.insert(ref);
1898}
1899
1900void Connection::StatementRefDeleted(StatementRef* ref) {
1901 StatementRefSet::iterator i = open_statements_.find(ref);
1902 if (i == open_statements_.end())
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521903 DLOG(DCHECK) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561904 else
1905 open_statements_.erase(i);
1906}
1907
shess58b8df82015-06-03 00:19:321908void Connection::set_histogram_tag(const std::string& tag) {
1909 DCHECK(!is_open());
1910 histogram_tag_ = tag;
1911}
1912
[email protected]210ce0af2013-05-15 09:10:391913void Connection::AddTaggedHistogram(const std::string& name,
1914 size_t sample) const {
1915 if (histogram_tag_.empty())
1916 return;
1917
1918 // TODO(shess): The histogram macros create a bit of static storage
1919 // for caching the histogram object. This code shouldn't execute
1920 // often enough for such caching to be crucial. If it becomes an
1921 // issue, the object could be cached alongside histogram_prefix_.
1922 std::string full_histogram_name = name + "." + histogram_tag_;
1923 base::HistogramBase* histogram =
1924 base::SparseHistogram::FactoryGet(
1925 full_histogram_name,
1926 base::HistogramBase::kUmaTargetedHistogramFlag);
1927 if (histogram)
1928 histogram->Add(sample);
1929}
1930
shess9e77283d2016-06-13 23:53:201931int Connection::OnSqliteError(
1932 int err, sql::Statement *stmt, const char* sql) const {
Ilya Sherman1c811db2017-12-14 10:36:181933 base::UmaHistogramSparse("Sqlite.Error", err);
[email protected]210ce0af2013-05-15 09:10:391934 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141935
1936 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581937 if (!sql && stmt)
1938 sql = stmt->GetSQLStatement();
1939 if (!sql)
1940 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061941
1942 std::string id = histogram_tag_;
1943 if (id.empty())
1944 id = DbPath().BaseName().AsUTF8Unsafe();
1945 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141946 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581947 << ": " << GetErrorMessage()
1948 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141949
[email protected]c3881b372013-05-17 08:39:461950 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561951 // Fire from a copy of the callback in case of reentry into
1952 // re/set_error_callback().
1953 // TODO(shess): <http://crbug.com/254584>
1954 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461955 return err;
1956 }
1957
[email protected]faa604e2009-09-25 22:38:591958 // The default handling is to assert on debug and to ignore on release.
shess976814402016-06-21 06:56:251959 if (!IsExpectedSqliteError(err))
Sigurdur Asgeirsson8d82bd02017-09-25 21:05:521960 DLOG(DCHECK) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591961 return err;
1962}
1963
[email protected]579446c2013-12-16 18:36:521964bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1965 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1966}
1967
1968bool Connection::QuickIntegrityCheck() {
1969 std::vector<std::string> messages;
1970 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1971 return false;
1972 return messages.size() == 1 && messages[0] == "ok";
1973}
1974
afakhry7c9abe72016-08-05 17:33:191975std::string Connection::GetDiagnosticInfo(int extended_error,
1976 Statement* statement) {
1977 // Prevent reentrant calls to the error callback.
1978 ErrorCallback original_callback = std::move(error_callback_);
1979 reset_error_callback();
1980
1981 // Trim extended error codes.
1982 const int error = (extended_error & 0xFF);
1983 // CollectCorruptionInfo() is implemented in terms of sql::Connection,
1984 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
1985 std::string result = (error == SQLITE_CORRUPT)
1986 ? CollectCorruptionInfo()
1987 : CollectErrorInfo(extended_error, statement);
1988
1989 // The following queries must be executed after CollectErrorInfo() above, so
1990 // if they result in their own errors, they don't interfere with
1991 // CollectErrorInfo().
1992 const bool has_valid_header =
1993 (ExecuteAndReturnErrorCode("PRAGMA auto_vacuum") == SQLITE_OK);
1994 const bool select_sqlite_master_result =
1995 (ExecuteAndReturnErrorCode("SELECT COUNT(*) FROM sqlite_master") ==
1996 SQLITE_OK);
1997
1998 // Restore the original error callback.
1999 error_callback_ = std::move(original_callback);
2000
2001 base::StringAppendF(&result, "Has valid header: %s\n",
2002 (has_valid_header ? "Yes" : "No"));
2003 base::StringAppendF(&result, "Has valid schema: %s\n",
2004 (select_sqlite_master_result ? "Yes" : "No"));
2005
2006 return result;
2007}
2008
[email protected]80abf152013-05-22 12:42:422009// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:522010bool Connection::IntegrityCheckHelper(
2011 const char* pragma_sql,
2012 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:422013 messages->clear();
2014
[email protected]4658e2a02013-06-06 23:05:002015 // This has the side effect of setting SQLITE_RecoveryMode, which
2016 // allows SQLite to process through certain cases of corruption.
2017 // Failing to set this pragma probably means that the database is
2018 // beyond recovery.
2019 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
2020 if (!Execute(kWritableSchema))
2021 return false;
2022
2023 bool ret = false;
2024 {
[email protected]579446c2013-12-16 18:36:522025 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:002026
2027 // The pragma appears to return all results (up to 100 by default)
2028 // as a single string. This doesn't appear to be an API contract,
2029 // it could return separate lines, so loop _and_ split.
2030 while (stmt.Step()) {
2031 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:182032 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
2033 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:002034 }
2035 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:422036 }
[email protected]4658e2a02013-06-06 23:05:002037
2038 // Best effort to put things back as they were before.
2039 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
2040 ignore_result(Execute(kNoWritableSchema));
2041
2042 return ret;
[email protected]80abf152013-05-22 12:42:422043}
2044
ssid1f4e5362016-12-08 20:41:382045bool Connection::ReportMemoryUsage(base::trace_event::ProcessMemoryDump* pmd,
2046 const std::string& dump_name) {
dskibab4199f82016-11-21 20:16:132047 return memory_dump_provider_ &&
ssid1f4e5362016-12-08 20:41:382048 memory_dump_provider_->ReportMemoryUsage(pmd, dump_name);
dskibab4199f82016-11-21 20:16:132049}
2050
shess58b8df82015-06-03 00:19:322051base::TimeTicks TimeSource::Now() {
2052 return base::TimeTicks::Now();
2053}
2054
[email protected]e5ffd0e42009-09-11 21:30:562055} // namespace sql