blob: 4d23f7df06d2928d95fa8d6c455200f23db8260f [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f0a54b22011-07-19 18:40:215#include "sql/connection.h"
[email protected]e5ffd0e42009-09-11 21:30:566
avi51ba3e692015-12-26 17:30:507#include <limits.h>
avi0b519202015-12-21 07:25:198#include <stddef.h>
9#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:5610#include <string.h>
11
shessc9e80ae22015-08-12 21:39:1112#include "base/bind.h"
shessc8cd2a162015-10-22 20:30:4613#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5214#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4415#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4616#include "base/format_macros.h"
17#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1818#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5619#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1120#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5021#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3922#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4223#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1924#include "base/strings/string_util.h"
25#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4526#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1827#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0328#include "base/trace_event/memory_dump_manager.h"
29#include "base/trace_event/process_memory_dump.h"
shess9bf2c672015-12-18 01:18:0830#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2131#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0332#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5633
[email protected]2e1cee762013-07-09 14:40:0034#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
35#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
36#endif
37
[email protected]5b96f3772010-09-28 16:30:5738namespace {
39
40// Spin for up to a second waiting for the lock to clear when setting
41// up the database.
42// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2743const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5744
45class ScopedBusyTimeout {
46 public:
47 explicit ScopedBusyTimeout(sqlite3* db)
48 : db_(db) {
49 }
50 ~ScopedBusyTimeout() {
51 sqlite3_busy_timeout(db_, 0);
52 }
53
54 int SetTimeout(base::TimeDelta timeout) {
55 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
56 return sqlite3_busy_timeout(db_,
57 static_cast<int>(timeout.InMilliseconds()));
58 }
59
60 private:
61 sqlite3* db_;
62};
63
[email protected]6d42f152012-11-10 00:38:2464// Helper to "safely" enable writable_schema. No error checking
65// because it is reasonable to just forge ahead in case of an error.
66// If turning it on fails, then most likely nothing will work, whereas
67// if turning it off fails, it only matters if some code attempts to
68// continue working with the database and tries to modify the
69// sqlite_master table (none of our code does this).
70class ScopedWritableSchema {
71 public:
72 explicit ScopedWritableSchema(sqlite3* db)
73 : db_(db) {
74 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
75 }
76 ~ScopedWritableSchema() {
77 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
78 }
79
80 private:
81 sqlite3* db_;
82};
83
[email protected]7bae5742013-07-10 20:46:1684// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
85// SQLite error code from running the backup step.
86int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
87 DCHECK_NE(src, dst);
88 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
89 if (!backup) {
90 // Since this call only sets things up, this indicates a gross
91 // error in SQLite.
92 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
93 return sqlite3_errcode(dst);
94 }
95
96 // -1 backs up the entire database.
97 int rc = sqlite3_backup_step(backup, -1);
98 int pages = sqlite3_backup_pagecount(backup);
99 sqlite3_backup_finish(backup);
100
101 // If successful, exactly one page should have been backed up. If
102 // this breaks, check this function to make sure assumptions aren't
103 // being broken.
104 if (rc == SQLITE_DONE)
105 DCHECK_EQ(pages, 1);
106
107 return rc;
108}
109
[email protected]8d409412013-07-19 18:25:30110// Be very strict on attachment point. SQLite can handle a much wider
111// character set with appropriate quoting, but Chromium code should
112// just use clean names to start with.
113bool ValidAttachmentPoint(const char* attachment_point) {
114 for (size_t i = 0; attachment_point[i]; ++i) {
115 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
116 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
117 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
118 attachment_point[i] == '_')) {
119 return false;
120 }
121 }
122 return true;
123}
124
shessc9e80ae22015-08-12 21:39:11125void RecordSqliteMemory10Min() {
avi0b519202015-12-21 07:25:19126 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11127 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
128}
129
130void RecordSqliteMemoryHour() {
avi0b519202015-12-21 07:25:19131 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11132 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
133}
134
135void RecordSqliteMemoryDay() {
avi0b519202015-12-21 07:25:19136 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11137 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
138}
139
shess2d48e942015-08-25 17:39:51140void RecordSqliteMemoryWeek() {
avi0b519202015-12-21 07:25:19141 const int64_t used = sqlite3_memory_used();
shess2d48e942015-08-25 17:39:51142 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
143}
144
[email protected]a7ec1292013-07-22 22:02:18145// SQLite automatically calls sqlite3_initialize() lazily, but
146// sqlite3_initialize() uses double-checked locking and thus can have
147// data races.
148//
149// TODO(shess): Another alternative would be to have
150// sqlite3_initialize() called as part of process bring-up. If this
151// is changed, remove the dynamic_annotations dependency in sql.gyp.
152base::LazyInstance<base::Lock>::Leaky
153 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
154void InitializeSqlite() {
155 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11156 static bool first_call = true;
157 if (first_call) {
158 sqlite3_initialize();
159
160 // Schedule callback to record memory footprint histograms at 10m, 1h, and
161 // 1d. There may not be a message loop in tests.
162 if (base::MessageLoop::current()) {
163 base::MessageLoop::current()->PostDelayedTask(
164 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
165 base::TimeDelta::FromMinutes(10));
166 base::MessageLoop::current()->PostDelayedTask(
167 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
168 base::TimeDelta::FromHours(1));
169 base::MessageLoop::current()->PostDelayedTask(
170 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
171 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51172 base::MessageLoop::current()->PostDelayedTask(
173 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
174 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11175 }
176
177 first_call = false;
178 }
[email protected]a7ec1292013-07-22 22:02:18179}
180
[email protected]8ada10f2013-12-21 00:42:34181// Helper to get the sqlite3_file* associated with the "main" database.
182int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
183 *file = NULL;
184 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
185 if (rc != SQLITE_OK)
186 return rc;
187
188 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
189 // content_unittests, even though it should not be possible.
190 // http://crbug.com/329982
191 if (!*file || !(*file)->pMethods)
192 return SQLITE_ERROR;
193
194 return rc;
195}
196
shess5dac334f2015-11-05 20:47:42197// Convenience to get the sqlite3_file* and the size for the "main" database.
198int GetSqlite3FileAndSize(sqlite3* db,
199 sqlite3_file** file, sqlite3_int64* db_size) {
200 int rc = GetSqlite3File(db, file);
201 if (rc != SQLITE_OK)
202 return rc;
203
204 return (*file)->pMethods->xFileSize(*file, db_size);
205}
206
shess58b8df82015-06-03 00:19:32207// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
208base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
209 return base::Histogram::FactoryTimeGet(
210 name,
211 base::TimeDelta::FromMilliseconds(10),
212 base::TimeDelta::FromMinutes(3),
213 50,
214 base::HistogramBase::kUmaTargetedHistogramFlag);
215}
216
erg102ceb412015-06-20 01:38:13217std::string AsUTF8ForSQL(const base::FilePath& path) {
218#if defined(OS_WIN)
219 return base::WideToUTF8(path.value());
220#elif defined(OS_POSIX)
221 return path.value();
222#endif
223}
224
[email protected]5b96f3772010-09-28 16:30:57225} // namespace
226
[email protected]e5ffd0e42009-09-11 21:30:56227namespace sql {
228
[email protected]4350e322013-06-18 22:18:10229// static
230Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
231
232// static
[email protected]74cdede2013-09-25 05:39:57233bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10234 if (!current_ignorer_cb_)
235 return false;
236 return current_ignorer_cb_->Run(error);
237}
238
shessf7e988f2015-11-13 00:41:06239// static
240bool Connection::ShouldIgnoreSqliteCompileError(int error) {
241 // Put this first in case tests need to see that the check happened.
242 if (ShouldIgnoreSqliteError(error))
243 return true;
244
245 // Trim extended error codes.
246 int basic_error = error & 0xff;
247
248 // These errors relate more to the runtime context of the system than to
249 // errors with a SQL statement or with the schema, so they aren't generally
250 // interesting to flag. This list is not comprehensive.
251 return basic_error == SQLITE_BUSY ||
252 basic_error == SQLITE_NOTADB ||
253 basic_error == SQLITE_CORRUPT;
254}
255
ssid9f8022f2015-10-12 17:49:03256bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
257 base::trace_event::ProcessMemoryDump* pmd) {
258 if (args.level_of_detail ==
259 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
260 !db_) {
261 return true;
262 }
263
264 // The high water mark is not tracked for the following usages.
265 int cache_size, dummy_int;
266 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
267 0 /* resetFlag */);
268 int schema_size;
269 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
270 0 /* resetFlag */);
271 int statement_size;
272 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
273 0 /* resetFlag */);
274
275 std::string name = base::StringPrintf(
276 "sqlite/%s_connection/%p",
277 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
278 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
279 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
280 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
281 cache_size + schema_size + statement_size);
282 dump->AddScalar("cache_size",
283 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
284 cache_size);
285 dump->AddScalar("schema_size",
286 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
287 schema_size);
288 dump->AddScalar("statement_size",
289 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
290 statement_size);
291 return true;
292}
293
shessc8cd2a162015-10-22 20:30:46294void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
295 AssertIOAllowed();
296
297 std::string debug_info;
298 const int error = (extended_error & 0xFF);
299 if (error == SQLITE_CORRUPT) {
300 debug_info = CollectCorruptionInfo();
301 } else {
302 debug_info = CollectErrorInfo(extended_error, stmt);
303 }
304
305 if (!debug_info.empty() && RegisterIntentToUpload()) {
306 char debug_buf[2000];
307 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
308 base::debug::Alias(&debug_buf);
309
310 base::debug::DumpWithoutCrashing();
311 }
312}
313
[email protected]4350e322013-06-18 22:18:10314// static
315void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
316 CHECK(current_ignorer_cb_ == NULL);
317 current_ignorer_cb_ = cb;
318}
319
320// static
321void Connection::ResetErrorIgnorer() {
322 CHECK(current_ignorer_cb_);
323 current_ignorer_cb_ = NULL;
324}
325
[email protected]e5ffd0e42009-09-11 21:30:56326bool StatementID::operator<(const StatementID& other) const {
327 if (number_ != other.number_)
328 return number_ < other.number_;
329 return strcmp(str_, other.str_) < 0;
330}
331
[email protected]e5ffd0e42009-09-11 21:30:56332Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38333 sqlite3_stmt* stmt,
334 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56335 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38336 stmt_(stmt),
337 was_valid_(was_valid) {
338 if (connection)
339 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56340}
341
342Connection::StatementRef::~StatementRef() {
343 if (connection_)
344 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38345 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56346}
347
[email protected]41a97c812013-02-07 02:35:38348void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56349 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50350 // Call to AssertIOAllowed() cannot go at the beginning of the function
351 // because Close() is called unconditionally from destructor to clean
352 // connection_. And if this is inactive statement this won't cause any
353 // disk access and destructor most probably will be called on thread
354 // not allowing disk access.
355 // TODO([email protected]): This should move to the beginning
356 // of the function. http://crbug.com/136655.
357 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56358 sqlite3_finalize(stmt_);
359 stmt_ = NULL;
360 }
361 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38362
363 // Forced close is expected to happen from a statement error
364 // handler. In that case maintain the sense of |was_valid_| which
365 // previously held for this ref.
366 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56367}
368
369Connection::Connection()
370 : db_(NULL),
371 page_size_(0),
372 cache_size_(0),
373 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36374 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56375 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50376 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16377 in_memory_(false),
shess58b8df82015-06-03 00:19:32378 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16379 mmap_disabled_(false),
380 mmap_enabled_(false),
381 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32382 stats_histogram_(NULL),
383 commit_time_histogram_(NULL),
384 autocommit_time_histogram_(NULL),
385 update_time_histogram_(NULL),
386 query_time_histogram_(NULL),
387 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03388 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40389 this, "sql::Connection", nullptr);
[email protected]526b4662013-06-14 04:09:12390}
[email protected]e5ffd0e42009-09-11 21:30:56391
392Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03393 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
394 this);
[email protected]e5ffd0e42009-09-11 21:30:56395 Close();
396}
397
shess58b8df82015-06-03 00:19:32398void Connection::RecordEvent(Events event, size_t count) {
399 for (size_t i = 0; i < count; ++i) {
400 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
401 }
402
403 if (stats_histogram_) {
404 for (size_t i = 0; i < count; ++i) {
405 stats_histogram_->Add(event);
406 }
407 }
408}
409
410void Connection::RecordCommitTime(const base::TimeDelta& delta) {
411 RecordUpdateTime(delta);
412 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
413 if (commit_time_histogram_)
414 commit_time_histogram_->AddTime(delta);
415}
416
417void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
418 RecordUpdateTime(delta);
419 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
420 if (autocommit_time_histogram_)
421 autocommit_time_histogram_->AddTime(delta);
422}
423
424void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
425 RecordQueryTime(delta);
426 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
427 if (update_time_histogram_)
428 update_time_histogram_->AddTime(delta);
429}
430
431void Connection::RecordQueryTime(const base::TimeDelta& delta) {
432 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
433 if (query_time_histogram_)
434 query_time_histogram_->AddTime(delta);
435}
436
437void Connection::RecordTimeAndChanges(
438 const base::TimeDelta& delta, bool read_only) {
439 if (read_only) {
440 RecordQueryTime(delta);
441 } else {
442 const int changes = sqlite3_changes(db_);
443 if (sqlite3_get_autocommit(db_)) {
444 RecordAutoCommitTime(delta);
445 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
446 } else {
447 RecordUpdateTime(delta);
448 RecordEvent(EVENT_CHANGES, changes);
449 }
450 }
451}
452
[email protected]a3ef4832013-02-02 05:12:33453bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02454 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26455 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49456 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02457 size_t sample = static_cast<size_t>(size_64 / 1024);
458 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
459 base::HistogramBase* histogram =
460 base::Histogram::FactoryGet(
461 full_histogram_name, 1, 1000000, 50,
462 base::HistogramBase::kUmaTargetedHistogramFlag);
463 if (histogram)
464 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08465 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02466 }
467 }
468
erg102ceb412015-06-20 01:38:13469 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42470}
[email protected]e5ffd0e42009-09-11 21:30:56471
[email protected]765b44502009-10-02 05:01:42472bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50473 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13474 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56475}
476
[email protected]8d409412013-07-19 18:25:30477bool Connection::OpenTemporary() {
478 return OpenInternal("", NO_RETRY);
479}
480
[email protected]41a97c812013-02-07 02:35:38481void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47482 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
483 // will delete the -journal file. For ChromiumOS or other more
484 // embedded systems, this is probably not appropriate, whereas on
485 // desktop it might make some sense.
486
[email protected]4b350052012-02-24 20:40:48487 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48488
[email protected]41a97c812013-02-07 02:35:38489 // Release cached statements.
490 statement_cache_.clear();
491
492 // With cached statements released, in-use statements will remain.
493 // Closing the database while statements are in use is an API
494 // violation, except for forced close (which happens from within a
495 // statement's error handler).
496 DCHECK(forced || open_statements_.empty());
497
498 // Deactivate any outstanding statements so sqlite3_close() works.
499 for (StatementRefSet::iterator i = open_statements_.begin();
500 i != open_statements_.end(); ++i)
501 (*i)->Close(forced);
502 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48503
[email protected]e5ffd0e42009-09-11 21:30:56504 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50505 // Call to AssertIOAllowed() cannot go at the beginning of the function
506 // because Close() must be called from destructor to clean
507 // statement_cache_, it won't cause any disk access and it most probably
508 // will happen on thread not allowing disk access.
509 // TODO([email protected]): This should move to the beginning
510 // of the function. http://crbug.com/136655.
511 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28512
513 int rc = sqlite3_close(db_);
514 if (rc != SQLITE_OK) {
515 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
516 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
517 }
[email protected]e5ffd0e42009-09-11 21:30:56518 }
[email protected]fed734a2013-07-17 04:45:13519 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56520}
521
[email protected]41a97c812013-02-07 02:35:38522void Connection::Close() {
523 // If the database was already closed by RazeAndClose(), then no
524 // need to close again. Clear the |poisoned_| bit so that incorrect
525 // API calls are caught.
526 if (poisoned_) {
527 poisoned_ = false;
528 return;
529 }
530
531 CloseInternal(false);
532}
533
[email protected]e5ffd0e42009-09-11 21:30:56534void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50535 AssertIOAllowed();
536
[email protected]e5ffd0e42009-09-11 21:30:56537 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38538 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56539 return;
540 }
541
[email protected]8ada10f2013-12-21 00:42:34542 // Use local settings if provided, otherwise use documented defaults. The
543 // actual results could be fetching via PRAGMA calls.
544 const int page_size = page_size_ ? page_size_ : 1024;
545 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
546 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56547 return;
548
[email protected]8ada10f2013-12-21 00:42:34549 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34550 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42551 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34552 if (rc != SQLITE_OK)
553 return;
554
555 // Don't preload more than the file contains.
556 if (preload_size > file_size)
557 preload_size = file_size;
558
559 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46560 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34561 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31562
563 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34564 if (rc != SQLITE_OK)
565 return;
566 }
[email protected]e5ffd0e42009-09-11 21:30:56567}
568
shess7dbd4dee2015-10-06 17:39:16569// SQLite keeps unused pages associated with a connection in a cache. It asks
570// the cache for pages by an id, and if the page is present and the database is
571// unchanged, it considers the content of the page valid and doesn't read it
572// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
573// structures created from the memory map data before consulting the cache. On
574// write SQLite creates a new in-memory page structure, copies the data from the
575// memory map, and later writes it, releasing the updated page back to the
576// cache.
577//
578// This means that in memory-mapped mode, the contents of the cached pages are
579// not re-used for reads, but they are re-used for writes if the re-written page
580// is still in the cache. The implementation of sqlite3_db_release_memory() as
581// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
582// connection, so it should free these pages.
583//
584// Unfortunately, the zero page is also freed. That page is never accessed
585// using memory-mapped I/O, and the cached copy can be re-used after verifying
586// the file change counter on disk. Also, fresh pages from cache receive some
587// pager-level initialization before they can be used. Since the information
588// involved will immediately be accessed in various ways, it is unclear if the
589// additional overhead is material, or just moving processor cache effects
590// around.
591//
592// TODO(shess): It would be better to release the pages immediately when they
593// are no longer needed. This would basically happen after SQLite commits a
594// transaction. I had implemented a pcache wrapper to do this, but it involved
595// layering violations, and it had to be setup before any other sqlite call,
596// which was brittle. Also, for large files it would actually make sense to
597// maintain the existing pcache behavior for blocks past the memory-mapped
598// segment. I think drh would accept a reasonable implementation of the overall
599// concept for upstreaming to SQLite core.
600//
601// TODO(shess): Another possibility would be to set the cache size small, which
602// would keep the zero page around, plus some pre-initialized pages, and SQLite
603// can manage things. The downside is that updates larger than the cache would
604// spill to the journal. That could be compensated by setting cache_spill to
605// false. The downside then is that it allows open-ended use of memory for
606// large transactions.
607//
608// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
609// work. There could be two prepared statements, one for cache_size=1 one for
610// cache_size=goal.
611void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
612 DCHECK(is_open());
613
614 // If memory-mapping is not enabled, the page cache helps performance.
615 if (!mmap_enabled_)
616 return;
617
618 // On caller request, force the change comparison to fail. Done before the
619 // transaction-nesting test so that the signal can carry to transaction
620 // commit.
621 if (implicit_change_performed)
622 --total_changes_at_last_release_;
623
624 // Cached pages may be re-used within the same transaction.
625 if (transaction_nesting())
626 return;
627
628 // If no changes have been made, skip flushing. This allows the first page of
629 // the database to remain in cache across multiple reads.
630 const int total_changes = sqlite3_total_changes(db_);
631 if (total_changes == total_changes_at_last_release_)
632 return;
633
634 total_changes_at_last_release_ = total_changes;
635 sqlite3_db_release_memory(db_);
636}
637
shessc8cd2a162015-10-22 20:30:46638base::FilePath Connection::DbPath() const {
639 if (!is_open())
640 return base::FilePath();
641
642 const char* path = sqlite3_db_filename(db_, "main");
643 const base::StringPiece db_path(path);
644#if defined(OS_WIN)
645 return base::FilePath(base::UTF8ToWide(db_path));
646#elif defined(OS_POSIX)
647 return base::FilePath(db_path);
648#else
649 NOTREACHED();
650 return base::FilePath();
651#endif
652}
653
654// Data is persisted in a file shared between databases in the same directory.
655// The "sqlite-diag" file contains a dictionary with the version number, and an
656// array of histogram tags for databases which have been dumped.
657bool Connection::RegisterIntentToUpload() const {
658 static const char* kVersionKey = "version";
659 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
660 static int kVersion = 1;
661
662 AssertIOAllowed();
663
664 if (histogram_tag_.empty())
665 return false;
666
667 if (!is_open())
668 return false;
669
670 if (in_memory_)
671 return false;
672
673 const base::FilePath db_path = DbPath();
674 if (db_path.empty())
675 return false;
676
677 // Put the collection of diagnostic data next to the databases. In most
678 // cases, this is the profile directory, but safe-browsing stores a Cookies
679 // file in the directory above the profile directory.
680 base::FilePath breadcrumb_path(
681 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
682
683 // Lock against multiple updates to the diagnostics file. This code should
684 // seldom be called in the first place, and when called it should seldom be
685 // called for multiple databases, and when called for multiple databases there
686 // is _probably_ something systemic wrong with the user's system. So the lock
687 // should never be contended, but when it is the database experience is
688 // already bad.
689 base::AutoLock lock(g_sqlite_init_lock.Get());
690
691 scoped_ptr<base::Value> root;
692 if (!base::PathExists(breadcrumb_path)) {
693 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
694 root_dict->SetInteger(kVersionKey, kVersion);
695
696 scoped_ptr<base::ListValue> dumps(new base::ListValue);
697 dumps->AppendString(histogram_tag_);
698 root_dict->Set(kDiagnosticDumpsKey, dumps.Pass());
699
700 root = root_dict.Pass();
701 } else {
702 // Failure to read a valid dictionary implies that something is going wrong
703 // on the system.
704 JSONFileValueDeserializer deserializer(breadcrumb_path);
705 scoped_ptr<base::Value> read_root(
706 deserializer.Deserialize(nullptr, nullptr));
707 if (!read_root.get())
708 return false;
709 scoped_ptr<base::DictionaryValue> root_dict =
710 base::DictionaryValue::From(read_root.Pass());
711 if (!root_dict)
712 return false;
713
714 // Don't upload if the version is missing or newer.
715 int version = 0;
716 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
717 return false;
718
719 base::ListValue* dumps = nullptr;
720 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
721 return false;
722
723 const size_t size = dumps->GetSize();
724 for (size_t i = 0; i < size; ++i) {
725 std::string s;
726
727 // Don't upload if the value isn't a string, or indicates a prior upload.
728 if (!dumps->GetString(i, &s) || s == histogram_tag_)
729 return false;
730 }
731
732 // Record intention to proceed with upload.
733 dumps->AppendString(histogram_tag_);
734 root = root_dict.Pass();
735 }
736
737 const base::FilePath breadcrumb_new =
738 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
739 base::DeleteFile(breadcrumb_new, false);
740
741 // No upload if the breadcrumb file cannot be updated.
742 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
743 // the data on disk. For now, losing the data is not a big problem, so the
744 // sync overhead would probably not be worth it.
745 JSONFileValueSerializer serializer(breadcrumb_new);
746 if (!serializer.Serialize(*root))
747 return false;
748 if (!base::PathExists(breadcrumb_new))
749 return false;
750 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
751 base::DeleteFile(breadcrumb_new, false);
752 return false;
753 }
754
755 return true;
756}
757
758std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
759 // Buffer for accumulating debugging info about the error. Place
760 // more-relevant information earlier, in case things overflow the
761 // fixed-size reporting buffer.
762 std::string debug_info;
763
764 // The error message from the failed operation.
765 base::StringAppendF(&debug_info, "db error: %d/%s\n",
766 GetErrorCode(), GetErrorMessage());
767
768 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
769 // reading code does not entirely convince me. Remove if they turn out to be
770 // the same.
771 if (error != GetErrorCode())
772 base::StringAppendF(&debug_info, "reported error: %d\n", error);
773
774 // System error information. Interpretation of Windows errors is different
775 // from posix.
776#if defined(OS_WIN)
777 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
778#elif defined(OS_POSIX)
779 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
780#else
781 NOTREACHED(); // Add appropriate log info.
782#endif
783
784 if (stmt) {
785 base::StringAppendF(&debug_info, "statement: %s\n",
786 stmt->GetSQLStatement());
787 } else {
788 base::StringAppendF(&debug_info, "statement: NULL\n");
789 }
790
791 // SQLITE_ERROR often indicates some sort of mismatch between the statement
792 // and the schema, possibly due to a failed schema migration.
793 if (error == SQLITE_ERROR) {
794 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
795 sqlite3_stmt* s;
796 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
797 if (rc == SQLITE_OK) {
798 rc = sqlite3_step(s);
799 if (rc == SQLITE_ROW) {
800 base::StringAppendF(&debug_info, "version: %d\n",
801 sqlite3_column_int(s, 0));
802 } else if (rc == SQLITE_DONE) {
803 debug_info += "version: none\n";
804 } else {
805 base::StringAppendF(&debug_info, "version: error %d\n", rc);
806 }
807 sqlite3_finalize(s);
808 } else {
809 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
810 }
811
812 debug_info += "schema:\n";
813
814 // sqlite_master has columns:
815 // type - "index" or "table".
816 // name - name of created element.
817 // tbl_name - name of element, or target table in case of index.
818 // rootpage - root page of the element in database file.
819 // sql - SQL to create the element.
820 // In general, the |sql| column is sufficient to derive the other columns.
821 // |rootpage| is not interesting for debugging, without the contents of the
822 // database. The COALESCE is because certain automatic elements will have a
823 // |name| but no |sql|,
824 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
825 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
826 if (rc == SQLITE_OK) {
827 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
828 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
829 }
830 if (rc != SQLITE_DONE)
831 base::StringAppendF(&debug_info, "error %d\n", rc);
832 sqlite3_finalize(s);
833 } else {
834 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
835 }
836 }
837
838 return debug_info;
839}
840
841// TODO(shess): Since this is only called in an error situation, it might be
842// prudent to rewrite in terms of SQLite API calls, and mark the function const.
843std::string Connection::CollectCorruptionInfo() {
844 AssertIOAllowed();
845
846 // If the file cannot be accessed it is unlikely that an integrity check will
847 // turn up actionable information.
848 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19849 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46850 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
851 return std::string();
852
853 // Buffer for accumulating debugging info about the error. Place
854 // more-relevant information earlier, in case things overflow the
855 // fixed-size reporting buffer.
856 std::string debug_info;
857 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
858 db_size);
859
860 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19861 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46862 if (db_size > kMaxIntegrityCheckSize) {
863 debug_info += "integrity_check skipped due to size\n";
864 } else {
865 std::vector<std::string> messages;
866
867 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
868 // into a string. Probably should be refactored.
869 const base::TimeTicks before = base::TimeTicks::Now();
870 FullIntegrityCheck(&messages);
871 base::StringAppendF(
872 &debug_info,
873 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
874 (base::TimeTicks::Now() - before).InMilliseconds(),
875 messages.size());
876
877 // SQLite returns up to 100 messages by default, trim deeper to
878 // keep close to the 2000-character size limit for dumping.
879 const size_t kMaxMessages = 20;
880 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
881 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
882 }
883 }
884
885 return debug_info;
886}
887
shessd90aeea82015-11-13 02:24:31888size_t Connection::GetAppropriateMmapSize() {
889 AssertIOAllowed();
890
shessd90aeea82015-11-13 02:24:31891#if defined(OS_IOS)
892 // iOS SQLite does not support memory mapping.
893 return 0;
894#endif
895
shess9bf2c672015-12-18 01:18:08896 // How much to map if no errors are found. 50MB encompasses the 99th
897 // percentile of Chrome databases in the wild, so this should be good.
898 const size_t kMmapEverything = 256 * 1024 * 1024;
899
900 // If the database doesn't have a place to track progress, assume the best.
901 // This will happen when new databases are created, or if a database doesn't
902 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
903 // TODO(shess): Databases not using meta include:
904 // DOMStorageDatabase (localstorage)
905 // ActivityDatabase (extensions activity log)
906 // PredictorDatabase (prefetch and autocomplete predictor data)
907 // SyncDirectory (sync metadata storage)
908 // For now, these all have mmap disabled to allow other databases to get the
909 // default-enable path. sqlite-diag could be an alternative for all but
910 // DOMStorageDatabase, which creates many small databases.
911 // http://crbug.com/537742
912 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31913 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08914 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31915 }
916
shess9bf2c672015-12-18 01:18:08917 int64_t mmap_ofs = 0;
918 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
919 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
920 return 0;
shessd90aeea82015-11-13 02:24:31921 }
922
923 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08924 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31925 RecordOneEvent(EVENT_MMAP_FAILED);
926 return 0;
shess9bf2c672015-12-18 01:18:08927 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31928 // Continue reading from previous offset.
929 DCHECK_GE(mmap_ofs, 0);
930
931 // TODO(shess): Could this reading code be shared with Preload()? It would
932 // require locking twice (this code wouldn't be able to access |db_size| so
933 // the helper would have to return amount read).
934
935 // Read more of the database looking for errors. The VFS interface is used
936 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
937 // to limit checking to 20MB per run of Chromium.
938 sqlite3_file* file = NULL;
939 sqlite3_int64 db_size = 0;
940 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
941 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
942 return 0;
943 }
944
945 // Read the data left, or |g_reads_allowed|, whichever is smaller.
946 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
947 // in a single Chromium run.
948 sqlite3_int64 amount = db_size - mmap_ofs;
949 if (amount < 0)
950 amount = 0;
951 if (amount > 0) {
952 base::AutoLock lock(g_sqlite_init_lock.Get());
953 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
954 if (g_reads_allowed < amount)
955 amount = g_reads_allowed;
956 g_reads_allowed -= amount;
957 }
958
959 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
960 // database was truncated after a previous pass.
961 if (amount <= 0 && mmap_ofs < db_size) {
962 DCHECK_EQ(0, amount);
963 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
964 } else {
965 static const int kPageSize = 4096;
966 char buf[kPageSize];
967 while (amount > 0) {
968 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
969 if (rc == SQLITE_OK) {
970 mmap_ofs += sizeof(buf);
971 amount -= sizeof(buf);
972 } else if (rc == SQLITE_IOERR_SHORT_READ) {
973 // Reached EOF for a database with page size < |kPageSize|.
974 mmap_ofs = db_size;
975 break;
976 } else {
977 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08978 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31979 break;
980 }
981 }
982
983 // Log these events after update to distinguish meta update failure.
984 Events event;
985 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08986 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31987 event = EVENT_MMAP_SUCCESS_NEW;
988 } else if (mmap_ofs > 0) {
989 event = EVENT_MMAP_SUCCESS_PARTIAL;
990 } else {
shess9bf2c672015-12-18 01:18:08991 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31992 event = EVENT_MMAP_FAILED_NEW;
993 }
994
shess9bf2c672015-12-18 01:18:08995 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31996 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
997 return 0;
998 }
999
1000 RecordOneEvent(event);
1001 }
1002 }
1003
shess9bf2c672015-12-18 01:18:081004 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:311005 return 0;
shess9bf2c672015-12-18 01:18:081006 if (mmap_ofs == MetaTable::kMmapSuccess)
1007 return kMmapEverything;
shessd90aeea82015-11-13 02:24:311008 return mmap_ofs;
1009}
1010
[email protected]be7995f12013-07-18 18:49:141011void Connection::TrimMemory(bool aggressively) {
1012 if (!db_)
1013 return;
1014
1015 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1016 int original_cache_size;
1017 {
1018 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1019 if (!sql_get_original.Step()) {
1020 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1021 return;
1022 }
1023 original_cache_size = sql_get_original.ColumnInt(0);
1024 }
1025 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1026
1027 // Force sqlite to try to reduce page cache usage.
1028 const std::string sql_shrink =
1029 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1030 if (!Execute(sql_shrink.c_str()))
1031 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1032
1033 // Restore cache size.
1034 const std::string sql_restore =
1035 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1036 if (!Execute(sql_restore.c_str()))
1037 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1038}
1039
[email protected]8e0c01282012-04-06 19:36:491040// Create an in-memory database with the existing database's page
1041// size, then backup that database over the existing database.
1042bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501043 AssertIOAllowed();
1044
[email protected]8e0c01282012-04-06 19:36:491045 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381046 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491047 return false;
1048 }
1049
1050 if (transaction_nesting_ > 0) {
1051 DLOG(FATAL) << "Cannot raze within a transaction";
1052 return false;
1053 }
1054
1055 sql::Connection null_db;
1056 if (!null_db.OpenInMemory()) {
1057 DLOG(FATAL) << "Unable to open in-memory database.";
1058 return false;
1059 }
1060
[email protected]6d42f152012-11-10 00:38:241061 if (page_size_) {
1062 // Enforce SQLite restrictions on |page_size_|.
1063 DCHECK(!(page_size_ & (page_size_ - 1)))
1064 << " page_size_ " << page_size_ << " is not a power of two.";
1065 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1066 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041067 const std::string sql =
1068 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421069 if (!null_db.Execute(sql.c_str()))
1070 return false;
1071 }
1072
[email protected]6d42f152012-11-10 00:38:241073#if defined(OS_ANDROID)
1074 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1075 // in-memory databases do not respect this define.
1076 // TODO(shess): Figure out a way to set this without using platform
1077 // specific code. AFAICT from sqlite3.c, the only way to do it
1078 // would be to create an actual filesystem database, which is
1079 // unfortunate.
1080 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1081 return false;
1082#endif
[email protected]8e0c01282012-04-06 19:36:491083
1084 // The page size doesn't take effect until a database has pages, and
1085 // at this point the null database has none. Changing the schema
1086 // version will create the first page. This will not affect the
1087 // schema version in the resulting database, as SQLite's backup
1088 // implementation propagates the schema version from the original
1089 // connection to the new version of the database, incremented by one
1090 // so that other readers see the schema change and act accordingly.
1091 if (!null_db.Execute("PRAGMA schema_version = 1"))
1092 return false;
1093
[email protected]6d42f152012-11-10 00:38:241094 // SQLite tracks the expected number of database pages in the first
1095 // page, and if it does not match the total retrieved from a
1096 // filesystem call, treats the database as corrupt. This situation
1097 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1098 // used to hint to SQLite to soldier on in that case, specifically
1099 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1100 // sqlite3.c lockBtree().]
1101 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1102 // page_size" can be used to query such a database.
1103 ScopedWritableSchema writable_schema(db_);
1104
[email protected]7bae5742013-07-10 20:46:161105 const char* kMain = "main";
1106 int rc = BackupDatabase(null_db.db_, db_, kMain);
1107 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491108
1109 // The destination database was locked.
1110 if (rc == SQLITE_BUSY) {
1111 return false;
1112 }
1113
[email protected]7bae5742013-07-10 20:46:161114 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1115 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1116 // isn't even big enough for one page. Either way, reach in and
1117 // truncate it before trying again.
1118 // TODO(shess): Maybe it would be worthwhile to just truncate from
1119 // the get-go?
1120 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1121 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341122 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161123 if (rc != SQLITE_OK) {
1124 DLOG(FATAL) << "Failure getting file handle.";
1125 return false;
[email protected]7bae5742013-07-10 20:46:161126 }
1127
1128 rc = file->pMethods->xTruncate(file, 0);
1129 if (rc != SQLITE_OK) {
1130 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1131 DLOG(FATAL) << "Failed to truncate file.";
1132 return false;
1133 }
1134
1135 rc = BackupDatabase(null_db.db_, db_, kMain);
1136 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1137
1138 if (rc != SQLITE_DONE) {
1139 DLOG(FATAL) << "Failed retrying Raze().";
1140 }
1141 }
1142
[email protected]8e0c01282012-04-06 19:36:491143 // The entire database should have been backed up.
1144 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161145 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491146 DLOG(FATAL) << "Unable to copy entire null database.";
1147 return false;
1148 }
1149
[email protected]8e0c01282012-04-06 19:36:491150 return true;
1151}
1152
1153bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1154 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381155 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491156 return false;
1157 }
1158
1159 ScopedBusyTimeout busy_timeout(db_);
1160 busy_timeout.SetTimeout(timeout);
1161 return Raze();
1162}
1163
[email protected]41a97c812013-02-07 02:35:381164bool Connection::RazeAndClose() {
1165 if (!db_) {
1166 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1167 return false;
1168 }
1169
1170 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301171 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381172
1173 bool result = Raze();
1174
1175 CloseInternal(true);
1176
1177 // Mark the database so that future API calls fail appropriately,
1178 // but don't DCHECK (because after calling this function they are
1179 // expected to fail).
1180 poisoned_ = true;
1181
1182 return result;
1183}
1184
[email protected]8d409412013-07-19 18:25:301185void Connection::Poison() {
1186 if (!db_) {
1187 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1188 return;
1189 }
1190
1191 RollbackAllTransactions();
1192 CloseInternal(true);
1193
1194 // Mark the database so that future API calls fail appropriately,
1195 // but don't DCHECK (because after calling this function they are
1196 // expected to fail).
1197 poisoned_ = true;
1198}
1199
[email protected]8d2e39e2013-06-24 05:55:081200// TODO(shess): To the extent possible, figure out the optimal
1201// ordering for these deletes which will prevent other connections
1202// from seeing odd behavior. For instance, it may be necessary to
1203// manually lock the main database file in a SQLite-compatible fashion
1204// (to prevent other processes from opening it), then delete the
1205// journal files, then delete the main database file. Another option
1206// might be to lock the main database file and poison the header with
1207// junk to prevent other processes from opening it successfully (like
1208// Gears "SQLite poison 3" trick).
1209//
1210// static
1211bool Connection::Delete(const base::FilePath& path) {
1212 base::ThreadRestrictions::AssertIOAllowed();
1213
1214 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1215 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1216
erg102ceb412015-06-20 01:38:131217 std::string journal_str = AsUTF8ForSQL(journal_path);
1218 std::string wal_str = AsUTF8ForSQL(wal_path);
1219 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081220
shess702467622015-09-16 19:04:551221 // Make sure sqlite3_initialize() is called before anything else.
1222 InitializeSqlite();
1223
erg102ceb412015-06-20 01:38:131224 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1225 CHECK(vfs);
1226 CHECK(vfs->xDelete);
1227 CHECK(vfs->xAccess);
1228
1229 // We only work with unix, win32 and mojo filesystems. If you're trying to
1230 // use this code with any other VFS, you're not in a good place.
1231 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1232 strncmp(vfs->zName, "win32", 5) == 0 ||
1233 strcmp(vfs->zName, "mojo") == 0);
1234
1235 vfs->xDelete(vfs, journal_str.c_str(), 0);
1236 vfs->xDelete(vfs, wal_str.c_str(), 0);
1237 vfs->xDelete(vfs, path_str.c_str(), 0);
1238
1239 int journal_exists = 0;
1240 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1241 &journal_exists);
1242
1243 int wal_exists = 0;
1244 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1245 &wal_exists);
1246
1247 int path_exists = 0;
1248 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1249 &path_exists);
1250
1251 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081252}
1253
[email protected]e5ffd0e42009-09-11 21:30:561254bool Connection::BeginTransaction() {
1255 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331256 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561257
1258 // When we're going to rollback, fail on this begin and don't actually
1259 // mark us as entering the nested transaction.
1260 return false;
1261 }
1262
1263 bool success = true;
1264 if (!transaction_nesting_) {
1265 needs_rollback_ = false;
1266
1267 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321268 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591269 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561270 return false;
1271 }
1272 transaction_nesting_++;
1273 return success;
1274}
1275
1276void Connection::RollbackTransaction() {
1277 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381278 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561279 return;
1280 }
1281
1282 transaction_nesting_--;
1283
1284 if (transaction_nesting_ > 0) {
1285 // Mark the outermost transaction as needing rollback.
1286 needs_rollback_ = true;
1287 return;
1288 }
1289
1290 DoRollback();
1291}
1292
1293bool Connection::CommitTransaction() {
1294 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181295 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561296 return false;
1297 }
1298 transaction_nesting_--;
1299
1300 if (transaction_nesting_ > 0) {
1301 // Mark any nested transactions as failing after we've already got one.
1302 return !needs_rollback_;
1303 }
1304
1305 if (needs_rollback_) {
1306 DoRollback();
1307 return false;
1308 }
1309
1310 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321311
1312 // Collect the commit time manually, sql::Statement would register it as query
1313 // time only.
1314 const base::TimeTicks before = Now();
1315 bool ret = commit.RunWithoutTimers();
1316 const base::TimeDelta delta = Now() - before;
1317
1318 RecordCommitTime(delta);
1319 RecordOneEvent(EVENT_COMMIT);
1320
shess7dbd4dee2015-10-06 17:39:161321 // Release dirty cache pages after the transaction closes.
1322 ReleaseCacheMemoryIfNeeded(false);
1323
shess58b8df82015-06-03 00:19:321324 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561325}
1326
[email protected]8d409412013-07-19 18:25:301327void Connection::RollbackAllTransactions() {
1328 if (transaction_nesting_ > 0) {
1329 transaction_nesting_ = 0;
1330 DoRollback();
1331 }
1332}
1333
1334bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1335 const char* attachment_point) {
1336 DCHECK(ValidAttachmentPoint(attachment_point));
1337
1338 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1339#if OS_WIN
1340 s.BindString16(0, other_db_path.value());
1341#else
1342 s.BindString(0, other_db_path.value());
1343#endif
1344 s.BindString(1, attachment_point);
1345 return s.Run();
1346}
1347
1348bool Connection::DetachDatabase(const char* attachment_point) {
1349 DCHECK(ValidAttachmentPoint(attachment_point));
1350
1351 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1352 s.BindString(0, attachment_point);
1353 return s.Run();
1354}
1355
shess58b8df82015-06-03 00:19:321356// TODO(shess): Consider changing this to execute exactly one statement. If a
1357// caller wishes to execute multiple statements, that should be explicit, and
1358// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591359int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501360 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381361 if (!db_) {
1362 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1363 return SQLITE_ERROR;
1364 }
shess58b8df82015-06-03 00:19:321365 DCHECK(sql);
1366
1367 RecordOneEvent(EVENT_EXECUTE);
1368 int rc = SQLITE_OK;
1369 while ((rc == SQLITE_OK) && *sql) {
1370 sqlite3_stmt *stmt = NULL;
1371 const char *leftover_sql;
1372
1373 const base::TimeTicks before = Now();
1374 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1375 sql = leftover_sql;
1376
1377 // Stop if an error is encountered.
1378 if (rc != SQLITE_OK)
1379 break;
1380
1381 // This happens if |sql| originally only contained comments or whitespace.
1382 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1383 // extraneous comments and whitespace in the SQL statements increases
1384 // runtime cost and can easily be shifted out to the C++ layer.
1385 if (!stmt)
1386 continue;
1387
1388 // Save for use after statement is finalized.
1389 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1390
1391 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1392 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1393 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1394 // is the only legitimate case for this.
1395 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1396 }
1397
1398 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1399 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1400 rc = sqlite3_finalize(stmt);
1401 if (rc == SQLITE_OK)
1402 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1403
1404 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1405 // trailing whitespace.
1406 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021407 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321408 sql++;
1409 }
1410
1411 const base::TimeDelta delta = Now() - before;
1412 RecordTimeAndChanges(delta, read_only);
1413 }
shess7dbd4dee2015-10-06 17:39:161414
1415 // Most calls to Execute() modify the database. The main exceptions would be
1416 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1417 // but sometimes don't.
1418 ReleaseCacheMemoryIfNeeded(true);
1419
shess58b8df82015-06-03 00:19:321420 return rc;
[email protected]eff1fa522011-12-12 23:50:591421}
1422
1423bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381424 if (!db_) {
1425 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1426 return false;
1427 }
1428
[email protected]eff1fa522011-12-12 23:50:591429 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001430 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581431 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001432
[email protected]28fe0ff2012-02-25 00:40:331433 // This needs to be a FATAL log because the error case of arriving here is
1434 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101435 // a change alters the schema but not all queries adjust. This can happen
1436 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591437 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331438 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591439 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561440}
1441
[email protected]5b96f3772010-09-28 16:30:571442bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381443 if (!db_) {
1444 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571445 return false;
[email protected]41a97c812013-02-07 02:35:381446 }
[email protected]5b96f3772010-09-28 16:30:571447
1448 ScopedBusyTimeout busy_timeout(db_);
1449 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591450 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571451}
1452
[email protected]e5ffd0e42009-09-11 21:30:561453bool Connection::HasCachedStatement(const StatementID& id) const {
1454 return statement_cache_.find(id) != statement_cache_.end();
1455}
1456
1457scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1458 const StatementID& id,
1459 const char* sql) {
1460 CachedStatementMap::iterator i = statement_cache_.find(id);
1461 if (i != statement_cache_.end()) {
1462 // Statement is in the cache. It should still be active (we're the only
1463 // one invalidating cached statements, and we'll remove it from the cache
1464 // if we do that. Make sure we reset it before giving out the cached one in
1465 // case it still has some stuff bound.
1466 DCHECK(i->second->is_valid());
1467 sqlite3_reset(i->second->stmt());
1468 return i->second;
1469 }
1470
1471 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1472 if (statement->is_valid())
1473 statement_cache_[id] = statement; // Only cache valid statements.
1474 return statement;
1475}
1476
1477scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1478 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501479 AssertIOAllowed();
1480
[email protected]41a97c812013-02-07 02:35:381481 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561482 if (!db_)
[email protected]41a97c812013-02-07 02:35:381483 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561484
1485 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001486 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1487 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591488 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061489 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021490 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001491
1492 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581493 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381494 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561495 }
[email protected]41a97c812013-02-07 02:35:381496 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561497}
1498
shessf7e988f2015-11-13 00:41:061499// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1500// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581501scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1502 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381503 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581504 if (!db_)
[email protected]41a97c812013-02-07 02:35:381505 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581506
1507 sqlite3_stmt* stmt = NULL;
1508 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1509 if (rc != SQLITE_OK) {
1510 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061511 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021512 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381513 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581514 }
[email protected]41a97c812013-02-07 02:35:381515 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581516}
1517
[email protected]92cd00a2013-08-16 11:09:581518std::string Connection::GetSchema() const {
1519 // The ORDER BY should not be necessary, but relying on organic
1520 // order for something like this is questionable.
1521 const char* kSql =
1522 "SELECT type, name, tbl_name, sql "
1523 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1524 Statement statement(GetUntrackedStatement(kSql));
1525
1526 std::string schema;
1527 while (statement.Step()) {
1528 schema += statement.ColumnString(0);
1529 schema += '|';
1530 schema += statement.ColumnString(1);
1531 schema += '|';
1532 schema += statement.ColumnString(2);
1533 schema += '|';
1534 schema += statement.ColumnString(3);
1535 schema += '\n';
1536 }
1537
1538 return schema;
1539}
1540
[email protected]eff1fa522011-12-12 23:50:591541bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501542 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381543 if (!db_) {
1544 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1545 return false;
1546 }
1547
[email protected]eff1fa522011-12-12 23:50:591548 sqlite3_stmt* stmt = NULL;
1549 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1550 return false;
1551
1552 sqlite3_finalize(stmt);
1553 return true;
1554}
1555
[email protected]1ed78a32009-09-15 20:24:171556bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531557 return DoesTableOrIndexExist(table_name, "table");
1558}
1559
1560bool Connection::DoesIndexExist(const char* index_name) const {
1561 return DoesTableOrIndexExist(index_name, "index");
1562}
1563
1564bool Connection::DoesTableOrIndexExist(
1565 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471566 const char* kSql =
1567 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581568 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471569
1570 // This can happen if the database is corrupt and the error is being ignored
1571 // for testing purposes.
1572 if (!statement.is_valid())
1573 return false;
1574
[email protected]e2cadec82011-12-13 02:00:531575 statement.BindString(0, type);
1576 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331577
[email protected]e5ffd0e42009-09-11 21:30:561578 return statement.Step(); // Table exists if any row was returned.
1579}
1580
1581bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171582 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561583 std::string sql("PRAGMA TABLE_INFO(");
1584 sql.append(table_name);
1585 sql.append(")");
1586
[email protected]2eec0a22012-07-24 01:59:581587 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471588
1589 // This can happen if the database is corrupt and the error is being ignored
1590 // for testing purposes.
1591 if (!statement.is_valid())
1592 return false;
1593
[email protected]e5ffd0e42009-09-11 21:30:561594 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331595 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1596 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561597 return true;
1598 }
1599 return false;
1600}
1601
tfarina720d4f32015-05-11 22:31:261602int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561603 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381604 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561605 return 0;
1606 }
1607 return sqlite3_last_insert_rowid(db_);
1608}
1609
[email protected]1ed78a32009-09-15 20:24:171610int Connection::GetLastChangeCount() const {
1611 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381612 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171613 return 0;
1614 }
1615 return sqlite3_changes(db_);
1616}
1617
[email protected]e5ffd0e42009-09-11 21:30:561618int Connection::GetErrorCode() const {
1619 if (!db_)
1620 return SQLITE_ERROR;
1621 return sqlite3_errcode(db_);
1622}
1623
[email protected]767718e52010-09-21 23:18:491624int Connection::GetLastErrno() const {
1625 if (!db_)
1626 return -1;
1627
1628 int err = 0;
1629 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1630 return -2;
1631
1632 return err;
1633}
1634
[email protected]e5ffd0e42009-09-11 21:30:561635const char* Connection::GetErrorMessage() const {
1636 if (!db_)
1637 return "sql::Connection has no connection.";
1638 return sqlite3_errmsg(db_);
1639}
1640
[email protected]fed734a2013-07-17 04:45:131641bool Connection::OpenInternal(const std::string& file_name,
1642 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501643 AssertIOAllowed();
1644
[email protected]9cfbc922009-11-17 20:13:171645 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591646 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171647 return false;
1648 }
1649
[email protected]a7ec1292013-07-22 22:02:181650 // Make sure sqlite3_initialize() is called before anything else.
1651 InitializeSqlite();
1652
shess58b8df82015-06-03 00:19:321653 // Setup the stats histograms immediately rather than allocating lazily.
1654 // Connections which won't exercise all of these probably shouldn't exist.
1655 if (!histogram_tag_.empty()) {
1656 stats_histogram_ =
1657 base::LinearHistogram::FactoryGet(
1658 "Sqlite.Stats." + histogram_tag_,
1659 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1660 base::HistogramBase::kUmaTargetedHistogramFlag);
1661
1662 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1663 // unreasonable time for any single operation, so there is not much value to
1664 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1665 // things are entirely busted.
1666 commit_time_histogram_ =
1667 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1668
1669 autocommit_time_histogram_ =
1670 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1671
1672 update_time_histogram_ =
1673 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1674
1675 query_time_histogram_ =
1676 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1677 }
1678
[email protected]41a97c812013-02-07 02:35:381679 // If |poisoned_| is set, it means an error handler called
1680 // RazeAndClose(). Until regular Close() is called, the caller
1681 // should be treating the database as open, but is_open() currently
1682 // only considers the sqlite3 handle's state.
1683 // TODO(shess): Revise is_open() to consider poisoned_, and review
1684 // to see if any non-testing code even depends on it.
1685 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161686 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381687
[email protected]765b44502009-10-02 05:01:421688 int err = sqlite3_open(file_name.c_str(), &db_);
1689 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281690 // Extended error codes cannot be enabled until a handle is
1691 // available, fetch manually.
1692 err = sqlite3_extended_errcode(db_);
1693
[email protected]bd2ccdb4a2012-12-07 22:14:501694 // Histogram failures specific to initial open for debugging
1695 // purposes.
[email protected]73fb8d52013-07-24 05:04:281696 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501697
[email protected]2f496b42013-09-26 18:36:581698 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131699 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291700 Close();
[email protected]fed734a2013-07-17 04:45:131701
1702 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1703 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421704 return false;
1705 }
1706
[email protected]81a2a602013-07-17 19:10:361707 // TODO(shess): OS_WIN support?
1708#if defined(OS_POSIX)
1709 if (restrict_to_user_) {
1710 DCHECK_NE(file_name, std::string(":memory"));
1711 base::FilePath file_path(file_name);
1712 int mode = 0;
1713 // TODO(shess): Arguably, failure to retrieve and change
1714 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081715 if (base::GetPosixFilePermissions(file_path, &mode)) {
1716 mode &= base::FILE_PERMISSION_USER_MASK;
1717 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361718
1719 // SQLite sets the permissions on these files from the main
1720 // database on create. Set them here in case they already exist
1721 // at this point. Failure to set these permissions should not
1722 // be fatal unless the file doesn't exist.
1723 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1724 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081725 base::SetPosixFilePermissions(journal_path, mode);
1726 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361727 }
1728 }
1729#endif // defined(OS_POSIX)
1730
[email protected]affa2da2013-06-06 22:20:341731 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1732 // Chromium already depends on small mallocs being efficient, so we disable
1733 // this to avoid the extra memory overhead.
1734 // This must be called immediatly after opening the database before any SQL
1735 // statements are run.
1736 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1737
[email protected]73fb8d52013-07-24 05:04:281738 // Enable extended result codes to provide more color on I/O errors.
1739 // Not having extended result codes is not a fatal problem, as
1740 // Chromium code does not attempt to handle I/O errors anyhow. The
1741 // current implementation always returns SQLITE_OK, the DCHECK is to
1742 // quickly notify someone if SQLite changes.
1743 err = sqlite3_extended_result_codes(db_, 1);
1744 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1745
[email protected]bd2ccdb4a2012-12-07 22:14:501746 // sqlite3_open() does not actually read the database file (unless a
1747 // hot journal is found). Successfully executing this pragma on an
1748 // existing database requires a valid header on page 1.
1749 // TODO(shess): For now, just probing to see what the lay of the
1750 // land is. If it's mostly SQLITE_NOTADB, then the database should
1751 // be razed.
1752 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1753 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281754 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431755
[email protected]2e1cee762013-07-09 14:40:001756#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1757 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1758 // REGEXP support. Add it in dynamically.
1759 err = sqlite3IcuInit(db_);
1760 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1761#endif // OS_IOS && USE_SYSTEM_SQLITE
1762
[email protected]5b96f3772010-09-28 16:30:571763 // If indicated, lock up the database before doing anything else, so
1764 // that the following code doesn't have to deal with locking.
1765 // TODO(shess): This code is brittle. Find the cases where code
1766 // doesn't request |exclusive_locking_| and audit that it does the
1767 // right thing with SQLITE_BUSY, and that it doesn't make
1768 // assumptions about who might change things in the database.
1769 // http://crbug.com/56559
1770 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101771 // TODO(shess): This should probably be a failure. Code which
1772 // requests exclusive locking but doesn't get it is almost certain
1773 // to be ill-tested.
1774 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571775 }
1776
[email protected]4e179ba2012-03-17 16:06:471777 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1778 // DELETE (default) - delete -journal file to commit.
1779 // TRUNCATE - truncate -journal file to commit.
1780 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091781 // TRUNCATE should be faster than DELETE because it won't need directory
1782 // changes for each transaction. PERSIST may break the spirit of using
1783 // secure_delete.
1784 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471785
[email protected]c68ce172011-11-24 22:30:271786 const base::TimeDelta kBusyTimeout =
1787 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1788
[email protected]765b44502009-10-02 05:01:421789 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571790 // Enforce SQLite restrictions on |page_size_|.
1791 DCHECK(!(page_size_ & (page_size_ - 1)))
1792 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241793 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571794 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041795 const std::string sql =
1796 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101797 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421798 }
1799
1800 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041801 const std::string sql =
1802 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101803 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421804 }
1805
[email protected]6e0b1442011-08-09 23:23:581806 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131807 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581808 Close();
[email protected]fed734a2013-07-17 04:45:131809 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1810 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581811 return false;
1812 }
1813
shess5dac334f2015-11-05 20:47:421814 // Set a reasonable chunk size for larger files. This reduces churn from
1815 // remapping memory on size changes. It also reduces filesystem
1816 // fragmentation.
1817 // TODO(shess): It may make sense to have this be hinted by the client.
1818 // Database sizes seem to be bimodal, some clients have consistently small
1819 // databases (<20k) while other clients have a broad distribution of sizes
1820 // (hundreds of kilobytes to many megabytes).
1821 sqlite3_file* file = NULL;
1822 sqlite3_int64 db_size = 0;
1823 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1824 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1825 int chunk_size = 4 * 1024;
1826 if (db_size > 128 * 1024)
1827 chunk_size = 32 * 1024;
1828 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1829 }
1830
shess2f3a814b2015-11-05 18:11:101831 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311832 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1833 // safe range to memory-map based on past regular I/O. This value will be
1834 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1835 // 64-bit platforms.
1836 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1837 std::string mmap_sql =
1838 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1839 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101840
1841 // Determine if memory-mapping has actually been enabled. The Execute() above
1842 // can succeed without changing the amount mapped.
1843 mmap_enabled_ = false;
1844 {
1845 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1846 if (s.Step() && s.ColumnInt64(0) > 0)
1847 mmap_enabled_ = true;
1848 }
1849
[email protected]765b44502009-10-02 05:01:421850 return true;
1851}
1852
[email protected]e5ffd0e42009-09-11 21:30:561853void Connection::DoRollback() {
1854 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321855
1856 // Collect the rollback time manually, sql::Statement would register it as
1857 // query time only.
1858 const base::TimeTicks before = Now();
1859 rollback.RunWithoutTimers();
1860 const base::TimeDelta delta = Now() - before;
1861
1862 RecordUpdateTime(delta);
1863 RecordOneEvent(EVENT_ROLLBACK);
1864
shess7dbd4dee2015-10-06 17:39:161865 // The cache may have been accumulating dirty pages for commit. Note that in
1866 // some cases sql::Transaction can fire rollback after a database is closed.
1867 if (is_open())
1868 ReleaseCacheMemoryIfNeeded(false);
1869
[email protected]44ad7d902012-03-23 00:09:051870 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561871}
1872
1873void Connection::StatementRefCreated(StatementRef* ref) {
1874 DCHECK(open_statements_.find(ref) == open_statements_.end());
1875 open_statements_.insert(ref);
1876}
1877
1878void Connection::StatementRefDeleted(StatementRef* ref) {
1879 StatementRefSet::iterator i = open_statements_.find(ref);
1880 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591881 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561882 else
1883 open_statements_.erase(i);
1884}
1885
shess58b8df82015-06-03 00:19:321886void Connection::set_histogram_tag(const std::string& tag) {
1887 DCHECK(!is_open());
1888 histogram_tag_ = tag;
1889}
1890
[email protected]210ce0af2013-05-15 09:10:391891void Connection::AddTaggedHistogram(const std::string& name,
1892 size_t sample) const {
1893 if (histogram_tag_.empty())
1894 return;
1895
1896 // TODO(shess): The histogram macros create a bit of static storage
1897 // for caching the histogram object. This code shouldn't execute
1898 // often enough for such caching to be crucial. If it becomes an
1899 // issue, the object could be cached alongside histogram_prefix_.
1900 std::string full_histogram_name = name + "." + histogram_tag_;
1901 base::HistogramBase* histogram =
1902 base::SparseHistogram::FactoryGet(
1903 full_histogram_name,
1904 base::HistogramBase::kUmaTargetedHistogramFlag);
1905 if (histogram)
1906 histogram->Add(sample);
1907}
1908
[email protected]2f496b42013-09-26 18:36:581909int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391910 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1911 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141912
1913 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581914 if (!sql && stmt)
1915 sql = stmt->GetSQLStatement();
1916 if (!sql)
1917 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061918
1919 std::string id = histogram_tag_;
1920 if (id.empty())
1921 id = DbPath().BaseName().AsUTF8Unsafe();
1922 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141923 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581924 << ": " << GetErrorMessage()
1925 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141926
[email protected]c3881b372013-05-17 08:39:461927 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561928 // Fire from a copy of the callback in case of reentry into
1929 // re/set_error_callback().
1930 // TODO(shess): <http://crbug.com/254584>
1931 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461932 return err;
1933 }
1934
[email protected]faa604e2009-09-25 22:38:591935 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571936 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101937 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591938 return err;
1939}
1940
[email protected]579446c2013-12-16 18:36:521941bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1942 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1943}
1944
1945bool Connection::QuickIntegrityCheck() {
1946 std::vector<std::string> messages;
1947 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1948 return false;
1949 return messages.size() == 1 && messages[0] == "ok";
1950}
1951
[email protected]80abf152013-05-22 12:42:421952// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521953bool Connection::IntegrityCheckHelper(
1954 const char* pragma_sql,
1955 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421956 messages->clear();
1957
[email protected]4658e2a02013-06-06 23:05:001958 // This has the side effect of setting SQLITE_RecoveryMode, which
1959 // allows SQLite to process through certain cases of corruption.
1960 // Failing to set this pragma probably means that the database is
1961 // beyond recovery.
1962 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1963 if (!Execute(kWritableSchema))
1964 return false;
1965
1966 bool ret = false;
1967 {
[email protected]579446c2013-12-16 18:36:521968 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001969
1970 // The pragma appears to return all results (up to 100 by default)
1971 // as a single string. This doesn't appear to be an API contract,
1972 // it could return separate lines, so loop _and_ split.
1973 while (stmt.Step()) {
1974 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181975 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1976 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001977 }
1978 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421979 }
[email protected]4658e2a02013-06-06 23:05:001980
1981 // Best effort to put things back as they were before.
1982 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1983 ignore_result(Execute(kNoWritableSchema));
1984
1985 return ret;
[email protected]80abf152013-05-22 12:42:421986}
1987
shess58b8df82015-06-03 00:19:321988base::TimeTicks TimeSource::Now() {
1989 return base::TimeTicks::Now();
1990}
1991
[email protected]e5ffd0e42009-09-11 21:30:561992} // namespace sql