blob: 825d3192f0d147790fd294620489ff685531c6b7 [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
shessf7e988f2015-11-13 00:41:06235// static
236bool Connection::ShouldIgnoreSqliteCompileError(int error) {
237 // Put this first in case tests need to see that the check happened.
238 if (ShouldIgnoreSqliteError(error))
239 return true;
240
241 // Trim extended error codes.
242 int basic_error = error & 0xff;
243
244 // These errors relate more to the runtime context of the system than to
245 // errors with a SQL statement or with the schema, so they aren't generally
246 // interesting to flag. This list is not comprehensive.
247 return basic_error == SQLITE_BUSY ||
248 basic_error == SQLITE_NOTADB ||
249 basic_error == SQLITE_CORRUPT;
250}
251
ssid9f8022f2015-10-12 17:49:03252bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
253 base::trace_event::ProcessMemoryDump* pmd) {
254 if (args.level_of_detail ==
255 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
256 !db_) {
257 return true;
258 }
259
260 // The high water mark is not tracked for the following usages.
261 int cache_size, dummy_int;
262 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
263 0 /* resetFlag */);
264 int schema_size;
265 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
266 0 /* resetFlag */);
267 int statement_size;
268 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
269 0 /* resetFlag */);
270
271 std::string name = base::StringPrintf(
272 "sqlite/%s_connection/%p",
273 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
274 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
275 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
276 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
277 cache_size + schema_size + statement_size);
278 dump->AddScalar("cache_size",
279 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
280 cache_size);
281 dump->AddScalar("schema_size",
282 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
283 schema_size);
284 dump->AddScalar("statement_size",
285 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
286 statement_size);
287 return true;
288}
289
shessc8cd2a162015-10-22 20:30:46290void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
291 AssertIOAllowed();
292
293 std::string debug_info;
294 const int error = (extended_error & 0xFF);
295 if (error == SQLITE_CORRUPT) {
296 debug_info = CollectCorruptionInfo();
297 } else {
298 debug_info = CollectErrorInfo(extended_error, stmt);
299 }
300
301 if (!debug_info.empty() && RegisterIntentToUpload()) {
302 char debug_buf[2000];
303 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
304 base::debug::Alias(&debug_buf);
305
306 base::debug::DumpWithoutCrashing();
307 }
308}
309
[email protected]4350e322013-06-18 22:18:10310// static
311void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
312 CHECK(current_ignorer_cb_ == NULL);
313 current_ignorer_cb_ = cb;
314}
315
316// static
317void Connection::ResetErrorIgnorer() {
318 CHECK(current_ignorer_cb_);
319 current_ignorer_cb_ = NULL;
320}
321
[email protected]e5ffd0e42009-09-11 21:30:56322bool StatementID::operator<(const StatementID& other) const {
323 if (number_ != other.number_)
324 return number_ < other.number_;
325 return strcmp(str_, other.str_) < 0;
326}
327
[email protected]e5ffd0e42009-09-11 21:30:56328Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38329 sqlite3_stmt* stmt,
330 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56331 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38332 stmt_(stmt),
333 was_valid_(was_valid) {
334 if (connection)
335 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56336}
337
338Connection::StatementRef::~StatementRef() {
339 if (connection_)
340 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38341 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56342}
343
[email protected]41a97c812013-02-07 02:35:38344void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56345 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50346 // Call to AssertIOAllowed() cannot go at the beginning of the function
347 // because Close() is called unconditionally from destructor to clean
348 // connection_. And if this is inactive statement this won't cause any
349 // disk access and destructor most probably will be called on thread
350 // not allowing disk access.
351 // TODO([email protected]): This should move to the beginning
352 // of the function. http://crbug.com/136655.
353 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56354 sqlite3_finalize(stmt_);
355 stmt_ = NULL;
356 }
357 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38358
359 // Forced close is expected to happen from a statement error
360 // handler. In that case maintain the sense of |was_valid_| which
361 // previously held for this ref.
362 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56363}
364
365Connection::Connection()
366 : db_(NULL),
367 page_size_(0),
368 cache_size_(0),
369 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36370 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56371 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50372 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16373 in_memory_(false),
shess58b8df82015-06-03 00:19:32374 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16375 mmap_disabled_(false),
376 mmap_enabled_(false),
377 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32378 stats_histogram_(NULL),
379 commit_time_histogram_(NULL),
380 autocommit_time_histogram_(NULL),
381 update_time_histogram_(NULL),
382 query_time_histogram_(NULL),
383 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03384 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40385 this, "sql::Connection", nullptr);
[email protected]526b4662013-06-14 04:09:12386}
[email protected]e5ffd0e42009-09-11 21:30:56387
388Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03389 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
390 this);
[email protected]e5ffd0e42009-09-11 21:30:56391 Close();
392}
393
shess58b8df82015-06-03 00:19:32394void Connection::RecordEvent(Events event, size_t count) {
395 for (size_t i = 0; i < count; ++i) {
396 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
397 }
398
399 if (stats_histogram_) {
400 for (size_t i = 0; i < count; ++i) {
401 stats_histogram_->Add(event);
402 }
403 }
404}
405
406void Connection::RecordCommitTime(const base::TimeDelta& delta) {
407 RecordUpdateTime(delta);
408 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
409 if (commit_time_histogram_)
410 commit_time_histogram_->AddTime(delta);
411}
412
413void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
414 RecordUpdateTime(delta);
415 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
416 if (autocommit_time_histogram_)
417 autocommit_time_histogram_->AddTime(delta);
418}
419
420void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
421 RecordQueryTime(delta);
422 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
423 if (update_time_histogram_)
424 update_time_histogram_->AddTime(delta);
425}
426
427void Connection::RecordQueryTime(const base::TimeDelta& delta) {
428 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
429 if (query_time_histogram_)
430 query_time_histogram_->AddTime(delta);
431}
432
433void Connection::RecordTimeAndChanges(
434 const base::TimeDelta& delta, bool read_only) {
435 if (read_only) {
436 RecordQueryTime(delta);
437 } else {
438 const int changes = sqlite3_changes(db_);
439 if (sqlite3_get_autocommit(db_)) {
440 RecordAutoCommitTime(delta);
441 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
442 } else {
443 RecordUpdateTime(delta);
444 RecordEvent(EVENT_CHANGES, changes);
445 }
446 }
447}
448
[email protected]a3ef4832013-02-02 05:12:33449bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02450 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26451 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49452 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02453 size_t sample = static_cast<size_t>(size_64 / 1024);
454 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
455 base::HistogramBase* histogram =
456 base::Histogram::FactoryGet(
457 full_histogram_name, 1, 1000000, 50,
458 base::HistogramBase::kUmaTargetedHistogramFlag);
459 if (histogram)
460 histogram->Add(sample);
461 }
462 }
463
erg102ceb412015-06-20 01:38:13464 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42465}
[email protected]e5ffd0e42009-09-11 21:30:56466
[email protected]765b44502009-10-02 05:01:42467bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50468 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13469 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56470}
471
[email protected]8d409412013-07-19 18:25:30472bool Connection::OpenTemporary() {
473 return OpenInternal("", NO_RETRY);
474}
475
[email protected]41a97c812013-02-07 02:35:38476void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47477 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
478 // will delete the -journal file. For ChromiumOS or other more
479 // embedded systems, this is probably not appropriate, whereas on
480 // desktop it might make some sense.
481
[email protected]4b350052012-02-24 20:40:48482 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48483
[email protected]41a97c812013-02-07 02:35:38484 // Release cached statements.
485 statement_cache_.clear();
486
487 // With cached statements released, in-use statements will remain.
488 // Closing the database while statements are in use is an API
489 // violation, except for forced close (which happens from within a
490 // statement's error handler).
491 DCHECK(forced || open_statements_.empty());
492
493 // Deactivate any outstanding statements so sqlite3_close() works.
494 for (StatementRefSet::iterator i = open_statements_.begin();
495 i != open_statements_.end(); ++i)
496 (*i)->Close(forced);
497 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48498
[email protected]e5ffd0e42009-09-11 21:30:56499 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50500 // Call to AssertIOAllowed() cannot go at the beginning of the function
501 // because Close() must be called from destructor to clean
502 // statement_cache_, it won't cause any disk access and it most probably
503 // will happen on thread not allowing disk access.
504 // TODO([email protected]): This should move to the beginning
505 // of the function. http://crbug.com/136655.
506 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28507
508 int rc = sqlite3_close(db_);
509 if (rc != SQLITE_OK) {
510 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
511 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
512 }
[email protected]e5ffd0e42009-09-11 21:30:56513 }
[email protected]fed734a2013-07-17 04:45:13514 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56515}
516
[email protected]41a97c812013-02-07 02:35:38517void Connection::Close() {
518 // If the database was already closed by RazeAndClose(), then no
519 // need to close again. Clear the |poisoned_| bit so that incorrect
520 // API calls are caught.
521 if (poisoned_) {
522 poisoned_ = false;
523 return;
524 }
525
526 CloseInternal(false);
527}
528
[email protected]e5ffd0e42009-09-11 21:30:56529void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50530 AssertIOAllowed();
531
[email protected]e5ffd0e42009-09-11 21:30:56532 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38533 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56534 return;
535 }
536
[email protected]8ada10f2013-12-21 00:42:34537 // Use local settings if provided, otherwise use documented defaults. The
538 // actual results could be fetching via PRAGMA calls.
539 const int page_size = page_size_ ? page_size_ : 1024;
540 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
541 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56542 return;
543
[email protected]8ada10f2013-12-21 00:42:34544 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34545 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42546 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34547 if (rc != SQLITE_OK)
548 return;
549
550 // Don't preload more than the file contains.
551 if (preload_size > file_size)
552 preload_size = file_size;
553
554 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46555 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34556 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31557
558 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34559 if (rc != SQLITE_OK)
560 return;
561 }
[email protected]e5ffd0e42009-09-11 21:30:56562}
563
shess7dbd4dee2015-10-06 17:39:16564// SQLite keeps unused pages associated with a connection in a cache. It asks
565// the cache for pages by an id, and if the page is present and the database is
566// unchanged, it considers the content of the page valid and doesn't read it
567// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
568// structures created from the memory map data before consulting the cache. On
569// write SQLite creates a new in-memory page structure, copies the data from the
570// memory map, and later writes it, releasing the updated page back to the
571// cache.
572//
573// This means that in memory-mapped mode, the contents of the cached pages are
574// not re-used for reads, but they are re-used for writes if the re-written page
575// is still in the cache. The implementation of sqlite3_db_release_memory() as
576// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
577// connection, so it should free these pages.
578//
579// Unfortunately, the zero page is also freed. That page is never accessed
580// using memory-mapped I/O, and the cached copy can be re-used after verifying
581// the file change counter on disk. Also, fresh pages from cache receive some
582// pager-level initialization before they can be used. Since the information
583// involved will immediately be accessed in various ways, it is unclear if the
584// additional overhead is material, or just moving processor cache effects
585// around.
586//
587// TODO(shess): It would be better to release the pages immediately when they
588// are no longer needed. This would basically happen after SQLite commits a
589// transaction. I had implemented a pcache wrapper to do this, but it involved
590// layering violations, and it had to be setup before any other sqlite call,
591// which was brittle. Also, for large files it would actually make sense to
592// maintain the existing pcache behavior for blocks past the memory-mapped
593// segment. I think drh would accept a reasonable implementation of the overall
594// concept for upstreaming to SQLite core.
595//
596// TODO(shess): Another possibility would be to set the cache size small, which
597// would keep the zero page around, plus some pre-initialized pages, and SQLite
598// can manage things. The downside is that updates larger than the cache would
599// spill to the journal. That could be compensated by setting cache_spill to
600// false. The downside then is that it allows open-ended use of memory for
601// large transactions.
602//
603// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
604// work. There could be two prepared statements, one for cache_size=1 one for
605// cache_size=goal.
606void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
607 DCHECK(is_open());
608
609 // If memory-mapping is not enabled, the page cache helps performance.
610 if (!mmap_enabled_)
611 return;
612
613 // On caller request, force the change comparison to fail. Done before the
614 // transaction-nesting test so that the signal can carry to transaction
615 // commit.
616 if (implicit_change_performed)
617 --total_changes_at_last_release_;
618
619 // Cached pages may be re-used within the same transaction.
620 if (transaction_nesting())
621 return;
622
623 // If no changes have been made, skip flushing. This allows the first page of
624 // the database to remain in cache across multiple reads.
625 const int total_changes = sqlite3_total_changes(db_);
626 if (total_changes == total_changes_at_last_release_)
627 return;
628
629 total_changes_at_last_release_ = total_changes;
630 sqlite3_db_release_memory(db_);
631}
632
shessc8cd2a162015-10-22 20:30:46633base::FilePath Connection::DbPath() const {
634 if (!is_open())
635 return base::FilePath();
636
637 const char* path = sqlite3_db_filename(db_, "main");
638 const base::StringPiece db_path(path);
639#if defined(OS_WIN)
640 return base::FilePath(base::UTF8ToWide(db_path));
641#elif defined(OS_POSIX)
642 return base::FilePath(db_path);
643#else
644 NOTREACHED();
645 return base::FilePath();
646#endif
647}
648
649// Data is persisted in a file shared between databases in the same directory.
650// The "sqlite-diag" file contains a dictionary with the version number, and an
651// array of histogram tags for databases which have been dumped.
652bool Connection::RegisterIntentToUpload() const {
653 static const char* kVersionKey = "version";
654 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
655 static int kVersion = 1;
656
657 AssertIOAllowed();
658
659 if (histogram_tag_.empty())
660 return false;
661
662 if (!is_open())
663 return false;
664
665 if (in_memory_)
666 return false;
667
668 const base::FilePath db_path = DbPath();
669 if (db_path.empty())
670 return false;
671
672 // Put the collection of diagnostic data next to the databases. In most
673 // cases, this is the profile directory, but safe-browsing stores a Cookies
674 // file in the directory above the profile directory.
675 base::FilePath breadcrumb_path(
676 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
677
678 // Lock against multiple updates to the diagnostics file. This code should
679 // seldom be called in the first place, and when called it should seldom be
680 // called for multiple databases, and when called for multiple databases there
681 // is _probably_ something systemic wrong with the user's system. So the lock
682 // should never be contended, but when it is the database experience is
683 // already bad.
684 base::AutoLock lock(g_sqlite_init_lock.Get());
685
686 scoped_ptr<base::Value> root;
687 if (!base::PathExists(breadcrumb_path)) {
688 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
689 root_dict->SetInteger(kVersionKey, kVersion);
690
691 scoped_ptr<base::ListValue> dumps(new base::ListValue);
692 dumps->AppendString(histogram_tag_);
693 root_dict->Set(kDiagnosticDumpsKey, dumps.Pass());
694
695 root = root_dict.Pass();
696 } else {
697 // Failure to read a valid dictionary implies that something is going wrong
698 // on the system.
699 JSONFileValueDeserializer deserializer(breadcrumb_path);
700 scoped_ptr<base::Value> read_root(
701 deserializer.Deserialize(nullptr, nullptr));
702 if (!read_root.get())
703 return false;
704 scoped_ptr<base::DictionaryValue> root_dict =
705 base::DictionaryValue::From(read_root.Pass());
706 if (!root_dict)
707 return false;
708
709 // Don't upload if the version is missing or newer.
710 int version = 0;
711 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
712 return false;
713
714 base::ListValue* dumps = nullptr;
715 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
716 return false;
717
718 const size_t size = dumps->GetSize();
719 for (size_t i = 0; i < size; ++i) {
720 std::string s;
721
722 // Don't upload if the value isn't a string, or indicates a prior upload.
723 if (!dumps->GetString(i, &s) || s == histogram_tag_)
724 return false;
725 }
726
727 // Record intention to proceed with upload.
728 dumps->AppendString(histogram_tag_);
729 root = root_dict.Pass();
730 }
731
732 const base::FilePath breadcrumb_new =
733 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
734 base::DeleteFile(breadcrumb_new, false);
735
736 // No upload if the breadcrumb file cannot be updated.
737 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
738 // the data on disk. For now, losing the data is not a big problem, so the
739 // sync overhead would probably not be worth it.
740 JSONFileValueSerializer serializer(breadcrumb_new);
741 if (!serializer.Serialize(*root))
742 return false;
743 if (!base::PathExists(breadcrumb_new))
744 return false;
745 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
746 base::DeleteFile(breadcrumb_new, false);
747 return false;
748 }
749
750 return true;
751}
752
753std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
754 // Buffer for accumulating debugging info about the error. Place
755 // more-relevant information earlier, in case things overflow the
756 // fixed-size reporting buffer.
757 std::string debug_info;
758
759 // The error message from the failed operation.
760 base::StringAppendF(&debug_info, "db error: %d/%s\n",
761 GetErrorCode(), GetErrorMessage());
762
763 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
764 // reading code does not entirely convince me. Remove if they turn out to be
765 // the same.
766 if (error != GetErrorCode())
767 base::StringAppendF(&debug_info, "reported error: %d\n", error);
768
769 // System error information. Interpretation of Windows errors is different
770 // from posix.
771#if defined(OS_WIN)
772 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
773#elif defined(OS_POSIX)
774 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
775#else
776 NOTREACHED(); // Add appropriate log info.
777#endif
778
779 if (stmt) {
780 base::StringAppendF(&debug_info, "statement: %s\n",
781 stmt->GetSQLStatement());
782 } else {
783 base::StringAppendF(&debug_info, "statement: NULL\n");
784 }
785
786 // SQLITE_ERROR often indicates some sort of mismatch between the statement
787 // and the schema, possibly due to a failed schema migration.
788 if (error == SQLITE_ERROR) {
789 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
790 sqlite3_stmt* s;
791 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
792 if (rc == SQLITE_OK) {
793 rc = sqlite3_step(s);
794 if (rc == SQLITE_ROW) {
795 base::StringAppendF(&debug_info, "version: %d\n",
796 sqlite3_column_int(s, 0));
797 } else if (rc == SQLITE_DONE) {
798 debug_info += "version: none\n";
799 } else {
800 base::StringAppendF(&debug_info, "version: error %d\n", rc);
801 }
802 sqlite3_finalize(s);
803 } else {
804 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
805 }
806
807 debug_info += "schema:\n";
808
809 // sqlite_master has columns:
810 // type - "index" or "table".
811 // name - name of created element.
812 // tbl_name - name of element, or target table in case of index.
813 // rootpage - root page of the element in database file.
814 // sql - SQL to create the element.
815 // In general, the |sql| column is sufficient to derive the other columns.
816 // |rootpage| is not interesting for debugging, without the contents of the
817 // database. The COALESCE is because certain automatic elements will have a
818 // |name| but no |sql|,
819 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
820 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
821 if (rc == SQLITE_OK) {
822 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
823 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
824 }
825 if (rc != SQLITE_DONE)
826 base::StringAppendF(&debug_info, "error %d\n", rc);
827 sqlite3_finalize(s);
828 } else {
829 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
830 }
831 }
832
833 return debug_info;
834}
835
836// TODO(shess): Since this is only called in an error situation, it might be
837// prudent to rewrite in terms of SQLite API calls, and mark the function const.
838std::string Connection::CollectCorruptionInfo() {
839 AssertIOAllowed();
840
841 // If the file cannot be accessed it is unlikely that an integrity check will
842 // turn up actionable information.
843 const base::FilePath db_path = DbPath();
844 int64 db_size = -1;
845 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
846 return std::string();
847
848 // Buffer for accumulating debugging info about the error. Place
849 // more-relevant information earlier, in case things overflow the
850 // fixed-size reporting buffer.
851 std::string debug_info;
852 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
853 db_size);
854
855 // Only check files up to 8M to keep things from blocking too long.
856 const int64 kMaxIntegrityCheckSize = 8192 * 1024;
857 if (db_size > kMaxIntegrityCheckSize) {
858 debug_info += "integrity_check skipped due to size\n";
859 } else {
860 std::vector<std::string> messages;
861
862 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
863 // into a string. Probably should be refactored.
864 const base::TimeTicks before = base::TimeTicks::Now();
865 FullIntegrityCheck(&messages);
866 base::StringAppendF(
867 &debug_info,
868 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
869 (base::TimeTicks::Now() - before).InMilliseconds(),
870 messages.size());
871
872 // SQLite returns up to 100 messages by default, trim deeper to
873 // keep close to the 2000-character size limit for dumping.
874 const size_t kMaxMessages = 20;
875 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
876 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
877 }
878 }
879
880 return debug_info;
881}
882
shessd90aeea82015-11-13 02:24:31883size_t Connection::GetAppropriateMmapSize() {
884 AssertIOAllowed();
885
886 // TODO(shess): Using sql::MetaTable seems indicated, but mixing
887 // sql::MetaTable and direct access seems error-prone. It might make sense to
888 // simply integrate sql::MetaTable functionality into sql::Connection.
889
890#if defined(OS_IOS)
891 // iOS SQLite does not support memory mapping.
892 return 0;
893#endif
894
895 // If the database doesn't have a place to track progress, assume the worst.
896 // This will happen when new databases are created.
897 if (!DoesTableExist("meta")) {
898 RecordOneEvent(EVENT_MMAP_META_MISSING);
899 return 0;
900 }
901
902 // Key into meta table to get status from a previous run. The value
903 // represents how much data in bytes has successfully been read from the
904 // database. |kMmapFailure| indicates that there was a read error and the
905 // database should not be memory-mapped, while |kMmapSuccess| indicates that
906 // the entire file was read at some point and can be memory-mapped without
907 // constraint.
908 const char* kMmapStatusKey = "mmap_status";
909 static const sqlite3_int64 kMmapFailure = -2;
910 static const sqlite3_int64 kMmapSuccess = -1;
911
912 // Start reading from 0 unless status is found in meta table.
913 sqlite3_int64 mmap_ofs = 0;
914
915 // Retrieve the current status. It is fine for the status to be missing
916 // entirely, but any error prevents memory-mapping.
917 {
918 const char* kMmapStatusSql = "SELECT value FROM meta WHERE key = ?";
919 Statement s(GetUniqueStatement(kMmapStatusSql));
920 s.BindString(0, kMmapStatusKey);
921 if (s.Step()) {
922 mmap_ofs = s.ColumnInt64(0);
923 } else if (!s.Succeeded()) {
924 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
925 return 0;
926 }
927 }
928
929 // Database read failed in the past, don't memory map.
930 if (mmap_ofs == kMmapFailure) {
931 RecordOneEvent(EVENT_MMAP_FAILED);
932 return 0;
933 } else if (mmap_ofs != kMmapSuccess) {
934 // Continue reading from previous offset.
935 DCHECK_GE(mmap_ofs, 0);
936
937 // TODO(shess): Could this reading code be shared with Preload()? It would
938 // require locking twice (this code wouldn't be able to access |db_size| so
939 // the helper would have to return amount read).
940
941 // Read more of the database looking for errors. The VFS interface is used
942 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
943 // to limit checking to 20MB per run of Chromium.
944 sqlite3_file* file = NULL;
945 sqlite3_int64 db_size = 0;
946 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
947 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
948 return 0;
949 }
950
951 // Read the data left, or |g_reads_allowed|, whichever is smaller.
952 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
953 // in a single Chromium run.
954 sqlite3_int64 amount = db_size - mmap_ofs;
955 if (amount < 0)
956 amount = 0;
957 if (amount > 0) {
958 base::AutoLock lock(g_sqlite_init_lock.Get());
959 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
960 if (g_reads_allowed < amount)
961 amount = g_reads_allowed;
962 g_reads_allowed -= amount;
963 }
964
965 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
966 // database was truncated after a previous pass.
967 if (amount <= 0 && mmap_ofs < db_size) {
968 DCHECK_EQ(0, amount);
969 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
970 } else {
971 static const int kPageSize = 4096;
972 char buf[kPageSize];
973 while (amount > 0) {
974 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
975 if (rc == SQLITE_OK) {
976 mmap_ofs += sizeof(buf);
977 amount -= sizeof(buf);
978 } else if (rc == SQLITE_IOERR_SHORT_READ) {
979 // Reached EOF for a database with page size < |kPageSize|.
980 mmap_ofs = db_size;
981 break;
982 } else {
983 // TODO(shess): Consider calling OnSqliteError().
984 mmap_ofs = kMmapFailure;
985 break;
986 }
987 }
988
989 // Log these events after update to distinguish meta update failure.
990 Events event;
991 if (mmap_ofs >= db_size) {
992 mmap_ofs = kMmapSuccess;
993 event = EVENT_MMAP_SUCCESS_NEW;
994 } else if (mmap_ofs > 0) {
995 event = EVENT_MMAP_SUCCESS_PARTIAL;
996 } else {
997 DCHECK_EQ(kMmapFailure, mmap_ofs);
998 event = EVENT_MMAP_FAILED_NEW;
999 }
1000
1001 const char* kMmapUpdateStatusSql = "REPLACE INTO meta VALUES (?, ?)";
1002 Statement s(GetUniqueStatement(kMmapUpdateStatusSql));
1003 s.BindString(0, kMmapStatusKey);
1004 s.BindInt64(1, mmap_ofs);
1005 if (!s.Run()) {
1006 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
1007 return 0;
1008 }
1009
1010 RecordOneEvent(event);
1011 }
1012 }
1013
1014 if (mmap_ofs == kMmapFailure)
1015 return 0;
1016 if (mmap_ofs == kMmapSuccess)
1017 return 256 * 1024 * 1024;
1018 return mmap_ofs;
1019}
1020
[email protected]be7995f12013-07-18 18:49:141021void Connection::TrimMemory(bool aggressively) {
1022 if (!db_)
1023 return;
1024
1025 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1026 int original_cache_size;
1027 {
1028 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1029 if (!sql_get_original.Step()) {
1030 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1031 return;
1032 }
1033 original_cache_size = sql_get_original.ColumnInt(0);
1034 }
1035 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1036
1037 // Force sqlite to try to reduce page cache usage.
1038 const std::string sql_shrink =
1039 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1040 if (!Execute(sql_shrink.c_str()))
1041 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1042
1043 // Restore cache size.
1044 const std::string sql_restore =
1045 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1046 if (!Execute(sql_restore.c_str()))
1047 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1048}
1049
[email protected]8e0c01282012-04-06 19:36:491050// Create an in-memory database with the existing database's page
1051// size, then backup that database over the existing database.
1052bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501053 AssertIOAllowed();
1054
[email protected]8e0c01282012-04-06 19:36:491055 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381056 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491057 return false;
1058 }
1059
1060 if (transaction_nesting_ > 0) {
1061 DLOG(FATAL) << "Cannot raze within a transaction";
1062 return false;
1063 }
1064
1065 sql::Connection null_db;
1066 if (!null_db.OpenInMemory()) {
1067 DLOG(FATAL) << "Unable to open in-memory database.";
1068 return false;
1069 }
1070
[email protected]6d42f152012-11-10 00:38:241071 if (page_size_) {
1072 // Enforce SQLite restrictions on |page_size_|.
1073 DCHECK(!(page_size_ & (page_size_ - 1)))
1074 << " page_size_ " << page_size_ << " is not a power of two.";
1075 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1076 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041077 const std::string sql =
1078 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421079 if (!null_db.Execute(sql.c_str()))
1080 return false;
1081 }
1082
[email protected]6d42f152012-11-10 00:38:241083#if defined(OS_ANDROID)
1084 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1085 // in-memory databases do not respect this define.
1086 // TODO(shess): Figure out a way to set this without using platform
1087 // specific code. AFAICT from sqlite3.c, the only way to do it
1088 // would be to create an actual filesystem database, which is
1089 // unfortunate.
1090 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1091 return false;
1092#endif
[email protected]8e0c01282012-04-06 19:36:491093
1094 // The page size doesn't take effect until a database has pages, and
1095 // at this point the null database has none. Changing the schema
1096 // version will create the first page. This will not affect the
1097 // schema version in the resulting database, as SQLite's backup
1098 // implementation propagates the schema version from the original
1099 // connection to the new version of the database, incremented by one
1100 // so that other readers see the schema change and act accordingly.
1101 if (!null_db.Execute("PRAGMA schema_version = 1"))
1102 return false;
1103
[email protected]6d42f152012-11-10 00:38:241104 // SQLite tracks the expected number of database pages in the first
1105 // page, and if it does not match the total retrieved from a
1106 // filesystem call, treats the database as corrupt. This situation
1107 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1108 // used to hint to SQLite to soldier on in that case, specifically
1109 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1110 // sqlite3.c lockBtree().]
1111 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1112 // page_size" can be used to query such a database.
1113 ScopedWritableSchema writable_schema(db_);
1114
[email protected]7bae5742013-07-10 20:46:161115 const char* kMain = "main";
1116 int rc = BackupDatabase(null_db.db_, db_, kMain);
1117 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491118
1119 // The destination database was locked.
1120 if (rc == SQLITE_BUSY) {
1121 return false;
1122 }
1123
[email protected]7bae5742013-07-10 20:46:161124 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1125 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1126 // isn't even big enough for one page. Either way, reach in and
1127 // truncate it before trying again.
1128 // TODO(shess): Maybe it would be worthwhile to just truncate from
1129 // the get-go?
1130 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1131 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341132 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161133 if (rc != SQLITE_OK) {
1134 DLOG(FATAL) << "Failure getting file handle.";
1135 return false;
[email protected]7bae5742013-07-10 20:46:161136 }
1137
1138 rc = file->pMethods->xTruncate(file, 0);
1139 if (rc != SQLITE_OK) {
1140 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1141 DLOG(FATAL) << "Failed to truncate file.";
1142 return false;
1143 }
1144
1145 rc = BackupDatabase(null_db.db_, db_, kMain);
1146 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1147
1148 if (rc != SQLITE_DONE) {
1149 DLOG(FATAL) << "Failed retrying Raze().";
1150 }
1151 }
1152
[email protected]8e0c01282012-04-06 19:36:491153 // The entire database should have been backed up.
1154 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161155 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491156 DLOG(FATAL) << "Unable to copy entire null database.";
1157 return false;
1158 }
1159
[email protected]8e0c01282012-04-06 19:36:491160 return true;
1161}
1162
1163bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1164 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381165 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491166 return false;
1167 }
1168
1169 ScopedBusyTimeout busy_timeout(db_);
1170 busy_timeout.SetTimeout(timeout);
1171 return Raze();
1172}
1173
[email protected]41a97c812013-02-07 02:35:381174bool Connection::RazeAndClose() {
1175 if (!db_) {
1176 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1177 return false;
1178 }
1179
1180 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301181 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381182
1183 bool result = Raze();
1184
1185 CloseInternal(true);
1186
1187 // Mark the database so that future API calls fail appropriately,
1188 // but don't DCHECK (because after calling this function they are
1189 // expected to fail).
1190 poisoned_ = true;
1191
1192 return result;
1193}
1194
[email protected]8d409412013-07-19 18:25:301195void Connection::Poison() {
1196 if (!db_) {
1197 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1198 return;
1199 }
1200
1201 RollbackAllTransactions();
1202 CloseInternal(true);
1203
1204 // Mark the database so that future API calls fail appropriately,
1205 // but don't DCHECK (because after calling this function they are
1206 // expected to fail).
1207 poisoned_ = true;
1208}
1209
[email protected]8d2e39e2013-06-24 05:55:081210// TODO(shess): To the extent possible, figure out the optimal
1211// ordering for these deletes which will prevent other connections
1212// from seeing odd behavior. For instance, it may be necessary to
1213// manually lock the main database file in a SQLite-compatible fashion
1214// (to prevent other processes from opening it), then delete the
1215// journal files, then delete the main database file. Another option
1216// might be to lock the main database file and poison the header with
1217// junk to prevent other processes from opening it successfully (like
1218// Gears "SQLite poison 3" trick).
1219//
1220// static
1221bool Connection::Delete(const base::FilePath& path) {
1222 base::ThreadRestrictions::AssertIOAllowed();
1223
1224 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1225 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1226
erg102ceb412015-06-20 01:38:131227 std::string journal_str = AsUTF8ForSQL(journal_path);
1228 std::string wal_str = AsUTF8ForSQL(wal_path);
1229 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081230
shess702467622015-09-16 19:04:551231 // Make sure sqlite3_initialize() is called before anything else.
1232 InitializeSqlite();
1233
erg102ceb412015-06-20 01:38:131234 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1235 CHECK(vfs);
1236 CHECK(vfs->xDelete);
1237 CHECK(vfs->xAccess);
1238
1239 // We only work with unix, win32 and mojo filesystems. If you're trying to
1240 // use this code with any other VFS, you're not in a good place.
1241 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1242 strncmp(vfs->zName, "win32", 5) == 0 ||
1243 strcmp(vfs->zName, "mojo") == 0);
1244
1245 vfs->xDelete(vfs, journal_str.c_str(), 0);
1246 vfs->xDelete(vfs, wal_str.c_str(), 0);
1247 vfs->xDelete(vfs, path_str.c_str(), 0);
1248
1249 int journal_exists = 0;
1250 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1251 &journal_exists);
1252
1253 int wal_exists = 0;
1254 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1255 &wal_exists);
1256
1257 int path_exists = 0;
1258 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1259 &path_exists);
1260
1261 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081262}
1263
[email protected]e5ffd0e42009-09-11 21:30:561264bool Connection::BeginTransaction() {
1265 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331266 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561267
1268 // When we're going to rollback, fail on this begin and don't actually
1269 // mark us as entering the nested transaction.
1270 return false;
1271 }
1272
1273 bool success = true;
1274 if (!transaction_nesting_) {
1275 needs_rollback_ = false;
1276
1277 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321278 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591279 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561280 return false;
1281 }
1282 transaction_nesting_++;
1283 return success;
1284}
1285
1286void Connection::RollbackTransaction() {
1287 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381288 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561289 return;
1290 }
1291
1292 transaction_nesting_--;
1293
1294 if (transaction_nesting_ > 0) {
1295 // Mark the outermost transaction as needing rollback.
1296 needs_rollback_ = true;
1297 return;
1298 }
1299
1300 DoRollback();
1301}
1302
1303bool Connection::CommitTransaction() {
1304 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181305 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561306 return false;
1307 }
1308 transaction_nesting_--;
1309
1310 if (transaction_nesting_ > 0) {
1311 // Mark any nested transactions as failing after we've already got one.
1312 return !needs_rollback_;
1313 }
1314
1315 if (needs_rollback_) {
1316 DoRollback();
1317 return false;
1318 }
1319
1320 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321321
1322 // Collect the commit time manually, sql::Statement would register it as query
1323 // time only.
1324 const base::TimeTicks before = Now();
1325 bool ret = commit.RunWithoutTimers();
1326 const base::TimeDelta delta = Now() - before;
1327
1328 RecordCommitTime(delta);
1329 RecordOneEvent(EVENT_COMMIT);
1330
shess7dbd4dee2015-10-06 17:39:161331 // Release dirty cache pages after the transaction closes.
1332 ReleaseCacheMemoryIfNeeded(false);
1333
shess58b8df82015-06-03 00:19:321334 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561335}
1336
[email protected]8d409412013-07-19 18:25:301337void Connection::RollbackAllTransactions() {
1338 if (transaction_nesting_ > 0) {
1339 transaction_nesting_ = 0;
1340 DoRollback();
1341 }
1342}
1343
1344bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1345 const char* attachment_point) {
1346 DCHECK(ValidAttachmentPoint(attachment_point));
1347
1348 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1349#if OS_WIN
1350 s.BindString16(0, other_db_path.value());
1351#else
1352 s.BindString(0, other_db_path.value());
1353#endif
1354 s.BindString(1, attachment_point);
1355 return s.Run();
1356}
1357
1358bool Connection::DetachDatabase(const char* attachment_point) {
1359 DCHECK(ValidAttachmentPoint(attachment_point));
1360
1361 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1362 s.BindString(0, attachment_point);
1363 return s.Run();
1364}
1365
shess58b8df82015-06-03 00:19:321366// TODO(shess): Consider changing this to execute exactly one statement. If a
1367// caller wishes to execute multiple statements, that should be explicit, and
1368// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591369int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501370 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381371 if (!db_) {
1372 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1373 return SQLITE_ERROR;
1374 }
shess58b8df82015-06-03 00:19:321375 DCHECK(sql);
1376
1377 RecordOneEvent(EVENT_EXECUTE);
1378 int rc = SQLITE_OK;
1379 while ((rc == SQLITE_OK) && *sql) {
1380 sqlite3_stmt *stmt = NULL;
1381 const char *leftover_sql;
1382
1383 const base::TimeTicks before = Now();
1384 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1385 sql = leftover_sql;
1386
1387 // Stop if an error is encountered.
1388 if (rc != SQLITE_OK)
1389 break;
1390
1391 // This happens if |sql| originally only contained comments or whitespace.
1392 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1393 // extraneous comments and whitespace in the SQL statements increases
1394 // runtime cost and can easily be shifted out to the C++ layer.
1395 if (!stmt)
1396 continue;
1397
1398 // Save for use after statement is finalized.
1399 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1400
1401 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1402 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1403 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1404 // is the only legitimate case for this.
1405 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1406 }
1407
1408 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1409 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1410 rc = sqlite3_finalize(stmt);
1411 if (rc == SQLITE_OK)
1412 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1413
1414 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1415 // trailing whitespace.
1416 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021417 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321418 sql++;
1419 }
1420
1421 const base::TimeDelta delta = Now() - before;
1422 RecordTimeAndChanges(delta, read_only);
1423 }
shess7dbd4dee2015-10-06 17:39:161424
1425 // Most calls to Execute() modify the database. The main exceptions would be
1426 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1427 // but sometimes don't.
1428 ReleaseCacheMemoryIfNeeded(true);
1429
shess58b8df82015-06-03 00:19:321430 return rc;
[email protected]eff1fa522011-12-12 23:50:591431}
1432
1433bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381434 if (!db_) {
1435 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1436 return false;
1437 }
1438
[email protected]eff1fa522011-12-12 23:50:591439 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001440 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581441 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001442
[email protected]28fe0ff2012-02-25 00:40:331443 // This needs to be a FATAL log because the error case of arriving here is
1444 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101445 // a change alters the schema but not all queries adjust. This can happen
1446 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591447 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331448 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591449 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561450}
1451
[email protected]5b96f3772010-09-28 16:30:571452bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381453 if (!db_) {
1454 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571455 return false;
[email protected]41a97c812013-02-07 02:35:381456 }
[email protected]5b96f3772010-09-28 16:30:571457
1458 ScopedBusyTimeout busy_timeout(db_);
1459 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591460 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571461}
1462
[email protected]e5ffd0e42009-09-11 21:30:561463bool Connection::HasCachedStatement(const StatementID& id) const {
1464 return statement_cache_.find(id) != statement_cache_.end();
1465}
1466
1467scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1468 const StatementID& id,
1469 const char* sql) {
1470 CachedStatementMap::iterator i = statement_cache_.find(id);
1471 if (i != statement_cache_.end()) {
1472 // Statement is in the cache. It should still be active (we're the only
1473 // one invalidating cached statements, and we'll remove it from the cache
1474 // if we do that. Make sure we reset it before giving out the cached one in
1475 // case it still has some stuff bound.
1476 DCHECK(i->second->is_valid());
1477 sqlite3_reset(i->second->stmt());
1478 return i->second;
1479 }
1480
1481 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1482 if (statement->is_valid())
1483 statement_cache_[id] = statement; // Only cache valid statements.
1484 return statement;
1485}
1486
1487scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1488 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501489 AssertIOAllowed();
1490
[email protected]41a97c812013-02-07 02:35:381491 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561492 if (!db_)
[email protected]41a97c812013-02-07 02:35:381493 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561494
1495 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001496 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1497 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591498 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061499 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021500 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001501
1502 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581503 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381504 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561505 }
[email protected]41a97c812013-02-07 02:35:381506 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561507}
1508
shessf7e988f2015-11-13 00:41:061509// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1510// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581511scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1512 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381513 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581514 if (!db_)
[email protected]41a97c812013-02-07 02:35:381515 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581516
1517 sqlite3_stmt* stmt = NULL;
1518 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1519 if (rc != SQLITE_OK) {
1520 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061521 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021522 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381523 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581524 }
[email protected]41a97c812013-02-07 02:35:381525 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581526}
1527
[email protected]92cd00a2013-08-16 11:09:581528std::string Connection::GetSchema() const {
1529 // The ORDER BY should not be necessary, but relying on organic
1530 // order for something like this is questionable.
1531 const char* kSql =
1532 "SELECT type, name, tbl_name, sql "
1533 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1534 Statement statement(GetUntrackedStatement(kSql));
1535
1536 std::string schema;
1537 while (statement.Step()) {
1538 schema += statement.ColumnString(0);
1539 schema += '|';
1540 schema += statement.ColumnString(1);
1541 schema += '|';
1542 schema += statement.ColumnString(2);
1543 schema += '|';
1544 schema += statement.ColumnString(3);
1545 schema += '\n';
1546 }
1547
1548 return schema;
1549}
1550
[email protected]eff1fa522011-12-12 23:50:591551bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501552 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381553 if (!db_) {
1554 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1555 return false;
1556 }
1557
[email protected]eff1fa522011-12-12 23:50:591558 sqlite3_stmt* stmt = NULL;
1559 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1560 return false;
1561
1562 sqlite3_finalize(stmt);
1563 return true;
1564}
1565
[email protected]1ed78a32009-09-15 20:24:171566bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531567 return DoesTableOrIndexExist(table_name, "table");
1568}
1569
1570bool Connection::DoesIndexExist(const char* index_name) const {
1571 return DoesTableOrIndexExist(index_name, "index");
1572}
1573
1574bool Connection::DoesTableOrIndexExist(
1575 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471576 const char* kSql =
1577 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581578 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471579
1580 // This can happen if the database is corrupt and the error is being ignored
1581 // for testing purposes.
1582 if (!statement.is_valid())
1583 return false;
1584
[email protected]e2cadec82011-12-13 02:00:531585 statement.BindString(0, type);
1586 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331587
[email protected]e5ffd0e42009-09-11 21:30:561588 return statement.Step(); // Table exists if any row was returned.
1589}
1590
1591bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171592 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561593 std::string sql("PRAGMA TABLE_INFO(");
1594 sql.append(table_name);
1595 sql.append(")");
1596
[email protected]2eec0a22012-07-24 01:59:581597 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471598
1599 // This can happen if the database is corrupt and the error is being ignored
1600 // for testing purposes.
1601 if (!statement.is_valid())
1602 return false;
1603
[email protected]e5ffd0e42009-09-11 21:30:561604 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331605 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1606 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561607 return true;
1608 }
1609 return false;
1610}
1611
tfarina720d4f32015-05-11 22:31:261612int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561613 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381614 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561615 return 0;
1616 }
1617 return sqlite3_last_insert_rowid(db_);
1618}
1619
[email protected]1ed78a32009-09-15 20:24:171620int Connection::GetLastChangeCount() const {
1621 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381622 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171623 return 0;
1624 }
1625 return sqlite3_changes(db_);
1626}
1627
[email protected]e5ffd0e42009-09-11 21:30:561628int Connection::GetErrorCode() const {
1629 if (!db_)
1630 return SQLITE_ERROR;
1631 return sqlite3_errcode(db_);
1632}
1633
[email protected]767718e52010-09-21 23:18:491634int Connection::GetLastErrno() const {
1635 if (!db_)
1636 return -1;
1637
1638 int err = 0;
1639 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1640 return -2;
1641
1642 return err;
1643}
1644
[email protected]e5ffd0e42009-09-11 21:30:561645const char* Connection::GetErrorMessage() const {
1646 if (!db_)
1647 return "sql::Connection has no connection.";
1648 return sqlite3_errmsg(db_);
1649}
1650
[email protected]fed734a2013-07-17 04:45:131651bool Connection::OpenInternal(const std::string& file_name,
1652 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501653 AssertIOAllowed();
1654
[email protected]9cfbc922009-11-17 20:13:171655 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591656 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171657 return false;
1658 }
1659
[email protected]a7ec1292013-07-22 22:02:181660 // Make sure sqlite3_initialize() is called before anything else.
1661 InitializeSqlite();
1662
shess58b8df82015-06-03 00:19:321663 // Setup the stats histograms immediately rather than allocating lazily.
1664 // Connections which won't exercise all of these probably shouldn't exist.
1665 if (!histogram_tag_.empty()) {
1666 stats_histogram_ =
1667 base::LinearHistogram::FactoryGet(
1668 "Sqlite.Stats." + histogram_tag_,
1669 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1670 base::HistogramBase::kUmaTargetedHistogramFlag);
1671
1672 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1673 // unreasonable time for any single operation, so there is not much value to
1674 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1675 // things are entirely busted.
1676 commit_time_histogram_ =
1677 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1678
1679 autocommit_time_histogram_ =
1680 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1681
1682 update_time_histogram_ =
1683 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1684
1685 query_time_histogram_ =
1686 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1687 }
1688
[email protected]41a97c812013-02-07 02:35:381689 // If |poisoned_| is set, it means an error handler called
1690 // RazeAndClose(). Until regular Close() is called, the caller
1691 // should be treating the database as open, but is_open() currently
1692 // only considers the sqlite3 handle's state.
1693 // TODO(shess): Revise is_open() to consider poisoned_, and review
1694 // to see if any non-testing code even depends on it.
1695 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161696 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381697
[email protected]765b44502009-10-02 05:01:421698 int err = sqlite3_open(file_name.c_str(), &db_);
1699 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281700 // Extended error codes cannot be enabled until a handle is
1701 // available, fetch manually.
1702 err = sqlite3_extended_errcode(db_);
1703
[email protected]bd2ccdb4a2012-12-07 22:14:501704 // Histogram failures specific to initial open for debugging
1705 // purposes.
[email protected]73fb8d52013-07-24 05:04:281706 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501707
[email protected]2f496b42013-09-26 18:36:581708 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131709 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291710 Close();
[email protected]fed734a2013-07-17 04:45:131711
1712 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1713 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421714 return false;
1715 }
1716
[email protected]81a2a602013-07-17 19:10:361717 // TODO(shess): OS_WIN support?
1718#if defined(OS_POSIX)
1719 if (restrict_to_user_) {
1720 DCHECK_NE(file_name, std::string(":memory"));
1721 base::FilePath file_path(file_name);
1722 int mode = 0;
1723 // TODO(shess): Arguably, failure to retrieve and change
1724 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081725 if (base::GetPosixFilePermissions(file_path, &mode)) {
1726 mode &= base::FILE_PERMISSION_USER_MASK;
1727 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361728
1729 // SQLite sets the permissions on these files from the main
1730 // database on create. Set them here in case they already exist
1731 // at this point. Failure to set these permissions should not
1732 // be fatal unless the file doesn't exist.
1733 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1734 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081735 base::SetPosixFilePermissions(journal_path, mode);
1736 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361737 }
1738 }
1739#endif // defined(OS_POSIX)
1740
[email protected]affa2da2013-06-06 22:20:341741 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1742 // Chromium already depends on small mallocs being efficient, so we disable
1743 // this to avoid the extra memory overhead.
1744 // This must be called immediatly after opening the database before any SQL
1745 // statements are run.
1746 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1747
[email protected]73fb8d52013-07-24 05:04:281748 // Enable extended result codes to provide more color on I/O errors.
1749 // Not having extended result codes is not a fatal problem, as
1750 // Chromium code does not attempt to handle I/O errors anyhow. The
1751 // current implementation always returns SQLITE_OK, the DCHECK is to
1752 // quickly notify someone if SQLite changes.
1753 err = sqlite3_extended_result_codes(db_, 1);
1754 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1755
[email protected]bd2ccdb4a2012-12-07 22:14:501756 // sqlite3_open() does not actually read the database file (unless a
1757 // hot journal is found). Successfully executing this pragma on an
1758 // existing database requires a valid header on page 1.
1759 // TODO(shess): For now, just probing to see what the lay of the
1760 // land is. If it's mostly SQLITE_NOTADB, then the database should
1761 // be razed.
1762 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1763 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281764 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431765
[email protected]2e1cee762013-07-09 14:40:001766#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1767 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1768 // REGEXP support. Add it in dynamically.
1769 err = sqlite3IcuInit(db_);
1770 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1771#endif // OS_IOS && USE_SYSTEM_SQLITE
1772
[email protected]5b96f3772010-09-28 16:30:571773 // If indicated, lock up the database before doing anything else, so
1774 // that the following code doesn't have to deal with locking.
1775 // TODO(shess): This code is brittle. Find the cases where code
1776 // doesn't request |exclusive_locking_| and audit that it does the
1777 // right thing with SQLITE_BUSY, and that it doesn't make
1778 // assumptions about who might change things in the database.
1779 // http://crbug.com/56559
1780 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101781 // TODO(shess): This should probably be a failure. Code which
1782 // requests exclusive locking but doesn't get it is almost certain
1783 // to be ill-tested.
1784 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571785 }
1786
[email protected]4e179ba2012-03-17 16:06:471787 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1788 // DELETE (default) - delete -journal file to commit.
1789 // TRUNCATE - truncate -journal file to commit.
1790 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091791 // TRUNCATE should be faster than DELETE because it won't need directory
1792 // changes for each transaction. PERSIST may break the spirit of using
1793 // secure_delete.
1794 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471795
[email protected]c68ce172011-11-24 22:30:271796 const base::TimeDelta kBusyTimeout =
1797 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1798
[email protected]765b44502009-10-02 05:01:421799 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571800 // Enforce SQLite restrictions on |page_size_|.
1801 DCHECK(!(page_size_ & (page_size_ - 1)))
1802 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241803 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571804 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041805 const std::string sql =
1806 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101807 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421808 }
1809
1810 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041811 const std::string sql =
1812 base::StringPrintf("PRAGMA cache_size=%d", cache_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
[email protected]6e0b1442011-08-09 23:23:581816 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131817 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581818 Close();
[email protected]fed734a2013-07-17 04:45:131819 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1820 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581821 return false;
1822 }
1823
shess5dac334f2015-11-05 20:47:421824 // Set a reasonable chunk size for larger files. This reduces churn from
1825 // remapping memory on size changes. It also reduces filesystem
1826 // fragmentation.
1827 // TODO(shess): It may make sense to have this be hinted by the client.
1828 // Database sizes seem to be bimodal, some clients have consistently small
1829 // databases (<20k) while other clients have a broad distribution of sizes
1830 // (hundreds of kilobytes to many megabytes).
1831 sqlite3_file* file = NULL;
1832 sqlite3_int64 db_size = 0;
1833 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1834 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1835 int chunk_size = 4 * 1024;
1836 if (db_size > 128 * 1024)
1837 chunk_size = 32 * 1024;
1838 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1839 }
1840
shess2f3a814b2015-11-05 18:11:101841 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311842 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1843 // safe range to memory-map based on past regular I/O. This value will be
1844 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1845 // 64-bit platforms.
1846 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1847 std::string mmap_sql =
1848 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1849 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101850
1851 // Determine if memory-mapping has actually been enabled. The Execute() above
1852 // can succeed without changing the amount mapped.
1853 mmap_enabled_ = false;
1854 {
1855 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1856 if (s.Step() && s.ColumnInt64(0) > 0)
1857 mmap_enabled_ = true;
1858 }
1859
[email protected]765b44502009-10-02 05:01:421860 return true;
1861}
1862
[email protected]e5ffd0e42009-09-11 21:30:561863void Connection::DoRollback() {
1864 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321865
1866 // Collect the rollback time manually, sql::Statement would register it as
1867 // query time only.
1868 const base::TimeTicks before = Now();
1869 rollback.RunWithoutTimers();
1870 const base::TimeDelta delta = Now() - before;
1871
1872 RecordUpdateTime(delta);
1873 RecordOneEvent(EVENT_ROLLBACK);
1874
shess7dbd4dee2015-10-06 17:39:161875 // The cache may have been accumulating dirty pages for commit. Note that in
1876 // some cases sql::Transaction can fire rollback after a database is closed.
1877 if (is_open())
1878 ReleaseCacheMemoryIfNeeded(false);
1879
[email protected]44ad7d902012-03-23 00:09:051880 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561881}
1882
1883void Connection::StatementRefCreated(StatementRef* ref) {
1884 DCHECK(open_statements_.find(ref) == open_statements_.end());
1885 open_statements_.insert(ref);
1886}
1887
1888void Connection::StatementRefDeleted(StatementRef* ref) {
1889 StatementRefSet::iterator i = open_statements_.find(ref);
1890 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591891 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561892 else
1893 open_statements_.erase(i);
1894}
1895
shess58b8df82015-06-03 00:19:321896void Connection::set_histogram_tag(const std::string& tag) {
1897 DCHECK(!is_open());
1898 histogram_tag_ = tag;
1899}
1900
[email protected]210ce0af2013-05-15 09:10:391901void Connection::AddTaggedHistogram(const std::string& name,
1902 size_t sample) const {
1903 if (histogram_tag_.empty())
1904 return;
1905
1906 // TODO(shess): The histogram macros create a bit of static storage
1907 // for caching the histogram object. This code shouldn't execute
1908 // often enough for such caching to be crucial. If it becomes an
1909 // issue, the object could be cached alongside histogram_prefix_.
1910 std::string full_histogram_name = name + "." + histogram_tag_;
1911 base::HistogramBase* histogram =
1912 base::SparseHistogram::FactoryGet(
1913 full_histogram_name,
1914 base::HistogramBase::kUmaTargetedHistogramFlag);
1915 if (histogram)
1916 histogram->Add(sample);
1917}
1918
[email protected]2f496b42013-09-26 18:36:581919int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391920 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1921 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141922
1923 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581924 if (!sql && stmt)
1925 sql = stmt->GetSQLStatement();
1926 if (!sql)
1927 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061928
1929 std::string id = histogram_tag_;
1930 if (id.empty())
1931 id = DbPath().BaseName().AsUTF8Unsafe();
1932 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141933 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581934 << ": " << GetErrorMessage()
1935 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141936
[email protected]c3881b372013-05-17 08:39:461937 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561938 // Fire from a copy of the callback in case of reentry into
1939 // re/set_error_callback().
1940 // TODO(shess): <http://crbug.com/254584>
1941 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461942 return err;
1943 }
1944
[email protected]faa604e2009-09-25 22:38:591945 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571946 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101947 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591948 return err;
1949}
1950
[email protected]579446c2013-12-16 18:36:521951bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1952 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1953}
1954
1955bool Connection::QuickIntegrityCheck() {
1956 std::vector<std::string> messages;
1957 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1958 return false;
1959 return messages.size() == 1 && messages[0] == "ok";
1960}
1961
[email protected]80abf152013-05-22 12:42:421962// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521963bool Connection::IntegrityCheckHelper(
1964 const char* pragma_sql,
1965 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421966 messages->clear();
1967
[email protected]4658e2a02013-06-06 23:05:001968 // This has the side effect of setting SQLITE_RecoveryMode, which
1969 // allows SQLite to process through certain cases of corruption.
1970 // Failing to set this pragma probably means that the database is
1971 // beyond recovery.
1972 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1973 if (!Execute(kWritableSchema))
1974 return false;
1975
1976 bool ret = false;
1977 {
[email protected]579446c2013-12-16 18:36:521978 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001979
1980 // The pragma appears to return all results (up to 100 by default)
1981 // as a single string. This doesn't appear to be an API contract,
1982 // it could return separate lines, so loop _and_ split.
1983 while (stmt.Step()) {
1984 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181985 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1986 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001987 }
1988 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421989 }
[email protected]4658e2a02013-06-06 23:05:001990
1991 // Best effort to put things back as they were before.
1992 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1993 ignore_result(Execute(kNoWritableSchema));
1994
1995 return ret;
[email protected]80abf152013-05-22 12:42:421996}
1997
shess58b8df82015-06-03 00:19:321998base::TimeTicks TimeSource::Now() {
1999 return base::TimeTicks::Now();
2000}
2001
[email protected]e5ffd0e42009-09-11 21:30:562002} // namespace sql