blob: 88acef040d0981fa65d5935651d1409d8dec8c98 [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
avi0b519202015-12-21 07:25:197#include <stddef.h>
8#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:569#include <string.h>
10
shessc9e80ae22015-08-12 21:39:1111#include "base/bind.h"
shessc8cd2a162015-10-22 20:30:4612#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5213#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4414#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4615#include "base/format_macros.h"
16#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1817#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5618#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1119#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5020#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3921#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4222#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1923#include "base/strings/string_util.h"
24#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4525#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1826#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0327#include "base/trace_event/memory_dump_manager.h"
28#include "base/trace_event/process_memory_dump.h"
shess9bf2c672015-12-18 01:18:0829#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2130#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0331#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5632
[email protected]2e1cee762013-07-09 14:40:0033#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
34#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
35#endif
36
[email protected]5b96f3772010-09-28 16:30:5737namespace {
38
39// Spin for up to a second waiting for the lock to clear when setting
40// up the database.
41// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2742const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5743
44class ScopedBusyTimeout {
45 public:
46 explicit ScopedBusyTimeout(sqlite3* db)
47 : db_(db) {
48 }
49 ~ScopedBusyTimeout() {
50 sqlite3_busy_timeout(db_, 0);
51 }
52
53 int SetTimeout(base::TimeDelta timeout) {
54 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
55 return sqlite3_busy_timeout(db_,
56 static_cast<int>(timeout.InMilliseconds()));
57 }
58
59 private:
60 sqlite3* db_;
61};
62
[email protected]6d42f152012-11-10 00:38:2463// Helper to "safely" enable writable_schema. No error checking
64// because it is reasonable to just forge ahead in case of an error.
65// If turning it on fails, then most likely nothing will work, whereas
66// if turning it off fails, it only matters if some code attempts to
67// continue working with the database and tries to modify the
68// sqlite_master table (none of our code does this).
69class ScopedWritableSchema {
70 public:
71 explicit ScopedWritableSchema(sqlite3* db)
72 : db_(db) {
73 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
74 }
75 ~ScopedWritableSchema() {
76 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
77 }
78
79 private:
80 sqlite3* db_;
81};
82
[email protected]7bae5742013-07-10 20:46:1683// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
84// SQLite error code from running the backup step.
85int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
86 DCHECK_NE(src, dst);
87 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
88 if (!backup) {
89 // Since this call only sets things up, this indicates a gross
90 // error in SQLite.
91 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
92 return sqlite3_errcode(dst);
93 }
94
95 // -1 backs up the entire database.
96 int rc = sqlite3_backup_step(backup, -1);
97 int pages = sqlite3_backup_pagecount(backup);
98 sqlite3_backup_finish(backup);
99
100 // If successful, exactly one page should have been backed up. If
101 // this breaks, check this function to make sure assumptions aren't
102 // being broken.
103 if (rc == SQLITE_DONE)
104 DCHECK_EQ(pages, 1);
105
106 return rc;
107}
108
[email protected]8d409412013-07-19 18:25:30109// Be very strict on attachment point. SQLite can handle a much wider
110// character set with appropriate quoting, but Chromium code should
111// just use clean names to start with.
112bool ValidAttachmentPoint(const char* attachment_point) {
113 for (size_t i = 0; attachment_point[i]; ++i) {
114 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
115 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
116 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
117 attachment_point[i] == '_')) {
118 return false;
119 }
120 }
121 return true;
122}
123
shessc9e80ae22015-08-12 21:39:11124void RecordSqliteMemory10Min() {
avi0b519202015-12-21 07:25:19125 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11126 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
127}
128
129void RecordSqliteMemoryHour() {
avi0b519202015-12-21 07:25:19130 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11131 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
132}
133
134void RecordSqliteMemoryDay() {
avi0b519202015-12-21 07:25:19135 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11136 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
137}
138
shess2d48e942015-08-25 17:39:51139void RecordSqliteMemoryWeek() {
avi0b519202015-12-21 07:25:19140 const int64_t used = sqlite3_memory_used();
shess2d48e942015-08-25 17:39:51141 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
142}
143
[email protected]a7ec1292013-07-22 22:02:18144// SQLite automatically calls sqlite3_initialize() lazily, but
145// sqlite3_initialize() uses double-checked locking and thus can have
146// data races.
147//
148// TODO(shess): Another alternative would be to have
149// sqlite3_initialize() called as part of process bring-up. If this
150// is changed, remove the dynamic_annotations dependency in sql.gyp.
151base::LazyInstance<base::Lock>::Leaky
152 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
153void InitializeSqlite() {
154 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11155 static bool first_call = true;
156 if (first_call) {
157 sqlite3_initialize();
158
159 // Schedule callback to record memory footprint histograms at 10m, 1h, and
160 // 1d. There may not be a message loop in tests.
161 if (base::MessageLoop::current()) {
162 base::MessageLoop::current()->PostDelayedTask(
163 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
164 base::TimeDelta::FromMinutes(10));
165 base::MessageLoop::current()->PostDelayedTask(
166 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
167 base::TimeDelta::FromHours(1));
168 base::MessageLoop::current()->PostDelayedTask(
169 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
170 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51171 base::MessageLoop::current()->PostDelayedTask(
172 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
173 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11174 }
175
176 first_call = false;
177 }
[email protected]a7ec1292013-07-22 22:02:18178}
179
[email protected]8ada10f2013-12-21 00:42:34180// Helper to get the sqlite3_file* associated with the "main" database.
181int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
182 *file = NULL;
183 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
184 if (rc != SQLITE_OK)
185 return rc;
186
187 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
188 // content_unittests, even though it should not be possible.
189 // http://crbug.com/329982
190 if (!*file || !(*file)->pMethods)
191 return SQLITE_ERROR;
192
193 return rc;
194}
195
shess5dac334f2015-11-05 20:47:42196// Convenience to get the sqlite3_file* and the size for the "main" database.
197int GetSqlite3FileAndSize(sqlite3* db,
198 sqlite3_file** file, sqlite3_int64* db_size) {
199 int rc = GetSqlite3File(db, file);
200 if (rc != SQLITE_OK)
201 return rc;
202
203 return (*file)->pMethods->xFileSize(*file, db_size);
204}
205
shess58b8df82015-06-03 00:19:32206// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
207base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
208 return base::Histogram::FactoryTimeGet(
209 name,
210 base::TimeDelta::FromMilliseconds(10),
211 base::TimeDelta::FromMinutes(3),
212 50,
213 base::HistogramBase::kUmaTargetedHistogramFlag);
214}
215
erg102ceb412015-06-20 01:38:13216std::string AsUTF8ForSQL(const base::FilePath& path) {
217#if defined(OS_WIN)
218 return base::WideToUTF8(path.value());
219#elif defined(OS_POSIX)
220 return path.value();
221#endif
222}
223
[email protected]5b96f3772010-09-28 16:30:57224} // namespace
225
[email protected]e5ffd0e42009-09-11 21:30:56226namespace sql {
227
[email protected]4350e322013-06-18 22:18:10228// static
229Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
230
231// static
[email protected]74cdede2013-09-25 05:39:57232bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10233 if (!current_ignorer_cb_)
234 return false;
235 return current_ignorer_cb_->Run(error);
236}
237
shessf7e988f2015-11-13 00:41:06238// static
239bool Connection::ShouldIgnoreSqliteCompileError(int error) {
240 // Put this first in case tests need to see that the check happened.
241 if (ShouldIgnoreSqliteError(error))
242 return true;
243
244 // Trim extended error codes.
245 int basic_error = error & 0xff;
246
247 // These errors relate more to the runtime context of the system than to
248 // errors with a SQL statement or with the schema, so they aren't generally
249 // interesting to flag. This list is not comprehensive.
250 return basic_error == SQLITE_BUSY ||
251 basic_error == SQLITE_NOTADB ||
252 basic_error == SQLITE_CORRUPT;
253}
254
ssid9f8022f2015-10-12 17:49:03255bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
256 base::trace_event::ProcessMemoryDump* pmd) {
257 if (args.level_of_detail ==
258 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
259 !db_) {
260 return true;
261 }
262
263 // The high water mark is not tracked for the following usages.
264 int cache_size, dummy_int;
265 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
266 0 /* resetFlag */);
267 int schema_size;
268 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
269 0 /* resetFlag */);
270 int statement_size;
271 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
272 0 /* resetFlag */);
273
274 std::string name = base::StringPrintf(
275 "sqlite/%s_connection/%p",
276 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
277 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
278 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
279 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
280 cache_size + schema_size + statement_size);
281 dump->AddScalar("cache_size",
282 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
283 cache_size);
284 dump->AddScalar("schema_size",
285 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
286 schema_size);
287 dump->AddScalar("statement_size",
288 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
289 statement_size);
290 return true;
291}
292
shessc8cd2a162015-10-22 20:30:46293void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
294 AssertIOAllowed();
295
296 std::string debug_info;
297 const int error = (extended_error & 0xFF);
298 if (error == SQLITE_CORRUPT) {
299 debug_info = CollectCorruptionInfo();
300 } else {
301 debug_info = CollectErrorInfo(extended_error, stmt);
302 }
303
304 if (!debug_info.empty() && RegisterIntentToUpload()) {
305 char debug_buf[2000];
306 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
307 base::debug::Alias(&debug_buf);
308
309 base::debug::DumpWithoutCrashing();
310 }
311}
312
[email protected]4350e322013-06-18 22:18:10313// static
314void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
315 CHECK(current_ignorer_cb_ == NULL);
316 current_ignorer_cb_ = cb;
317}
318
319// static
320void Connection::ResetErrorIgnorer() {
321 CHECK(current_ignorer_cb_);
322 current_ignorer_cb_ = NULL;
323}
324
[email protected]e5ffd0e42009-09-11 21:30:56325bool StatementID::operator<(const StatementID& other) const {
326 if (number_ != other.number_)
327 return number_ < other.number_;
328 return strcmp(str_, other.str_) < 0;
329}
330
[email protected]e5ffd0e42009-09-11 21:30:56331Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38332 sqlite3_stmt* stmt,
333 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56334 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38335 stmt_(stmt),
336 was_valid_(was_valid) {
337 if (connection)
338 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56339}
340
341Connection::StatementRef::~StatementRef() {
342 if (connection_)
343 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38344 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56345}
346
[email protected]41a97c812013-02-07 02:35:38347void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56348 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50349 // Call to AssertIOAllowed() cannot go at the beginning of the function
350 // because Close() is called unconditionally from destructor to clean
351 // connection_. And if this is inactive statement this won't cause any
352 // disk access and destructor most probably will be called on thread
353 // not allowing disk access.
354 // TODO([email protected]): This should move to the beginning
355 // of the function. http://crbug.com/136655.
356 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56357 sqlite3_finalize(stmt_);
358 stmt_ = NULL;
359 }
360 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38361
362 // Forced close is expected to happen from a statement error
363 // handler. In that case maintain the sense of |was_valid_| which
364 // previously held for this ref.
365 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56366}
367
368Connection::Connection()
369 : db_(NULL),
370 page_size_(0),
371 cache_size_(0),
372 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36373 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56374 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50375 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16376 in_memory_(false),
shess58b8df82015-06-03 00:19:32377 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16378 mmap_disabled_(false),
379 mmap_enabled_(false),
380 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32381 stats_histogram_(NULL),
382 commit_time_histogram_(NULL),
383 autocommit_time_histogram_(NULL),
384 update_time_histogram_(NULL),
385 query_time_histogram_(NULL),
386 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03387 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40388 this, "sql::Connection", nullptr);
[email protected]526b4662013-06-14 04:09:12389}
[email protected]e5ffd0e42009-09-11 21:30:56390
391Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03392 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
393 this);
[email protected]e5ffd0e42009-09-11 21:30:56394 Close();
395}
396
shess58b8df82015-06-03 00:19:32397void Connection::RecordEvent(Events event, size_t count) {
398 for (size_t i = 0; i < count; ++i) {
399 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
400 }
401
402 if (stats_histogram_) {
403 for (size_t i = 0; i < count; ++i) {
404 stats_histogram_->Add(event);
405 }
406 }
407}
408
409void Connection::RecordCommitTime(const base::TimeDelta& delta) {
410 RecordUpdateTime(delta);
411 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
412 if (commit_time_histogram_)
413 commit_time_histogram_->AddTime(delta);
414}
415
416void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
417 RecordUpdateTime(delta);
418 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
419 if (autocommit_time_histogram_)
420 autocommit_time_histogram_->AddTime(delta);
421}
422
423void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
424 RecordQueryTime(delta);
425 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
426 if (update_time_histogram_)
427 update_time_histogram_->AddTime(delta);
428}
429
430void Connection::RecordQueryTime(const base::TimeDelta& delta) {
431 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
432 if (query_time_histogram_)
433 query_time_histogram_->AddTime(delta);
434}
435
436void Connection::RecordTimeAndChanges(
437 const base::TimeDelta& delta, bool read_only) {
438 if (read_only) {
439 RecordQueryTime(delta);
440 } else {
441 const int changes = sqlite3_changes(db_);
442 if (sqlite3_get_autocommit(db_)) {
443 RecordAutoCommitTime(delta);
444 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
445 } else {
446 RecordUpdateTime(delta);
447 RecordEvent(EVENT_CHANGES, changes);
448 }
449 }
450}
451
[email protected]a3ef4832013-02-02 05:12:33452bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02453 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26454 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49455 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02456 size_t sample = static_cast<size_t>(size_64 / 1024);
457 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
458 base::HistogramBase* histogram =
459 base::Histogram::FactoryGet(
460 full_histogram_name, 1, 1000000, 50,
461 base::HistogramBase::kUmaTargetedHistogramFlag);
462 if (histogram)
463 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08464 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02465 }
466 }
467
erg102ceb412015-06-20 01:38:13468 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42469}
[email protected]e5ffd0e42009-09-11 21:30:56470
[email protected]765b44502009-10-02 05:01:42471bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50472 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13473 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56474}
475
[email protected]8d409412013-07-19 18:25:30476bool Connection::OpenTemporary() {
477 return OpenInternal("", NO_RETRY);
478}
479
[email protected]41a97c812013-02-07 02:35:38480void Connection::CloseInternal(bool forced) {
[email protected]4e179ba62012-03-17 16:06:47481 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
482 // will delete the -journal file. For ChromiumOS or other more
483 // embedded systems, this is probably not appropriate, whereas on
484 // desktop it might make some sense.
485
[email protected]4b350052012-02-24 20:40:48486 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48487
[email protected]41a97c812013-02-07 02:35:38488 // Release cached statements.
489 statement_cache_.clear();
490
491 // With cached statements released, in-use statements will remain.
492 // Closing the database while statements are in use is an API
493 // violation, except for forced close (which happens from within a
494 // statement's error handler).
495 DCHECK(forced || open_statements_.empty());
496
497 // Deactivate any outstanding statements so sqlite3_close() works.
498 for (StatementRefSet::iterator i = open_statements_.begin();
499 i != open_statements_.end(); ++i)
500 (*i)->Close(forced);
501 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48502
[email protected]e5ffd0e42009-09-11 21:30:56503 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50504 // Call to AssertIOAllowed() cannot go at the beginning of the function
505 // because Close() must be called from destructor to clean
506 // statement_cache_, it won't cause any disk access and it most probably
507 // will happen on thread not allowing disk access.
508 // TODO([email protected]): This should move to the beginning
509 // of the function. http://crbug.com/136655.
510 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28511
512 int rc = sqlite3_close(db_);
513 if (rc != SQLITE_OK) {
514 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
515 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
516 }
[email protected]e5ffd0e42009-09-11 21:30:56517 }
[email protected]fed734a2013-07-17 04:45:13518 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56519}
520
[email protected]41a97c812013-02-07 02:35:38521void Connection::Close() {
522 // If the database was already closed by RazeAndClose(), then no
523 // need to close again. Clear the |poisoned_| bit so that incorrect
524 // API calls are caught.
525 if (poisoned_) {
526 poisoned_ = false;
527 return;
528 }
529
530 CloseInternal(false);
531}
532
[email protected]e5ffd0e42009-09-11 21:30:56533void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50534 AssertIOAllowed();
535
[email protected]e5ffd0e42009-09-11 21:30:56536 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38537 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56538 return;
539 }
540
[email protected]8ada10f2013-12-21 00:42:34541 // Use local settings if provided, otherwise use documented defaults. The
542 // actual results could be fetching via PRAGMA calls.
543 const int page_size = page_size_ ? page_size_ : 1024;
544 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
545 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56546 return;
547
[email protected]8ada10f2013-12-21 00:42:34548 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34549 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42550 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34551 if (rc != SQLITE_OK)
552 return;
553
554 // Don't preload more than the file contains.
555 if (preload_size > file_size)
556 preload_size = file_size;
557
558 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46559 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34560 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31561
562 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34563 if (rc != SQLITE_OK)
564 return;
565 }
[email protected]e5ffd0e42009-09-11 21:30:56566}
567
shess7dbd4dee2015-10-06 17:39:16568// SQLite keeps unused pages associated with a connection in a cache. It asks
569// the cache for pages by an id, and if the page is present and the database is
570// unchanged, it considers the content of the page valid and doesn't read it
571// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
572// structures created from the memory map data before consulting the cache. On
573// write SQLite creates a new in-memory page structure, copies the data from the
574// memory map, and later writes it, releasing the updated page back to the
575// cache.
576//
577// This means that in memory-mapped mode, the contents of the cached pages are
578// not re-used for reads, but they are re-used for writes if the re-written page
579// is still in the cache. The implementation of sqlite3_db_release_memory() as
580// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
581// connection, so it should free these pages.
582//
583// Unfortunately, the zero page is also freed. That page is never accessed
584// using memory-mapped I/O, and the cached copy can be re-used after verifying
585// the file change counter on disk. Also, fresh pages from cache receive some
586// pager-level initialization before they can be used. Since the information
587// involved will immediately be accessed in various ways, it is unclear if the
588// additional overhead is material, or just moving processor cache effects
589// around.
590//
591// TODO(shess): It would be better to release the pages immediately when they
592// are no longer needed. This would basically happen after SQLite commits a
593// transaction. I had implemented a pcache wrapper to do this, but it involved
594// layering violations, and it had to be setup before any other sqlite call,
595// which was brittle. Also, for large files it would actually make sense to
596// maintain the existing pcache behavior for blocks past the memory-mapped
597// segment. I think drh would accept a reasonable implementation of the overall
598// concept for upstreaming to SQLite core.
599//
600// TODO(shess): Another possibility would be to set the cache size small, which
601// would keep the zero page around, plus some pre-initialized pages, and SQLite
602// can manage things. The downside is that updates larger than the cache would
603// spill to the journal. That could be compensated by setting cache_spill to
604// false. The downside then is that it allows open-ended use of memory for
605// large transactions.
606//
607// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
608// work. There could be two prepared statements, one for cache_size=1 one for
609// cache_size=goal.
610void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
611 DCHECK(is_open());
612
613 // If memory-mapping is not enabled, the page cache helps performance.
614 if (!mmap_enabled_)
615 return;
616
617 // On caller request, force the change comparison to fail. Done before the
618 // transaction-nesting test so that the signal can carry to transaction
619 // commit.
620 if (implicit_change_performed)
621 --total_changes_at_last_release_;
622
623 // Cached pages may be re-used within the same transaction.
624 if (transaction_nesting())
625 return;
626
627 // If no changes have been made, skip flushing. This allows the first page of
628 // the database to remain in cache across multiple reads.
629 const int total_changes = sqlite3_total_changes(db_);
630 if (total_changes == total_changes_at_last_release_)
631 return;
632
633 total_changes_at_last_release_ = total_changes;
634 sqlite3_db_release_memory(db_);
635}
636
shessc8cd2a162015-10-22 20:30:46637base::FilePath Connection::DbPath() const {
638 if (!is_open())
639 return base::FilePath();
640
641 const char* path = sqlite3_db_filename(db_, "main");
642 const base::StringPiece db_path(path);
643#if defined(OS_WIN)
644 return base::FilePath(base::UTF8ToWide(db_path));
645#elif defined(OS_POSIX)
646 return base::FilePath(db_path);
647#else
648 NOTREACHED();
649 return base::FilePath();
650#endif
651}
652
653// Data is persisted in a file shared between databases in the same directory.
654// The "sqlite-diag" file contains a dictionary with the version number, and an
655// array of histogram tags for databases which have been dumped.
656bool Connection::RegisterIntentToUpload() const {
657 static const char* kVersionKey = "version";
658 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
659 static int kVersion = 1;
660
661 AssertIOAllowed();
662
663 if (histogram_tag_.empty())
664 return false;
665
666 if (!is_open())
667 return false;
668
669 if (in_memory_)
670 return false;
671
672 const base::FilePath db_path = DbPath();
673 if (db_path.empty())
674 return false;
675
676 // Put the collection of diagnostic data next to the databases. In most
677 // cases, this is the profile directory, but safe-browsing stores a Cookies
678 // file in the directory above the profile directory.
679 base::FilePath breadcrumb_path(
680 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
681
682 // Lock against multiple updates to the diagnostics file. This code should
683 // seldom be called in the first place, and when called it should seldom be
684 // called for multiple databases, and when called for multiple databases there
685 // is _probably_ something systemic wrong with the user's system. So the lock
686 // should never be contended, but when it is the database experience is
687 // already bad.
688 base::AutoLock lock(g_sqlite_init_lock.Get());
689
690 scoped_ptr<base::Value> root;
691 if (!base::PathExists(breadcrumb_path)) {
692 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
693 root_dict->SetInteger(kVersionKey, kVersion);
694
695 scoped_ptr<base::ListValue> dumps(new base::ListValue);
696 dumps->AppendString(histogram_tag_);
697 root_dict->Set(kDiagnosticDumpsKey, dumps.Pass());
698
699 root = root_dict.Pass();
700 } else {
701 // Failure to read a valid dictionary implies that something is going wrong
702 // on the system.
703 JSONFileValueDeserializer deserializer(breadcrumb_path);
704 scoped_ptr<base::Value> read_root(
705 deserializer.Deserialize(nullptr, nullptr));
706 if (!read_root.get())
707 return false;
708 scoped_ptr<base::DictionaryValue> root_dict =
709 base::DictionaryValue::From(read_root.Pass());
710 if (!root_dict)
711 return false;
712
713 // Don't upload if the version is missing or newer.
714 int version = 0;
715 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
716 return false;
717
718 base::ListValue* dumps = nullptr;
719 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
720 return false;
721
722 const size_t size = dumps->GetSize();
723 for (size_t i = 0; i < size; ++i) {
724 std::string s;
725
726 // Don't upload if the value isn't a string, or indicates a prior upload.
727 if (!dumps->GetString(i, &s) || s == histogram_tag_)
728 return false;
729 }
730
731 // Record intention to proceed with upload.
732 dumps->AppendString(histogram_tag_);
733 root = root_dict.Pass();
734 }
735
736 const base::FilePath breadcrumb_new =
737 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
738 base::DeleteFile(breadcrumb_new, false);
739
740 // No upload if the breadcrumb file cannot be updated.
741 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
742 // the data on disk. For now, losing the data is not a big problem, so the
743 // sync overhead would probably not be worth it.
744 JSONFileValueSerializer serializer(breadcrumb_new);
745 if (!serializer.Serialize(*root))
746 return false;
747 if (!base::PathExists(breadcrumb_new))
748 return false;
749 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
750 base::DeleteFile(breadcrumb_new, false);
751 return false;
752 }
753
754 return true;
755}
756
757std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
758 // Buffer for accumulating debugging info about the error. Place
759 // more-relevant information earlier, in case things overflow the
760 // fixed-size reporting buffer.
761 std::string debug_info;
762
763 // The error message from the failed operation.
764 base::StringAppendF(&debug_info, "db error: %d/%s\n",
765 GetErrorCode(), GetErrorMessage());
766
767 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
768 // reading code does not entirely convince me. Remove if they turn out to be
769 // the same.
770 if (error != GetErrorCode())
771 base::StringAppendF(&debug_info, "reported error: %d\n", error);
772
773 // System error information. Interpretation of Windows errors is different
774 // from posix.
775#if defined(OS_WIN)
776 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
777#elif defined(OS_POSIX)
778 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
779#else
780 NOTREACHED(); // Add appropriate log info.
781#endif
782
783 if (stmt) {
784 base::StringAppendF(&debug_info, "statement: %s\n",
785 stmt->GetSQLStatement());
786 } else {
787 base::StringAppendF(&debug_info, "statement: NULL\n");
788 }
789
790 // SQLITE_ERROR often indicates some sort of mismatch between the statement
791 // and the schema, possibly due to a failed schema migration.
792 if (error == SQLITE_ERROR) {
793 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
794 sqlite3_stmt* s;
795 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
796 if (rc == SQLITE_OK) {
797 rc = sqlite3_step(s);
798 if (rc == SQLITE_ROW) {
799 base::StringAppendF(&debug_info, "version: %d\n",
800 sqlite3_column_int(s, 0));
801 } else if (rc == SQLITE_DONE) {
802 debug_info += "version: none\n";
803 } else {
804 base::StringAppendF(&debug_info, "version: error %d\n", rc);
805 }
806 sqlite3_finalize(s);
807 } else {
808 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
809 }
810
811 debug_info += "schema:\n";
812
813 // sqlite_master has columns:
814 // type - "index" or "table".
815 // name - name of created element.
816 // tbl_name - name of element, or target table in case of index.
817 // rootpage - root page of the element in database file.
818 // sql - SQL to create the element.
819 // In general, the |sql| column is sufficient to derive the other columns.
820 // |rootpage| is not interesting for debugging, without the contents of the
821 // database. The COALESCE is because certain automatic elements will have a
822 // |name| but no |sql|,
823 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
824 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
825 if (rc == SQLITE_OK) {
826 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
827 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
828 }
829 if (rc != SQLITE_DONE)
830 base::StringAppendF(&debug_info, "error %d\n", rc);
831 sqlite3_finalize(s);
832 } else {
833 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
834 }
835 }
836
837 return debug_info;
838}
839
840// TODO(shess): Since this is only called in an error situation, it might be
841// prudent to rewrite in terms of SQLite API calls, and mark the function const.
842std::string Connection::CollectCorruptionInfo() {
843 AssertIOAllowed();
844
845 // If the file cannot be accessed it is unlikely that an integrity check will
846 // turn up actionable information.
847 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19848 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46849 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
850 return std::string();
851
852 // Buffer for accumulating debugging info about the error. Place
853 // more-relevant information earlier, in case things overflow the
854 // fixed-size reporting buffer.
855 std::string debug_info;
856 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
857 db_size);
858
859 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19860 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46861 if (db_size > kMaxIntegrityCheckSize) {
862 debug_info += "integrity_check skipped due to size\n";
863 } else {
864 std::vector<std::string> messages;
865
866 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
867 // into a string. Probably should be refactored.
868 const base::TimeTicks before = base::TimeTicks::Now();
869 FullIntegrityCheck(&messages);
870 base::StringAppendF(
871 &debug_info,
872 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
873 (base::TimeTicks::Now() - before).InMilliseconds(),
874 messages.size());
875
876 // SQLite returns up to 100 messages by default, trim deeper to
877 // keep close to the 2000-character size limit for dumping.
878 const size_t kMaxMessages = 20;
879 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
880 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
881 }
882 }
883
884 return debug_info;
885}
886
shessd90aeea82015-11-13 02:24:31887size_t Connection::GetAppropriateMmapSize() {
888 AssertIOAllowed();
889
shessd90aeea82015-11-13 02:24:31890#if defined(OS_IOS)
891 // iOS SQLite does not support memory mapping.
892 return 0;
893#endif
894
shess9bf2c672015-12-18 01:18:08895 // How much to map if no errors are found. 50MB encompasses the 99th
896 // percentile of Chrome databases in the wild, so this should be good.
897 const size_t kMmapEverything = 256 * 1024 * 1024;
898
899 // If the database doesn't have a place to track progress, assume the best.
900 // This will happen when new databases are created, or if a database doesn't
901 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
902 // TODO(shess): Databases not using meta include:
903 // DOMStorageDatabase (localstorage)
904 // ActivityDatabase (extensions activity log)
905 // PredictorDatabase (prefetch and autocomplete predictor data)
906 // SyncDirectory (sync metadata storage)
907 // For now, these all have mmap disabled to allow other databases to get the
908 // default-enable path. sqlite-diag could be an alternative for all but
909 // DOMStorageDatabase, which creates many small databases.
910 // http://crbug.com/537742
911 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31912 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08913 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31914 }
915
shess9bf2c672015-12-18 01:18:08916 int64_t mmap_ofs = 0;
917 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
918 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
919 return 0;
shessd90aeea82015-11-13 02:24:31920 }
921
922 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08923 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31924 RecordOneEvent(EVENT_MMAP_FAILED);
925 return 0;
shess9bf2c672015-12-18 01:18:08926 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31927 // Continue reading from previous offset.
928 DCHECK_GE(mmap_ofs, 0);
929
930 // TODO(shess): Could this reading code be shared with Preload()? It would
931 // require locking twice (this code wouldn't be able to access |db_size| so
932 // the helper would have to return amount read).
933
934 // Read more of the database looking for errors. The VFS interface is used
935 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
936 // to limit checking to 20MB per run of Chromium.
937 sqlite3_file* file = NULL;
938 sqlite3_int64 db_size = 0;
939 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
940 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
941 return 0;
942 }
943
944 // Read the data left, or |g_reads_allowed|, whichever is smaller.
945 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
946 // in a single Chromium run.
947 sqlite3_int64 amount = db_size - mmap_ofs;
948 if (amount < 0)
949 amount = 0;
950 if (amount > 0) {
951 base::AutoLock lock(g_sqlite_init_lock.Get());
952 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
953 if (g_reads_allowed < amount)
954 amount = g_reads_allowed;
955 g_reads_allowed -= amount;
956 }
957
958 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
959 // database was truncated after a previous pass.
960 if (amount <= 0 && mmap_ofs < db_size) {
961 DCHECK_EQ(0, amount);
962 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
963 } else {
964 static const int kPageSize = 4096;
965 char buf[kPageSize];
966 while (amount > 0) {
967 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
968 if (rc == SQLITE_OK) {
969 mmap_ofs += sizeof(buf);
970 amount -= sizeof(buf);
971 } else if (rc == SQLITE_IOERR_SHORT_READ) {
972 // Reached EOF for a database with page size < |kPageSize|.
973 mmap_ofs = db_size;
974 break;
975 } else {
976 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08977 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31978 break;
979 }
980 }
981
982 // Log these events after update to distinguish meta update failure.
983 Events event;
984 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08985 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31986 event = EVENT_MMAP_SUCCESS_NEW;
987 } else if (mmap_ofs > 0) {
988 event = EVENT_MMAP_SUCCESS_PARTIAL;
989 } else {
shess9bf2c672015-12-18 01:18:08990 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31991 event = EVENT_MMAP_FAILED_NEW;
992 }
993
shess9bf2c672015-12-18 01:18:08994 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31995 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
996 return 0;
997 }
998
999 RecordOneEvent(event);
1000 }
1001 }
1002
shess9bf2c672015-12-18 01:18:081003 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:311004 return 0;
shess9bf2c672015-12-18 01:18:081005 if (mmap_ofs == MetaTable::kMmapSuccess)
1006 return kMmapEverything;
shessd90aeea82015-11-13 02:24:311007 return mmap_ofs;
1008}
1009
[email protected]be7995f12013-07-18 18:49:141010void Connection::TrimMemory(bool aggressively) {
1011 if (!db_)
1012 return;
1013
1014 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1015 int original_cache_size;
1016 {
1017 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1018 if (!sql_get_original.Step()) {
1019 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1020 return;
1021 }
1022 original_cache_size = sql_get_original.ColumnInt(0);
1023 }
1024 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1025
1026 // Force sqlite to try to reduce page cache usage.
1027 const std::string sql_shrink =
1028 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1029 if (!Execute(sql_shrink.c_str()))
1030 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1031
1032 // Restore cache size.
1033 const std::string sql_restore =
1034 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1035 if (!Execute(sql_restore.c_str()))
1036 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1037}
1038
[email protected]8e0c01282012-04-06 19:36:491039// Create an in-memory database with the existing database's page
1040// size, then backup that database over the existing database.
1041bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501042 AssertIOAllowed();
1043
[email protected]8e0c01282012-04-06 19:36:491044 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381045 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491046 return false;
1047 }
1048
1049 if (transaction_nesting_ > 0) {
1050 DLOG(FATAL) << "Cannot raze within a transaction";
1051 return false;
1052 }
1053
1054 sql::Connection null_db;
1055 if (!null_db.OpenInMemory()) {
1056 DLOG(FATAL) << "Unable to open in-memory database.";
1057 return false;
1058 }
1059
[email protected]6d42f152012-11-10 00:38:241060 if (page_size_) {
1061 // Enforce SQLite restrictions on |page_size_|.
1062 DCHECK(!(page_size_ & (page_size_ - 1)))
1063 << " page_size_ " << page_size_ << " is not a power of two.";
1064 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1065 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041066 const std::string sql =
1067 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421068 if (!null_db.Execute(sql.c_str()))
1069 return false;
1070 }
1071
[email protected]6d42f152012-11-10 00:38:241072#if defined(OS_ANDROID)
1073 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1074 // in-memory databases do not respect this define.
1075 // TODO(shess): Figure out a way to set this without using platform
1076 // specific code. AFAICT from sqlite3.c, the only way to do it
1077 // would be to create an actual filesystem database, which is
1078 // unfortunate.
1079 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1080 return false;
1081#endif
[email protected]8e0c01282012-04-06 19:36:491082
1083 // The page size doesn't take effect until a database has pages, and
1084 // at this point the null database has none. Changing the schema
1085 // version will create the first page. This will not affect the
1086 // schema version in the resulting database, as SQLite's backup
1087 // implementation propagates the schema version from the original
1088 // connection to the new version of the database, incremented by one
1089 // so that other readers see the schema change and act accordingly.
1090 if (!null_db.Execute("PRAGMA schema_version = 1"))
1091 return false;
1092
[email protected]6d42f152012-11-10 00:38:241093 // SQLite tracks the expected number of database pages in the first
1094 // page, and if it does not match the total retrieved from a
1095 // filesystem call, treats the database as corrupt. This situation
1096 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1097 // used to hint to SQLite to soldier on in that case, specifically
1098 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1099 // sqlite3.c lockBtree().]
1100 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1101 // page_size" can be used to query such a database.
1102 ScopedWritableSchema writable_schema(db_);
1103
[email protected]7bae5742013-07-10 20:46:161104 const char* kMain = "main";
1105 int rc = BackupDatabase(null_db.db_, db_, kMain);
1106 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491107
1108 // The destination database was locked.
1109 if (rc == SQLITE_BUSY) {
1110 return false;
1111 }
1112
[email protected]7bae5742013-07-10 20:46:161113 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1114 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1115 // isn't even big enough for one page. Either way, reach in and
1116 // truncate it before trying again.
1117 // TODO(shess): Maybe it would be worthwhile to just truncate from
1118 // the get-go?
1119 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1120 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341121 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161122 if (rc != SQLITE_OK) {
1123 DLOG(FATAL) << "Failure getting file handle.";
1124 return false;
[email protected]7bae5742013-07-10 20:46:161125 }
1126
1127 rc = file->pMethods->xTruncate(file, 0);
1128 if (rc != SQLITE_OK) {
1129 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1130 DLOG(FATAL) << "Failed to truncate file.";
1131 return false;
1132 }
1133
1134 rc = BackupDatabase(null_db.db_, db_, kMain);
1135 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1136
1137 if (rc != SQLITE_DONE) {
1138 DLOG(FATAL) << "Failed retrying Raze().";
1139 }
1140 }
1141
[email protected]8e0c01282012-04-06 19:36:491142 // The entire database should have been backed up.
1143 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161144 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491145 DLOG(FATAL) << "Unable to copy entire null database.";
1146 return false;
1147 }
1148
[email protected]8e0c01282012-04-06 19:36:491149 return true;
1150}
1151
1152bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1153 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381154 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491155 return false;
1156 }
1157
1158 ScopedBusyTimeout busy_timeout(db_);
1159 busy_timeout.SetTimeout(timeout);
1160 return Raze();
1161}
1162
[email protected]41a97c812013-02-07 02:35:381163bool Connection::RazeAndClose() {
1164 if (!db_) {
1165 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1166 return false;
1167 }
1168
1169 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301170 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381171
1172 bool result = Raze();
1173
1174 CloseInternal(true);
1175
1176 // Mark the database so that future API calls fail appropriately,
1177 // but don't DCHECK (because after calling this function they are
1178 // expected to fail).
1179 poisoned_ = true;
1180
1181 return result;
1182}
1183
[email protected]8d409412013-07-19 18:25:301184void Connection::Poison() {
1185 if (!db_) {
1186 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1187 return;
1188 }
1189
1190 RollbackAllTransactions();
1191 CloseInternal(true);
1192
1193 // Mark the database so that future API calls fail appropriately,
1194 // but don't DCHECK (because after calling this function they are
1195 // expected to fail).
1196 poisoned_ = true;
1197}
1198
[email protected]8d2e39e2013-06-24 05:55:081199// TODO(shess): To the extent possible, figure out the optimal
1200// ordering for these deletes which will prevent other connections
1201// from seeing odd behavior. For instance, it may be necessary to
1202// manually lock the main database file in a SQLite-compatible fashion
1203// (to prevent other processes from opening it), then delete the
1204// journal files, then delete the main database file. Another option
1205// might be to lock the main database file and poison the header with
1206// junk to prevent other processes from opening it successfully (like
1207// Gears "SQLite poison 3" trick).
1208//
1209// static
1210bool Connection::Delete(const base::FilePath& path) {
1211 base::ThreadRestrictions::AssertIOAllowed();
1212
1213 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1214 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1215
erg102ceb412015-06-20 01:38:131216 std::string journal_str = AsUTF8ForSQL(journal_path);
1217 std::string wal_str = AsUTF8ForSQL(wal_path);
1218 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081219
shess702467622015-09-16 19:04:551220 // Make sure sqlite3_initialize() is called before anything else.
1221 InitializeSqlite();
1222
erg102ceb412015-06-20 01:38:131223 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1224 CHECK(vfs);
1225 CHECK(vfs->xDelete);
1226 CHECK(vfs->xAccess);
1227
1228 // We only work with unix, win32 and mojo filesystems. If you're trying to
1229 // use this code with any other VFS, you're not in a good place.
1230 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1231 strncmp(vfs->zName, "win32", 5) == 0 ||
1232 strcmp(vfs->zName, "mojo") == 0);
1233
1234 vfs->xDelete(vfs, journal_str.c_str(), 0);
1235 vfs->xDelete(vfs, wal_str.c_str(), 0);
1236 vfs->xDelete(vfs, path_str.c_str(), 0);
1237
1238 int journal_exists = 0;
1239 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1240 &journal_exists);
1241
1242 int wal_exists = 0;
1243 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1244 &wal_exists);
1245
1246 int path_exists = 0;
1247 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1248 &path_exists);
1249
1250 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081251}
1252
[email protected]e5ffd0e42009-09-11 21:30:561253bool Connection::BeginTransaction() {
1254 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331255 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561256
1257 // When we're going to rollback, fail on this begin and don't actually
1258 // mark us as entering the nested transaction.
1259 return false;
1260 }
1261
1262 bool success = true;
1263 if (!transaction_nesting_) {
1264 needs_rollback_ = false;
1265
1266 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321267 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591268 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561269 return false;
1270 }
1271 transaction_nesting_++;
1272 return success;
1273}
1274
1275void Connection::RollbackTransaction() {
1276 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381277 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561278 return;
1279 }
1280
1281 transaction_nesting_--;
1282
1283 if (transaction_nesting_ > 0) {
1284 // Mark the outermost transaction as needing rollback.
1285 needs_rollback_ = true;
1286 return;
1287 }
1288
1289 DoRollback();
1290}
1291
1292bool Connection::CommitTransaction() {
1293 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181294 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561295 return false;
1296 }
1297 transaction_nesting_--;
1298
1299 if (transaction_nesting_ > 0) {
1300 // Mark any nested transactions as failing after we've already got one.
1301 return !needs_rollback_;
1302 }
1303
1304 if (needs_rollback_) {
1305 DoRollback();
1306 return false;
1307 }
1308
1309 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321310
1311 // Collect the commit time manually, sql::Statement would register it as query
1312 // time only.
1313 const base::TimeTicks before = Now();
1314 bool ret = commit.RunWithoutTimers();
1315 const base::TimeDelta delta = Now() - before;
1316
1317 RecordCommitTime(delta);
1318 RecordOneEvent(EVENT_COMMIT);
1319
shess7dbd4dee2015-10-06 17:39:161320 // Release dirty cache pages after the transaction closes.
1321 ReleaseCacheMemoryIfNeeded(false);
1322
shess58b8df82015-06-03 00:19:321323 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561324}
1325
[email protected]8d409412013-07-19 18:25:301326void Connection::RollbackAllTransactions() {
1327 if (transaction_nesting_ > 0) {
1328 transaction_nesting_ = 0;
1329 DoRollback();
1330 }
1331}
1332
1333bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1334 const char* attachment_point) {
1335 DCHECK(ValidAttachmentPoint(attachment_point));
1336
1337 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1338#if OS_WIN
1339 s.BindString16(0, other_db_path.value());
1340#else
1341 s.BindString(0, other_db_path.value());
1342#endif
1343 s.BindString(1, attachment_point);
1344 return s.Run();
1345}
1346
1347bool Connection::DetachDatabase(const char* attachment_point) {
1348 DCHECK(ValidAttachmentPoint(attachment_point));
1349
1350 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1351 s.BindString(0, attachment_point);
1352 return s.Run();
1353}
1354
shess58b8df82015-06-03 00:19:321355// TODO(shess): Consider changing this to execute exactly one statement. If a
1356// caller wishes to execute multiple statements, that should be explicit, and
1357// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591358int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501359 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381360 if (!db_) {
1361 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1362 return SQLITE_ERROR;
1363 }
shess58b8df82015-06-03 00:19:321364 DCHECK(sql);
1365
1366 RecordOneEvent(EVENT_EXECUTE);
1367 int rc = SQLITE_OK;
1368 while ((rc == SQLITE_OK) && *sql) {
1369 sqlite3_stmt *stmt = NULL;
1370 const char *leftover_sql;
1371
1372 const base::TimeTicks before = Now();
1373 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1374 sql = leftover_sql;
1375
1376 // Stop if an error is encountered.
1377 if (rc != SQLITE_OK)
1378 break;
1379
1380 // This happens if |sql| originally only contained comments or whitespace.
1381 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1382 // extraneous comments and whitespace in the SQL statements increases
1383 // runtime cost and can easily be shifted out to the C++ layer.
1384 if (!stmt)
1385 continue;
1386
1387 // Save for use after statement is finalized.
1388 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1389
1390 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1391 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1392 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1393 // is the only legitimate case for this.
1394 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1395 }
1396
1397 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1398 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1399 rc = sqlite3_finalize(stmt);
1400 if (rc == SQLITE_OK)
1401 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1402
1403 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1404 // trailing whitespace.
1405 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021406 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321407 sql++;
1408 }
1409
1410 const base::TimeDelta delta = Now() - before;
1411 RecordTimeAndChanges(delta, read_only);
1412 }
shess7dbd4dee2015-10-06 17:39:161413
1414 // Most calls to Execute() modify the database. The main exceptions would be
1415 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1416 // but sometimes don't.
1417 ReleaseCacheMemoryIfNeeded(true);
1418
shess58b8df82015-06-03 00:19:321419 return rc;
[email protected]eff1fa522011-12-12 23:50:591420}
1421
1422bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381423 if (!db_) {
1424 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1425 return false;
1426 }
1427
[email protected]eff1fa522011-12-12 23:50:591428 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001429 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581430 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001431
[email protected]28fe0ff2012-02-25 00:40:331432 // This needs to be a FATAL log because the error case of arriving here is
1433 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101434 // a change alters the schema but not all queries adjust. This can happen
1435 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591436 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331437 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591438 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561439}
1440
[email protected]5b96f3772010-09-28 16:30:571441bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381442 if (!db_) {
1443 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571444 return false;
[email protected]41a97c812013-02-07 02:35:381445 }
[email protected]5b96f3772010-09-28 16:30:571446
1447 ScopedBusyTimeout busy_timeout(db_);
1448 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591449 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571450}
1451
[email protected]e5ffd0e42009-09-11 21:30:561452bool Connection::HasCachedStatement(const StatementID& id) const {
1453 return statement_cache_.find(id) != statement_cache_.end();
1454}
1455
1456scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1457 const StatementID& id,
1458 const char* sql) {
1459 CachedStatementMap::iterator i = statement_cache_.find(id);
1460 if (i != statement_cache_.end()) {
1461 // Statement is in the cache. It should still be active (we're the only
1462 // one invalidating cached statements, and we'll remove it from the cache
1463 // if we do that. Make sure we reset it before giving out the cached one in
1464 // case it still has some stuff bound.
1465 DCHECK(i->second->is_valid());
1466 sqlite3_reset(i->second->stmt());
1467 return i->second;
1468 }
1469
1470 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1471 if (statement->is_valid())
1472 statement_cache_[id] = statement; // Only cache valid statements.
1473 return statement;
1474}
1475
1476scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1477 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501478 AssertIOAllowed();
1479
[email protected]41a97c812013-02-07 02:35:381480 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561481 if (!db_)
[email protected]41a97c812013-02-07 02:35:381482 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561483
1484 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001485 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1486 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591487 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061488 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021489 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001490
1491 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581492 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381493 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561494 }
[email protected]41a97c812013-02-07 02:35:381495 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561496}
1497
shessf7e988f2015-11-13 00:41:061498// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1499// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581500scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1501 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381502 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581503 if (!db_)
[email protected]41a97c812013-02-07 02:35:381504 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581505
1506 sqlite3_stmt* stmt = NULL;
1507 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1508 if (rc != SQLITE_OK) {
1509 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061510 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021511 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381512 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581513 }
[email protected]41a97c812013-02-07 02:35:381514 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581515}
1516
[email protected]92cd00a2013-08-16 11:09:581517std::string Connection::GetSchema() const {
1518 // The ORDER BY should not be necessary, but relying on organic
1519 // order for something like this is questionable.
1520 const char* kSql =
1521 "SELECT type, name, tbl_name, sql "
1522 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1523 Statement statement(GetUntrackedStatement(kSql));
1524
1525 std::string schema;
1526 while (statement.Step()) {
1527 schema += statement.ColumnString(0);
1528 schema += '|';
1529 schema += statement.ColumnString(1);
1530 schema += '|';
1531 schema += statement.ColumnString(2);
1532 schema += '|';
1533 schema += statement.ColumnString(3);
1534 schema += '\n';
1535 }
1536
1537 return schema;
1538}
1539
[email protected]eff1fa522011-12-12 23:50:591540bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501541 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381542 if (!db_) {
1543 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1544 return false;
1545 }
1546
[email protected]eff1fa522011-12-12 23:50:591547 sqlite3_stmt* stmt = NULL;
1548 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1549 return false;
1550
1551 sqlite3_finalize(stmt);
1552 return true;
1553}
1554
[email protected]1ed78a32009-09-15 20:24:171555bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531556 return DoesTableOrIndexExist(table_name, "table");
1557}
1558
1559bool Connection::DoesIndexExist(const char* index_name) const {
1560 return DoesTableOrIndexExist(index_name, "index");
1561}
1562
1563bool Connection::DoesTableOrIndexExist(
1564 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471565 const char* kSql =
1566 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581567 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471568
1569 // This can happen if the database is corrupt and the error is being ignored
1570 // for testing purposes.
1571 if (!statement.is_valid())
1572 return false;
1573
[email protected]e2cadec82011-12-13 02:00:531574 statement.BindString(0, type);
1575 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331576
[email protected]e5ffd0e42009-09-11 21:30:561577 return statement.Step(); // Table exists if any row was returned.
1578}
1579
1580bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171581 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561582 std::string sql("PRAGMA TABLE_INFO(");
1583 sql.append(table_name);
1584 sql.append(")");
1585
[email protected]2eec0a22012-07-24 01:59:581586 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471587
1588 // This can happen if the database is corrupt and the error is being ignored
1589 // for testing purposes.
1590 if (!statement.is_valid())
1591 return false;
1592
[email protected]e5ffd0e42009-09-11 21:30:561593 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331594 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1595 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561596 return true;
1597 }
1598 return false;
1599}
1600
tfarina720d4f32015-05-11 22:31:261601int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561602 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381603 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561604 return 0;
1605 }
1606 return sqlite3_last_insert_rowid(db_);
1607}
1608
[email protected]1ed78a32009-09-15 20:24:171609int Connection::GetLastChangeCount() const {
1610 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381611 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171612 return 0;
1613 }
1614 return sqlite3_changes(db_);
1615}
1616
[email protected]e5ffd0e42009-09-11 21:30:561617int Connection::GetErrorCode() const {
1618 if (!db_)
1619 return SQLITE_ERROR;
1620 return sqlite3_errcode(db_);
1621}
1622
[email protected]767718e52010-09-21 23:18:491623int Connection::GetLastErrno() const {
1624 if (!db_)
1625 return -1;
1626
1627 int err = 0;
1628 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1629 return -2;
1630
1631 return err;
1632}
1633
[email protected]e5ffd0e42009-09-11 21:30:561634const char* Connection::GetErrorMessage() const {
1635 if (!db_)
1636 return "sql::Connection has no connection.";
1637 return sqlite3_errmsg(db_);
1638}
1639
[email protected]fed734a2013-07-17 04:45:131640bool Connection::OpenInternal(const std::string& file_name,
1641 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501642 AssertIOAllowed();
1643
[email protected]9cfbc922009-11-17 20:13:171644 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591645 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171646 return false;
1647 }
1648
[email protected]a7ec1292013-07-22 22:02:181649 // Make sure sqlite3_initialize() is called before anything else.
1650 InitializeSqlite();
1651
shess58b8df82015-06-03 00:19:321652 // Setup the stats histograms immediately rather than allocating lazily.
1653 // Connections which won't exercise all of these probably shouldn't exist.
1654 if (!histogram_tag_.empty()) {
1655 stats_histogram_ =
1656 base::LinearHistogram::FactoryGet(
1657 "Sqlite.Stats." + histogram_tag_,
1658 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1659 base::HistogramBase::kUmaTargetedHistogramFlag);
1660
1661 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1662 // unreasonable time for any single operation, so there is not much value to
1663 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1664 // things are entirely busted.
1665 commit_time_histogram_ =
1666 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1667
1668 autocommit_time_histogram_ =
1669 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1670
1671 update_time_histogram_ =
1672 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1673
1674 query_time_histogram_ =
1675 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1676 }
1677
[email protected]41a97c812013-02-07 02:35:381678 // If |poisoned_| is set, it means an error handler called
1679 // RazeAndClose(). Until regular Close() is called, the caller
1680 // should be treating the database as open, but is_open() currently
1681 // only considers the sqlite3 handle's state.
1682 // TODO(shess): Revise is_open() to consider poisoned_, and review
1683 // to see if any non-testing code even depends on it.
1684 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161685 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381686
[email protected]765b44502009-10-02 05:01:421687 int err = sqlite3_open(file_name.c_str(), &db_);
1688 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281689 // Extended error codes cannot be enabled until a handle is
1690 // available, fetch manually.
1691 err = sqlite3_extended_errcode(db_);
1692
[email protected]bd2ccdb4a2012-12-07 22:14:501693 // Histogram failures specific to initial open for debugging
1694 // purposes.
[email protected]73fb8d52013-07-24 05:04:281695 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501696
[email protected]2f496b42013-09-26 18:36:581697 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131698 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291699 Close();
[email protected]fed734a2013-07-17 04:45:131700
1701 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1702 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421703 return false;
1704 }
1705
[email protected]81a2a602013-07-17 19:10:361706 // TODO(shess): OS_WIN support?
1707#if defined(OS_POSIX)
1708 if (restrict_to_user_) {
1709 DCHECK_NE(file_name, std::string(":memory"));
1710 base::FilePath file_path(file_name);
1711 int mode = 0;
1712 // TODO(shess): Arguably, failure to retrieve and change
1713 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081714 if (base::GetPosixFilePermissions(file_path, &mode)) {
1715 mode &= base::FILE_PERMISSION_USER_MASK;
1716 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361717
1718 // SQLite sets the permissions on these files from the main
1719 // database on create. Set them here in case they already exist
1720 // at this point. Failure to set these permissions should not
1721 // be fatal unless the file doesn't exist.
1722 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1723 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081724 base::SetPosixFilePermissions(journal_path, mode);
1725 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361726 }
1727 }
1728#endif // defined(OS_POSIX)
1729
[email protected]affa2da2013-06-06 22:20:341730 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1731 // Chromium already depends on small mallocs being efficient, so we disable
1732 // this to avoid the extra memory overhead.
1733 // This must be called immediatly after opening the database before any SQL
1734 // statements are run.
1735 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1736
[email protected]73fb8d52013-07-24 05:04:281737 // Enable extended result codes to provide more color on I/O errors.
1738 // Not having extended result codes is not a fatal problem, as
1739 // Chromium code does not attempt to handle I/O errors anyhow. The
1740 // current implementation always returns SQLITE_OK, the DCHECK is to
1741 // quickly notify someone if SQLite changes.
1742 err = sqlite3_extended_result_codes(db_, 1);
1743 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1744
[email protected]bd2ccdb4a2012-12-07 22:14:501745 // sqlite3_open() does not actually read the database file (unless a
1746 // hot journal is found). Successfully executing this pragma on an
1747 // existing database requires a valid header on page 1.
1748 // TODO(shess): For now, just probing to see what the lay of the
1749 // land is. If it's mostly SQLITE_NOTADB, then the database should
1750 // be razed.
1751 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1752 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281753 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431754
[email protected]2e1cee762013-07-09 14:40:001755#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1756 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1757 // REGEXP support. Add it in dynamically.
1758 err = sqlite3IcuInit(db_);
1759 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1760#endif // OS_IOS && USE_SYSTEM_SQLITE
1761
[email protected]5b96f3772010-09-28 16:30:571762 // If indicated, lock up the database before doing anything else, so
1763 // that the following code doesn't have to deal with locking.
1764 // TODO(shess): This code is brittle. Find the cases where code
1765 // doesn't request |exclusive_locking_| and audit that it does the
1766 // right thing with SQLITE_BUSY, and that it doesn't make
1767 // assumptions about who might change things in the database.
1768 // http://crbug.com/56559
1769 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101770 // TODO(shess): This should probably be a failure. Code which
1771 // requests exclusive locking but doesn't get it is almost certain
1772 // to be ill-tested.
1773 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571774 }
1775
[email protected]4e179ba62012-03-17 16:06:471776 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1777 // DELETE (default) - delete -journal file to commit.
1778 // TRUNCATE - truncate -journal file to commit.
1779 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091780 // TRUNCATE should be faster than DELETE because it won't need directory
1781 // changes for each transaction. PERSIST may break the spirit of using
1782 // secure_delete.
1783 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba62012-03-17 16:06:471784
[email protected]c68ce172011-11-24 22:30:271785 const base::TimeDelta kBusyTimeout =
1786 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1787
[email protected]765b44502009-10-02 05:01:421788 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571789 // Enforce SQLite restrictions on |page_size_|.
1790 DCHECK(!(page_size_ & (page_size_ - 1)))
1791 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241792 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571793 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041794 const std::string sql =
1795 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101796 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421797 }
1798
1799 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041800 const std::string sql =
1801 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101802 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421803 }
1804
[email protected]6e0b1442011-08-09 23:23:581805 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131806 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581807 Close();
[email protected]fed734a2013-07-17 04:45:131808 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1809 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581810 return false;
1811 }
1812
shess5dac334f2015-11-05 20:47:421813 // Set a reasonable chunk size for larger files. This reduces churn from
1814 // remapping memory on size changes. It also reduces filesystem
1815 // fragmentation.
1816 // TODO(shess): It may make sense to have this be hinted by the client.
1817 // Database sizes seem to be bimodal, some clients have consistently small
1818 // databases (<20k) while other clients have a broad distribution of sizes
1819 // (hundreds of kilobytes to many megabytes).
1820 sqlite3_file* file = NULL;
1821 sqlite3_int64 db_size = 0;
1822 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1823 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1824 int chunk_size = 4 * 1024;
1825 if (db_size > 128 * 1024)
1826 chunk_size = 32 * 1024;
1827 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1828 }
1829
shess2f3a814b2015-11-05 18:11:101830 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311831 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1832 // safe range to memory-map based on past regular I/O. This value will be
1833 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1834 // 64-bit platforms.
1835 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1836 std::string mmap_sql =
1837 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1838 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101839
1840 // Determine if memory-mapping has actually been enabled. The Execute() above
1841 // can succeed without changing the amount mapped.
1842 mmap_enabled_ = false;
1843 {
1844 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1845 if (s.Step() && s.ColumnInt64(0) > 0)
1846 mmap_enabled_ = true;
1847 }
1848
[email protected]765b44502009-10-02 05:01:421849 return true;
1850}
1851
[email protected]e5ffd0e42009-09-11 21:30:561852void Connection::DoRollback() {
1853 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321854
1855 // Collect the rollback time manually, sql::Statement would register it as
1856 // query time only.
1857 const base::TimeTicks before = Now();
1858 rollback.RunWithoutTimers();
1859 const base::TimeDelta delta = Now() - before;
1860
1861 RecordUpdateTime(delta);
1862 RecordOneEvent(EVENT_ROLLBACK);
1863
shess7dbd4dee2015-10-06 17:39:161864 // The cache may have been accumulating dirty pages for commit. Note that in
1865 // some cases sql::Transaction can fire rollback after a database is closed.
1866 if (is_open())
1867 ReleaseCacheMemoryIfNeeded(false);
1868
[email protected]44ad7d902012-03-23 00:09:051869 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561870}
1871
1872void Connection::StatementRefCreated(StatementRef* ref) {
1873 DCHECK(open_statements_.find(ref) == open_statements_.end());
1874 open_statements_.insert(ref);
1875}
1876
1877void Connection::StatementRefDeleted(StatementRef* ref) {
1878 StatementRefSet::iterator i = open_statements_.find(ref);
1879 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591880 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561881 else
1882 open_statements_.erase(i);
1883}
1884
shess58b8df82015-06-03 00:19:321885void Connection::set_histogram_tag(const std::string& tag) {
1886 DCHECK(!is_open());
1887 histogram_tag_ = tag;
1888}
1889
[email protected]210ce0af2013-05-15 09:10:391890void Connection::AddTaggedHistogram(const std::string& name,
1891 size_t sample) const {
1892 if (histogram_tag_.empty())
1893 return;
1894
1895 // TODO(shess): The histogram macros create a bit of static storage
1896 // for caching the histogram object. This code shouldn't execute
1897 // often enough for such caching to be crucial. If it becomes an
1898 // issue, the object could be cached alongside histogram_prefix_.
1899 std::string full_histogram_name = name + "." + histogram_tag_;
1900 base::HistogramBase* histogram =
1901 base::SparseHistogram::FactoryGet(
1902 full_histogram_name,
1903 base::HistogramBase::kUmaTargetedHistogramFlag);
1904 if (histogram)
1905 histogram->Add(sample);
1906}
1907
[email protected]2f496b42013-09-26 18:36:581908int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391909 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1910 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141911
1912 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581913 if (!sql && stmt)
1914 sql = stmt->GetSQLStatement();
1915 if (!sql)
1916 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061917
1918 std::string id = histogram_tag_;
1919 if (id.empty())
1920 id = DbPath().BaseName().AsUTF8Unsafe();
1921 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141922 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581923 << ": " << GetErrorMessage()
1924 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141925
[email protected]c3881b372013-05-17 08:39:461926 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561927 // Fire from a copy of the callback in case of reentry into
1928 // re/set_error_callback().
1929 // TODO(shess): <http://crbug.com/254584>
1930 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461931 return err;
1932 }
1933
[email protected]faa604e2009-09-25 22:38:591934 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571935 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101936 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591937 return err;
1938}
1939
[email protected]579446c2013-12-16 18:36:521940bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1941 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1942}
1943
1944bool Connection::QuickIntegrityCheck() {
1945 std::vector<std::string> messages;
1946 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1947 return false;
1948 return messages.size() == 1 && messages[0] == "ok";
1949}
1950
[email protected]80abf152013-05-22 12:42:421951// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521952bool Connection::IntegrityCheckHelper(
1953 const char* pragma_sql,
1954 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421955 messages->clear();
1956
[email protected]4658e2a02013-06-06 23:05:001957 // This has the side effect of setting SQLITE_RecoveryMode, which
1958 // allows SQLite to process through certain cases of corruption.
1959 // Failing to set this pragma probably means that the database is
1960 // beyond recovery.
1961 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1962 if (!Execute(kWritableSchema))
1963 return false;
1964
1965 bool ret = false;
1966 {
[email protected]579446c2013-12-16 18:36:521967 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001968
1969 // The pragma appears to return all results (up to 100 by default)
1970 // as a single string. This doesn't appear to be an API contract,
1971 // it could return separate lines, so loop _and_ split.
1972 while (stmt.Step()) {
1973 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181974 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1975 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001976 }
1977 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421978 }
[email protected]4658e2a02013-06-06 23:05:001979
1980 // Best effort to put things back as they were before.
1981 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1982 ignore_result(Execute(kNoWritableSchema));
1983
1984 return ret;
[email protected]80abf152013-05-22 12:42:421985}
1986
shess58b8df82015-06-03 00:19:321987base::TimeTicks TimeSource::Now() {
1988 return base::TimeTicks::Now();
1989}
1990
[email protected]e5ffd0e42009-09-11 21:30:561991} // namespace sql