blob: 3d584a65e11095a8e0c86becdcf16486fa3c306b [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
7#include <string.h>
8
shessc9e80ae22015-08-12 21:39:119#include "base/bind.h"
shessc8cd2a162015-10-22 20:30:4610#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5211#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4412#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4613#include "base/format_macros.h"
14#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1815#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5616#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1117#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5018#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3919#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4220#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1921#include "base/strings/string_util.h"
22#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4523#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1824#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0325#include "base/trace_event/memory_dump_manager.h"
26#include "base/trace_event/process_memory_dump.h"
[email protected]f0a54b22011-07-19 18:40:2127#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0328#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5629
[email protected]2e1cee762013-07-09 14:40:0030#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
31#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
32#endif
33
[email protected]5b96f3772010-09-28 16:30:5734namespace {
35
36// Spin for up to a second waiting for the lock to clear when setting
37// up the database.
38// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2739const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5740
41class ScopedBusyTimeout {
42 public:
43 explicit ScopedBusyTimeout(sqlite3* db)
44 : db_(db) {
45 }
46 ~ScopedBusyTimeout() {
47 sqlite3_busy_timeout(db_, 0);
48 }
49
50 int SetTimeout(base::TimeDelta timeout) {
51 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
52 return sqlite3_busy_timeout(db_,
53 static_cast<int>(timeout.InMilliseconds()));
54 }
55
56 private:
57 sqlite3* db_;
58};
59
[email protected]6d42f152012-11-10 00:38:2460// Helper to "safely" enable writable_schema. No error checking
61// because it is reasonable to just forge ahead in case of an error.
62// If turning it on fails, then most likely nothing will work, whereas
63// if turning it off fails, it only matters if some code attempts to
64// continue working with the database and tries to modify the
65// sqlite_master table (none of our code does this).
66class ScopedWritableSchema {
67 public:
68 explicit ScopedWritableSchema(sqlite3* db)
69 : db_(db) {
70 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
71 }
72 ~ScopedWritableSchema() {
73 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
74 }
75
76 private:
77 sqlite3* db_;
78};
79
[email protected]7bae5742013-07-10 20:46:1680// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
81// SQLite error code from running the backup step.
82int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
83 DCHECK_NE(src, dst);
84 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
85 if (!backup) {
86 // Since this call only sets things up, this indicates a gross
87 // error in SQLite.
88 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
89 return sqlite3_errcode(dst);
90 }
91
92 // -1 backs up the entire database.
93 int rc = sqlite3_backup_step(backup, -1);
94 int pages = sqlite3_backup_pagecount(backup);
95 sqlite3_backup_finish(backup);
96
97 // If successful, exactly one page should have been backed up. If
98 // this breaks, check this function to make sure assumptions aren't
99 // being broken.
100 if (rc == SQLITE_DONE)
101 DCHECK_EQ(pages, 1);
102
103 return rc;
104}
105
[email protected]8d409412013-07-19 18:25:30106// Be very strict on attachment point. SQLite can handle a much wider
107// character set with appropriate quoting, but Chromium code should
108// just use clean names to start with.
109bool ValidAttachmentPoint(const char* attachment_point) {
110 for (size_t i = 0; attachment_point[i]; ++i) {
111 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
112 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
113 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
114 attachment_point[i] == '_')) {
115 return false;
116 }
117 }
118 return true;
119}
120
shessc9e80ae22015-08-12 21:39:11121void RecordSqliteMemory10Min() {
122 const int64 used = sqlite3_memory_used();
123 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
124}
125
126void RecordSqliteMemoryHour() {
127 const int64 used = sqlite3_memory_used();
128 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
129}
130
131void RecordSqliteMemoryDay() {
132 const int64 used = sqlite3_memory_used();
133 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
134}
135
shess2d48e942015-08-25 17:39:51136void RecordSqliteMemoryWeek() {
137 const int64 used = sqlite3_memory_used();
138 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
139}
140
[email protected]a7ec1292013-07-22 22:02:18141// SQLite automatically calls sqlite3_initialize() lazily, but
142// sqlite3_initialize() uses double-checked locking and thus can have
143// data races.
144//
145// TODO(shess): Another alternative would be to have
146// sqlite3_initialize() called as part of process bring-up. If this
147// is changed, remove the dynamic_annotations dependency in sql.gyp.
148base::LazyInstance<base::Lock>::Leaky
149 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
150void InitializeSqlite() {
151 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11152 static bool first_call = true;
153 if (first_call) {
154 sqlite3_initialize();
155
156 // Schedule callback to record memory footprint histograms at 10m, 1h, and
157 // 1d. There may not be a message loop in tests.
158 if (base::MessageLoop::current()) {
159 base::MessageLoop::current()->PostDelayedTask(
160 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
161 base::TimeDelta::FromMinutes(10));
162 base::MessageLoop::current()->PostDelayedTask(
163 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
164 base::TimeDelta::FromHours(1));
165 base::MessageLoop::current()->PostDelayedTask(
166 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
167 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51168 base::MessageLoop::current()->PostDelayedTask(
169 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
170 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11171 }
172
173 first_call = false;
174 }
[email protected]a7ec1292013-07-22 22:02:18175}
176
[email protected]8ada10f2013-12-21 00:42:34177// Helper to get the sqlite3_file* associated with the "main" database.
178int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
179 *file = NULL;
180 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
181 if (rc != SQLITE_OK)
182 return rc;
183
184 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
185 // content_unittests, even though it should not be possible.
186 // http://crbug.com/329982
187 if (!*file || !(*file)->pMethods)
188 return SQLITE_ERROR;
189
190 return rc;
191}
192
shess5dac334f2015-11-05 20:47:42193// Convenience to get the sqlite3_file* and the size for the "main" database.
194int GetSqlite3FileAndSize(sqlite3* db,
195 sqlite3_file** file, sqlite3_int64* db_size) {
196 int rc = GetSqlite3File(db, file);
197 if (rc != SQLITE_OK)
198 return rc;
199
200 return (*file)->pMethods->xFileSize(*file, db_size);
201}
202
shess58b8df82015-06-03 00:19:32203// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
204base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
205 return base::Histogram::FactoryTimeGet(
206 name,
207 base::TimeDelta::FromMilliseconds(10),
208 base::TimeDelta::FromMinutes(3),
209 50,
210 base::HistogramBase::kUmaTargetedHistogramFlag);
211}
212
erg102ceb412015-06-20 01:38:13213std::string AsUTF8ForSQL(const base::FilePath& path) {
214#if defined(OS_WIN)
215 return base::WideToUTF8(path.value());
216#elif defined(OS_POSIX)
217 return path.value();
218#endif
219}
220
[email protected]5b96f3772010-09-28 16:30:57221} // namespace
222
[email protected]e5ffd0e42009-09-11 21:30:56223namespace sql {
224
[email protected]4350e322013-06-18 22:18:10225// static
226Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
227
228// static
[email protected]74cdede2013-09-25 05:39:57229bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10230 if (!current_ignorer_cb_)
231 return false;
232 return current_ignorer_cb_->Run(error);
233}
234
ssid9f8022f2015-10-12 17:49:03235bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
236 base::trace_event::ProcessMemoryDump* pmd) {
237 if (args.level_of_detail ==
238 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
239 !db_) {
240 return true;
241 }
242
243 // The high water mark is not tracked for the following usages.
244 int cache_size, dummy_int;
245 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
246 0 /* resetFlag */);
247 int schema_size;
248 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
249 0 /* resetFlag */);
250 int statement_size;
251 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
252 0 /* resetFlag */);
253
254 std::string name = base::StringPrintf(
255 "sqlite/%s_connection/%p",
256 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
257 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
258 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
259 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
260 cache_size + schema_size + statement_size);
261 dump->AddScalar("cache_size",
262 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
263 cache_size);
264 dump->AddScalar("schema_size",
265 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
266 schema_size);
267 dump->AddScalar("statement_size",
268 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
269 statement_size);
270 return true;
271}
272
shessc8cd2a162015-10-22 20:30:46273void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
274 AssertIOAllowed();
275
276 std::string debug_info;
277 const int error = (extended_error & 0xFF);
278 if (error == SQLITE_CORRUPT) {
279 debug_info = CollectCorruptionInfo();
280 } else {
281 debug_info = CollectErrorInfo(extended_error, stmt);
282 }
283
284 if (!debug_info.empty() && RegisterIntentToUpload()) {
285 char debug_buf[2000];
286 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
287 base::debug::Alias(&debug_buf);
288
289 base::debug::DumpWithoutCrashing();
290 }
291}
292
[email protected]4350e322013-06-18 22:18:10293// static
294void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
295 CHECK(current_ignorer_cb_ == NULL);
296 current_ignorer_cb_ = cb;
297}
298
299// static
300void Connection::ResetErrorIgnorer() {
301 CHECK(current_ignorer_cb_);
302 current_ignorer_cb_ = NULL;
303}
304
[email protected]e5ffd0e42009-09-11 21:30:56305bool StatementID::operator<(const StatementID& other) const {
306 if (number_ != other.number_)
307 return number_ < other.number_;
308 return strcmp(str_, other.str_) < 0;
309}
310
[email protected]e5ffd0e42009-09-11 21:30:56311Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38312 sqlite3_stmt* stmt,
313 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56314 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38315 stmt_(stmt),
316 was_valid_(was_valid) {
317 if (connection)
318 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56319}
320
321Connection::StatementRef::~StatementRef() {
322 if (connection_)
323 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38324 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56325}
326
[email protected]41a97c812013-02-07 02:35:38327void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56328 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50329 // Call to AssertIOAllowed() cannot go at the beginning of the function
330 // because Close() is called unconditionally from destructor to clean
331 // connection_. And if this is inactive statement this won't cause any
332 // disk access and destructor most probably will be called on thread
333 // not allowing disk access.
334 // TODO([email protected]): This should move to the beginning
335 // of the function. http://crbug.com/136655.
336 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56337 sqlite3_finalize(stmt_);
338 stmt_ = NULL;
339 }
340 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38341
342 // Forced close is expected to happen from a statement error
343 // handler. In that case maintain the sense of |was_valid_| which
344 // previously held for this ref.
345 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56346}
347
348Connection::Connection()
349 : db_(NULL),
350 page_size_(0),
351 cache_size_(0),
352 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36353 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56354 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50355 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16356 in_memory_(false),
shess58b8df82015-06-03 00:19:32357 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16358 mmap_disabled_(false),
359 mmap_enabled_(false),
360 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32361 stats_histogram_(NULL),
362 commit_time_histogram_(NULL),
363 autocommit_time_histogram_(NULL),
364 update_time_histogram_(NULL),
365 query_time_histogram_(NULL),
366 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03367 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40368 this, "sql::Connection", nullptr);
[email protected]526b4662013-06-14 04:09:12369}
[email protected]e5ffd0e42009-09-11 21:30:56370
371Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03372 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
373 this);
[email protected]e5ffd0e42009-09-11 21:30:56374 Close();
375}
376
shess58b8df82015-06-03 00:19:32377void Connection::RecordEvent(Events event, size_t count) {
378 for (size_t i = 0; i < count; ++i) {
379 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
380 }
381
382 if (stats_histogram_) {
383 for (size_t i = 0; i < count; ++i) {
384 stats_histogram_->Add(event);
385 }
386 }
387}
388
389void Connection::RecordCommitTime(const base::TimeDelta& delta) {
390 RecordUpdateTime(delta);
391 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
392 if (commit_time_histogram_)
393 commit_time_histogram_->AddTime(delta);
394}
395
396void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
397 RecordUpdateTime(delta);
398 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
399 if (autocommit_time_histogram_)
400 autocommit_time_histogram_->AddTime(delta);
401}
402
403void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
404 RecordQueryTime(delta);
405 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
406 if (update_time_histogram_)
407 update_time_histogram_->AddTime(delta);
408}
409
410void Connection::RecordQueryTime(const base::TimeDelta& delta) {
411 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
412 if (query_time_histogram_)
413 query_time_histogram_->AddTime(delta);
414}
415
416void Connection::RecordTimeAndChanges(
417 const base::TimeDelta& delta, bool read_only) {
418 if (read_only) {
419 RecordQueryTime(delta);
420 } else {
421 const int changes = sqlite3_changes(db_);
422 if (sqlite3_get_autocommit(db_)) {
423 RecordAutoCommitTime(delta);
424 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
425 } else {
426 RecordUpdateTime(delta);
427 RecordEvent(EVENT_CHANGES, changes);
428 }
429 }
430}
431
[email protected]a3ef4832013-02-02 05:12:33432bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02433 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26434 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49435 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02436 size_t sample = static_cast<size_t>(size_64 / 1024);
437 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
438 base::HistogramBase* histogram =
439 base::Histogram::FactoryGet(
440 full_histogram_name, 1, 1000000, 50,
441 base::HistogramBase::kUmaTargetedHistogramFlag);
442 if (histogram)
443 histogram->Add(sample);
444 }
445 }
446
erg102ceb412015-06-20 01:38:13447 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42448}
[email protected]e5ffd0e42009-09-11 21:30:56449
[email protected]765b44502009-10-02 05:01:42450bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50451 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13452 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56453}
454
[email protected]8d409412013-07-19 18:25:30455bool Connection::OpenTemporary() {
456 return OpenInternal("", NO_RETRY);
457}
458
[email protected]41a97c812013-02-07 02:35:38459void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47460 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
461 // will delete the -journal file. For ChromiumOS or other more
462 // embedded systems, this is probably not appropriate, whereas on
463 // desktop it might make some sense.
464
[email protected]4b350052012-02-24 20:40:48465 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48466
[email protected]41a97c812013-02-07 02:35:38467 // Release cached statements.
468 statement_cache_.clear();
469
470 // With cached statements released, in-use statements will remain.
471 // Closing the database while statements are in use is an API
472 // violation, except for forced close (which happens from within a
473 // statement's error handler).
474 DCHECK(forced || open_statements_.empty());
475
476 // Deactivate any outstanding statements so sqlite3_close() works.
477 for (StatementRefSet::iterator i = open_statements_.begin();
478 i != open_statements_.end(); ++i)
479 (*i)->Close(forced);
480 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48481
[email protected]e5ffd0e42009-09-11 21:30:56482 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50483 // Call to AssertIOAllowed() cannot go at the beginning of the function
484 // because Close() must be called from destructor to clean
485 // statement_cache_, it won't cause any disk access and it most probably
486 // will happen on thread not allowing disk access.
487 // TODO([email protected]): This should move to the beginning
488 // of the function. http://crbug.com/136655.
489 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28490
491 int rc = sqlite3_close(db_);
492 if (rc != SQLITE_OK) {
493 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
494 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
495 }
[email protected]e5ffd0e42009-09-11 21:30:56496 }
[email protected]fed734a2013-07-17 04:45:13497 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56498}
499
[email protected]41a97c812013-02-07 02:35:38500void Connection::Close() {
501 // If the database was already closed by RazeAndClose(), then no
502 // need to close again. Clear the |poisoned_| bit so that incorrect
503 // API calls are caught.
504 if (poisoned_) {
505 poisoned_ = false;
506 return;
507 }
508
509 CloseInternal(false);
510}
511
[email protected]e5ffd0e42009-09-11 21:30:56512void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50513 AssertIOAllowed();
514
[email protected]e5ffd0e42009-09-11 21:30:56515 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38516 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56517 return;
518 }
519
[email protected]8ada10f2013-12-21 00:42:34520 // Use local settings if provided, otherwise use documented defaults. The
521 // actual results could be fetching via PRAGMA calls.
522 const int page_size = page_size_ ? page_size_ : 1024;
523 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
524 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56525 return;
526
[email protected]8ada10f2013-12-21 00:42:34527 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34528 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42529 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34530 if (rc != SQLITE_OK)
531 return;
532
533 // Don't preload more than the file contains.
534 if (preload_size > file_size)
535 preload_size = file_size;
536
537 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46538 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34539 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
540 if (rc != SQLITE_OK)
541 return;
542 }
[email protected]e5ffd0e42009-09-11 21:30:56543}
544
shess7dbd4dee2015-10-06 17:39:16545// SQLite keeps unused pages associated with a connection in a cache. It asks
546// the cache for pages by an id, and if the page is present and the database is
547// unchanged, it considers the content of the page valid and doesn't read it
548// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
549// structures created from the memory map data before consulting the cache. On
550// write SQLite creates a new in-memory page structure, copies the data from the
551// memory map, and later writes it, releasing the updated page back to the
552// cache.
553//
554// This means that in memory-mapped mode, the contents of the cached pages are
555// not re-used for reads, but they are re-used for writes if the re-written page
556// is still in the cache. The implementation of sqlite3_db_release_memory() as
557// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
558// connection, so it should free these pages.
559//
560// Unfortunately, the zero page is also freed. That page is never accessed
561// using memory-mapped I/O, and the cached copy can be re-used after verifying
562// the file change counter on disk. Also, fresh pages from cache receive some
563// pager-level initialization before they can be used. Since the information
564// involved will immediately be accessed in various ways, it is unclear if the
565// additional overhead is material, or just moving processor cache effects
566// around.
567//
568// TODO(shess): It would be better to release the pages immediately when they
569// are no longer needed. This would basically happen after SQLite commits a
570// transaction. I had implemented a pcache wrapper to do this, but it involved
571// layering violations, and it had to be setup before any other sqlite call,
572// which was brittle. Also, for large files it would actually make sense to
573// maintain the existing pcache behavior for blocks past the memory-mapped
574// segment. I think drh would accept a reasonable implementation of the overall
575// concept for upstreaming to SQLite core.
576//
577// TODO(shess): Another possibility would be to set the cache size small, which
578// would keep the zero page around, plus some pre-initialized pages, and SQLite
579// can manage things. The downside is that updates larger than the cache would
580// spill to the journal. That could be compensated by setting cache_spill to
581// false. The downside then is that it allows open-ended use of memory for
582// large transactions.
583//
584// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
585// work. There could be two prepared statements, one for cache_size=1 one for
586// cache_size=goal.
587void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
588 DCHECK(is_open());
589
590 // If memory-mapping is not enabled, the page cache helps performance.
591 if (!mmap_enabled_)
592 return;
593
594 // On caller request, force the change comparison to fail. Done before the
595 // transaction-nesting test so that the signal can carry to transaction
596 // commit.
597 if (implicit_change_performed)
598 --total_changes_at_last_release_;
599
600 // Cached pages may be re-used within the same transaction.
601 if (transaction_nesting())
602 return;
603
604 // If no changes have been made, skip flushing. This allows the first page of
605 // the database to remain in cache across multiple reads.
606 const int total_changes = sqlite3_total_changes(db_);
607 if (total_changes == total_changes_at_last_release_)
608 return;
609
610 total_changes_at_last_release_ = total_changes;
611 sqlite3_db_release_memory(db_);
612}
613
shessc8cd2a162015-10-22 20:30:46614base::FilePath Connection::DbPath() const {
615 if (!is_open())
616 return base::FilePath();
617
618 const char* path = sqlite3_db_filename(db_, "main");
619 const base::StringPiece db_path(path);
620#if defined(OS_WIN)
621 return base::FilePath(base::UTF8ToWide(db_path));
622#elif defined(OS_POSIX)
623 return base::FilePath(db_path);
624#else
625 NOTREACHED();
626 return base::FilePath();
627#endif
628}
629
630// Data is persisted in a file shared between databases in the same directory.
631// The "sqlite-diag" file contains a dictionary with the version number, and an
632// array of histogram tags for databases which have been dumped.
633bool Connection::RegisterIntentToUpload() const {
634 static const char* kVersionKey = "version";
635 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
636 static int kVersion = 1;
637
638 AssertIOAllowed();
639
640 if (histogram_tag_.empty())
641 return false;
642
643 if (!is_open())
644 return false;
645
646 if (in_memory_)
647 return false;
648
649 const base::FilePath db_path = DbPath();
650 if (db_path.empty())
651 return false;
652
653 // Put the collection of diagnostic data next to the databases. In most
654 // cases, this is the profile directory, but safe-browsing stores a Cookies
655 // file in the directory above the profile directory.
656 base::FilePath breadcrumb_path(
657 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
658
659 // Lock against multiple updates to the diagnostics file. This code should
660 // seldom be called in the first place, and when called it should seldom be
661 // called for multiple databases, and when called for multiple databases there
662 // is _probably_ something systemic wrong with the user's system. So the lock
663 // should never be contended, but when it is the database experience is
664 // already bad.
665 base::AutoLock lock(g_sqlite_init_lock.Get());
666
667 scoped_ptr<base::Value> root;
668 if (!base::PathExists(breadcrumb_path)) {
669 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
670 root_dict->SetInteger(kVersionKey, kVersion);
671
672 scoped_ptr<base::ListValue> dumps(new base::ListValue);
673 dumps->AppendString(histogram_tag_);
674 root_dict->Set(kDiagnosticDumpsKey, dumps.Pass());
675
676 root = root_dict.Pass();
677 } else {
678 // Failure to read a valid dictionary implies that something is going wrong
679 // on the system.
680 JSONFileValueDeserializer deserializer(breadcrumb_path);
681 scoped_ptr<base::Value> read_root(
682 deserializer.Deserialize(nullptr, nullptr));
683 if (!read_root.get())
684 return false;
685 scoped_ptr<base::DictionaryValue> root_dict =
686 base::DictionaryValue::From(read_root.Pass());
687 if (!root_dict)
688 return false;
689
690 // Don't upload if the version is missing or newer.
691 int version = 0;
692 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
693 return false;
694
695 base::ListValue* dumps = nullptr;
696 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
697 return false;
698
699 const size_t size = dumps->GetSize();
700 for (size_t i = 0; i < size; ++i) {
701 std::string s;
702
703 // Don't upload if the value isn't a string, or indicates a prior upload.
704 if (!dumps->GetString(i, &s) || s == histogram_tag_)
705 return false;
706 }
707
708 // Record intention to proceed with upload.
709 dumps->AppendString(histogram_tag_);
710 root = root_dict.Pass();
711 }
712
713 const base::FilePath breadcrumb_new =
714 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
715 base::DeleteFile(breadcrumb_new, false);
716
717 // No upload if the breadcrumb file cannot be updated.
718 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
719 // the data on disk. For now, losing the data is not a big problem, so the
720 // sync overhead would probably not be worth it.
721 JSONFileValueSerializer serializer(breadcrumb_new);
722 if (!serializer.Serialize(*root))
723 return false;
724 if (!base::PathExists(breadcrumb_new))
725 return false;
726 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
727 base::DeleteFile(breadcrumb_new, false);
728 return false;
729 }
730
731 return true;
732}
733
734std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
735 // Buffer for accumulating debugging info about the error. Place
736 // more-relevant information earlier, in case things overflow the
737 // fixed-size reporting buffer.
738 std::string debug_info;
739
740 // The error message from the failed operation.
741 base::StringAppendF(&debug_info, "db error: %d/%s\n",
742 GetErrorCode(), GetErrorMessage());
743
744 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
745 // reading code does not entirely convince me. Remove if they turn out to be
746 // the same.
747 if (error != GetErrorCode())
748 base::StringAppendF(&debug_info, "reported error: %d\n", error);
749
750 // System error information. Interpretation of Windows errors is different
751 // from posix.
752#if defined(OS_WIN)
753 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
754#elif defined(OS_POSIX)
755 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
756#else
757 NOTREACHED(); // Add appropriate log info.
758#endif
759
760 if (stmt) {
761 base::StringAppendF(&debug_info, "statement: %s\n",
762 stmt->GetSQLStatement());
763 } else {
764 base::StringAppendF(&debug_info, "statement: NULL\n");
765 }
766
767 // SQLITE_ERROR often indicates some sort of mismatch between the statement
768 // and the schema, possibly due to a failed schema migration.
769 if (error == SQLITE_ERROR) {
770 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
771 sqlite3_stmt* s;
772 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
773 if (rc == SQLITE_OK) {
774 rc = sqlite3_step(s);
775 if (rc == SQLITE_ROW) {
776 base::StringAppendF(&debug_info, "version: %d\n",
777 sqlite3_column_int(s, 0));
778 } else if (rc == SQLITE_DONE) {
779 debug_info += "version: none\n";
780 } else {
781 base::StringAppendF(&debug_info, "version: error %d\n", rc);
782 }
783 sqlite3_finalize(s);
784 } else {
785 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
786 }
787
788 debug_info += "schema:\n";
789
790 // sqlite_master has columns:
791 // type - "index" or "table".
792 // name - name of created element.
793 // tbl_name - name of element, or target table in case of index.
794 // rootpage - root page of the element in database file.
795 // sql - SQL to create the element.
796 // In general, the |sql| column is sufficient to derive the other columns.
797 // |rootpage| is not interesting for debugging, without the contents of the
798 // database. The COALESCE is because certain automatic elements will have a
799 // |name| but no |sql|,
800 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
801 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
802 if (rc == SQLITE_OK) {
803 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
804 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
805 }
806 if (rc != SQLITE_DONE)
807 base::StringAppendF(&debug_info, "error %d\n", rc);
808 sqlite3_finalize(s);
809 } else {
810 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
811 }
812 }
813
814 return debug_info;
815}
816
817// TODO(shess): Since this is only called in an error situation, it might be
818// prudent to rewrite in terms of SQLite API calls, and mark the function const.
819std::string Connection::CollectCorruptionInfo() {
820 AssertIOAllowed();
821
822 // If the file cannot be accessed it is unlikely that an integrity check will
823 // turn up actionable information.
824 const base::FilePath db_path = DbPath();
825 int64 db_size = -1;
826 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
827 return std::string();
828
829 // Buffer for accumulating debugging info about the error. Place
830 // more-relevant information earlier, in case things overflow the
831 // fixed-size reporting buffer.
832 std::string debug_info;
833 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
834 db_size);
835
836 // Only check files up to 8M to keep things from blocking too long.
837 const int64 kMaxIntegrityCheckSize = 8192 * 1024;
838 if (db_size > kMaxIntegrityCheckSize) {
839 debug_info += "integrity_check skipped due to size\n";
840 } else {
841 std::vector<std::string> messages;
842
843 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
844 // into a string. Probably should be refactored.
845 const base::TimeTicks before = base::TimeTicks::Now();
846 FullIntegrityCheck(&messages);
847 base::StringAppendF(
848 &debug_info,
849 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
850 (base::TimeTicks::Now() - before).InMilliseconds(),
851 messages.size());
852
853 // SQLite returns up to 100 messages by default, trim deeper to
854 // keep close to the 2000-character size limit for dumping.
855 const size_t kMaxMessages = 20;
856 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
857 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
858 }
859 }
860
861 return debug_info;
862}
863
[email protected]be7995f12013-07-18 18:49:14864void Connection::TrimMemory(bool aggressively) {
865 if (!db_)
866 return;
867
868 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
869 int original_cache_size;
870 {
871 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
872 if (!sql_get_original.Step()) {
873 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
874 return;
875 }
876 original_cache_size = sql_get_original.ColumnInt(0);
877 }
878 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
879
880 // Force sqlite to try to reduce page cache usage.
881 const std::string sql_shrink =
882 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
883 if (!Execute(sql_shrink.c_str()))
884 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
885
886 // Restore cache size.
887 const std::string sql_restore =
888 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
889 if (!Execute(sql_restore.c_str()))
890 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
891}
892
[email protected]8e0c01282012-04-06 19:36:49893// Create an in-memory database with the existing database's page
894// size, then backup that database over the existing database.
895bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50896 AssertIOAllowed();
897
[email protected]8e0c01282012-04-06 19:36:49898 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38899 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49900 return false;
901 }
902
903 if (transaction_nesting_ > 0) {
904 DLOG(FATAL) << "Cannot raze within a transaction";
905 return false;
906 }
907
908 sql::Connection null_db;
909 if (!null_db.OpenInMemory()) {
910 DLOG(FATAL) << "Unable to open in-memory database.";
911 return false;
912 }
913
[email protected]6d42f152012-11-10 00:38:24914 if (page_size_) {
915 // Enforce SQLite restrictions on |page_size_|.
916 DCHECK(!(page_size_ & (page_size_ - 1)))
917 << " page_size_ " << page_size_ << " is not a power of two.";
918 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
919 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04920 const std::string sql =
921 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42922 if (!null_db.Execute(sql.c_str()))
923 return false;
924 }
925
[email protected]6d42f152012-11-10 00:38:24926#if defined(OS_ANDROID)
927 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
928 // in-memory databases do not respect this define.
929 // TODO(shess): Figure out a way to set this without using platform
930 // specific code. AFAICT from sqlite3.c, the only way to do it
931 // would be to create an actual filesystem database, which is
932 // unfortunate.
933 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
934 return false;
935#endif
[email protected]8e0c01282012-04-06 19:36:49936
937 // The page size doesn't take effect until a database has pages, and
938 // at this point the null database has none. Changing the schema
939 // version will create the first page. This will not affect the
940 // schema version in the resulting database, as SQLite's backup
941 // implementation propagates the schema version from the original
942 // connection to the new version of the database, incremented by one
943 // so that other readers see the schema change and act accordingly.
944 if (!null_db.Execute("PRAGMA schema_version = 1"))
945 return false;
946
[email protected]6d42f152012-11-10 00:38:24947 // SQLite tracks the expected number of database pages in the first
948 // page, and if it does not match the total retrieved from a
949 // filesystem call, treats the database as corrupt. This situation
950 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
951 // used to hint to SQLite to soldier on in that case, specifically
952 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
953 // sqlite3.c lockBtree().]
954 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
955 // page_size" can be used to query such a database.
956 ScopedWritableSchema writable_schema(db_);
957
[email protected]7bae5742013-07-10 20:46:16958 const char* kMain = "main";
959 int rc = BackupDatabase(null_db.db_, db_, kMain);
960 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:49961
962 // The destination database was locked.
963 if (rc == SQLITE_BUSY) {
964 return false;
965 }
966
[email protected]7bae5742013-07-10 20:46:16967 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
968 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
969 // isn't even big enough for one page. Either way, reach in and
970 // truncate it before trying again.
971 // TODO(shess): Maybe it would be worthwhile to just truncate from
972 // the get-go?
973 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
974 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34975 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:16976 if (rc != SQLITE_OK) {
977 DLOG(FATAL) << "Failure getting file handle.";
978 return false;
[email protected]7bae5742013-07-10 20:46:16979 }
980
981 rc = file->pMethods->xTruncate(file, 0);
982 if (rc != SQLITE_OK) {
983 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
984 DLOG(FATAL) << "Failed to truncate file.";
985 return false;
986 }
987
988 rc = BackupDatabase(null_db.db_, db_, kMain);
989 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
990
991 if (rc != SQLITE_DONE) {
992 DLOG(FATAL) << "Failed retrying Raze().";
993 }
994 }
995
[email protected]8e0c01282012-04-06 19:36:49996 // The entire database should have been backed up.
997 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:16998 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:49999 DLOG(FATAL) << "Unable to copy entire null database.";
1000 return false;
1001 }
1002
[email protected]8e0c01282012-04-06 19:36:491003 return true;
1004}
1005
1006bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1007 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381008 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491009 return false;
1010 }
1011
1012 ScopedBusyTimeout busy_timeout(db_);
1013 busy_timeout.SetTimeout(timeout);
1014 return Raze();
1015}
1016
[email protected]41a97c812013-02-07 02:35:381017bool Connection::RazeAndClose() {
1018 if (!db_) {
1019 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1020 return false;
1021 }
1022
1023 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301024 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381025
1026 bool result = Raze();
1027
1028 CloseInternal(true);
1029
1030 // Mark the database so that future API calls fail appropriately,
1031 // but don't DCHECK (because after calling this function they are
1032 // expected to fail).
1033 poisoned_ = true;
1034
1035 return result;
1036}
1037
[email protected]8d409412013-07-19 18:25:301038void Connection::Poison() {
1039 if (!db_) {
1040 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1041 return;
1042 }
1043
1044 RollbackAllTransactions();
1045 CloseInternal(true);
1046
1047 // Mark the database so that future API calls fail appropriately,
1048 // but don't DCHECK (because after calling this function they are
1049 // expected to fail).
1050 poisoned_ = true;
1051}
1052
[email protected]8d2e39e2013-06-24 05:55:081053// TODO(shess): To the extent possible, figure out the optimal
1054// ordering for these deletes which will prevent other connections
1055// from seeing odd behavior. For instance, it may be necessary to
1056// manually lock the main database file in a SQLite-compatible fashion
1057// (to prevent other processes from opening it), then delete the
1058// journal files, then delete the main database file. Another option
1059// might be to lock the main database file and poison the header with
1060// junk to prevent other processes from opening it successfully (like
1061// Gears "SQLite poison 3" trick).
1062//
1063// static
1064bool Connection::Delete(const base::FilePath& path) {
1065 base::ThreadRestrictions::AssertIOAllowed();
1066
1067 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1068 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1069
erg102ceb412015-06-20 01:38:131070 std::string journal_str = AsUTF8ForSQL(journal_path);
1071 std::string wal_str = AsUTF8ForSQL(wal_path);
1072 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081073
shess702467622015-09-16 19:04:551074 // Make sure sqlite3_initialize() is called before anything else.
1075 InitializeSqlite();
1076
erg102ceb412015-06-20 01:38:131077 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1078 CHECK(vfs);
1079 CHECK(vfs->xDelete);
1080 CHECK(vfs->xAccess);
1081
1082 // We only work with unix, win32 and mojo filesystems. If you're trying to
1083 // use this code with any other VFS, you're not in a good place.
1084 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1085 strncmp(vfs->zName, "win32", 5) == 0 ||
1086 strcmp(vfs->zName, "mojo") == 0);
1087
1088 vfs->xDelete(vfs, journal_str.c_str(), 0);
1089 vfs->xDelete(vfs, wal_str.c_str(), 0);
1090 vfs->xDelete(vfs, path_str.c_str(), 0);
1091
1092 int journal_exists = 0;
1093 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1094 &journal_exists);
1095
1096 int wal_exists = 0;
1097 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1098 &wal_exists);
1099
1100 int path_exists = 0;
1101 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1102 &path_exists);
1103
1104 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081105}
1106
[email protected]e5ffd0e42009-09-11 21:30:561107bool Connection::BeginTransaction() {
1108 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331109 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561110
1111 // When we're going to rollback, fail on this begin and don't actually
1112 // mark us as entering the nested transaction.
1113 return false;
1114 }
1115
1116 bool success = true;
1117 if (!transaction_nesting_) {
1118 needs_rollback_ = false;
1119
1120 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321121 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591122 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561123 return false;
1124 }
1125 transaction_nesting_++;
1126 return success;
1127}
1128
1129void Connection::RollbackTransaction() {
1130 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381131 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561132 return;
1133 }
1134
1135 transaction_nesting_--;
1136
1137 if (transaction_nesting_ > 0) {
1138 // Mark the outermost transaction as needing rollback.
1139 needs_rollback_ = true;
1140 return;
1141 }
1142
1143 DoRollback();
1144}
1145
1146bool Connection::CommitTransaction() {
1147 if (!transaction_nesting_) {
michaelndea7ae92015-10-28 22:43:031148 DLOG_IF(FATAL, !poisoned_) << "Committing back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561149 return false;
1150 }
1151 transaction_nesting_--;
1152
1153 if (transaction_nesting_ > 0) {
1154 // Mark any nested transactions as failing after we've already got one.
1155 return !needs_rollback_;
1156 }
1157
1158 if (needs_rollback_) {
1159 DoRollback();
1160 return false;
1161 }
1162
1163 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321164
1165 // Collect the commit time manually, sql::Statement would register it as query
1166 // time only.
1167 const base::TimeTicks before = Now();
1168 bool ret = commit.RunWithoutTimers();
1169 const base::TimeDelta delta = Now() - before;
1170
1171 RecordCommitTime(delta);
1172 RecordOneEvent(EVENT_COMMIT);
1173
shess7dbd4dee2015-10-06 17:39:161174 // Release dirty cache pages after the transaction closes.
1175 ReleaseCacheMemoryIfNeeded(false);
1176
shess58b8df82015-06-03 00:19:321177 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561178}
1179
[email protected]8d409412013-07-19 18:25:301180void Connection::RollbackAllTransactions() {
1181 if (transaction_nesting_ > 0) {
1182 transaction_nesting_ = 0;
1183 DoRollback();
1184 }
1185}
1186
1187bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1188 const char* attachment_point) {
1189 DCHECK(ValidAttachmentPoint(attachment_point));
1190
1191 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1192#if OS_WIN
1193 s.BindString16(0, other_db_path.value());
1194#else
1195 s.BindString(0, other_db_path.value());
1196#endif
1197 s.BindString(1, attachment_point);
1198 return s.Run();
1199}
1200
1201bool Connection::DetachDatabase(const char* attachment_point) {
1202 DCHECK(ValidAttachmentPoint(attachment_point));
1203
1204 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1205 s.BindString(0, attachment_point);
1206 return s.Run();
1207}
1208
shess58b8df82015-06-03 00:19:321209// TODO(shess): Consider changing this to execute exactly one statement. If a
1210// caller wishes to execute multiple statements, that should be explicit, and
1211// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591212int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501213 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381214 if (!db_) {
1215 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1216 return SQLITE_ERROR;
1217 }
shess58b8df82015-06-03 00:19:321218 DCHECK(sql);
1219
1220 RecordOneEvent(EVENT_EXECUTE);
1221 int rc = SQLITE_OK;
1222 while ((rc == SQLITE_OK) && *sql) {
1223 sqlite3_stmt *stmt = NULL;
1224 const char *leftover_sql;
1225
1226 const base::TimeTicks before = Now();
1227 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1228 sql = leftover_sql;
1229
1230 // Stop if an error is encountered.
1231 if (rc != SQLITE_OK)
1232 break;
1233
1234 // This happens if |sql| originally only contained comments or whitespace.
1235 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1236 // extraneous comments and whitespace in the SQL statements increases
1237 // runtime cost and can easily be shifted out to the C++ layer.
1238 if (!stmt)
1239 continue;
1240
1241 // Save for use after statement is finalized.
1242 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1243
1244 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1245 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1246 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1247 // is the only legitimate case for this.
1248 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1249 }
1250
1251 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1252 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1253 rc = sqlite3_finalize(stmt);
1254 if (rc == SQLITE_OK)
1255 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1256
1257 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1258 // trailing whitespace.
1259 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021260 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321261 sql++;
1262 }
1263
1264 const base::TimeDelta delta = Now() - before;
1265 RecordTimeAndChanges(delta, read_only);
1266 }
shess7dbd4dee2015-10-06 17:39:161267
1268 // Most calls to Execute() modify the database. The main exceptions would be
1269 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1270 // but sometimes don't.
1271 ReleaseCacheMemoryIfNeeded(true);
1272
shess58b8df82015-06-03 00:19:321273 return rc;
[email protected]eff1fa522011-12-12 23:50:591274}
1275
1276bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381277 if (!db_) {
1278 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1279 return false;
1280 }
1281
[email protected]eff1fa522011-12-12 23:50:591282 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001283 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581284 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001285
[email protected]28fe0ff2012-02-25 00:40:331286 // This needs to be a FATAL log because the error case of arriving here is
1287 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101288 // a change alters the schema but not all queries adjust. This can happen
1289 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591290 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331291 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591292 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561293}
1294
[email protected]5b96f3772010-09-28 16:30:571295bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381296 if (!db_) {
1297 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571298 return false;
[email protected]41a97c812013-02-07 02:35:381299 }
[email protected]5b96f3772010-09-28 16:30:571300
1301 ScopedBusyTimeout busy_timeout(db_);
1302 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591303 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571304}
1305
[email protected]e5ffd0e42009-09-11 21:30:561306bool Connection::HasCachedStatement(const StatementID& id) const {
1307 return statement_cache_.find(id) != statement_cache_.end();
1308}
1309
1310scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1311 const StatementID& id,
1312 const char* sql) {
1313 CachedStatementMap::iterator i = statement_cache_.find(id);
1314 if (i != statement_cache_.end()) {
1315 // Statement is in the cache. It should still be active (we're the only
1316 // one invalidating cached statements, and we'll remove it from the cache
1317 // if we do that. Make sure we reset it before giving out the cached one in
1318 // case it still has some stuff bound.
1319 DCHECK(i->second->is_valid());
1320 sqlite3_reset(i->second->stmt());
1321 return i->second;
1322 }
1323
1324 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1325 if (statement->is_valid())
1326 statement_cache_[id] = statement; // Only cache valid statements.
1327 return statement;
1328}
1329
1330scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1331 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501332 AssertIOAllowed();
1333
[email protected]41a97c812013-02-07 02:35:381334 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561335 if (!db_)
[email protected]41a97c812013-02-07 02:35:381336 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561337
1338 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001339 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1340 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591341 // This is evidence of a syntax error in the incoming SQL.
shess193bfb622015-04-10 22:30:021342 if (!ShouldIgnoreSqliteError(rc))
1343 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001344
1345 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581346 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381347 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561348 }
[email protected]41a97c812013-02-07 02:35:381349 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561350}
1351
[email protected]2eec0a22012-07-24 01:59:581352scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1353 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381354 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581355 if (!db_)
[email protected]41a97c812013-02-07 02:35:381356 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581357
1358 sqlite3_stmt* stmt = NULL;
1359 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1360 if (rc != SQLITE_OK) {
1361 // This is evidence of a syntax error in the incoming SQL.
shess193bfb622015-04-10 22:30:021362 if (!ShouldIgnoreSqliteError(rc))
1363 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381364 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581365 }
[email protected]41a97c812013-02-07 02:35:381366 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581367}
1368
[email protected]92cd00a2013-08-16 11:09:581369std::string Connection::GetSchema() const {
1370 // The ORDER BY should not be necessary, but relying on organic
1371 // order for something like this is questionable.
1372 const char* kSql =
1373 "SELECT type, name, tbl_name, sql "
1374 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1375 Statement statement(GetUntrackedStatement(kSql));
1376
1377 std::string schema;
1378 while (statement.Step()) {
1379 schema += statement.ColumnString(0);
1380 schema += '|';
1381 schema += statement.ColumnString(1);
1382 schema += '|';
1383 schema += statement.ColumnString(2);
1384 schema += '|';
1385 schema += statement.ColumnString(3);
1386 schema += '\n';
1387 }
1388
1389 return schema;
1390}
1391
[email protected]eff1fa522011-12-12 23:50:591392bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501393 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381394 if (!db_) {
1395 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1396 return false;
1397 }
1398
[email protected]eff1fa522011-12-12 23:50:591399 sqlite3_stmt* stmt = NULL;
1400 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1401 return false;
1402
1403 sqlite3_finalize(stmt);
1404 return true;
1405}
1406
[email protected]1ed78a32009-09-15 20:24:171407bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531408 return DoesTableOrIndexExist(table_name, "table");
1409}
1410
1411bool Connection::DoesIndexExist(const char* index_name) const {
1412 return DoesTableOrIndexExist(index_name, "index");
1413}
1414
1415bool Connection::DoesTableOrIndexExist(
1416 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471417 const char* kSql =
1418 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581419 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471420
1421 // This can happen if the database is corrupt and the error is being ignored
1422 // for testing purposes.
1423 if (!statement.is_valid())
1424 return false;
1425
[email protected]e2cadec82011-12-13 02:00:531426 statement.BindString(0, type);
1427 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331428
[email protected]e5ffd0e42009-09-11 21:30:561429 return statement.Step(); // Table exists if any row was returned.
1430}
1431
1432bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171433 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561434 std::string sql("PRAGMA TABLE_INFO(");
1435 sql.append(table_name);
1436 sql.append(")");
1437
[email protected]2eec0a22012-07-24 01:59:581438 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471439
1440 // This can happen if the database is corrupt and the error is being ignored
1441 // for testing purposes.
1442 if (!statement.is_valid())
1443 return false;
1444
[email protected]e5ffd0e42009-09-11 21:30:561445 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331446 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1447 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561448 return true;
1449 }
1450 return false;
1451}
1452
tfarina720d4f32015-05-11 22:31:261453int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561454 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381455 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561456 return 0;
1457 }
1458 return sqlite3_last_insert_rowid(db_);
1459}
1460
[email protected]1ed78a32009-09-15 20:24:171461int Connection::GetLastChangeCount() const {
1462 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381463 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171464 return 0;
1465 }
1466 return sqlite3_changes(db_);
1467}
1468
[email protected]e5ffd0e42009-09-11 21:30:561469int Connection::GetErrorCode() const {
1470 if (!db_)
1471 return SQLITE_ERROR;
1472 return sqlite3_errcode(db_);
1473}
1474
[email protected]767718e52010-09-21 23:18:491475int Connection::GetLastErrno() const {
1476 if (!db_)
1477 return -1;
1478
1479 int err = 0;
1480 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1481 return -2;
1482
1483 return err;
1484}
1485
[email protected]e5ffd0e42009-09-11 21:30:561486const char* Connection::GetErrorMessage() const {
1487 if (!db_)
1488 return "sql::Connection has no connection.";
1489 return sqlite3_errmsg(db_);
1490}
1491
[email protected]fed734a2013-07-17 04:45:131492bool Connection::OpenInternal(const std::string& file_name,
1493 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501494 AssertIOAllowed();
1495
[email protected]9cfbc922009-11-17 20:13:171496 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591497 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171498 return false;
1499 }
1500
[email protected]a7ec1292013-07-22 22:02:181501 // Make sure sqlite3_initialize() is called before anything else.
1502 InitializeSqlite();
1503
shess58b8df82015-06-03 00:19:321504 // Setup the stats histograms immediately rather than allocating lazily.
1505 // Connections which won't exercise all of these probably shouldn't exist.
1506 if (!histogram_tag_.empty()) {
1507 stats_histogram_ =
1508 base::LinearHistogram::FactoryGet(
1509 "Sqlite.Stats." + histogram_tag_,
1510 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1511 base::HistogramBase::kUmaTargetedHistogramFlag);
1512
1513 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1514 // unreasonable time for any single operation, so there is not much value to
1515 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1516 // things are entirely busted.
1517 commit_time_histogram_ =
1518 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1519
1520 autocommit_time_histogram_ =
1521 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1522
1523 update_time_histogram_ =
1524 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1525
1526 query_time_histogram_ =
1527 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1528 }
1529
[email protected]41a97c812013-02-07 02:35:381530 // If |poisoned_| is set, it means an error handler called
1531 // RazeAndClose(). Until regular Close() is called, the caller
1532 // should be treating the database as open, but is_open() currently
1533 // only considers the sqlite3 handle's state.
1534 // TODO(shess): Revise is_open() to consider poisoned_, and review
1535 // to see if any non-testing code even depends on it.
1536 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161537 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381538
[email protected]765b44502009-10-02 05:01:421539 int err = sqlite3_open(file_name.c_str(), &db_);
1540 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281541 // Extended error codes cannot be enabled until a handle is
1542 // available, fetch manually.
1543 err = sqlite3_extended_errcode(db_);
1544
[email protected]bd2ccdb4a2012-12-07 22:14:501545 // Histogram failures specific to initial open for debugging
1546 // purposes.
[email protected]73fb8d52013-07-24 05:04:281547 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501548
[email protected]2f496b42013-09-26 18:36:581549 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131550 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291551 Close();
[email protected]fed734a2013-07-17 04:45:131552
1553 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1554 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421555 return false;
1556 }
1557
[email protected]81a2a602013-07-17 19:10:361558 // TODO(shess): OS_WIN support?
1559#if defined(OS_POSIX)
1560 if (restrict_to_user_) {
1561 DCHECK_NE(file_name, std::string(":memory"));
1562 base::FilePath file_path(file_name);
1563 int mode = 0;
1564 // TODO(shess): Arguably, failure to retrieve and change
1565 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081566 if (base::GetPosixFilePermissions(file_path, &mode)) {
1567 mode &= base::FILE_PERMISSION_USER_MASK;
1568 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361569
1570 // SQLite sets the permissions on these files from the main
1571 // database on create. Set them here in case they already exist
1572 // at this point. Failure to set these permissions should not
1573 // be fatal unless the file doesn't exist.
1574 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1575 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081576 base::SetPosixFilePermissions(journal_path, mode);
1577 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361578 }
1579 }
1580#endif // defined(OS_POSIX)
1581
[email protected]affa2da2013-06-06 22:20:341582 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1583 // Chromium already depends on small mallocs being efficient, so we disable
1584 // this to avoid the extra memory overhead.
1585 // This must be called immediatly after opening the database before any SQL
1586 // statements are run.
1587 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1588
[email protected]73fb8d52013-07-24 05:04:281589 // Enable extended result codes to provide more color on I/O errors.
1590 // Not having extended result codes is not a fatal problem, as
1591 // Chromium code does not attempt to handle I/O errors anyhow. The
1592 // current implementation always returns SQLITE_OK, the DCHECK is to
1593 // quickly notify someone if SQLite changes.
1594 err = sqlite3_extended_result_codes(db_, 1);
1595 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1596
[email protected]bd2ccdb4a2012-12-07 22:14:501597 // sqlite3_open() does not actually read the database file (unless a
1598 // hot journal is found). Successfully executing this pragma on an
1599 // existing database requires a valid header on page 1.
1600 // TODO(shess): For now, just probing to see what the lay of the
1601 // land is. If it's mostly SQLITE_NOTADB, then the database should
1602 // be razed.
1603 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1604 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281605 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431606
[email protected]2e1cee762013-07-09 14:40:001607#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1608 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1609 // REGEXP support. Add it in dynamically.
1610 err = sqlite3IcuInit(db_);
1611 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1612#endif // OS_IOS && USE_SYSTEM_SQLITE
1613
[email protected]5b96f3772010-09-28 16:30:571614 // If indicated, lock up the database before doing anything else, so
1615 // that the following code doesn't have to deal with locking.
1616 // TODO(shess): This code is brittle. Find the cases where code
1617 // doesn't request |exclusive_locking_| and audit that it does the
1618 // right thing with SQLITE_BUSY, and that it doesn't make
1619 // assumptions about who might change things in the database.
1620 // http://crbug.com/56559
1621 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101622 // TODO(shess): This should probably be a failure. Code which
1623 // requests exclusive locking but doesn't get it is almost certain
1624 // to be ill-tested.
1625 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571626 }
1627
[email protected]4e179ba2012-03-17 16:06:471628 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1629 // DELETE (default) - delete -journal file to commit.
1630 // TRUNCATE - truncate -journal file to commit.
1631 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091632 // TRUNCATE should be faster than DELETE because it won't need directory
1633 // changes for each transaction. PERSIST may break the spirit of using
1634 // secure_delete.
1635 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471636
[email protected]c68ce172011-11-24 22:30:271637 const base::TimeDelta kBusyTimeout =
1638 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1639
[email protected]765b44502009-10-02 05:01:421640 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571641 // Enforce SQLite restrictions on |page_size_|.
1642 DCHECK(!(page_size_ & (page_size_ - 1)))
1643 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241644 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571645 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041646 const std::string sql =
1647 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101648 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421649 }
1650
1651 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041652 const std::string sql =
1653 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101654 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421655 }
1656
[email protected]6e0b1442011-08-09 23:23:581657 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131658 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581659 Close();
[email protected]fed734a2013-07-17 04:45:131660 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1661 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581662 return false;
1663 }
1664
shess5dac334f2015-11-05 20:47:421665 // Set a reasonable chunk size for larger files. This reduces churn from
1666 // remapping memory on size changes. It also reduces filesystem
1667 // fragmentation.
1668 // TODO(shess): It may make sense to have this be hinted by the client.
1669 // Database sizes seem to be bimodal, some clients have consistently small
1670 // databases (<20k) while other clients have a broad distribution of sizes
1671 // (hundreds of kilobytes to many megabytes).
1672 sqlite3_file* file = NULL;
1673 sqlite3_int64 db_size = 0;
1674 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1675 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1676 int chunk_size = 4 * 1024;
1677 if (db_size > 128 * 1024)
1678 chunk_size = 32 * 1024;
1679 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1680 }
1681
shess2f3a814b2015-11-05 18:11:101682 // Enable memory-mapped access. The explicit-disable case is because SQLite
1683 // can be built to default-enable mmap. This value will be capped by
1684 // SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and 64-bit
1685 // platforms.
1686 if (mmap_disabled_) {
1687 ignore_result(Execute("PRAGMA mmap_size = 0"));
1688 } else {
1689 ignore_result(Execute("PRAGMA mmap_size = 268435456")); // 256MB.
1690 }
1691
1692 // Determine if memory-mapping has actually been enabled. The Execute() above
1693 // can succeed without changing the amount mapped.
1694 mmap_enabled_ = false;
1695 {
1696 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1697 if (s.Step() && s.ColumnInt64(0) > 0)
1698 mmap_enabled_ = true;
1699 }
1700
[email protected]765b44502009-10-02 05:01:421701 return true;
1702}
1703
[email protected]e5ffd0e42009-09-11 21:30:561704void Connection::DoRollback() {
1705 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321706
1707 // Collect the rollback time manually, sql::Statement would register it as
1708 // query time only.
1709 const base::TimeTicks before = Now();
1710 rollback.RunWithoutTimers();
1711 const base::TimeDelta delta = Now() - before;
1712
1713 RecordUpdateTime(delta);
1714 RecordOneEvent(EVENT_ROLLBACK);
1715
shess7dbd4dee2015-10-06 17:39:161716 // The cache may have been accumulating dirty pages for commit. Note that in
1717 // some cases sql::Transaction can fire rollback after a database is closed.
1718 if (is_open())
1719 ReleaseCacheMemoryIfNeeded(false);
1720
[email protected]44ad7d902012-03-23 00:09:051721 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561722}
1723
1724void Connection::StatementRefCreated(StatementRef* ref) {
1725 DCHECK(open_statements_.find(ref) == open_statements_.end());
1726 open_statements_.insert(ref);
1727}
1728
1729void Connection::StatementRefDeleted(StatementRef* ref) {
1730 StatementRefSet::iterator i = open_statements_.find(ref);
1731 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591732 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561733 else
1734 open_statements_.erase(i);
1735}
1736
shess58b8df82015-06-03 00:19:321737void Connection::set_histogram_tag(const std::string& tag) {
1738 DCHECK(!is_open());
1739 histogram_tag_ = tag;
1740}
1741
[email protected]210ce0af2013-05-15 09:10:391742void Connection::AddTaggedHistogram(const std::string& name,
1743 size_t sample) const {
1744 if (histogram_tag_.empty())
1745 return;
1746
1747 // TODO(shess): The histogram macros create a bit of static storage
1748 // for caching the histogram object. This code shouldn't execute
1749 // often enough for such caching to be crucial. If it becomes an
1750 // issue, the object could be cached alongside histogram_prefix_.
1751 std::string full_histogram_name = name + "." + histogram_tag_;
1752 base::HistogramBase* histogram =
1753 base::SparseHistogram::FactoryGet(
1754 full_histogram_name,
1755 base::HistogramBase::kUmaTargetedHistogramFlag);
1756 if (histogram)
1757 histogram->Add(sample);
1758}
1759
[email protected]2f496b42013-09-26 18:36:581760int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391761 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1762 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141763
1764 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581765 if (!sql && stmt)
1766 sql = stmt->GetSQLStatement();
1767 if (!sql)
1768 sql = "-- unknown";
1769 LOG(ERROR) << histogram_tag_ << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141770 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581771 << ": " << GetErrorMessage()
1772 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141773
[email protected]c3881b372013-05-17 08:39:461774 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561775 // Fire from a copy of the callback in case of reentry into
1776 // re/set_error_callback().
1777 // TODO(shess): <http://crbug.com/254584>
1778 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461779 return err;
1780 }
1781
[email protected]faa604e2009-09-25 22:38:591782 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571783 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101784 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591785 return err;
1786}
1787
[email protected]579446c2013-12-16 18:36:521788bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1789 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1790}
1791
1792bool Connection::QuickIntegrityCheck() {
1793 std::vector<std::string> messages;
1794 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1795 return false;
1796 return messages.size() == 1 && messages[0] == "ok";
1797}
1798
[email protected]80abf152013-05-22 12:42:421799// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521800bool Connection::IntegrityCheckHelper(
1801 const char* pragma_sql,
1802 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421803 messages->clear();
1804
[email protected]4658e2a02013-06-06 23:05:001805 // This has the side effect of setting SQLITE_RecoveryMode, which
1806 // allows SQLite to process through certain cases of corruption.
1807 // Failing to set this pragma probably means that the database is
1808 // beyond recovery.
1809 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1810 if (!Execute(kWritableSchema))
1811 return false;
1812
1813 bool ret = false;
1814 {
[email protected]579446c2013-12-16 18:36:521815 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001816
1817 // The pragma appears to return all results (up to 100 by default)
1818 // as a single string. This doesn't appear to be an API contract,
1819 // it could return separate lines, so loop _and_ split.
1820 while (stmt.Step()) {
1821 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181822 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1823 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001824 }
1825 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421826 }
[email protected]4658e2a02013-06-06 23:05:001827
1828 // Best effort to put things back as they were before.
1829 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1830 ignore_result(Execute(kNoWritableSchema));
1831
1832 return ret;
[email protected]80abf152013-05-22 12:42:421833}
1834
shess58b8df82015-06-03 00:19:321835base::TimeTicks TimeSource::Now() {
1836 return base::TimeTicks::Now();
1837}
1838
[email protected]e5ffd0e42009-09-11 21:30:561839} // namespace sql