blob: 1213a77fa78a0912b726e2d02a508c52a9f23b3d [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"
shess9bf2c672015-12-18 01:18:0827#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2128#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0329#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5630
[email protected]2e1cee762013-07-09 14:40:0031#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
32#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
33#endif
34
[email protected]5b96f3772010-09-28 16:30:5735namespace {
36
37// Spin for up to a second waiting for the lock to clear when setting
38// up the database.
39// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2740const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5741
42class ScopedBusyTimeout {
43 public:
44 explicit ScopedBusyTimeout(sqlite3* db)
45 : db_(db) {
46 }
47 ~ScopedBusyTimeout() {
48 sqlite3_busy_timeout(db_, 0);
49 }
50
51 int SetTimeout(base::TimeDelta timeout) {
52 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
53 return sqlite3_busy_timeout(db_,
54 static_cast<int>(timeout.InMilliseconds()));
55 }
56
57 private:
58 sqlite3* db_;
59};
60
[email protected]6d42f152012-11-10 00:38:2461// Helper to "safely" enable writable_schema. No error checking
62// because it is reasonable to just forge ahead in case of an error.
63// If turning it on fails, then most likely nothing will work, whereas
64// if turning it off fails, it only matters if some code attempts to
65// continue working with the database and tries to modify the
66// sqlite_master table (none of our code does this).
67class ScopedWritableSchema {
68 public:
69 explicit ScopedWritableSchema(sqlite3* db)
70 : db_(db) {
71 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
72 }
73 ~ScopedWritableSchema() {
74 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
75 }
76
77 private:
78 sqlite3* db_;
79};
80
[email protected]7bae5742013-07-10 20:46:1681// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
82// SQLite error code from running the backup step.
83int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
84 DCHECK_NE(src, dst);
85 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
86 if (!backup) {
87 // Since this call only sets things up, this indicates a gross
88 // error in SQLite.
89 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
90 return sqlite3_errcode(dst);
91 }
92
93 // -1 backs up the entire database.
94 int rc = sqlite3_backup_step(backup, -1);
95 int pages = sqlite3_backup_pagecount(backup);
96 sqlite3_backup_finish(backup);
97
98 // If successful, exactly one page should have been backed up. If
99 // this breaks, check this function to make sure assumptions aren't
100 // being broken.
101 if (rc == SQLITE_DONE)
102 DCHECK_EQ(pages, 1);
103
104 return rc;
105}
106
[email protected]8d409412013-07-19 18:25:30107// Be very strict on attachment point. SQLite can handle a much wider
108// character set with appropriate quoting, but Chromium code should
109// just use clean names to start with.
110bool ValidAttachmentPoint(const char* attachment_point) {
111 for (size_t i = 0; attachment_point[i]; ++i) {
112 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
113 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
114 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
115 attachment_point[i] == '_')) {
116 return false;
117 }
118 }
119 return true;
120}
121
shessc9e80ae22015-08-12 21:39:11122void RecordSqliteMemory10Min() {
123 const int64 used = sqlite3_memory_used();
124 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
125}
126
127void RecordSqliteMemoryHour() {
128 const int64 used = sqlite3_memory_used();
129 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
130}
131
132void RecordSqliteMemoryDay() {
133 const int64 used = sqlite3_memory_used();
134 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
135}
136
shess2d48e942015-08-25 17:39:51137void RecordSqliteMemoryWeek() {
138 const int64 used = sqlite3_memory_used();
139 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
140}
141
[email protected]a7ec1292013-07-22 22:02:18142// SQLite automatically calls sqlite3_initialize() lazily, but
143// sqlite3_initialize() uses double-checked locking and thus can have
144// data races.
145//
146// TODO(shess): Another alternative would be to have
147// sqlite3_initialize() called as part of process bring-up. If this
148// is changed, remove the dynamic_annotations dependency in sql.gyp.
149base::LazyInstance<base::Lock>::Leaky
150 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
151void InitializeSqlite() {
152 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11153 static bool first_call = true;
154 if (first_call) {
155 sqlite3_initialize();
156
157 // Schedule callback to record memory footprint histograms at 10m, 1h, and
158 // 1d. There may not be a message loop in tests.
159 if (base::MessageLoop::current()) {
160 base::MessageLoop::current()->PostDelayedTask(
161 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
162 base::TimeDelta::FromMinutes(10));
163 base::MessageLoop::current()->PostDelayedTask(
164 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
165 base::TimeDelta::FromHours(1));
166 base::MessageLoop::current()->PostDelayedTask(
167 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
168 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51169 base::MessageLoop::current()->PostDelayedTask(
170 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
171 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11172 }
173
174 first_call = false;
175 }
[email protected]a7ec1292013-07-22 22:02:18176}
177
[email protected]8ada10f2013-12-21 00:42:34178// Helper to get the sqlite3_file* associated with the "main" database.
179int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
180 *file = NULL;
181 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
182 if (rc != SQLITE_OK)
183 return rc;
184
185 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
186 // content_unittests, even though it should not be possible.
187 // http://crbug.com/329982
188 if (!*file || !(*file)->pMethods)
189 return SQLITE_ERROR;
190
191 return rc;
192}
193
shess5dac334f2015-11-05 20:47:42194// Convenience to get the sqlite3_file* and the size for the "main" database.
195int GetSqlite3FileAndSize(sqlite3* db,
196 sqlite3_file** file, sqlite3_int64* db_size) {
197 int rc = GetSqlite3File(db, file);
198 if (rc != SQLITE_OK)
199 return rc;
200
201 return (*file)->pMethods->xFileSize(*file, db_size);
202}
203
shess58b8df82015-06-03 00:19:32204// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
205base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
206 return base::Histogram::FactoryTimeGet(
207 name,
208 base::TimeDelta::FromMilliseconds(10),
209 base::TimeDelta::FromMinutes(3),
210 50,
211 base::HistogramBase::kUmaTargetedHistogramFlag);
212}
213
erg102ceb412015-06-20 01:38:13214std::string AsUTF8ForSQL(const base::FilePath& path) {
215#if defined(OS_WIN)
216 return base::WideToUTF8(path.value());
217#elif defined(OS_POSIX)
218 return path.value();
219#endif
220}
221
[email protected]5b96f3772010-09-28 16:30:57222} // namespace
223
[email protected]e5ffd0e42009-09-11 21:30:56224namespace sql {
225
[email protected]4350e322013-06-18 22:18:10226// static
227Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
228
229// static
[email protected]74cdede2013-09-25 05:39:57230bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10231 if (!current_ignorer_cb_)
232 return false;
233 return current_ignorer_cb_->Run(error);
234}
235
shessf7e988f2015-11-13 00:41:06236// static
237bool Connection::ShouldIgnoreSqliteCompileError(int error) {
238 // Put this first in case tests need to see that the check happened.
239 if (ShouldIgnoreSqliteError(error))
240 return true;
241
242 // Trim extended error codes.
243 int basic_error = error & 0xff;
244
245 // These errors relate more to the runtime context of the system than to
246 // errors with a SQL statement or with the schema, so they aren't generally
247 // interesting to flag. This list is not comprehensive.
248 return basic_error == SQLITE_BUSY ||
249 basic_error == SQLITE_NOTADB ||
250 basic_error == SQLITE_CORRUPT;
251}
252
ssid9f8022f2015-10-12 17:49:03253bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
254 base::trace_event::ProcessMemoryDump* pmd) {
255 if (args.level_of_detail ==
256 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
257 !db_) {
258 return true;
259 }
260
261 // The high water mark is not tracked for the following usages.
262 int cache_size, dummy_int;
263 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
264 0 /* resetFlag */);
265 int schema_size;
266 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
267 0 /* resetFlag */);
268 int statement_size;
269 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
270 0 /* resetFlag */);
271
272 std::string name = base::StringPrintf(
273 "sqlite/%s_connection/%p",
274 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
275 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
276 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
277 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
278 cache_size + schema_size + statement_size);
279 dump->AddScalar("cache_size",
280 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
281 cache_size);
282 dump->AddScalar("schema_size",
283 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
284 schema_size);
285 dump->AddScalar("statement_size",
286 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
287 statement_size);
288 return true;
289}
290
shessc8cd2a162015-10-22 20:30:46291void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
292 AssertIOAllowed();
293
294 std::string debug_info;
295 const int error = (extended_error & 0xFF);
296 if (error == SQLITE_CORRUPT) {
297 debug_info = CollectCorruptionInfo();
298 } else {
299 debug_info = CollectErrorInfo(extended_error, stmt);
300 }
301
302 if (!debug_info.empty() && RegisterIntentToUpload()) {
303 char debug_buf[2000];
304 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
305 base::debug::Alias(&debug_buf);
306
307 base::debug::DumpWithoutCrashing();
308 }
309}
310
[email protected]4350e322013-06-18 22:18:10311// static
312void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
313 CHECK(current_ignorer_cb_ == NULL);
314 current_ignorer_cb_ = cb;
315}
316
317// static
318void Connection::ResetErrorIgnorer() {
319 CHECK(current_ignorer_cb_);
320 current_ignorer_cb_ = NULL;
321}
322
[email protected]e5ffd0e42009-09-11 21:30:56323bool StatementID::operator<(const StatementID& other) const {
324 if (number_ != other.number_)
325 return number_ < other.number_;
326 return strcmp(str_, other.str_) < 0;
327}
328
[email protected]e5ffd0e42009-09-11 21:30:56329Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38330 sqlite3_stmt* stmt,
331 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56332 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38333 stmt_(stmt),
334 was_valid_(was_valid) {
335 if (connection)
336 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56337}
338
339Connection::StatementRef::~StatementRef() {
340 if (connection_)
341 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38342 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56343}
344
[email protected]41a97c812013-02-07 02:35:38345void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56346 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50347 // Call to AssertIOAllowed() cannot go at the beginning of the function
348 // because Close() is called unconditionally from destructor to clean
349 // connection_. And if this is inactive statement this won't cause any
350 // disk access and destructor most probably will be called on thread
351 // not allowing disk access.
352 // TODO([email protected]): This should move to the beginning
353 // of the function. http://crbug.com/136655.
354 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56355 sqlite3_finalize(stmt_);
356 stmt_ = NULL;
357 }
358 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38359
360 // Forced close is expected to happen from a statement error
361 // handler. In that case maintain the sense of |was_valid_| which
362 // previously held for this ref.
363 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56364}
365
366Connection::Connection()
367 : db_(NULL),
368 page_size_(0),
369 cache_size_(0),
370 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36371 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56372 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50373 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16374 in_memory_(false),
shess58b8df82015-06-03 00:19:32375 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16376 mmap_disabled_(false),
377 mmap_enabled_(false),
378 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32379 stats_histogram_(NULL),
380 commit_time_histogram_(NULL),
381 autocommit_time_histogram_(NULL),
382 update_time_histogram_(NULL),
383 query_time_histogram_(NULL),
384 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03385 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40386 this, "sql::Connection", nullptr);
[email protected]526b4662013-06-14 04:09:12387}
[email protected]e5ffd0e42009-09-11 21:30:56388
389Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03390 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
391 this);
[email protected]e5ffd0e42009-09-11 21:30:56392 Close();
393}
394
shess58b8df82015-06-03 00:19:32395void Connection::RecordEvent(Events event, size_t count) {
396 for (size_t i = 0; i < count; ++i) {
397 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
398 }
399
400 if (stats_histogram_) {
401 for (size_t i = 0; i < count; ++i) {
402 stats_histogram_->Add(event);
403 }
404 }
405}
406
407void Connection::RecordCommitTime(const base::TimeDelta& delta) {
408 RecordUpdateTime(delta);
409 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
410 if (commit_time_histogram_)
411 commit_time_histogram_->AddTime(delta);
412}
413
414void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
415 RecordUpdateTime(delta);
416 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
417 if (autocommit_time_histogram_)
418 autocommit_time_histogram_->AddTime(delta);
419}
420
421void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
422 RecordQueryTime(delta);
423 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
424 if (update_time_histogram_)
425 update_time_histogram_->AddTime(delta);
426}
427
428void Connection::RecordQueryTime(const base::TimeDelta& delta) {
429 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
430 if (query_time_histogram_)
431 query_time_histogram_->AddTime(delta);
432}
433
434void Connection::RecordTimeAndChanges(
435 const base::TimeDelta& delta, bool read_only) {
436 if (read_only) {
437 RecordQueryTime(delta);
438 } else {
439 const int changes = sqlite3_changes(db_);
440 if (sqlite3_get_autocommit(db_)) {
441 RecordAutoCommitTime(delta);
442 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
443 } else {
444 RecordUpdateTime(delta);
445 RecordEvent(EVENT_CHANGES, changes);
446 }
447 }
448}
449
[email protected]a3ef4832013-02-02 05:12:33450bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02451 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26452 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49453 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02454 size_t sample = static_cast<size_t>(size_64 / 1024);
455 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
456 base::HistogramBase* histogram =
457 base::Histogram::FactoryGet(
458 full_histogram_name, 1, 1000000, 50,
459 base::HistogramBase::kUmaTargetedHistogramFlag);
460 if (histogram)
461 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08462 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02463 }
464 }
465
erg102ceb412015-06-20 01:38:13466 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42467}
[email protected]e5ffd0e42009-09-11 21:30:56468
[email protected]765b44502009-10-02 05:01:42469bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50470 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13471 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56472}
473
[email protected]8d409412013-07-19 18:25:30474bool Connection::OpenTemporary() {
475 return OpenInternal("", NO_RETRY);
476}
477
[email protected]41a97c812013-02-07 02:35:38478void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47479 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
480 // will delete the -journal file. For ChromiumOS or other more
481 // embedded systems, this is probably not appropriate, whereas on
482 // desktop it might make some sense.
483
[email protected]4b350052012-02-24 20:40:48484 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48485
[email protected]41a97c812013-02-07 02:35:38486 // Release cached statements.
487 statement_cache_.clear();
488
489 // With cached statements released, in-use statements will remain.
490 // Closing the database while statements are in use is an API
491 // violation, except for forced close (which happens from within a
492 // statement's error handler).
493 DCHECK(forced || open_statements_.empty());
494
495 // Deactivate any outstanding statements so sqlite3_close() works.
496 for (StatementRefSet::iterator i = open_statements_.begin();
497 i != open_statements_.end(); ++i)
498 (*i)->Close(forced);
499 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48500
[email protected]e5ffd0e42009-09-11 21:30:56501 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50502 // Call to AssertIOAllowed() cannot go at the beginning of the function
503 // because Close() must be called from destructor to clean
504 // statement_cache_, it won't cause any disk access and it most probably
505 // will happen on thread not allowing disk access.
506 // TODO([email protected]): This should move to the beginning
507 // of the function. http://crbug.com/136655.
508 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28509
510 int rc = sqlite3_close(db_);
511 if (rc != SQLITE_OK) {
512 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
513 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
514 }
[email protected]e5ffd0e42009-09-11 21:30:56515 }
[email protected]fed734a2013-07-17 04:45:13516 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56517}
518
[email protected]41a97c812013-02-07 02:35:38519void Connection::Close() {
520 // If the database was already closed by RazeAndClose(), then no
521 // need to close again. Clear the |poisoned_| bit so that incorrect
522 // API calls are caught.
523 if (poisoned_) {
524 poisoned_ = false;
525 return;
526 }
527
528 CloseInternal(false);
529}
530
[email protected]e5ffd0e42009-09-11 21:30:56531void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50532 AssertIOAllowed();
533
[email protected]e5ffd0e42009-09-11 21:30:56534 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38535 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56536 return;
537 }
538
[email protected]8ada10f2013-12-21 00:42:34539 // Use local settings if provided, otherwise use documented defaults. The
540 // actual results could be fetching via PRAGMA calls.
541 const int page_size = page_size_ ? page_size_ : 1024;
542 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
543 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56544 return;
545
[email protected]8ada10f2013-12-21 00:42:34546 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34547 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42548 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34549 if (rc != SQLITE_OK)
550 return;
551
552 // Don't preload more than the file contains.
553 if (preload_size > file_size)
554 preload_size = file_size;
555
556 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46557 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34558 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31559
560 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34561 if (rc != SQLITE_OK)
562 return;
563 }
[email protected]e5ffd0e42009-09-11 21:30:56564}
565
shess7dbd4dee2015-10-06 17:39:16566// SQLite keeps unused pages associated with a connection in a cache. It asks
567// the cache for pages by an id, and if the page is present and the database is
568// unchanged, it considers the content of the page valid and doesn't read it
569// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
570// structures created from the memory map data before consulting the cache. On
571// write SQLite creates a new in-memory page structure, copies the data from the
572// memory map, and later writes it, releasing the updated page back to the
573// cache.
574//
575// This means that in memory-mapped mode, the contents of the cached pages are
576// not re-used for reads, but they are re-used for writes if the re-written page
577// is still in the cache. The implementation of sqlite3_db_release_memory() as
578// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
579// connection, so it should free these pages.
580//
581// Unfortunately, the zero page is also freed. That page is never accessed
582// using memory-mapped I/O, and the cached copy can be re-used after verifying
583// the file change counter on disk. Also, fresh pages from cache receive some
584// pager-level initialization before they can be used. Since the information
585// involved will immediately be accessed in various ways, it is unclear if the
586// additional overhead is material, or just moving processor cache effects
587// around.
588//
589// TODO(shess): It would be better to release the pages immediately when they
590// are no longer needed. This would basically happen after SQLite commits a
591// transaction. I had implemented a pcache wrapper to do this, but it involved
592// layering violations, and it had to be setup before any other sqlite call,
593// which was brittle. Also, for large files it would actually make sense to
594// maintain the existing pcache behavior for blocks past the memory-mapped
595// segment. I think drh would accept a reasonable implementation of the overall
596// concept for upstreaming to SQLite core.
597//
598// TODO(shess): Another possibility would be to set the cache size small, which
599// would keep the zero page around, plus some pre-initialized pages, and SQLite
600// can manage things. The downside is that updates larger than the cache would
601// spill to the journal. That could be compensated by setting cache_spill to
602// false. The downside then is that it allows open-ended use of memory for
603// large transactions.
604//
605// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
606// work. There could be two prepared statements, one for cache_size=1 one for
607// cache_size=goal.
608void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
609 DCHECK(is_open());
610
611 // If memory-mapping is not enabled, the page cache helps performance.
612 if (!mmap_enabled_)
613 return;
614
615 // On caller request, force the change comparison to fail. Done before the
616 // transaction-nesting test so that the signal can carry to transaction
617 // commit.
618 if (implicit_change_performed)
619 --total_changes_at_last_release_;
620
621 // Cached pages may be re-used within the same transaction.
622 if (transaction_nesting())
623 return;
624
625 // If no changes have been made, skip flushing. This allows the first page of
626 // the database to remain in cache across multiple reads.
627 const int total_changes = sqlite3_total_changes(db_);
628 if (total_changes == total_changes_at_last_release_)
629 return;
630
631 total_changes_at_last_release_ = total_changes;
632 sqlite3_db_release_memory(db_);
633}
634
shessc8cd2a162015-10-22 20:30:46635base::FilePath Connection::DbPath() const {
636 if (!is_open())
637 return base::FilePath();
638
639 const char* path = sqlite3_db_filename(db_, "main");
640 const base::StringPiece db_path(path);
641#if defined(OS_WIN)
642 return base::FilePath(base::UTF8ToWide(db_path));
643#elif defined(OS_POSIX)
644 return base::FilePath(db_path);
645#else
646 NOTREACHED();
647 return base::FilePath();
648#endif
649}
650
651// Data is persisted in a file shared between databases in the same directory.
652// The "sqlite-diag" file contains a dictionary with the version number, and an
653// array of histogram tags for databases which have been dumped.
654bool Connection::RegisterIntentToUpload() const {
655 static const char* kVersionKey = "version";
656 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
657 static int kVersion = 1;
658
659 AssertIOAllowed();
660
661 if (histogram_tag_.empty())
662 return false;
663
664 if (!is_open())
665 return false;
666
667 if (in_memory_)
668 return false;
669
670 const base::FilePath db_path = DbPath();
671 if (db_path.empty())
672 return false;
673
674 // Put the collection of diagnostic data next to the databases. In most
675 // cases, this is the profile directory, but safe-browsing stores a Cookies
676 // file in the directory above the profile directory.
677 base::FilePath breadcrumb_path(
678 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
679
680 // Lock against multiple updates to the diagnostics file. This code should
681 // seldom be called in the first place, and when called it should seldom be
682 // called for multiple databases, and when called for multiple databases there
683 // is _probably_ something systemic wrong with the user's system. So the lock
684 // should never be contended, but when it is the database experience is
685 // already bad.
686 base::AutoLock lock(g_sqlite_init_lock.Get());
687
688 scoped_ptr<base::Value> root;
689 if (!base::PathExists(breadcrumb_path)) {
690 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
691 root_dict->SetInteger(kVersionKey, kVersion);
692
693 scoped_ptr<base::ListValue> dumps(new base::ListValue);
694 dumps->AppendString(histogram_tag_);
695 root_dict->Set(kDiagnosticDumpsKey, dumps.Pass());
696
697 root = root_dict.Pass();
698 } else {
699 // Failure to read a valid dictionary implies that something is going wrong
700 // on the system.
701 JSONFileValueDeserializer deserializer(breadcrumb_path);
702 scoped_ptr<base::Value> read_root(
703 deserializer.Deserialize(nullptr, nullptr));
704 if (!read_root.get())
705 return false;
706 scoped_ptr<base::DictionaryValue> root_dict =
707 base::DictionaryValue::From(read_root.Pass());
708 if (!root_dict)
709 return false;
710
711 // Don't upload if the version is missing or newer.
712 int version = 0;
713 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
714 return false;
715
716 base::ListValue* dumps = nullptr;
717 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
718 return false;
719
720 const size_t size = dumps->GetSize();
721 for (size_t i = 0; i < size; ++i) {
722 std::string s;
723
724 // Don't upload if the value isn't a string, or indicates a prior upload.
725 if (!dumps->GetString(i, &s) || s == histogram_tag_)
726 return false;
727 }
728
729 // Record intention to proceed with upload.
730 dumps->AppendString(histogram_tag_);
731 root = root_dict.Pass();
732 }
733
734 const base::FilePath breadcrumb_new =
735 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
736 base::DeleteFile(breadcrumb_new, false);
737
738 // No upload if the breadcrumb file cannot be updated.
739 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
740 // the data on disk. For now, losing the data is not a big problem, so the
741 // sync overhead would probably not be worth it.
742 JSONFileValueSerializer serializer(breadcrumb_new);
743 if (!serializer.Serialize(*root))
744 return false;
745 if (!base::PathExists(breadcrumb_new))
746 return false;
747 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
748 base::DeleteFile(breadcrumb_new, false);
749 return false;
750 }
751
752 return true;
753}
754
755std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
756 // Buffer for accumulating debugging info about the error. Place
757 // more-relevant information earlier, in case things overflow the
758 // fixed-size reporting buffer.
759 std::string debug_info;
760
761 // The error message from the failed operation.
762 base::StringAppendF(&debug_info, "db error: %d/%s\n",
763 GetErrorCode(), GetErrorMessage());
764
765 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
766 // reading code does not entirely convince me. Remove if they turn out to be
767 // the same.
768 if (error != GetErrorCode())
769 base::StringAppendF(&debug_info, "reported error: %d\n", error);
770
771 // System error information. Interpretation of Windows errors is different
772 // from posix.
773#if defined(OS_WIN)
774 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
775#elif defined(OS_POSIX)
776 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
777#else
778 NOTREACHED(); // Add appropriate log info.
779#endif
780
781 if (stmt) {
782 base::StringAppendF(&debug_info, "statement: %s\n",
783 stmt->GetSQLStatement());
784 } else {
785 base::StringAppendF(&debug_info, "statement: NULL\n");
786 }
787
788 // SQLITE_ERROR often indicates some sort of mismatch between the statement
789 // and the schema, possibly due to a failed schema migration.
790 if (error == SQLITE_ERROR) {
791 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
792 sqlite3_stmt* s;
793 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
794 if (rc == SQLITE_OK) {
795 rc = sqlite3_step(s);
796 if (rc == SQLITE_ROW) {
797 base::StringAppendF(&debug_info, "version: %d\n",
798 sqlite3_column_int(s, 0));
799 } else if (rc == SQLITE_DONE) {
800 debug_info += "version: none\n";
801 } else {
802 base::StringAppendF(&debug_info, "version: error %d\n", rc);
803 }
804 sqlite3_finalize(s);
805 } else {
806 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
807 }
808
809 debug_info += "schema:\n";
810
811 // sqlite_master has columns:
812 // type - "index" or "table".
813 // name - name of created element.
814 // tbl_name - name of element, or target table in case of index.
815 // rootpage - root page of the element in database file.
816 // sql - SQL to create the element.
817 // In general, the |sql| column is sufficient to derive the other columns.
818 // |rootpage| is not interesting for debugging, without the contents of the
819 // database. The COALESCE is because certain automatic elements will have a
820 // |name| but no |sql|,
821 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
822 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
823 if (rc == SQLITE_OK) {
824 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
825 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
826 }
827 if (rc != SQLITE_DONE)
828 base::StringAppendF(&debug_info, "error %d\n", rc);
829 sqlite3_finalize(s);
830 } else {
831 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
832 }
833 }
834
835 return debug_info;
836}
837
838// TODO(shess): Since this is only called in an error situation, it might be
839// prudent to rewrite in terms of SQLite API calls, and mark the function const.
840std::string Connection::CollectCorruptionInfo() {
841 AssertIOAllowed();
842
843 // If the file cannot be accessed it is unlikely that an integrity check will
844 // turn up actionable information.
845 const base::FilePath db_path = DbPath();
846 int64 db_size = -1;
847 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
848 return std::string();
849
850 // Buffer for accumulating debugging info about the error. Place
851 // more-relevant information earlier, in case things overflow the
852 // fixed-size reporting buffer.
853 std::string debug_info;
854 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
855 db_size);
856
857 // Only check files up to 8M to keep things from blocking too long.
858 const int64 kMaxIntegrityCheckSize = 8192 * 1024;
859 if (db_size > kMaxIntegrityCheckSize) {
860 debug_info += "integrity_check skipped due to size\n";
861 } else {
862 std::vector<std::string> messages;
863
864 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
865 // into a string. Probably should be refactored.
866 const base::TimeTicks before = base::TimeTicks::Now();
867 FullIntegrityCheck(&messages);
868 base::StringAppendF(
869 &debug_info,
870 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
871 (base::TimeTicks::Now() - before).InMilliseconds(),
872 messages.size());
873
874 // SQLite returns up to 100 messages by default, trim deeper to
875 // keep close to the 2000-character size limit for dumping.
876 const size_t kMaxMessages = 20;
877 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
878 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
879 }
880 }
881
882 return debug_info;
883}
884
shessd90aeea82015-11-13 02:24:31885size_t Connection::GetAppropriateMmapSize() {
886 AssertIOAllowed();
887
shessd90aeea82015-11-13 02:24:31888#if defined(OS_IOS)
889 // iOS SQLite does not support memory mapping.
890 return 0;
891#endif
892
shess9bf2c672015-12-18 01:18:08893 // How much to map if no errors are found. 50MB encompasses the 99th
894 // percentile of Chrome databases in the wild, so this should be good.
895 const size_t kMmapEverything = 256 * 1024 * 1024;
896
897 // If the database doesn't have a place to track progress, assume the best.
898 // This will happen when new databases are created, or if a database doesn't
899 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
900 // TODO(shess): Databases not using meta include:
901 // DOMStorageDatabase (localstorage)
902 // ActivityDatabase (extensions activity log)
903 // PredictorDatabase (prefetch and autocomplete predictor data)
904 // SyncDirectory (sync metadata storage)
905 // For now, these all have mmap disabled to allow other databases to get the
906 // default-enable path. sqlite-diag could be an alternative for all but
907 // DOMStorageDatabase, which creates many small databases.
908 // http://crbug.com/537742
909 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31910 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08911 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31912 }
913
shess9bf2c672015-12-18 01:18:08914 int64_t mmap_ofs = 0;
915 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
916 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
917 return 0;
shessd90aeea82015-11-13 02:24:31918 }
919
920 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08921 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31922 RecordOneEvent(EVENT_MMAP_FAILED);
923 return 0;
shess9bf2c672015-12-18 01:18:08924 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31925 // Continue reading from previous offset.
926 DCHECK_GE(mmap_ofs, 0);
927
928 // TODO(shess): Could this reading code be shared with Preload()? It would
929 // require locking twice (this code wouldn't be able to access |db_size| so
930 // the helper would have to return amount read).
931
932 // Read more of the database looking for errors. The VFS interface is used
933 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
934 // to limit checking to 20MB per run of Chromium.
935 sqlite3_file* file = NULL;
936 sqlite3_int64 db_size = 0;
937 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
938 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
939 return 0;
940 }
941
942 // Read the data left, or |g_reads_allowed|, whichever is smaller.
943 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
944 // in a single Chromium run.
945 sqlite3_int64 amount = db_size - mmap_ofs;
946 if (amount < 0)
947 amount = 0;
948 if (amount > 0) {
949 base::AutoLock lock(g_sqlite_init_lock.Get());
950 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
951 if (g_reads_allowed < amount)
952 amount = g_reads_allowed;
953 g_reads_allowed -= amount;
954 }
955
956 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
957 // database was truncated after a previous pass.
958 if (amount <= 0 && mmap_ofs < db_size) {
959 DCHECK_EQ(0, amount);
960 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
961 } else {
962 static const int kPageSize = 4096;
963 char buf[kPageSize];
964 while (amount > 0) {
965 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
966 if (rc == SQLITE_OK) {
967 mmap_ofs += sizeof(buf);
968 amount -= sizeof(buf);
969 } else if (rc == SQLITE_IOERR_SHORT_READ) {
970 // Reached EOF for a database with page size < |kPageSize|.
971 mmap_ofs = db_size;
972 break;
973 } else {
974 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08975 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31976 break;
977 }
978 }
979
980 // Log these events after update to distinguish meta update failure.
981 Events event;
982 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08983 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31984 event = EVENT_MMAP_SUCCESS_NEW;
985 } else if (mmap_ofs > 0) {
986 event = EVENT_MMAP_SUCCESS_PARTIAL;
987 } else {
shess9bf2c672015-12-18 01:18:08988 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31989 event = EVENT_MMAP_FAILED_NEW;
990 }
991
shess9bf2c672015-12-18 01:18:08992 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31993 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
994 return 0;
995 }
996
997 RecordOneEvent(event);
998 }
999 }
1000
shess9bf2c672015-12-18 01:18:081001 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:311002 return 0;
shess9bf2c672015-12-18 01:18:081003 if (mmap_ofs == MetaTable::kMmapSuccess)
1004 return kMmapEverything;
shessd90aeea82015-11-13 02:24:311005 return mmap_ofs;
1006}
1007
[email protected]be7995f12013-07-18 18:49:141008void Connection::TrimMemory(bool aggressively) {
1009 if (!db_)
1010 return;
1011
1012 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1013 int original_cache_size;
1014 {
1015 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1016 if (!sql_get_original.Step()) {
1017 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1018 return;
1019 }
1020 original_cache_size = sql_get_original.ColumnInt(0);
1021 }
1022 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1023
1024 // Force sqlite to try to reduce page cache usage.
1025 const std::string sql_shrink =
1026 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1027 if (!Execute(sql_shrink.c_str()))
1028 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1029
1030 // Restore cache size.
1031 const std::string sql_restore =
1032 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1033 if (!Execute(sql_restore.c_str()))
1034 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1035}
1036
[email protected]8e0c01282012-04-06 19:36:491037// Create an in-memory database with the existing database's page
1038// size, then backup that database over the existing database.
1039bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501040 AssertIOAllowed();
1041
[email protected]8e0c01282012-04-06 19:36:491042 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381043 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491044 return false;
1045 }
1046
1047 if (transaction_nesting_ > 0) {
1048 DLOG(FATAL) << "Cannot raze within a transaction";
1049 return false;
1050 }
1051
1052 sql::Connection null_db;
1053 if (!null_db.OpenInMemory()) {
1054 DLOG(FATAL) << "Unable to open in-memory database.";
1055 return false;
1056 }
1057
[email protected]6d42f152012-11-10 00:38:241058 if (page_size_) {
1059 // Enforce SQLite restrictions on |page_size_|.
1060 DCHECK(!(page_size_ & (page_size_ - 1)))
1061 << " page_size_ " << page_size_ << " is not a power of two.";
1062 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1063 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041064 const std::string sql =
1065 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421066 if (!null_db.Execute(sql.c_str()))
1067 return false;
1068 }
1069
[email protected]6d42f152012-11-10 00:38:241070#if defined(OS_ANDROID)
1071 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1072 // in-memory databases do not respect this define.
1073 // TODO(shess): Figure out a way to set this without using platform
1074 // specific code. AFAICT from sqlite3.c, the only way to do it
1075 // would be to create an actual filesystem database, which is
1076 // unfortunate.
1077 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1078 return false;
1079#endif
[email protected]8e0c01282012-04-06 19:36:491080
1081 // The page size doesn't take effect until a database has pages, and
1082 // at this point the null database has none. Changing the schema
1083 // version will create the first page. This will not affect the
1084 // schema version in the resulting database, as SQLite's backup
1085 // implementation propagates the schema version from the original
1086 // connection to the new version of the database, incremented by one
1087 // so that other readers see the schema change and act accordingly.
1088 if (!null_db.Execute("PRAGMA schema_version = 1"))
1089 return false;
1090
[email protected]6d42f152012-11-10 00:38:241091 // SQLite tracks the expected number of database pages in the first
1092 // page, and if it does not match the total retrieved from a
1093 // filesystem call, treats the database as corrupt. This situation
1094 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1095 // used to hint to SQLite to soldier on in that case, specifically
1096 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1097 // sqlite3.c lockBtree().]
1098 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1099 // page_size" can be used to query such a database.
1100 ScopedWritableSchema writable_schema(db_);
1101
[email protected]7bae5742013-07-10 20:46:161102 const char* kMain = "main";
1103 int rc = BackupDatabase(null_db.db_, db_, kMain);
1104 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491105
1106 // The destination database was locked.
1107 if (rc == SQLITE_BUSY) {
1108 return false;
1109 }
1110
[email protected]7bae5742013-07-10 20:46:161111 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1112 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1113 // isn't even big enough for one page. Either way, reach in and
1114 // truncate it before trying again.
1115 // TODO(shess): Maybe it would be worthwhile to just truncate from
1116 // the get-go?
1117 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1118 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341119 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161120 if (rc != SQLITE_OK) {
1121 DLOG(FATAL) << "Failure getting file handle.";
1122 return false;
[email protected]7bae5742013-07-10 20:46:161123 }
1124
1125 rc = file->pMethods->xTruncate(file, 0);
1126 if (rc != SQLITE_OK) {
1127 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1128 DLOG(FATAL) << "Failed to truncate file.";
1129 return false;
1130 }
1131
1132 rc = BackupDatabase(null_db.db_, db_, kMain);
1133 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1134
1135 if (rc != SQLITE_DONE) {
1136 DLOG(FATAL) << "Failed retrying Raze().";
1137 }
1138 }
1139
[email protected]8e0c01282012-04-06 19:36:491140 // The entire database should have been backed up.
1141 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161142 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491143 DLOG(FATAL) << "Unable to copy entire null database.";
1144 return false;
1145 }
1146
[email protected]8e0c01282012-04-06 19:36:491147 return true;
1148}
1149
1150bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1151 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381152 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491153 return false;
1154 }
1155
1156 ScopedBusyTimeout busy_timeout(db_);
1157 busy_timeout.SetTimeout(timeout);
1158 return Raze();
1159}
1160
[email protected]41a97c812013-02-07 02:35:381161bool Connection::RazeAndClose() {
1162 if (!db_) {
1163 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1164 return false;
1165 }
1166
1167 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301168 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381169
1170 bool result = Raze();
1171
1172 CloseInternal(true);
1173
1174 // Mark the database so that future API calls fail appropriately,
1175 // but don't DCHECK (because after calling this function they are
1176 // expected to fail).
1177 poisoned_ = true;
1178
1179 return result;
1180}
1181
[email protected]8d409412013-07-19 18:25:301182void Connection::Poison() {
1183 if (!db_) {
1184 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1185 return;
1186 }
1187
1188 RollbackAllTransactions();
1189 CloseInternal(true);
1190
1191 // Mark the database so that future API calls fail appropriately,
1192 // but don't DCHECK (because after calling this function they are
1193 // expected to fail).
1194 poisoned_ = true;
1195}
1196
[email protected]8d2e39e2013-06-24 05:55:081197// TODO(shess): To the extent possible, figure out the optimal
1198// ordering for these deletes which will prevent other connections
1199// from seeing odd behavior. For instance, it may be necessary to
1200// manually lock the main database file in a SQLite-compatible fashion
1201// (to prevent other processes from opening it), then delete the
1202// journal files, then delete the main database file. Another option
1203// might be to lock the main database file and poison the header with
1204// junk to prevent other processes from opening it successfully (like
1205// Gears "SQLite poison 3" trick).
1206//
1207// static
1208bool Connection::Delete(const base::FilePath& path) {
1209 base::ThreadRestrictions::AssertIOAllowed();
1210
1211 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1212 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1213
erg102ceb412015-06-20 01:38:131214 std::string journal_str = AsUTF8ForSQL(journal_path);
1215 std::string wal_str = AsUTF8ForSQL(wal_path);
1216 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081217
shess702467622015-09-16 19:04:551218 // Make sure sqlite3_initialize() is called before anything else.
1219 InitializeSqlite();
1220
erg102ceb412015-06-20 01:38:131221 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1222 CHECK(vfs);
1223 CHECK(vfs->xDelete);
1224 CHECK(vfs->xAccess);
1225
1226 // We only work with unix, win32 and mojo filesystems. If you're trying to
1227 // use this code with any other VFS, you're not in a good place.
1228 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1229 strncmp(vfs->zName, "win32", 5) == 0 ||
1230 strcmp(vfs->zName, "mojo") == 0);
1231
1232 vfs->xDelete(vfs, journal_str.c_str(), 0);
1233 vfs->xDelete(vfs, wal_str.c_str(), 0);
1234 vfs->xDelete(vfs, path_str.c_str(), 0);
1235
1236 int journal_exists = 0;
1237 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1238 &journal_exists);
1239
1240 int wal_exists = 0;
1241 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1242 &wal_exists);
1243
1244 int path_exists = 0;
1245 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1246 &path_exists);
1247
1248 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081249}
1250
[email protected]e5ffd0e42009-09-11 21:30:561251bool Connection::BeginTransaction() {
1252 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331253 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561254
1255 // When we're going to rollback, fail on this begin and don't actually
1256 // mark us as entering the nested transaction.
1257 return false;
1258 }
1259
1260 bool success = true;
1261 if (!transaction_nesting_) {
1262 needs_rollback_ = false;
1263
1264 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321265 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591266 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561267 return false;
1268 }
1269 transaction_nesting_++;
1270 return success;
1271}
1272
1273void Connection::RollbackTransaction() {
1274 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381275 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561276 return;
1277 }
1278
1279 transaction_nesting_--;
1280
1281 if (transaction_nesting_ > 0) {
1282 // Mark the outermost transaction as needing rollback.
1283 needs_rollback_ = true;
1284 return;
1285 }
1286
1287 DoRollback();
1288}
1289
1290bool Connection::CommitTransaction() {
1291 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181292 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561293 return false;
1294 }
1295 transaction_nesting_--;
1296
1297 if (transaction_nesting_ > 0) {
1298 // Mark any nested transactions as failing after we've already got one.
1299 return !needs_rollback_;
1300 }
1301
1302 if (needs_rollback_) {
1303 DoRollback();
1304 return false;
1305 }
1306
1307 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321308
1309 // Collect the commit time manually, sql::Statement would register it as query
1310 // time only.
1311 const base::TimeTicks before = Now();
1312 bool ret = commit.RunWithoutTimers();
1313 const base::TimeDelta delta = Now() - before;
1314
1315 RecordCommitTime(delta);
1316 RecordOneEvent(EVENT_COMMIT);
1317
shess7dbd4dee2015-10-06 17:39:161318 // Release dirty cache pages after the transaction closes.
1319 ReleaseCacheMemoryIfNeeded(false);
1320
shess58b8df82015-06-03 00:19:321321 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561322}
1323
[email protected]8d409412013-07-19 18:25:301324void Connection::RollbackAllTransactions() {
1325 if (transaction_nesting_ > 0) {
1326 transaction_nesting_ = 0;
1327 DoRollback();
1328 }
1329}
1330
1331bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1332 const char* attachment_point) {
1333 DCHECK(ValidAttachmentPoint(attachment_point));
1334
1335 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1336#if OS_WIN
1337 s.BindString16(0, other_db_path.value());
1338#else
1339 s.BindString(0, other_db_path.value());
1340#endif
1341 s.BindString(1, attachment_point);
1342 return s.Run();
1343}
1344
1345bool Connection::DetachDatabase(const char* attachment_point) {
1346 DCHECK(ValidAttachmentPoint(attachment_point));
1347
1348 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1349 s.BindString(0, attachment_point);
1350 return s.Run();
1351}
1352
shess58b8df82015-06-03 00:19:321353// TODO(shess): Consider changing this to execute exactly one statement. If a
1354// caller wishes to execute multiple statements, that should be explicit, and
1355// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591356int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501357 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381358 if (!db_) {
1359 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1360 return SQLITE_ERROR;
1361 }
shess58b8df82015-06-03 00:19:321362 DCHECK(sql);
1363
1364 RecordOneEvent(EVENT_EXECUTE);
1365 int rc = SQLITE_OK;
1366 while ((rc == SQLITE_OK) && *sql) {
1367 sqlite3_stmt *stmt = NULL;
1368 const char *leftover_sql;
1369
1370 const base::TimeTicks before = Now();
1371 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1372 sql = leftover_sql;
1373
1374 // Stop if an error is encountered.
1375 if (rc != SQLITE_OK)
1376 break;
1377
1378 // This happens if |sql| originally only contained comments or whitespace.
1379 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1380 // extraneous comments and whitespace in the SQL statements increases
1381 // runtime cost and can easily be shifted out to the C++ layer.
1382 if (!stmt)
1383 continue;
1384
1385 // Save for use after statement is finalized.
1386 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1387
1388 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1389 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1390 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1391 // is the only legitimate case for this.
1392 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1393 }
1394
1395 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1396 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1397 rc = sqlite3_finalize(stmt);
1398 if (rc == SQLITE_OK)
1399 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1400
1401 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1402 // trailing whitespace.
1403 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021404 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321405 sql++;
1406 }
1407
1408 const base::TimeDelta delta = Now() - before;
1409 RecordTimeAndChanges(delta, read_only);
1410 }
shess7dbd4dee2015-10-06 17:39:161411
1412 // Most calls to Execute() modify the database. The main exceptions would be
1413 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1414 // but sometimes don't.
1415 ReleaseCacheMemoryIfNeeded(true);
1416
shess58b8df82015-06-03 00:19:321417 return rc;
[email protected]eff1fa522011-12-12 23:50:591418}
1419
1420bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381421 if (!db_) {
1422 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1423 return false;
1424 }
1425
[email protected]eff1fa522011-12-12 23:50:591426 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001427 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581428 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001429
[email protected]28fe0ff2012-02-25 00:40:331430 // This needs to be a FATAL log because the error case of arriving here is
1431 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101432 // a change alters the schema but not all queries adjust. This can happen
1433 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591434 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331435 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591436 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561437}
1438
[email protected]5b96f3772010-09-28 16:30:571439bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381440 if (!db_) {
1441 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571442 return false;
[email protected]41a97c812013-02-07 02:35:381443 }
[email protected]5b96f3772010-09-28 16:30:571444
1445 ScopedBusyTimeout busy_timeout(db_);
1446 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591447 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571448}
1449
[email protected]e5ffd0e42009-09-11 21:30:561450bool Connection::HasCachedStatement(const StatementID& id) const {
1451 return statement_cache_.find(id) != statement_cache_.end();
1452}
1453
1454scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1455 const StatementID& id,
1456 const char* sql) {
1457 CachedStatementMap::iterator i = statement_cache_.find(id);
1458 if (i != statement_cache_.end()) {
1459 // Statement is in the cache. It should still be active (we're the only
1460 // one invalidating cached statements, and we'll remove it from the cache
1461 // if we do that. Make sure we reset it before giving out the cached one in
1462 // case it still has some stuff bound.
1463 DCHECK(i->second->is_valid());
1464 sqlite3_reset(i->second->stmt());
1465 return i->second;
1466 }
1467
1468 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1469 if (statement->is_valid())
1470 statement_cache_[id] = statement; // Only cache valid statements.
1471 return statement;
1472}
1473
1474scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1475 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501476 AssertIOAllowed();
1477
[email protected]41a97c812013-02-07 02:35:381478 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561479 if (!db_)
[email protected]41a97c812013-02-07 02:35:381480 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561481
1482 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001483 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1484 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591485 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061486 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021487 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001488
1489 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581490 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381491 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561492 }
[email protected]41a97c812013-02-07 02:35:381493 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561494}
1495
shessf7e988f2015-11-13 00:41:061496// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1497// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581498scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1499 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381500 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581501 if (!db_)
[email protected]41a97c812013-02-07 02:35:381502 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581503
1504 sqlite3_stmt* stmt = NULL;
1505 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1506 if (rc != SQLITE_OK) {
1507 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061508 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021509 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381510 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581511 }
[email protected]41a97c812013-02-07 02:35:381512 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581513}
1514
[email protected]92cd00a2013-08-16 11:09:581515std::string Connection::GetSchema() const {
1516 // The ORDER BY should not be necessary, but relying on organic
1517 // order for something like this is questionable.
1518 const char* kSql =
1519 "SELECT type, name, tbl_name, sql "
1520 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1521 Statement statement(GetUntrackedStatement(kSql));
1522
1523 std::string schema;
1524 while (statement.Step()) {
1525 schema += statement.ColumnString(0);
1526 schema += '|';
1527 schema += statement.ColumnString(1);
1528 schema += '|';
1529 schema += statement.ColumnString(2);
1530 schema += '|';
1531 schema += statement.ColumnString(3);
1532 schema += '\n';
1533 }
1534
1535 return schema;
1536}
1537
[email protected]eff1fa522011-12-12 23:50:591538bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501539 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381540 if (!db_) {
1541 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1542 return false;
1543 }
1544
[email protected]eff1fa522011-12-12 23:50:591545 sqlite3_stmt* stmt = NULL;
1546 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1547 return false;
1548
1549 sqlite3_finalize(stmt);
1550 return true;
1551}
1552
[email protected]1ed78a32009-09-15 20:24:171553bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531554 return DoesTableOrIndexExist(table_name, "table");
1555}
1556
1557bool Connection::DoesIndexExist(const char* index_name) const {
1558 return DoesTableOrIndexExist(index_name, "index");
1559}
1560
1561bool Connection::DoesTableOrIndexExist(
1562 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471563 const char* kSql =
1564 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581565 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471566
1567 // This can happen if the database is corrupt and the error is being ignored
1568 // for testing purposes.
1569 if (!statement.is_valid())
1570 return false;
1571
[email protected]e2cadec82011-12-13 02:00:531572 statement.BindString(0, type);
1573 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331574
[email protected]e5ffd0e42009-09-11 21:30:561575 return statement.Step(); // Table exists if any row was returned.
1576}
1577
1578bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171579 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561580 std::string sql("PRAGMA TABLE_INFO(");
1581 sql.append(table_name);
1582 sql.append(")");
1583
[email protected]2eec0a22012-07-24 01:59:581584 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471585
1586 // This can happen if the database is corrupt and the error is being ignored
1587 // for testing purposes.
1588 if (!statement.is_valid())
1589 return false;
1590
[email protected]e5ffd0e42009-09-11 21:30:561591 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331592 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1593 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561594 return true;
1595 }
1596 return false;
1597}
1598
tfarina720d4f32015-05-11 22:31:261599int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561600 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381601 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561602 return 0;
1603 }
1604 return sqlite3_last_insert_rowid(db_);
1605}
1606
[email protected]1ed78a32009-09-15 20:24:171607int Connection::GetLastChangeCount() const {
1608 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381609 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171610 return 0;
1611 }
1612 return sqlite3_changes(db_);
1613}
1614
[email protected]e5ffd0e42009-09-11 21:30:561615int Connection::GetErrorCode() const {
1616 if (!db_)
1617 return SQLITE_ERROR;
1618 return sqlite3_errcode(db_);
1619}
1620
[email protected]767718e52010-09-21 23:18:491621int Connection::GetLastErrno() const {
1622 if (!db_)
1623 return -1;
1624
1625 int err = 0;
1626 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1627 return -2;
1628
1629 return err;
1630}
1631
[email protected]e5ffd0e42009-09-11 21:30:561632const char* Connection::GetErrorMessage() const {
1633 if (!db_)
1634 return "sql::Connection has no connection.";
1635 return sqlite3_errmsg(db_);
1636}
1637
[email protected]fed734a2013-07-17 04:45:131638bool Connection::OpenInternal(const std::string& file_name,
1639 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501640 AssertIOAllowed();
1641
[email protected]9cfbc922009-11-17 20:13:171642 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591643 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171644 return false;
1645 }
1646
[email protected]a7ec1292013-07-22 22:02:181647 // Make sure sqlite3_initialize() is called before anything else.
1648 InitializeSqlite();
1649
shess58b8df82015-06-03 00:19:321650 // Setup the stats histograms immediately rather than allocating lazily.
1651 // Connections which won't exercise all of these probably shouldn't exist.
1652 if (!histogram_tag_.empty()) {
1653 stats_histogram_ =
1654 base::LinearHistogram::FactoryGet(
1655 "Sqlite.Stats." + histogram_tag_,
1656 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1657 base::HistogramBase::kUmaTargetedHistogramFlag);
1658
1659 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1660 // unreasonable time for any single operation, so there is not much value to
1661 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1662 // things are entirely busted.
1663 commit_time_histogram_ =
1664 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1665
1666 autocommit_time_histogram_ =
1667 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1668
1669 update_time_histogram_ =
1670 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1671
1672 query_time_histogram_ =
1673 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1674 }
1675
[email protected]41a97c812013-02-07 02:35:381676 // If |poisoned_| is set, it means an error handler called
1677 // RazeAndClose(). Until regular Close() is called, the caller
1678 // should be treating the database as open, but is_open() currently
1679 // only considers the sqlite3 handle's state.
1680 // TODO(shess): Revise is_open() to consider poisoned_, and review
1681 // to see if any non-testing code even depends on it.
1682 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161683 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381684
[email protected]765b44502009-10-02 05:01:421685 int err = sqlite3_open(file_name.c_str(), &db_);
1686 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281687 // Extended error codes cannot be enabled until a handle is
1688 // available, fetch manually.
1689 err = sqlite3_extended_errcode(db_);
1690
[email protected]bd2ccdb4a2012-12-07 22:14:501691 // Histogram failures specific to initial open for debugging
1692 // purposes.
[email protected]73fb8d52013-07-24 05:04:281693 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501694
[email protected]2f496b42013-09-26 18:36:581695 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131696 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291697 Close();
[email protected]fed734a2013-07-17 04:45:131698
1699 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1700 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421701 return false;
1702 }
1703
[email protected]81a2a602013-07-17 19:10:361704 // TODO(shess): OS_WIN support?
1705#if defined(OS_POSIX)
1706 if (restrict_to_user_) {
1707 DCHECK_NE(file_name, std::string(":memory"));
1708 base::FilePath file_path(file_name);
1709 int mode = 0;
1710 // TODO(shess): Arguably, failure to retrieve and change
1711 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081712 if (base::GetPosixFilePermissions(file_path, &mode)) {
1713 mode &= base::FILE_PERMISSION_USER_MASK;
1714 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361715
1716 // SQLite sets the permissions on these files from the main
1717 // database on create. Set them here in case they already exist
1718 // at this point. Failure to set these permissions should not
1719 // be fatal unless the file doesn't exist.
1720 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1721 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081722 base::SetPosixFilePermissions(journal_path, mode);
1723 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361724 }
1725 }
1726#endif // defined(OS_POSIX)
1727
[email protected]affa2da2013-06-06 22:20:341728 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1729 // Chromium already depends on small mallocs being efficient, so we disable
1730 // this to avoid the extra memory overhead.
1731 // This must be called immediatly after opening the database before any SQL
1732 // statements are run.
1733 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1734
[email protected]73fb8d52013-07-24 05:04:281735 // Enable extended result codes to provide more color on I/O errors.
1736 // Not having extended result codes is not a fatal problem, as
1737 // Chromium code does not attempt to handle I/O errors anyhow. The
1738 // current implementation always returns SQLITE_OK, the DCHECK is to
1739 // quickly notify someone if SQLite changes.
1740 err = sqlite3_extended_result_codes(db_, 1);
1741 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1742
[email protected]bd2ccdb4a2012-12-07 22:14:501743 // sqlite3_open() does not actually read the database file (unless a
1744 // hot journal is found). Successfully executing this pragma on an
1745 // existing database requires a valid header on page 1.
1746 // TODO(shess): For now, just probing to see what the lay of the
1747 // land is. If it's mostly SQLITE_NOTADB, then the database should
1748 // be razed.
1749 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1750 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281751 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431752
[email protected]2e1cee762013-07-09 14:40:001753#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1754 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1755 // REGEXP support. Add it in dynamically.
1756 err = sqlite3IcuInit(db_);
1757 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1758#endif // OS_IOS && USE_SYSTEM_SQLITE
1759
[email protected]5b96f3772010-09-28 16:30:571760 // If indicated, lock up the database before doing anything else, so
1761 // that the following code doesn't have to deal with locking.
1762 // TODO(shess): This code is brittle. Find the cases where code
1763 // doesn't request |exclusive_locking_| and audit that it does the
1764 // right thing with SQLITE_BUSY, and that it doesn't make
1765 // assumptions about who might change things in the database.
1766 // http://crbug.com/56559
1767 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101768 // TODO(shess): This should probably be a failure. Code which
1769 // requests exclusive locking but doesn't get it is almost certain
1770 // to be ill-tested.
1771 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571772 }
1773
[email protected]4e179ba2012-03-17 16:06:471774 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1775 // DELETE (default) - delete -journal file to commit.
1776 // TRUNCATE - truncate -journal file to commit.
1777 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091778 // TRUNCATE should be faster than DELETE because it won't need directory
1779 // changes for each transaction. PERSIST may break the spirit of using
1780 // secure_delete.
1781 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471782
[email protected]c68ce172011-11-24 22:30:271783 const base::TimeDelta kBusyTimeout =
1784 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1785
[email protected]765b44502009-10-02 05:01:421786 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571787 // Enforce SQLite restrictions on |page_size_|.
1788 DCHECK(!(page_size_ & (page_size_ - 1)))
1789 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241790 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571791 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041792 const std::string sql =
1793 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101794 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421795 }
1796
1797 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041798 const std::string sql =
1799 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101800 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421801 }
1802
[email protected]6e0b1442011-08-09 23:23:581803 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131804 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581805 Close();
[email protected]fed734a2013-07-17 04:45:131806 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1807 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581808 return false;
1809 }
1810
shess5dac334f2015-11-05 20:47:421811 // Set a reasonable chunk size for larger files. This reduces churn from
1812 // remapping memory on size changes. It also reduces filesystem
1813 // fragmentation.
1814 // TODO(shess): It may make sense to have this be hinted by the client.
1815 // Database sizes seem to be bimodal, some clients have consistently small
1816 // databases (<20k) while other clients have a broad distribution of sizes
1817 // (hundreds of kilobytes to many megabytes).
1818 sqlite3_file* file = NULL;
1819 sqlite3_int64 db_size = 0;
1820 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1821 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1822 int chunk_size = 4 * 1024;
1823 if (db_size > 128 * 1024)
1824 chunk_size = 32 * 1024;
1825 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1826 }
1827
shess2f3a814b2015-11-05 18:11:101828 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311829 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1830 // safe range to memory-map based on past regular I/O. This value will be
1831 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1832 // 64-bit platforms.
1833 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1834 std::string mmap_sql =
1835 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1836 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101837
1838 // Determine if memory-mapping has actually been enabled. The Execute() above
1839 // can succeed without changing the amount mapped.
1840 mmap_enabled_ = false;
1841 {
1842 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1843 if (s.Step() && s.ColumnInt64(0) > 0)
1844 mmap_enabled_ = true;
1845 }
1846
[email protected]765b44502009-10-02 05:01:421847 return true;
1848}
1849
[email protected]e5ffd0e42009-09-11 21:30:561850void Connection::DoRollback() {
1851 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321852
1853 // Collect the rollback time manually, sql::Statement would register it as
1854 // query time only.
1855 const base::TimeTicks before = Now();
1856 rollback.RunWithoutTimers();
1857 const base::TimeDelta delta = Now() - before;
1858
1859 RecordUpdateTime(delta);
1860 RecordOneEvent(EVENT_ROLLBACK);
1861
shess7dbd4dee2015-10-06 17:39:161862 // The cache may have been accumulating dirty pages for commit. Note that in
1863 // some cases sql::Transaction can fire rollback after a database is closed.
1864 if (is_open())
1865 ReleaseCacheMemoryIfNeeded(false);
1866
[email protected]44ad7d902012-03-23 00:09:051867 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561868}
1869
1870void Connection::StatementRefCreated(StatementRef* ref) {
1871 DCHECK(open_statements_.find(ref) == open_statements_.end());
1872 open_statements_.insert(ref);
1873}
1874
1875void Connection::StatementRefDeleted(StatementRef* ref) {
1876 StatementRefSet::iterator i = open_statements_.find(ref);
1877 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591878 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561879 else
1880 open_statements_.erase(i);
1881}
1882
shess58b8df82015-06-03 00:19:321883void Connection::set_histogram_tag(const std::string& tag) {
1884 DCHECK(!is_open());
1885 histogram_tag_ = tag;
1886}
1887
[email protected]210ce0af2013-05-15 09:10:391888void Connection::AddTaggedHistogram(const std::string& name,
1889 size_t sample) const {
1890 if (histogram_tag_.empty())
1891 return;
1892
1893 // TODO(shess): The histogram macros create a bit of static storage
1894 // for caching the histogram object. This code shouldn't execute
1895 // often enough for such caching to be crucial. If it becomes an
1896 // issue, the object could be cached alongside histogram_prefix_.
1897 std::string full_histogram_name = name + "." + histogram_tag_;
1898 base::HistogramBase* histogram =
1899 base::SparseHistogram::FactoryGet(
1900 full_histogram_name,
1901 base::HistogramBase::kUmaTargetedHistogramFlag);
1902 if (histogram)
1903 histogram->Add(sample);
1904}
1905
[email protected]2f496b42013-09-26 18:36:581906int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391907 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1908 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141909
1910 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581911 if (!sql && stmt)
1912 sql = stmt->GetSQLStatement();
1913 if (!sql)
1914 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061915
1916 std::string id = histogram_tag_;
1917 if (id.empty())
1918 id = DbPath().BaseName().AsUTF8Unsafe();
1919 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141920 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581921 << ": " << GetErrorMessage()
1922 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141923
[email protected]c3881b372013-05-17 08:39:461924 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561925 // Fire from a copy of the callback in case of reentry into
1926 // re/set_error_callback().
1927 // TODO(shess): <http://crbug.com/254584>
1928 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461929 return err;
1930 }
1931
[email protected]faa604e2009-09-25 22:38:591932 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571933 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101934 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591935 return err;
1936}
1937
[email protected]579446c2013-12-16 18:36:521938bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1939 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1940}
1941
1942bool Connection::QuickIntegrityCheck() {
1943 std::vector<std::string> messages;
1944 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1945 return false;
1946 return messages.size() == 1 && messages[0] == "ok";
1947}
1948
[email protected]80abf152013-05-22 12:42:421949// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521950bool Connection::IntegrityCheckHelper(
1951 const char* pragma_sql,
1952 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421953 messages->clear();
1954
[email protected]4658e2a02013-06-06 23:05:001955 // This has the side effect of setting SQLITE_RecoveryMode, which
1956 // allows SQLite to process through certain cases of corruption.
1957 // Failing to set this pragma probably means that the database is
1958 // beyond recovery.
1959 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1960 if (!Execute(kWritableSchema))
1961 return false;
1962
1963 bool ret = false;
1964 {
[email protected]579446c2013-12-16 18:36:521965 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001966
1967 // The pragma appears to return all results (up to 100 by default)
1968 // as a single string. This doesn't appear to be an API contract,
1969 // it could return separate lines, so loop _and_ split.
1970 while (stmt.Step()) {
1971 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181972 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1973 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001974 }
1975 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421976 }
[email protected]4658e2a02013-06-06 23:05:001977
1978 // Best effort to put things back as they were before.
1979 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1980 ignore_result(Execute(kNoWritableSchema));
1981
1982 return ret;
[email protected]80abf152013-05-22 12:42:421983}
1984
shess58b8df82015-06-03 00:19:321985base::TimeTicks TimeSource::Now() {
1986 return base::TimeTicks::Now();
1987}
1988
[email protected]e5ffd0e42009-09-11 21:30:561989} // namespace sql